iobroker.telegram 6.1.0 → 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.
package/build/main.js CHANGED
@@ -41,6 +41,38 @@ const actions = [
41
41
  * can pass any documented parameter of the underlying method (e.g. `parse_mode`, `reply_markup`,
42
42
  * `protect_content`, `message_thread_id`).
43
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
+ }
44
76
  const INTERNAL_OPTION_KEYS = new Set([
45
77
  'chatId',
46
78
  'user',
@@ -697,6 +729,37 @@ class Telegram extends adapter_core_1.Adapter {
697
729
  setStateSafe(id, value) {
698
730
  this.setState(id, value).catch(e => this.log.error(`Cannot set state "${id}": ${e}`));
699
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
+ }
700
763
  connectionState(connected, logSuccess) {
701
764
  let errorCounter = 0;
702
765
  // Note: Do NOT reset pollingConflictCount here. connectionState() is called after getMe() succeeds,
@@ -1572,7 +1635,7 @@ class Telegram extends adapter_core_1.Adapter {
1572
1635
  return Promise.all(tPromiseList).catch(e => e);
1573
1636
  }
1574
1637
  saveFile(fileID, fileName, callback) {
1575
- this.downloadFile(fileID)
1638
+ this.downloadFileOnce(fileID)
1576
1639
  .then(content => this.storeFile(fileName, content, callback))
1577
1640
  .catch(err => callback({ error: `Error: ${err}` }));
1578
1641
  }
@@ -1595,8 +1658,49 @@ class Telegram extends adapter_core_1.Adapter {
1595
1658
  }
1596
1659
  return Buffer.from(await response.arrayBuffer());
1597
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
+ }
1598
1677
  /** Set once an assistant instance answered a voice message as an empty question (too old for audio). */
1599
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
+ }
1600
1704
  /**
1601
1705
  * Forward a voice message to the ioBroker.assistant instance: it recognises the speech, answers like a text
1602
1706
  * question (same `source`, so the conversation continues) and returns what it heard. The same user check as for
@@ -1630,16 +1734,22 @@ class Telegram extends adapter_core_1.Adapter {
1630
1734
  // recognition + answer take a few seconds: show that something is happening
1631
1735
  bot.api.sendChatAction({ ...options, chat_id: msg.chat.id, action: 'typing' }).catch(() => { });
1632
1736
  this.log.debug(`Forward voice message from ${user} (${content.length} bytes) to ${this.config.assistantInstance}`);
1633
- const response = (await this.sendToIfAlive(this.config.assistantInstance, 'ask', {
1634
- text: '',
1635
- audio: content.toString('base64'),
1636
- format: 'ogg',
1637
- source: `telegram:${user}`,
1638
- user,
1639
- chatId: msg.chat.id,
1640
- userId: from.id.toString(),
1641
- messageThreadId: msg.is_topic_message ? msg.message_thread_id : 0,
1642
- }));
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
+ }
1643
1753
  if (!response) {
1644
1754
  return;
1645
1755
  }
@@ -1662,6 +1772,186 @@ class Telegram extends adapter_core_1.Adapter {
1662
1772
  .sendMessage({ ...options, chat_id: msg.chat.id, text })
1663
1773
  .catch(error => this.log.error(`send Message Error: ${error}`));
1664
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}`));
1844
+ }
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
+ }
1665
1955
  /**
1666
1956
  * Store a downloaded file where `saveFilesTo` says (file system or ioBroker file storage).
1667
1957
  *
@@ -1678,6 +1968,7 @@ class Telegram extends adapter_core_1.Adapter {
1678
1968
  info: `media file has been saved to "${this.config.saveFilesTo}": ${fileLocation}`,
1679
1969
  location: this.config.saveFilesTo,
1680
1970
  path: fileLocation,
1971
+ url: this.getReceivedFileUrl(fileLocation),
1681
1972
  });
1682
1973
  }
1683
1974
  else if (this.config.saveFilesTo == 'iobroker') {
@@ -1736,6 +2027,10 @@ class Telegram extends adapter_core_1.Adapter {
1736
2027
  ack: true,
1737
2028
  });
1738
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
+ }
1739
2034
  if (msg.voice) {
1740
2035
  // Downloaded once: stored as before (communicate.pathFile) and, with an assistant instance, recognised
1741
2036
  // and answered there. A voice message with a caption is answered by its caption (text pipeline) instead.
@@ -1746,7 +2041,7 @@ class Telegram extends adapter_core_1.Adapter {
1746
2041
  download
1747
2042
  .then(content => this.storeFile(this.config.saveFiles ? `/voice/${date}.ogg` : '/voice/temp.ogg', content, res => {
1748
2043
  this.log.info(res.info);
1749
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2044
+ this.setReceivedFile(res);
1750
2045
  }))
1751
2046
  .catch(err => this.log.debug(`Error saving voice file: ${err}`));
1752
2047
  }
@@ -1801,7 +2096,7 @@ class Telegram extends adapter_core_1.Adapter {
1801
2096
  this.saveFile(item.file_id, fileName, res => {
1802
2097
  if (!res.error) {
1803
2098
  this.log.info(res.info);
1804
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2099
+ this.setReceivedFile(res);
1805
2100
  }
1806
2101
  else {
1807
2102
  this.log.debug(res.error);
@@ -1818,7 +2113,7 @@ class Telegram extends adapter_core_1.Adapter {
1818
2113
  this.saveFile(msg.video.file_id, `/video/${date}.mp4`, res => {
1819
2114
  if (!res.error) {
1820
2115
  this.log.info(res.info);
1821
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2116
+ this.setReceivedFile(res);
1822
2117
  }
1823
2118
  else {
1824
2119
  this.log.debug(res.error);
@@ -1834,7 +2129,7 @@ class Telegram extends adapter_core_1.Adapter {
1834
2129
  this.saveFile(msg.video_note.file_id, `/video/${date}.mp4`, res => {
1835
2130
  if (!res.error) {
1836
2131
  this.log.info(res.info);
1837
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2132
+ this.setReceivedFile(res);
1838
2133
  }
1839
2134
  else {
1840
2135
  this.log.debug(res.error);
@@ -1850,7 +2145,7 @@ class Telegram extends adapter_core_1.Adapter {
1850
2145
  this.saveFile(msg.audio.file_id, `/audio/${date}.mp3`, res => {
1851
2146
  if (!res.error) {
1852
2147
  this.log.info(res.info);
1853
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2148
+ this.setReceivedFile(res);
1854
2149
  }
1855
2150
  else {
1856
2151
  this.log.debug(res.error);
@@ -1866,7 +2161,7 @@ class Telegram extends adapter_core_1.Adapter {
1866
2161
  this.saveFile(msg.document.file_id, `/document/${msg.document.file_name}`, res => {
1867
2162
  if (!res.error) {
1868
2163
  this.log.info(res.info);
1869
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2164
+ this.setReceivedFile(res);
1870
2165
  }
1871
2166
  else {
1872
2167
  this.log.debug(res.error);
@@ -2286,7 +2581,15 @@ class Telegram extends adapter_core_1.Adapter {
2286
2581
  * @param command the `sendTo` command
2287
2582
  * @param message the payload to forward
2288
2583
  */
2289
- 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) {
2290
2593
  // depending on the admin version the configured instance is stored as `text2command.0` or as
2291
2594
  // `system.adapter.text2command.0`, so normalize it to the short form
2292
2595
  const instanceId = instance.startsWith('system.adapter.')
@@ -2303,7 +2606,24 @@ class Telegram extends adapter_core_1.Adapter {
2303
2606
  this.log.warn(`Cannot check if "${instanceId}" is alive: ${err instanceof Error ? err.message : err}`);
2304
2607
  return;
2305
2608
  }
2306
- 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
+ }
2307
2627
  }
2308
2628
  async processTelegramText(msg) {
2309
2629
  this.connectionState(true);
@@ -2620,8 +2940,8 @@ class Telegram extends adapter_core_1.Adapter {
2620
2940
  }
2621
2941
  // Forward messages that no internal rule/command matched to the ioBroker.assistant instance and
2622
2942
  // reply with its answer. The reply is routed via this closure (msg.chat.id), so the answer always
2623
- // goes back to the right chat/thread.
2624
- 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)) {
2625
2945
  this.sendToIfAlive(this.config.assistantInstance, 'ask', {
2626
2946
  text: msgText,
2627
2947
  source: `telegram:${user}`,
@@ -2629,7 +2949,7 @@ class Telegram extends adapter_core_1.Adapter {
2629
2949
  chatId: msg.chat.id,
2630
2950
  userId: from.id.toString(),
2631
2951
  messageThreadId: msg.is_topic_message ? msg.message_thread_id : 0,
2632
- })
2952
+ }, this.assistantTimeoutMs)
2633
2953
  // @ts-expect-error types fixed in js-controller
2634
2954
  .then((response) => {
2635
2955
  const text = response && (response.answer || response.error);
@@ -2641,7 +2961,7 @@ class Telegram extends adapter_core_1.Adapter {
2641
2961
  .catch(error => this.log.error(`send Message Error: ${error}`));
2642
2962
  }
2643
2963
  })
2644
- .catch(err => this.log.error(`Cannot send message to ${this.config.assistantInstance}: ${err}`));
2964
+ .catch(err => this.assistantFailed(msg, err));
2645
2965
  }
2646
2966
  this.setStateSafe('communicate.requestChatId', { val: msg.chat.id, ack: true });
2647
2967
  this.setStateSafe('communicate.requestMessageId', { val: msg.message_id, ack: true });
@@ -3078,6 +3398,7 @@ class Telegram extends adapter_core_1.Adapter {
3078
3398
  await this.setState('communicate.responseSilentJson', { val: '', ack: true });
3079
3399
  await this.setState('communicate.requestResponse', { val: '', ack: true });
3080
3400
  await this.setState('communicate.pathFile', { val: '', ack: true });
3401
+ await this.setState('communicate.pathFileUrl', { val: '', ack: true });
3081
3402
  this.config.password ||= '';
3082
3403
  this.config.keyboard ||= '/cmds';
3083
3404
  await this.updateUsers();