iobroker.telegram 6.0.2 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +14 -9
  2. package/admin/blockly.js +53 -5
  3. package/admin/custom/assets/Components-joLukTKa.js +1 -0
  4. package/admin/custom/assets/TelegramComponent-C3-GtI7c.js +1 -0
  5. package/admin/custom/assets/_virtual_mf-localSharedImportMap___mfe_internal__ConfigCustomTelegramSet__mf_owner__1-DJIdwwyD.js +1 -0
  6. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__228362784883620__loadShare___mf_0_emotion_mf_1_react__loadShare__.js-BqNtIUwy.js +1 -0
  7. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__228362784883620__loadShare___mf_0_emotion_mf_1_styled__loadShare__.js-_NCgGj0v.js +1 -0
  8. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__228362784883620__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-xkznT_KX.js +1386 -0
  9. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__228362784883620__loadShare__shared-AcdRJ9g1.js +2 -0
  10. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__228362784883620__prebuild___mf_0_iobroker_mf_1_json_mf_2_config__prebuild__-CzaA27i4.js +122 -0
  11. package/admin/custom/assets/{_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__110562917496850__prebuild__react_mf_1_jsx_mf_2_runtime__prebuild__-HABeMIRl.js → _virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__228362784883620__prebuild__react_mf_1_jsx_mf_2_runtime__prebuild__-M61rjtmp.js} +1 -1
  12. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__228362784883620__prebuild__react_mf_2_dom_mf_1_client__prebuild__-OUz4TPLO.js +9 -0
  13. package/admin/custom/assets/dist-ClWhWsnT.js +1 -0
  14. package/admin/custom/assets/helpers-DYkm0lQU.js +1 -0
  15. package/admin/custom/assets/hostInit-CR7X3BVU.js +1 -0
  16. package/admin/custom/assets/iconLibraryData-B5fiyl1C.js +1 -0
  17. package/admin/custom/assets/index-DASuFkWw.js +1 -0
  18. package/admin/custom/assets/lib-Bo8s9r0H.js +3 -0
  19. package/admin/custom/assets/{mf-entry-bootstrap-0-df2bf7ab.js → mf-entry-bootstrap-0-153fe003.js} +3 -3
  20. package/admin/custom/assets/pendingShares-BLi3_Mzu.js +2 -0
  21. package/admin/custom/assets/prod-B1LT4e-j.js +502 -0
  22. package/admin/custom/assets/rolldown-runtime-COiEfhsA.js +1 -0
  23. package/admin/custom/assets/utils-BLvN1RVq.js +4 -0
  24. package/admin/custom/assets/vite-preload-helper-BbbETgeG.js +1 -0
  25. package/admin/custom/customComponents.js +2 -2
  26. package/admin/custom/i18n/de.json +6 -6
  27. package/admin/custom/i18n/en.json +6 -6
  28. package/admin/custom/i18n/es.json +6 -6
  29. package/admin/custom/i18n/fr.json +6 -6
  30. package/admin/custom/i18n/it.json +6 -6
  31. package/admin/custom/i18n/nl.json +6 -6
  32. package/admin/custom/i18n/pl.json +6 -6
  33. package/admin/custom/i18n/pt.json +6 -6
  34. package/admin/custom/i18n/ru.json +6 -6
  35. package/admin/custom/i18n/uk.json +6 -6
  36. package/admin/custom/i18n/zh-cn.json +6 -6
  37. package/admin/i18n/de.json +3 -0
  38. package/admin/i18n/en.json +3 -0
  39. package/admin/i18n/es.json +5 -2
  40. package/admin/i18n/fr.json +4 -1
  41. package/admin/i18n/it.json +4 -1
  42. package/admin/i18n/nl.json +3 -0
  43. package/admin/i18n/pl.json +3 -0
  44. package/admin/i18n/pt.json +4 -1
  45. package/admin/i18n/ru.json +3 -0
  46. package/admin/i18n/uk.json +13 -10
  47. package/admin/i18n/zh-cn.json +3 -0
  48. package/admin/jsonConfig.json +11 -0
  49. package/admin/rules/@mf-types.zip +0 -0
  50. package/admin/rules/assets/{ActionTelegram-LF8bnDSA.js → ActionTelegram-DYcZv36t.js} +1 -1
  51. package/admin/rules/assets/_virtual_mf-localSharedImportMap___mfe_internal__ActionTelegram__mf_owner__1-BsHXqCvo.js +1 -0
  52. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__34670834521048__loadShare__shared-BIBHA1kT.js +2 -0
  53. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__34670834521048__prebuild___mf_0_iobroker_mf_1_gui_mf_2_components__prebuild__-DpkR8IYJ.js +1358 -0
  54. package/admin/rules/assets/{_virtual_mf___mfe_internal__ActionTelegram__mf_owner__133816889156788__prebuild__prop_mf_2_types__prebuild__-uB_fYF0E.js → _virtual_mf___mfe_internal__ActionTelegram__mf_owner__34670834521048__prebuild__prop_mf_2_types__prebuild__-B1D0xwSZ.js} +1 -1
  55. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__34670834521048__prebuild__react__prebuild__-CCVlBWKm.js +1 -0
  56. package/admin/rules/assets/{_virtual_mf___mfe_internal__ActionTelegram__mf_owner__133816889156788__prebuild__react_mf_1_jsx_mf_2_runtime__prebuild__-CtgG8yGZ.js → _virtual_mf___mfe_internal__ActionTelegram__mf_owner__34670834521048__prebuild__react_mf_1_jsx_mf_2_runtime__prebuild__-lLn5ruiO.js} +1 -1
  57. package/admin/rules/assets/{_virtual_mf___mfe_internal__ActionTelegram__mf_owner__133816889156788__prebuild__react_mf_2_dom__prebuild__-Dh8puMC1.js → _virtual_mf___mfe_internal__ActionTelegram__mf_owner__34670834521048__prebuild__react_mf_2_dom__prebuild__-h_a0kZzS.js} +1 -1
  58. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__34670834521048__prebuild__react_mf_2_dom_mf_1_client__prebuild__-BRmB6rdf.js +9 -0
  59. package/admin/rules/assets/bootstrap-770dTuCT.js +1 -0
  60. package/admin/rules/assets/dist-CWBlVvfj.js +1 -0
  61. package/admin/rules/assets/helpers-BtFDi3IY.js +1 -0
  62. package/admin/rules/assets/hostInit-DHMkrH3X.js +1 -0
  63. package/admin/rules/assets/iconLibraryData-B5fiyl1C.js +1 -0
  64. package/admin/rules/assets/index-ClFbFt3x.js +2 -0
  65. package/admin/rules/assets/{mf-entry-bootstrap-0-5a126c10.js → mf-entry-bootstrap-0-6b56715e.js} +3 -3
  66. package/admin/rules/assets/pendingShares-qfYu7oWw.js +2 -0
  67. package/admin/rules/assets/prod-CbyVAouU.js +502 -0
  68. package/admin/rules/assets/react-BZk3575t.js +1 -0
  69. package/admin/rules/assets/react-dom-1nogLxXJ.js +1 -0
  70. package/admin/rules/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  71. package/admin/rules/assets/utils-BQKOadwq.js +4 -0
  72. package/admin/rules/assets/vite-preload-helper-BbbETgeG.js +1 -0
  73. package/admin/rules/customRuleBlocks.js +2 -2
  74. package/admin/rules/i18n/de.json +7 -7
  75. package/admin/rules/i18n/en.json +7 -7
  76. package/admin/rules/i18n/es.json +7 -7
  77. package/admin/rules/i18n/fr.json +7 -7
  78. package/admin/rules/i18n/it.json +7 -7
  79. package/admin/rules/i18n/nl.json +7 -7
  80. package/admin/rules/i18n/pl.json +7 -7
  81. package/admin/rules/i18n/pt.json +7 -7
  82. package/admin/rules/i18n/ru.json +7 -7
  83. package/admin/rules/i18n/uk.json +7 -7
  84. package/admin/rules/i18n/zh-cn.json +7 -7
  85. package/admin/rules/index.html +3 -2
  86. package/admin/rules/mf-manifest.json +1 -1
  87. package/admin/rules/mf-stats.json +1 -1
  88. package/build/main.d.ts +9 -1
  89. package/build/main.js +509 -60
  90. package/build/main.js.map +1 -1
  91. package/build/types.d.ts +9 -0
  92. package/i18n/de.json +2 -1
  93. package/i18n/en.json +4 -3
  94. package/i18n/es.json +2 -1
  95. package/i18n/fr.json +2 -1
  96. package/i18n/it.json +2 -1
  97. package/i18n/nl.json +2 -1
  98. package/i18n/pl.json +2 -1
  99. package/i18n/pt.json +2 -1
  100. package/i18n/ru.json +2 -1
  101. package/i18n/uk.json +2 -1
  102. package/i18n/zh-cn.json +2 -1
  103. package/io-package.json +52 -27
  104. package/package.json +6 -6
  105. package/admin/custom/assets/Components-D_wyfR3E.js +0 -1
  106. package/admin/custom/assets/TelegramComponent-mtwgdiDL.js +0 -1
  107. package/admin/custom/assets/_virtual_mf-localSharedImportMap___mfe_internal__ConfigCustomTelegramSet__mf_owner__1-B79-UQNs.js +0 -1
  108. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__110562917496850__loadShare___mf_0_emotion_mf_1_react__loadShare__.js-Cf0HuXvk.js +0 -1
  109. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__110562917496850__loadShare___mf_0_emotion_mf_1_styled__loadShare__.js-D4WsXgCI.js +0 -1
  110. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__110562917496850__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js--1ddskV_.js +0 -1217
  111. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__110562917496850__loadShare___mf_0_iobroker_mf_1_json_mf_2_config__loadShare__.js-B_Noke_B.js +0 -1
  112. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__110562917496850__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-hSzk9lxI.js +0 -1
  113. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__110562917496850__prebuild___mf_0_iobroker_mf_1_json_mf_2_config__prebuild__-CTtfI7qj.js +0 -122
  114. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__110562917496850__prebuild__react_mf_2_dom_mf_1_client__prebuild__-CDCo4Xq9.js +0 -9
  115. package/admin/custom/assets/dist-D4uJqRBO.js +0 -4
  116. package/admin/custom/assets/hostInit-CuMnfnDC.js +0 -1
  117. package/admin/custom/assets/index-DvK7dHLG.js +0 -1
  118. package/admin/custom/assets/lib-CrKlFI04.js +0 -3
  119. package/admin/custom/assets/pendingShares-Cxf76vil.js +0 -1
  120. package/admin/custom/assets/rolldown-runtime-C0FnF6B9.js +0 -1
  121. package/admin/custom/assets/virtualExposes-Ditkhfhv.js +0 -1
  122. package/admin/custom/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__ConfigCustomTelegramSet__customComponents_js-CVo5tXt9.js +0 -1
  123. package/admin/custom/assets/virtual_mf-exposes___mfe_internal__ConfigCustomTelegramSet__customComponents_js-YXqBAHsP.js +0 -2
  124. package/admin/custom/assets/vite-preload-helper-CaC3yEL3.js +0 -1
  125. package/admin/rules/assets/_virtual_mf-localSharedImportMap___mfe_internal__ActionTelegram__mf_owner__1-BvzkKHbn.js +0 -1
  126. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__133816889156788__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-Dbd89DjA.js +0 -2
  127. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__133816889156788__loadShare__prop_mf_2_types__loadShare__.js-BytPB1-A.js +0 -1
  128. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__133816889156788__loadShare__react__loadShare__.js-BjT36qD9.js +0 -1
  129. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__133816889156788__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.js-Ce-vuE6u.js +0 -1
  130. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__133816889156788__loadShare__react_mf_2_dom__loadShare__.js-BhMYnOkj.js +0 -2
  131. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__133816889156788__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-UxQBSbjm.js +0 -2
  132. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__133816889156788__prebuild___mf_0_iobroker_mf_1_gui_mf_2_components__prebuild__-DoGm_8Dn.js +0 -1187
  133. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__133816889156788__prebuild__react__prebuild__-D6jUEQ6q.js +0 -1
  134. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__133816889156788__prebuild__react_mf_2_dom_mf_1_client__prebuild__-C_ZCK_bw.js +0 -9
  135. package/admin/rules/assets/bootstrap-7ieO1qm_.js +0 -1
  136. package/admin/rules/assets/dist-DHz0uAC3.js +0 -4
  137. package/admin/rules/assets/hostInit-Hz1_LmSZ.js +0 -1
  138. package/admin/rules/assets/index-CrXv2SiL.js +0 -2
  139. package/admin/rules/assets/pendingShares-B6ElLznA.js +0 -1
  140. package/admin/rules/assets/react-dom-CM5my6za.js +0 -1
  141. package/admin/rules/assets/rolldown-runtime-B0Z9INg1.js +0 -1
  142. package/admin/rules/assets/virtualExposes-DrYqIznn.js +0 -1
  143. package/admin/rules/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__ActionTelegram__customRuleBlocks_js-BD5Ca8t-.js +0 -1
  144. package/admin/rules/assets/virtual_mf-exposes___mfe_internal__ActionTelegram__customRuleBlocks_js-DMAzv1EL.js +0 -2
  145. package/admin/rules/assets/vite-preload-helper-AwKPl3Sr.js +0 -1
package/build/main.js CHANGED
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.mergeMessageIds = mergeMessageIds;
6
7
  const node_fs_1 = require("node:fs");
7
8
  const node_path_1 = require("node:path");
8
9
  const axios_1 = __importDefault(require("axios"));
@@ -40,6 +41,38 @@ const actions = [
40
41
  * can pass any documented parameter of the underlying method (e.g. `parse_mode`, `reply_markup`,
41
42
  * `protect_content`, `message_thread_id`).
42
43
  */
44
+ /**
45
+ * How long a question to the assistant instance may take: speech recognition plus an LLM that may call tools. Without
46
+ * a limit a request lost on the way (e.g. the assistant restarted meanwhile) would leave the user without any reply.
47
+ */
48
+ const ASSISTANT_TIMEOUT_MS = 120_000;
49
+ /** Rejected by `sendToIfAlive` when the instance did not answer in time. */
50
+ class SendToTimeoutError extends Error {
51
+ }
52
+ /** Telegram lets bots download files up to this size only. */
53
+ const TELEGRAM_DOWNLOAD_LIMIT = 20 * 1024 * 1024;
54
+ /** The photos and videos of an album arrive as separate messages within a moment: wait this long for the rest. */
55
+ const ALBUM_WAIT_MS = 1500;
56
+ /** At most this many pictures go to the assistant with one question (as many as it accepts). */
57
+ const ASSISTANT_MAX_IMAGES = 4;
58
+ /** The size of a photo for the assistant: the largest one up to this edge (Telegram has e.g. 320, 800, 1280, 2560). */
59
+ const ASSISTANT_IMAGE_EDGE = 1600;
60
+ /** Videos for the assistant stay in the file storage (`<instance>/assistant/`); older ones are deleted. */
61
+ const ASSISTANT_VIDEOS_KEPT = 20;
62
+ /**
63
+ * The size of a photo that goes to the assistant: the largest one up to {@link ASSISTANT_IMAGE_EDGE}, else the
64
+ * smallest. Enough to see what is on it, and far below the limit of the models.
65
+ *
66
+ * @param sizes the sizes Telegram offers (`msg.photo`)
67
+ */
68
+ function assistantPhotoSize(sizes) {
69
+ const area = (s) => s.width * s.height;
70
+ const fitting = sizes.filter(s => Math.max(s.width, s.height) <= ASSISTANT_IMAGE_EDGE);
71
+ if (fitting.length) {
72
+ return fitting.reduce((a, b) => (area(b) > area(a) ? b : a));
73
+ }
74
+ return sizes.reduce((a, b) => (area(b) < area(a) ? b : a));
75
+ }
43
76
  const INTERNAL_OPTION_KEYS = new Set([
44
77
  'chatId',
45
78
  'user',
@@ -57,7 +90,42 @@ const INTERNAL_OPTION_KEYS = new Set([
57
90
  'editMessageCaption',
58
91
  'deleteMessage',
59
92
  'answerCallbackQuery',
93
+ 'returnMessageIds',
60
94
  ]);
95
+ /**
96
+ * Merge the per-recipient results of `sendMessage` - each a JSON `{ "<chatId>": messageId }`, with `error` for a
97
+ * recipient that failed - into one object, e.g. `{ "12345": 678, "error": { "999": "Forbidden: ..." } }`.
98
+ *
99
+ * @param results what `sendMessage` resolved with
100
+ * @returns chat id => message id, plus `error` (chat id => reason) if a recipient failed
101
+ */
102
+ function mergeMessageIds(results) {
103
+ const merged = {};
104
+ if (!Array.isArray(results)) {
105
+ return merged;
106
+ }
107
+ for (const item of results) {
108
+ let ids;
109
+ try {
110
+ ids = typeof item === 'string' ? JSON.parse(item) : item;
111
+ }
112
+ catch {
113
+ continue;
114
+ }
115
+ if (!ids || typeof ids !== 'object') {
116
+ continue;
117
+ }
118
+ for (const [key, value] of Object.entries(ids)) {
119
+ if (key === 'error' && value && typeof value === 'object') {
120
+ merged.error = { ...merged.error, ...value };
121
+ }
122
+ else if (typeof value === 'number' || typeof value === 'string') {
123
+ merged[key] = value;
124
+ }
125
+ }
126
+ }
127
+ return merged;
128
+ }
61
129
  /**
62
130
  * Pick the Bot API parameters out of the option bag, dropping the adapter-internal keys.
63
131
  *
@@ -661,6 +729,37 @@ class Telegram extends adapter_core_1.Adapter {
661
729
  setStateSafe(id, value) {
662
730
  this.setState(id, value).catch(e => this.log.error(`Cannot set state "${id}": ${e}`));
663
731
  }
732
+ /**
733
+ * Publish the last received file: its path on this host (`communicate.pathFile`) and its `iobdisk://` URL
734
+ * (`communicate.pathFileUrl`), which an instance on another host can read with `readDiskFile(url)`.
735
+ *
736
+ * @param res the result of storeFile
737
+ */
738
+ setReceivedFile(res) {
739
+ this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
740
+ this.setStateSafe('communicate.pathFileUrl', { val: res.url || '', ack: true });
741
+ }
742
+ /**
743
+ * The `iobdisk://` URL of a file in the data directory of this instance, e.g.
744
+ * `iobdisk://pi4/telegram.0/video/2026-11-04_10-00-00.mp4`
745
+ *
746
+ * @param fileLocation absolute path of the file
747
+ * @returns the URL, or an empty string if js-controller is older than 8.0
748
+ */
749
+ getReceivedFileUrl(fileLocation) {
750
+ // js-controller 8.0 and newer
751
+ const getDiskFileUrl = this.getDiskFileUrl;
752
+ if (typeof getDiskFileUrl !== 'function') {
753
+ return '';
754
+ }
755
+ try {
756
+ return getDiskFileUrl.call(this, fileLocation);
757
+ }
758
+ catch (e) {
759
+ this.log.debug(`Cannot build the URL of ${fileLocation}: ${e.message}`);
760
+ return '';
761
+ }
762
+ }
664
763
  connectionState(connected, logSuccess) {
665
764
  let errorCounter = 0;
666
765
  // Note: Do NOT reset pollingConflictCount here. connectionState() is called after getMe() succeeds,
@@ -1385,8 +1484,10 @@ class Telegram extends adapter_core_1.Adapter {
1385
1484
  resolve(JSON.stringify(messageIds));
1386
1485
  })
1387
1486
  .catch(error => {
1388
- // add the error to the message ids object
1389
- messageIds.error = { [String(options.chat_id ?? options.chatId)]: error };
1487
+ // add the error to the message ids object - as text: an Error object becomes `{}` in JSON
1488
+ messageIds.error = {
1489
+ [String(options.chat_id ?? options.chatId)]: error instanceof Error ? error.message : String(error),
1490
+ };
1390
1491
  // log error to the system
1391
1492
  this.log.error(`Failed sending [${options.chatId ? 'chatId' : 'user'} - ${options.chatId ? options.chatId : options.user}]: ${error}`);
1392
1493
  // If telegram was unreachable, queue the send so it can be retried on reconnect (issue #839).
@@ -1534,40 +1635,351 @@ class Telegram extends adapter_core_1.Adapter {
1534
1635
  return Promise.all(tPromiseList).catch(e => e);
1535
1636
  }
1536
1637
  saveFile(fileID, fileName, callback) {
1537
- this.log.debug(`Saving media file ${fileID} to ${fileName} (location = ${this.config.saveFilesTo})`);
1538
- this.bot.api.getFile({ file_id: fileID })
1539
- .then(async (file) => {
1540
- if (!file.file_path) {
1541
- throw new Error('telegram did not return a file path');
1542
- }
1543
- // the library offers no download helper, so build the file URL ourselves
1544
- const url = `${this.config.baseApiUrl}/file/bot${this.config.token}/${file.file_path}`;
1545
- this.log.debug(`Download media file: ${url.replace(this.config.token, '<token>')}`);
1546
- const response = await this.fetchImpl(url);
1547
- if (!response.ok) {
1548
- throw new Error(`statusCode ${response.status}`);
1549
- }
1550
- const content = Buffer.from(await response.arrayBuffer());
1551
- if (this.config.saveFilesTo == 'filesystem') {
1552
- const fileLocation = (0, node_path_1.join)(this.tmpDirName, fileName);
1553
- (0, node_fs_1.writeFileSync)(fileLocation, content);
1554
- callback({
1555
- info: `media file has been saved to "${this.config.saveFilesTo}": ${fileLocation}`,
1556
- location: this.config.saveFilesTo,
1557
- path: fileLocation,
1558
- });
1638
+ this.downloadFileOnce(fileID)
1639
+ .then(content => this.storeFile(fileName, content, callback))
1640
+ .catch(err => callback({ error: `Error: ${err}` }));
1641
+ }
1642
+ /**
1643
+ * Download a file the user sent (photo, voice, document, ...) from the Telegram servers.
1644
+ *
1645
+ * @param fileID the Telegram file id
1646
+ */
1647
+ async downloadFile(fileID) {
1648
+ const file = await this.bot.api.getFile({ file_id: fileID });
1649
+ if (!file.file_path) {
1650
+ throw new Error('telegram did not return a file path');
1651
+ }
1652
+ // the library offers no download helper, so build the file URL ourselves
1653
+ const url = `${this.config.baseApiUrl}/file/bot${this.config.token}/${file.file_path}`;
1654
+ this.log.debug(`Download media file: ${url.replace(this.config.token, '<token>')}`);
1655
+ const response = await this.fetchImpl(url);
1656
+ if (!response.ok) {
1657
+ throw new Error(`statusCode ${response.status}`);
1658
+ }
1659
+ return Buffer.from(await response.arrayBuffer());
1660
+ }
1661
+ /** Downloads of the last minute by file id: a photo or video that is saved and forwarded is downloaded once. */
1662
+ downloads = new Map();
1663
+ /**
1664
+ * {@link downloadFile}, but a second call for the same file within a minute gets the same download.
1665
+ *
1666
+ * @param fileID the Telegram file id
1667
+ */
1668
+ downloadFileOnce(fileID) {
1669
+ let download = this.downloads.get(fileID);
1670
+ if (!download) {
1671
+ download = this.downloadFile(fileID);
1672
+ this.downloads.set(fileID, download);
1673
+ download.then(() => this.setTimeout(() => this.downloads.delete(fileID), 60_000), () => this.downloads.delete(fileID));
1674
+ }
1675
+ return download;
1676
+ }
1677
+ /** Set once an assistant instance answered a voice message as an empty question (too old for audio). */
1678
+ assistantVoiceWarned = false;
1679
+ /** Set once an assistant instance answered pictures as an empty question (too old for pictures). */
1680
+ assistantMediaWarned = false;
1681
+ /** Albums waiting for their last photo or video, by `media_group_id`. */
1682
+ assistantAlbums = new Map();
1683
+ /** How long the assistant may take for an answer (a field so that tests can shorten it). */
1684
+ assistantTimeoutMs = ASSISTANT_TIMEOUT_MS;
1685
+ /**
1686
+ * Tell the user that the assistant did not answer, instead of leaving the question unanswered.
1687
+ *
1688
+ * @param msg the message that was forwarded
1689
+ * @param error why: a timeout gets a message in the chat, anything else only a log entry
1690
+ */
1691
+ async assistantFailed(msg, error) {
1692
+ if (!(error instanceof SendToTimeoutError)) {
1693
+ this.log.error(`Cannot send message to ${this.config.assistantInstance}: ${error instanceof Error ? error.message : String(error)}`);
1694
+ return;
1695
+ }
1696
+ this.log.warn(error.message);
1697
+ const options = msg.is_topic_message ? { message_thread_id: msg.message_thread_id } : undefined;
1698
+ await this.bot.api.sendMessage({
1699
+ ...options,
1700
+ chat_id: msg.chat.id,
1701
+ text: adapter_core_1.I18n.translate('The assistant did not answer in time.'),
1702
+ }).catch(err => this.log.error(`send Message Error: ${err}`));
1703
+ }
1704
+ /**
1705
+ * Forward a voice message to the ioBroker.assistant instance: it recognises the speech, answers like a text
1706
+ * question (same `source`, so the conversation continues) and returns what it heard. The same user check as for
1707
+ * text messages applies — without it anyone could talk to the assistant just by sending a voice message.
1708
+ *
1709
+ * @param msg the voice message
1710
+ * @param download the running download of the recording (OGG/Opus)
1711
+ */
1712
+ async askAssistantByVoice(msg, download) {
1713
+ const bot = this.bot;
1714
+ const from = msg.from;
1715
+ const user = !this.config.useUsername ? from.first_name : !from.username ? from.first_name : from.username;
1716
+ const pollingInterval = parseInt(String(this.config.pollingInterval ?? 0), 10) || 0;
1717
+ if (Date.now() - msg.date * 1000 > pollingInterval + 30000) {
1718
+ this.log.warn(`Voice message from ${from.first_name} ignored, because too old`);
1719
+ return;
1720
+ }
1721
+ if ((this.config.password || this.config.doNotAcceptNewUsers) && !this.storedUsers[from.id]) {
1722
+ await bot.api
1723
+ .sendMessage({
1724
+ chat_id: from.id,
1725
+ text: adapter_core_1.I18n.translate(this.config.doNotAcceptNewUsers
1726
+ ? 'User is not in the list'
1727
+ : 'Please enter password in form "/password phrase"'),
1728
+ })
1729
+ .catch(error => this.log.error(`send Message Error: ${error}`));
1730
+ return;
1731
+ }
1732
+ const content = await download;
1733
+ const options = msg.is_topic_message ? { message_thread_id: msg.message_thread_id } : undefined;
1734
+ // recognition + answer take a few seconds: show that something is happening
1735
+ bot.api.sendChatAction({ ...options, chat_id: msg.chat.id, action: 'typing' }).catch(() => { });
1736
+ this.log.debug(`Forward voice message from ${user} (${content.length} bytes) to ${this.config.assistantInstance}`);
1737
+ let response;
1738
+ try {
1739
+ response = (await this.sendToIfAlive(this.config.assistantInstance, 'ask', {
1740
+ text: '',
1741
+ audio: content.toString('base64'),
1742
+ format: 'ogg',
1743
+ source: `telegram:${user}`,
1744
+ user,
1745
+ chatId: msg.chat.id,
1746
+ userId: from.id.toString(),
1747
+ messageThreadId: msg.is_topic_message ? msg.message_thread_id : 0,
1748
+ }, this.assistantTimeoutMs));
1749
+ }
1750
+ catch (error) {
1751
+ return this.assistantFailed(msg, error);
1752
+ }
1753
+ if (!response) {
1754
+ return;
1755
+ }
1756
+ // an assistant that does not know `audio` sees no text and rejects the request as an empty question
1757
+ if (response.error === 'empty question' && response.heard === undefined) {
1758
+ if (!this.assistantVoiceWarned) {
1759
+ this.assistantVoiceWarned = true;
1760
+ this.log.warn(`${this.config.assistantInstance} cannot recognise voice messages - update ioBroker.assistant to the latest version`);
1559
1761
  }
1560
- else if (this.config.saveFilesTo == 'iobroker') {
1561
- const fileLocation = (0, node_path_1.join)(this.tmpDirName, fileName); // TODO: check new urn format https://github.com/ioBroker/ioBroker.js-controller/issues/2710
1562
- await this.writeFileAsync(this.namespace, fileName, content);
1563
- callback({
1564
- info: `media file has been saved to "${this.config.saveFilesTo}": ${fileLocation}`,
1565
- location: this.config.saveFilesTo,
1566
- path: fileLocation,
1567
- });
1762
+ return;
1763
+ }
1764
+ const answer = response.answer || response.error;
1765
+ if (!answer) {
1766
+ return;
1767
+ }
1768
+ // show what was understood, so a wrong answer can be told apart from a misheard question
1769
+ const text = response.heard ? `🎤 ${response.heard}\n\n${answer}` : answer;
1770
+ this.log.debug(`Assistant response: ${text}`);
1771
+ await bot.api
1772
+ .sendMessage({ ...options, chat_id: msg.chat.id, text })
1773
+ .catch(error => this.log.error(`send Message Error: ${error}`));
1774
+ }
1775
+ /**
1776
+ * Whether the photos and videos of this message go to the assistant. Its caption then goes along with them and not
1777
+ * a second time through the text pipeline.
1778
+ *
1779
+ * @param msg the received message
1780
+ */
1781
+ forwardsMediaToAssistant(msg) {
1782
+ return !!(this.config.assistantInstance &&
1783
+ this.config.assistantMedia !== false &&
1784
+ msg.from &&
1785
+ (msg.photo?.length || msg.video || msg.video_note));
1786
+ }
1787
+ /**
1788
+ * Forward a photo or video message to the assistant. The parts of an album are collected first and go as one
1789
+ * question - otherwise ten photos would get ten answers.
1790
+ *
1791
+ * @param msg the received message
1792
+ */
1793
+ queueAssistantMedia(msg) {
1794
+ const group = msg.media_group_id;
1795
+ const forward = (msgs) => {
1796
+ this.askAssistantWithMedia(msgs).catch(err => this.log.error(`Cannot send media to ${this.config.assistantInstance}: ${err}`));
1797
+ };
1798
+ if (!group) {
1799
+ forward([msg]);
1800
+ return;
1801
+ }
1802
+ const album = this.assistantAlbums.get(group) || { msgs: [] };
1803
+ album.msgs.push(msg);
1804
+ if (album.timer) {
1805
+ this.clearTimeout(album.timer);
1806
+ }
1807
+ album.timer = this.setTimeout(() => {
1808
+ this.assistantAlbums.delete(group);
1809
+ forward(album.msgs);
1810
+ }, ALBUM_WAIT_MS);
1811
+ this.assistantAlbums.set(group, album);
1812
+ }
1813
+ /**
1814
+ * Forward photos and a video to the ioBroker.assistant instance. The photos go along as base64 (one size each, see
1815
+ * {@link assistantPhotoSize}); a video never does: it is stored in the ioBroker file storage of this instance
1816
+ * (`assistant/`, the newest {@link ASSISTANT_VIDEOS_KEPT}), which every host reads, and only its place goes along.
1817
+ * The caption is the question. The same user check as for text messages applies.
1818
+ *
1819
+ * @param msgs the message, or all messages of an album
1820
+ */
1821
+ async askAssistantWithMedia(msgs) {
1822
+ const bot = this.bot;
1823
+ const msg = msgs[0];
1824
+ const from = msg.from;
1825
+ const user = !this.config.useUsername ? from.first_name : !from.username ? from.first_name : from.username;
1826
+ // only one message of an album has the caption
1827
+ const caption = (msgs.find(m => m.caption)?.caption || '').trim();
1828
+ const pollingInterval = parseInt(String(this.config.pollingInterval ?? 0), 10) || 0;
1829
+ if (Date.now() - msg.date * 1000 > pollingInterval + 30000) {
1830
+ this.log.warn(`Photo/video from ${from.first_name} ignored, because too old`);
1831
+ return;
1832
+ }
1833
+ if ((this.config.password || this.config.doNotAcceptNewUsers) && !this.storedUsers[from.id]) {
1834
+ // a caption went through the text pipeline, which has told the user already
1835
+ if (!caption) {
1836
+ await bot.api
1837
+ .sendMessage({
1838
+ chat_id: from.id,
1839
+ text: adapter_core_1.I18n.translate(this.config.doNotAcceptNewUsers
1840
+ ? 'User is not in the list'
1841
+ : 'Please enter password in form "/password phrase"'),
1842
+ })
1843
+ .catch(error => this.log.error(`send Message Error: ${error}`));
1568
1844
  }
1569
- })
1570
- .catch(err => callback({ error: `Error: ${err}` }));
1845
+ return;
1846
+ }
1847
+ const options = msg.is_topic_message ? { message_thread_id: msg.message_thread_id } : undefined;
1848
+ bot.api.sendChatAction({ ...options, chat_id: msg.chat.id, action: 'typing' }).catch(() => { });
1849
+ const photos = msgs.filter(m => m.photo?.length);
1850
+ if (photos.length > ASSISTANT_MAX_IMAGES) {
1851
+ this.log.info(`Album with ${photos.length} photos: only the first ${ASSISTANT_MAX_IMAGES} go to ${this.config.assistantInstance}`);
1852
+ }
1853
+ let images;
1854
+ try {
1855
+ images = await Promise.all(photos.slice(0, ASSISTANT_MAX_IMAGES).map(async (m) => ({
1856
+ data: (await this.downloadFileOnce(assistantPhotoSize(m.photo).file_id)).toString('base64'),
1857
+ // Telegram sends every photo as JPEG
1858
+ mimeType: 'image/jpeg',
1859
+ })));
1860
+ }
1861
+ catch (error) {
1862
+ this.log.warn(`Cannot download the photo for ${this.config.assistantInstance}: ${error}`);
1863
+ return;
1864
+ }
1865
+ const videoMsg = msgs.find(m => m.video || m.video_note);
1866
+ const video = videoMsg ? await this.storeVideoForAssistant(videoMsg) : undefined;
1867
+ if (!images.length && !video) {
1868
+ return;
1869
+ }
1870
+ this.log.debug(`Forward ${images.length} photo(s)${video ? ` and a video (${video.path || video.error})` : ''} from ${user} to ${this.config.assistantInstance}`);
1871
+ let response;
1872
+ try {
1873
+ response = (await this.sendToIfAlive(this.config.assistantInstance, 'ask', {
1874
+ text: caption,
1875
+ ...(images.length ? { images } : {}),
1876
+ ...(video ? { video } : {}),
1877
+ source: `telegram:${user}`,
1878
+ user,
1879
+ chatId: msg.chat.id,
1880
+ userId: from.id.toString(),
1881
+ messageThreadId: msg.is_topic_message ? msg.message_thread_id : 0,
1882
+ }, this.assistantTimeoutMs));
1883
+ }
1884
+ catch (error) {
1885
+ return this.assistantFailed(msg, error);
1886
+ }
1887
+ if (!response) {
1888
+ return;
1889
+ }
1890
+ // an assistant that does not know pictures sees no text and rejects the request as an empty question
1891
+ if (response.error === 'empty question') {
1892
+ if (!this.assistantMediaWarned) {
1893
+ this.assistantMediaWarned = true;
1894
+ this.log.warn(`${this.config.assistantInstance} cannot look at pictures - update ioBroker.assistant to the latest version`);
1895
+ }
1896
+ return;
1897
+ }
1898
+ const answer = response.answer || response.error;
1899
+ if (!answer) {
1900
+ return;
1901
+ }
1902
+ this.log.debug(`Assistant response: ${answer}`);
1903
+ await bot.api
1904
+ .sendMessage({ ...options, chat_id: msg.chat.id, text: answer })
1905
+ .catch(error => this.log.error(`send Message Error: ${error}`));
1906
+ }
1907
+ /**
1908
+ * Store a video for the assistant in the ioBroker file storage of this instance - the assistant may run on another
1909
+ * host, and a video does not go through the message bus. Keeps the newest {@link ASSISTANT_VIDEOS_KEPT}.
1910
+ *
1911
+ * @param msg the message with the video or video note
1912
+ * @returns where it is, or why it is not there
1913
+ */
1914
+ async storeVideoForAssistant(msg) {
1915
+ const file = (msg.video || msg.video_note);
1916
+ const mimeType = msg.video?.mime_type || 'video/mp4';
1917
+ const info = { mimeType, durationSec: file.duration, size: file.file_size };
1918
+ if (file.file_size && file.file_size > TELEGRAM_DOWNLOAD_LIMIT) {
1919
+ return {
1920
+ ...info,
1921
+ error: `too big to download (${Math.round(file.file_size / 1024 / 1024)} MB, Telegram allows bots 20 MB)`,
1922
+ };
1923
+ }
1924
+ try {
1925
+ const content = await this.downloadFileOnce(file.file_id);
1926
+ const date = new Date().toISOString().replace(/T/, '_').replace(/\..+/, '').replace(/:/g, '-');
1927
+ const ext = mimeType === 'video/quicktime' ? 'mov' : (mimeType.split('/')[1] || 'mp4').replace(/\W/g, '');
1928
+ const path = `assistant/video_${date}_${msg.message_id}.${ext}`;
1929
+ await this.writeFileAsync(this.namespace, path, content);
1930
+ void this.pruneAssistantVideos();
1931
+ return { ...info, adapter: this.namespace, path, size: content.length };
1932
+ }
1933
+ catch (error) {
1934
+ this.log.warn(`Cannot store the video for ${this.config.assistantInstance}: ${error}`);
1935
+ return { ...info, error: `could not be stored: ${error instanceof Error ? error.message : String(error)}` };
1936
+ }
1937
+ }
1938
+ /** Delete all but the newest {@link ASSISTANT_VIDEOS_KEPT} videos for the assistant. */
1939
+ async pruneAssistantVideos() {
1940
+ try {
1941
+ const files = await this.readDirAsync(this.namespace, 'assistant');
1942
+ // the names start with the date, so the order of the names is the order of time
1943
+ const videos = files
1944
+ .filter(f => !f.isDir && f.file.startsWith('video_'))
1945
+ .map(f => f.file)
1946
+ .sort();
1947
+ for (const file of videos.slice(0, Math.max(0, videos.length - ASSISTANT_VIDEOS_KEPT))) {
1948
+ await this.delFileAsync(this.namespace, `assistant/${file}`);
1949
+ }
1950
+ }
1951
+ catch (error) {
1952
+ this.log.debug(`Cannot delete old videos of the assistant: ${error}`);
1953
+ }
1954
+ }
1955
+ /**
1956
+ * Store a downloaded file where `saveFilesTo` says (file system or ioBroker file storage).
1957
+ *
1958
+ * @param fileName path below the storage root, e.g. `/voice/temp.ogg`
1959
+ * @param content the file content
1960
+ * @param callback called with the stored location (not called when saving is off)
1961
+ */
1962
+ async storeFile(fileName, content, callback) {
1963
+ this.log.debug(`Saving media file to ${fileName} (location = ${this.config.saveFilesTo})`);
1964
+ if (this.config.saveFilesTo == 'filesystem') {
1965
+ const fileLocation = (0, node_path_1.join)(this.tmpDirName, fileName);
1966
+ (0, node_fs_1.writeFileSync)(fileLocation, content);
1967
+ callback({
1968
+ info: `media file has been saved to "${this.config.saveFilesTo}": ${fileLocation}`,
1969
+ location: this.config.saveFilesTo,
1970
+ path: fileLocation,
1971
+ url: this.getReceivedFileUrl(fileLocation),
1972
+ });
1973
+ }
1974
+ else if (this.config.saveFilesTo == 'iobroker') {
1975
+ const fileLocation = (0, node_path_1.join)(this.tmpDirName, fileName); // TODO: check new urn format https://github.com/ioBroker/ioBroker.js-controller/issues/2710
1976
+ await this.writeFileAsync(this.namespace, fileName, content);
1977
+ callback({
1978
+ info: `media file has been saved to "${this.config.saveFilesTo}": ${fileLocation}`,
1979
+ location: this.config.saveFilesTo,
1980
+ path: fileLocation,
1981
+ });
1982
+ }
1571
1983
  }
1572
1984
  getMessage(msg) {
1573
1985
  const date = new Date().toISOString().replace(/T/, '_').replace(/\..+/, '').replace(/:/g, '-');
@@ -1615,21 +2027,23 @@ class Telegram extends adapter_core_1.Adapter {
1615
2027
  ack: true,
1616
2028
  });
1617
2029
  }
2030
+ // Photos and videos (with their caption) to the assistant; saved below as before
2031
+ if (this.forwardsMediaToAssistant(msg)) {
2032
+ this.queueAssistantMedia(msg);
2033
+ }
1618
2034
  if (msg.voice) {
1619
- try {
1620
- this.saveFile(msg.voice.file_id, this.config.saveFiles ? `/voice/${date}.ogg` : '/voice/temp.ogg', res => {
1621
- if (!res.error) {
1622
- this.log.info(res.info);
1623
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
1624
- }
1625
- else {
1626
- this.log.debug(res.error);
1627
- }
1628
- });
1629
- }
1630
- catch (err) {
1631
- this.log.error(`Error saving voice file: ${err}`);
1632
- }
2035
+ // Downloaded once: stored as before (communicate.pathFile) and, with an assistant instance, recognised
2036
+ // and answered there. A voice message with a caption is answered by its caption (text pipeline) instead.
2037
+ const download = this.downloadFile(msg.voice.file_id);
2038
+ if (this.config.assistantInstance && msg.from && !msg.caption) {
2039
+ this.askAssistantByVoice(msg, download).catch(err => this.log.error(`Cannot send voice message to ${this.config.assistantInstance}: ${err}`));
2040
+ }
2041
+ download
2042
+ .then(content => this.storeFile(this.config.saveFiles ? `/voice/${date}.ogg` : '/voice/temp.ogg', content, res => {
2043
+ this.log.info(res.info);
2044
+ this.setReceivedFile(res);
2045
+ }))
2046
+ .catch(err => this.log.debug(`Error saving voice file: ${err}`));
1633
2047
  }
1634
2048
  else if (this.config.saveFiles && msg.photo) {
1635
2049
  try {
@@ -1682,7 +2096,7 @@ class Telegram extends adapter_core_1.Adapter {
1682
2096
  this.saveFile(item.file_id, fileName, res => {
1683
2097
  if (!res.error) {
1684
2098
  this.log.info(res.info);
1685
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2099
+ this.setReceivedFile(res);
1686
2100
  }
1687
2101
  else {
1688
2102
  this.log.debug(res.error);
@@ -1699,7 +2113,7 @@ class Telegram extends adapter_core_1.Adapter {
1699
2113
  this.saveFile(msg.video.file_id, `/video/${date}.mp4`, res => {
1700
2114
  if (!res.error) {
1701
2115
  this.log.info(res.info);
1702
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2116
+ this.setReceivedFile(res);
1703
2117
  }
1704
2118
  else {
1705
2119
  this.log.debug(res.error);
@@ -1715,7 +2129,7 @@ class Telegram extends adapter_core_1.Adapter {
1715
2129
  this.saveFile(msg.video_note.file_id, `/video/${date}.mp4`, res => {
1716
2130
  if (!res.error) {
1717
2131
  this.log.info(res.info);
1718
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2132
+ this.setReceivedFile(res);
1719
2133
  }
1720
2134
  else {
1721
2135
  this.log.debug(res.error);
@@ -1731,7 +2145,7 @@ class Telegram extends adapter_core_1.Adapter {
1731
2145
  this.saveFile(msg.audio.file_id, `/audio/${date}.mp3`, res => {
1732
2146
  if (!res.error) {
1733
2147
  this.log.info(res.info);
1734
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2148
+ this.setReceivedFile(res);
1735
2149
  }
1736
2150
  else {
1737
2151
  this.log.debug(res.error);
@@ -1747,7 +2161,7 @@ class Telegram extends adapter_core_1.Adapter {
1747
2161
  this.saveFile(msg.document.file_id, `/document/${msg.document.file_name}`, res => {
1748
2162
  if (!res.error) {
1749
2163
  this.log.info(res.info);
1750
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2164
+ this.setReceivedFile(res);
1751
2165
  }
1752
2166
  else {
1753
2167
  this.log.debug(res.error);
@@ -1786,7 +2200,16 @@ class Telegram extends adapter_core_1.Adapter {
1786
2200
  tPromise = this.sendMessage(obj.message);
1787
2201
  }
1788
2202
  tPromise
1789
- .then(results => obj.callback && this.sendTo(obj.from, obj.command, results.length, obj.callback))
2203
+ .then(results => {
2204
+ if (!obj.callback) {
2205
+ return;
2206
+ }
2207
+ // Before 5.0 the callback got the message ids, and scripts used them to edit or delete
2208
+ // the message later (#1389). Since then it gets the number of recipients, which newer
2209
+ // scripts rely on - so the ids come on request.
2210
+ const wantIds = typeof obj.message === 'object' && !!obj.message.returnMessageIds;
2211
+ this.sendTo(obj.from, obj.command, wantIds ? mergeMessageIds(results) : results.length, obj.callback);
2212
+ })
1790
2213
  .catch(e => this.log.error(`Cannot send command: ${e}`));
1791
2214
  }
1792
2215
  break;
@@ -2158,7 +2581,15 @@ class Telegram extends adapter_core_1.Adapter {
2158
2581
  * @param command the `sendTo` command
2159
2582
  * @param message the payload to forward
2160
2583
  */
2161
- async sendToIfAlive(instance, command, message) {
2584
+ /**
2585
+ * `sendTo` an instance that is running; a stopped one is only logged.
2586
+ *
2587
+ * @param instance the instance, short (`assistant.0`) or long (`system.adapter.assistant.0`)
2588
+ * @param command the command
2589
+ * @param message the message
2590
+ * @param timeoutMs if set, rejects with a `SendToTimeoutError` when there is no answer by then
2591
+ */
2592
+ async sendToIfAlive(instance, command, message, timeoutMs) {
2162
2593
  // depending on the admin version the configured instance is stored as `text2command.0` or as
2163
2594
  // `system.adapter.text2command.0`, so normalize it to the short form
2164
2595
  const instanceId = instance.startsWith('system.adapter.')
@@ -2175,7 +2606,24 @@ class Telegram extends adapter_core_1.Adapter {
2175
2606
  this.log.warn(`Cannot check if "${instanceId}" is alive: ${err instanceof Error ? err.message : err}`);
2176
2607
  return;
2177
2608
  }
2178
- return await this.sendToAsync(instanceId, command, message);
2609
+ if (!timeoutMs) {
2610
+ return await this.sendToAsync(instanceId, command, message);
2611
+ }
2612
+ let timer;
2613
+ try {
2614
+ return await Promise.race([
2615
+ // The controller gets a timeout too, a bit later, only so that it forgets the callback.
2616
+ this.sendToAsync(instanceId, command, message, { timeout: timeoutMs + 5000 }),
2617
+ new Promise((_, reject) => {
2618
+ timer = this.setTimeout(() => reject(new SendToTimeoutError(`${instanceId} did not answer "${command}" within ${Math.round(timeoutMs / 1000)} s`)), timeoutMs);
2619
+ }),
2620
+ ]);
2621
+ }
2622
+ finally {
2623
+ if (timer) {
2624
+ this.clearTimeout(timer);
2625
+ }
2626
+ }
2179
2627
  }
2180
2628
  async processTelegramText(msg) {
2181
2629
  this.connectionState(true);
@@ -2492,8 +2940,8 @@ class Telegram extends adapter_core_1.Adapter {
2492
2940
  }
2493
2941
  // Forward messages that no internal rule/command matched to the ioBroker.assistant instance and
2494
2942
  // reply with its answer. The reply is routed via this closure (msg.chat.id), so the answer always
2495
- // goes back to the right chat/thread.
2496
- if (this.config.assistantInstance) {
2943
+ // goes back to the right chat/thread. The caption of a photo or video goes there with the media instead.
2944
+ if (this.config.assistantInstance && !this.forwardsMediaToAssistant(msg)) {
2497
2945
  this.sendToIfAlive(this.config.assistantInstance, 'ask', {
2498
2946
  text: msgText,
2499
2947
  source: `telegram:${user}`,
@@ -2501,7 +2949,7 @@ class Telegram extends adapter_core_1.Adapter {
2501
2949
  chatId: msg.chat.id,
2502
2950
  userId: from.id.toString(),
2503
2951
  messageThreadId: msg.is_topic_message ? msg.message_thread_id : 0,
2504
- })
2952
+ }, this.assistantTimeoutMs)
2505
2953
  // @ts-expect-error types fixed in js-controller
2506
2954
  .then((response) => {
2507
2955
  const text = response && (response.answer || response.error);
@@ -2513,7 +2961,7 @@ class Telegram extends adapter_core_1.Adapter {
2513
2961
  .catch(error => this.log.error(`send Message Error: ${error}`));
2514
2962
  }
2515
2963
  })
2516
- .catch(err => this.log.error(`Cannot send message to ${this.config.assistantInstance}: ${err}`));
2964
+ .catch(err => this.assistantFailed(msg, err));
2517
2965
  }
2518
2966
  this.setStateSafe('communicate.requestChatId', { val: msg.chat.id, ack: true });
2519
2967
  this.setStateSafe('communicate.requestMessageId', { val: msg.message_id, ack: true });
@@ -2950,6 +3398,7 @@ class Telegram extends adapter_core_1.Adapter {
2950
3398
  await this.setState('communicate.responseSilentJson', { val: '', ack: true });
2951
3399
  await this.setState('communicate.requestResponse', { val: '', ack: true });
2952
3400
  await this.setState('communicate.pathFile', { val: '', ack: true });
3401
+ await this.setState('communicate.pathFileUrl', { val: '', ack: true });
2953
3402
  this.config.password ||= '';
2954
3403
  this.config.keyboard ||= '/cmds';
2955
3404
  await this.updateUsers();