iobroker.telegram 6.1.0 → 6.2.1

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
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.mergeMessageIds = mergeMessageIds;
7
7
  const node_fs_1 = require("node:fs");
8
+ const promises_1 = require("node:fs/promises");
8
9
  const node_path_1 = require("node:path");
9
10
  const axios_1 = __importDefault(require("axios"));
10
11
  const node_telegram_bot_api_1 = require("node-telegram-bot-api");
@@ -41,6 +42,41 @@ const actions = [
41
42
  * can pass any documented parameter of the underlying method (e.g. `parse_mode`, `reply_markup`,
42
43
  * `protect_content`, `message_thread_id`).
43
44
  */
45
+ /**
46
+ * How long a question to the assistant instance may take: speech recognition plus an LLM that may call tools. Without
47
+ * a limit a request lost on the way (e.g. the assistant restarted meanwhile) would leave the user without any reply.
48
+ */
49
+ const ASSISTANT_TIMEOUT_MS = 120_000;
50
+ /** Rejected by `sendToIfAlive` when the instance did not answer in time. */
51
+ class SendToTimeoutError extends Error {
52
+ }
53
+ /** Telegram lets bots download files up to this size only. */
54
+ const TELEGRAM_DOWNLOAD_LIMIT = 20 * 1024 * 1024;
55
+ /** The photos and videos of an album arrive as separate messages within a moment: wait this long for the rest. */
56
+ const ALBUM_WAIT_MS = 1500;
57
+ /** At most this many pictures go to the assistant with one question (as many as it accepts). */
58
+ const ASSISTANT_MAX_IMAGES = 4;
59
+ /** The size of a photo for the assistant: the largest one up to this edge (Telegram has e.g. 320, 800, 1280, 2560). */
60
+ const ASSISTANT_IMAGE_EDGE = 1600;
61
+ /**
62
+ * Videos for the assistant stay in the folder `assistant` - in the data directory of the instance with js-controller
63
+ * 8.0+, else in its file storage; older ones are deleted.
64
+ */
65
+ const ASSISTANT_VIDEOS_KEPT = 20;
66
+ /**
67
+ * The size of a photo that goes to the assistant: the largest one up to {@link ASSISTANT_IMAGE_EDGE}, else the
68
+ * smallest. Enough to see what is on it, and far below the limit of the models.
69
+ *
70
+ * @param sizes the sizes Telegram offers (`msg.photo`)
71
+ */
72
+ function assistantPhotoSize(sizes) {
73
+ const area = (s) => s.width * s.height;
74
+ const fitting = sizes.filter(s => Math.max(s.width, s.height) <= ASSISTANT_IMAGE_EDGE);
75
+ if (fitting.length) {
76
+ return fitting.reduce((a, b) => (area(b) > area(a) ? b : a));
77
+ }
78
+ return sizes.reduce((a, b) => (area(b) < area(a) ? b : a));
79
+ }
44
80
  const INTERNAL_OPTION_KEYS = new Set([
45
81
  'chatId',
46
82
  'user',
@@ -697,6 +733,37 @@ class Telegram extends adapter_core_1.Adapter {
697
733
  setStateSafe(id, value) {
698
734
  this.setState(id, value).catch(e => this.log.error(`Cannot set state "${id}": ${e}`));
699
735
  }
736
+ /**
737
+ * Publish the last received file: its path on this host (`communicate.pathFile`) and its `iobdisk://` URL
738
+ * (`communicate.pathFileUrl`), which an instance on another host can read with `readDiskFile(url)`.
739
+ *
740
+ * @param res the result of storeFile
741
+ */
742
+ setReceivedFile(res) {
743
+ this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
744
+ this.setStateSafe('communicate.pathFileUrl', { val: res.url || '', ack: true });
745
+ }
746
+ /**
747
+ * The `iobdisk://` URL of a file in the data directory of this instance, e.g.
748
+ * `iobdisk://pi4/telegram.0/video/2026-11-04_10-00-00.mp4`
749
+ *
750
+ * @param fileLocation absolute path of the file
751
+ * @returns the URL, or an empty string if js-controller is older than 8.0
752
+ */
753
+ getReceivedFileUrl(fileLocation) {
754
+ // js-controller 8.0 and newer
755
+ const getDiskFileUrl = this.getDiskFileUrl;
756
+ if (typeof getDiskFileUrl !== 'function') {
757
+ return '';
758
+ }
759
+ try {
760
+ return getDiskFileUrl.call(this, fileLocation);
761
+ }
762
+ catch (e) {
763
+ this.log.debug(`Cannot build the URL of ${fileLocation}: ${e.message}`);
764
+ return '';
765
+ }
766
+ }
700
767
  connectionState(connected, logSuccess) {
701
768
  let errorCounter = 0;
702
769
  // Note: Do NOT reset pollingConflictCount here. connectionState() is called after getMe() succeeds,
@@ -1572,7 +1639,7 @@ class Telegram extends adapter_core_1.Adapter {
1572
1639
  return Promise.all(tPromiseList).catch(e => e);
1573
1640
  }
1574
1641
  saveFile(fileID, fileName, callback) {
1575
- this.downloadFile(fileID)
1642
+ this.downloadFileOnce(fileID)
1576
1643
  .then(content => this.storeFile(fileName, content, callback))
1577
1644
  .catch(err => callback({ error: `Error: ${err}` }));
1578
1645
  }
@@ -1595,8 +1662,49 @@ class Telegram extends adapter_core_1.Adapter {
1595
1662
  }
1596
1663
  return Buffer.from(await response.arrayBuffer());
1597
1664
  }
1665
+ /** Downloads of the last minute by file id: a photo or video that is saved and forwarded is downloaded once. */
1666
+ downloads = new Map();
1667
+ /**
1668
+ * {@link downloadFile}, but a second call for the same file within a minute gets the same download.
1669
+ *
1670
+ * @param fileID the Telegram file id
1671
+ */
1672
+ downloadFileOnce(fileID) {
1673
+ let download = this.downloads.get(fileID);
1674
+ if (!download) {
1675
+ download = this.downloadFile(fileID);
1676
+ this.downloads.set(fileID, download);
1677
+ download.then(() => this.setTimeout(() => this.downloads.delete(fileID), 60_000), () => this.downloads.delete(fileID));
1678
+ }
1679
+ return download;
1680
+ }
1598
1681
  /** Set once an assistant instance answered a voice message as an empty question (too old for audio). */
1599
1682
  assistantVoiceWarned = false;
1683
+ /** Set once an assistant instance answered pictures as an empty question (too old for pictures). */
1684
+ assistantMediaWarned = false;
1685
+ /** Albums waiting for their last photo or video, by `media_group_id`. */
1686
+ assistantAlbums = new Map();
1687
+ /** How long the assistant may take for an answer (a field so that tests can shorten it). */
1688
+ assistantTimeoutMs = ASSISTANT_TIMEOUT_MS;
1689
+ /**
1690
+ * Tell the user that the assistant did not answer, instead of leaving the question unanswered.
1691
+ *
1692
+ * @param msg the message that was forwarded
1693
+ * @param error why: a timeout gets a message in the chat, anything else only a log entry
1694
+ */
1695
+ async assistantFailed(msg, error) {
1696
+ if (!(error instanceof SendToTimeoutError)) {
1697
+ this.log.error(`Cannot send message to ${this.config.assistantInstance}: ${error instanceof Error ? error.message : String(error)}`);
1698
+ return;
1699
+ }
1700
+ this.log.warn(error.message);
1701
+ const options = msg.is_topic_message ? { message_thread_id: msg.message_thread_id } : undefined;
1702
+ await this.bot.api.sendMessage({
1703
+ ...options,
1704
+ chat_id: msg.chat.id,
1705
+ text: adapter_core_1.I18n.translate('The assistant did not answer in time.'),
1706
+ }).catch(err => this.log.error(`send Message Error: ${err}`));
1707
+ }
1600
1708
  /**
1601
1709
  * Forward a voice message to the ioBroker.assistant instance: it recognises the speech, answers like a text
1602
1710
  * question (same `source`, so the conversation continues) and returns what it heard. The same user check as for
@@ -1630,16 +1738,22 @@ class Telegram extends adapter_core_1.Adapter {
1630
1738
  // recognition + answer take a few seconds: show that something is happening
1631
1739
  bot.api.sendChatAction({ ...options, chat_id: msg.chat.id, action: 'typing' }).catch(() => { });
1632
1740
  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
- }));
1741
+ let response;
1742
+ try {
1743
+ response = (await this.sendToIfAlive(this.config.assistantInstance, 'ask', {
1744
+ text: '',
1745
+ audio: content.toString('base64'),
1746
+ format: 'ogg',
1747
+ source: `telegram:${user}`,
1748
+ user,
1749
+ chatId: msg.chat.id,
1750
+ userId: from.id.toString(),
1751
+ messageThreadId: msg.is_topic_message ? msg.message_thread_id : 0,
1752
+ }, this.assistantTimeoutMs));
1753
+ }
1754
+ catch (error) {
1755
+ return this.assistantFailed(msg, error);
1756
+ }
1643
1757
  if (!response) {
1644
1758
  return;
1645
1759
  }
@@ -1662,6 +1776,240 @@ class Telegram extends adapter_core_1.Adapter {
1662
1776
  .sendMessage({ ...options, chat_id: msg.chat.id, text })
1663
1777
  .catch(error => this.log.error(`send Message Error: ${error}`));
1664
1778
  }
1779
+ /**
1780
+ * Whether the photos and videos of this message go to the assistant. Its caption then goes along with them and not
1781
+ * a second time through the text pipeline.
1782
+ *
1783
+ * @param msg the received message
1784
+ */
1785
+ forwardsMediaToAssistant(msg) {
1786
+ return !!(this.config.assistantInstance &&
1787
+ this.config.assistantMedia !== false &&
1788
+ msg.from &&
1789
+ (msg.photo?.length || msg.video || msg.video_note));
1790
+ }
1791
+ /**
1792
+ * Forward a photo or video message to the assistant. The parts of an album are collected first and go as one
1793
+ * question - otherwise ten photos would get ten answers.
1794
+ *
1795
+ * @param msg the received message
1796
+ */
1797
+ queueAssistantMedia(msg) {
1798
+ const group = msg.media_group_id;
1799
+ const forward = (msgs) => {
1800
+ this.askAssistantWithMedia(msgs).catch(err => this.log.error(`Cannot send media to ${this.config.assistantInstance}: ${err}`));
1801
+ };
1802
+ if (!group) {
1803
+ forward([msg]);
1804
+ return;
1805
+ }
1806
+ const album = this.assistantAlbums.get(group) || { msgs: [] };
1807
+ album.msgs.push(msg);
1808
+ if (album.timer) {
1809
+ this.clearTimeout(album.timer);
1810
+ }
1811
+ album.timer = this.setTimeout(() => {
1812
+ this.assistantAlbums.delete(group);
1813
+ forward(album.msgs);
1814
+ }, ALBUM_WAIT_MS);
1815
+ this.assistantAlbums.set(group, album);
1816
+ }
1817
+ /**
1818
+ * Forward photos and a video to the ioBroker.assistant instance. The photos go along as base64 (one size each, see
1819
+ * {@link assistantPhotoSize}); a video never does: it is stored by
1820
+ * {@link storeVideoForAssistant} and only its place goes along.
1821
+ * The caption is the question. The same user check as for text messages applies.
1822
+ *
1823
+ * @param msgs the message, or all messages of an album
1824
+ */
1825
+ async askAssistantWithMedia(msgs) {
1826
+ const bot = this.bot;
1827
+ const msg = msgs[0];
1828
+ const from = msg.from;
1829
+ const user = !this.config.useUsername ? from.first_name : !from.username ? from.first_name : from.username;
1830
+ // only one message of an album has the caption
1831
+ const caption = (msgs.find(m => m.caption)?.caption || '').trim();
1832
+ const pollingInterval = parseInt(String(this.config.pollingInterval ?? 0), 10) || 0;
1833
+ if (Date.now() - msg.date * 1000 > pollingInterval + 30000) {
1834
+ this.log.warn(`Photo/video from ${from.first_name} ignored, because too old`);
1835
+ return;
1836
+ }
1837
+ if ((this.config.password || this.config.doNotAcceptNewUsers) && !this.storedUsers[from.id]) {
1838
+ // a caption went through the text pipeline, which has told the user already
1839
+ if (!caption) {
1840
+ await bot.api
1841
+ .sendMessage({
1842
+ chat_id: from.id,
1843
+ text: adapter_core_1.I18n.translate(this.config.doNotAcceptNewUsers
1844
+ ? 'User is not in the list'
1845
+ : 'Please enter password in form "/password phrase"'),
1846
+ })
1847
+ .catch(error => this.log.error(`send Message Error: ${error}`));
1848
+ }
1849
+ return;
1850
+ }
1851
+ const options = msg.is_topic_message ? { message_thread_id: msg.message_thread_id } : undefined;
1852
+ bot.api.sendChatAction({ ...options, chat_id: msg.chat.id, action: 'typing' }).catch(() => { });
1853
+ const photos = msgs.filter(m => m.photo?.length);
1854
+ if (photos.length > ASSISTANT_MAX_IMAGES) {
1855
+ this.log.info(`Album with ${photos.length} photos: only the first ${ASSISTANT_MAX_IMAGES} go to ${this.config.assistantInstance}`);
1856
+ }
1857
+ let images;
1858
+ try {
1859
+ images = await Promise.all(photos.slice(0, ASSISTANT_MAX_IMAGES).map(async (m) => ({
1860
+ data: (await this.downloadFileOnce(assistantPhotoSize(m.photo).file_id)).toString('base64'),
1861
+ // Telegram sends every photo as JPEG
1862
+ mimeType: 'image/jpeg',
1863
+ })));
1864
+ }
1865
+ catch (error) {
1866
+ this.log.warn(`Cannot download the photo for ${this.config.assistantInstance}: ${error}`);
1867
+ return;
1868
+ }
1869
+ const videoMsg = msgs.find(m => m.video || m.video_note);
1870
+ const video = videoMsg ? await this.storeVideoForAssistant(videoMsg) : undefined;
1871
+ if (!images.length && !video) {
1872
+ return;
1873
+ }
1874
+ this.log.debug(`Forward ${images.length} photo(s)${video ? ` and a video (${video.url || video.path || video.error})` : ''} from ${user} to ${this.config.assistantInstance}`);
1875
+ let response;
1876
+ try {
1877
+ response = (await this.sendToIfAlive(this.config.assistantInstance, 'ask', {
1878
+ text: caption,
1879
+ ...(images.length ? { images } : {}),
1880
+ ...(video ? { video } : {}),
1881
+ source: `telegram:${user}`,
1882
+ user,
1883
+ chatId: msg.chat.id,
1884
+ userId: from.id.toString(),
1885
+ messageThreadId: msg.is_topic_message ? msg.message_thread_id : 0,
1886
+ }, this.assistantTimeoutMs));
1887
+ }
1888
+ catch (error) {
1889
+ return this.assistantFailed(msg, error);
1890
+ }
1891
+ if (!response) {
1892
+ return;
1893
+ }
1894
+ // an assistant that does not know pictures sees no text and rejects the request as an empty question
1895
+ if (response.error === 'empty question') {
1896
+ if (!this.assistantMediaWarned) {
1897
+ this.assistantMediaWarned = true;
1898
+ this.log.warn(`${this.config.assistantInstance} cannot look at pictures - update ioBroker.assistant to the latest version`);
1899
+ }
1900
+ return;
1901
+ }
1902
+ const answer = response.answer || response.error;
1903
+ if (!answer) {
1904
+ return;
1905
+ }
1906
+ this.log.debug(`Assistant response: ${answer}`);
1907
+ await bot.api
1908
+ .sendMessage({ ...options, chat_id: msg.chat.id, text: answer })
1909
+ .catch(error => this.log.error(`send Message Error: ${error}`));
1910
+ }
1911
+ /**
1912
+ * Store a video for the assistant - it may run on another host, and a video does not go through the message bus.
1913
+ * With js-controller 8.0+ the video is written to the folder `assistant` in the data directory of this instance and
1914
+ * goes along as `iobdisk://` URL, which the assistant reads from any host with `readDiskFile(url)`. With an older
1915
+ * js-controller it goes to the ioBroker file storage of this instance as `{ adapter, path }`. Keeps the newest
1916
+ * {@link ASSISTANT_VIDEOS_KEPT}.
1917
+ *
1918
+ * @param msg the message with the video or video note
1919
+ * @returns where it is, or why it is not there
1920
+ */
1921
+ async storeVideoForAssistant(msg) {
1922
+ const file = (msg.video || msg.video_note);
1923
+ const mimeType = msg.video?.mime_type || 'video/mp4';
1924
+ const info = { mimeType, durationSec: file.duration, size: file.file_size };
1925
+ if (file.file_size && file.file_size > TELEGRAM_DOWNLOAD_LIMIT) {
1926
+ return {
1927
+ ...info,
1928
+ error: `too big to download (${Math.round(file.file_size / 1024 / 1024)} MB, Telegram allows bots 20 MB)`,
1929
+ };
1930
+ }
1931
+ try {
1932
+ const content = await this.downloadFileOnce(file.file_id);
1933
+ const date = new Date().toISOString().replace(/T/, '_').replace(/\..+/, '').replace(/:/g, '-');
1934
+ const ext = mimeType === 'video/quicktime' ? 'mov' : (mimeType.split('/')[1] || 'mp4').replace(/\W/g, '');
1935
+ const name = `video_${date}_${msg.message_id}.${ext}`;
1936
+ const url = await this.storeAssistantVideoOnDisk(name, content);
1937
+ if (url) {
1938
+ void this.pruneAssistantVideos();
1939
+ return { ...info, url, size: content.length };
1940
+ }
1941
+ const path = `assistant/${name}`;
1942
+ await this.writeFileAsync(this.namespace, path, content);
1943
+ void this.pruneAssistantVideos();
1944
+ return { ...info, adapter: this.namespace, path, size: content.length };
1945
+ }
1946
+ catch (error) {
1947
+ this.log.warn(`Cannot store the video for ${this.config.assistantInstance}: ${error}`);
1948
+ return { ...info, error: `could not be stored: ${error instanceof Error ? error.message : String(error)}` };
1949
+ }
1950
+ }
1951
+ /**
1952
+ * Write a video for the assistant to the folder `assistant` in the data directory of this instance.
1953
+ *
1954
+ * @param name the file name
1955
+ * @param content the video
1956
+ * @returns its `iobdisk://` URL, or an empty string if js-controller is older than 8.0 or writing failed
1957
+ */
1958
+ async storeAssistantVideoOnDisk(name, content) {
1959
+ // js-controller 8.0 and newer
1960
+ if (!this.tmpDirName ||
1961
+ typeof this.getDiskFileUrl !== 'function') {
1962
+ return '';
1963
+ }
1964
+ const fileLocation = (0, node_path_1.join)(this.tmpDirName, 'assistant', name);
1965
+ try {
1966
+ await (0, promises_1.mkdir)((0, node_path_1.join)(this.tmpDirName, 'assistant'), { recursive: true });
1967
+ await (0, promises_1.writeFile)(fileLocation, content);
1968
+ }
1969
+ catch (error) {
1970
+ this.log.debug(`Cannot write the video to ${fileLocation}, it goes to the file storage: ${error}`);
1971
+ return '';
1972
+ }
1973
+ const url = this.getReceivedFileUrl(fileLocation);
1974
+ if (!url) {
1975
+ await (0, promises_1.unlink)(fileLocation).catch(() => { });
1976
+ }
1977
+ return url;
1978
+ }
1979
+ /**
1980
+ * Delete all but the newest {@link ASSISTANT_VIDEOS_KEPT} videos for the assistant, in the data directory and in the
1981
+ * file storage (where they were before js-controller 8.0).
1982
+ */
1983
+ async pruneAssistantVideos() {
1984
+ // the names start with the date, so the order of the names is the order of time
1985
+ const tooOld = (names) => {
1986
+ const videos = names.filter(name => name.startsWith('video_')).sort();
1987
+ return videos.slice(0, Math.max(0, videos.length - ASSISTANT_VIDEOS_KEPT));
1988
+ };
1989
+ if (this.tmpDirName) {
1990
+ const dir = (0, node_path_1.join)(this.tmpDirName, 'assistant');
1991
+ try {
1992
+ const entries = await (0, promises_1.readdir)(dir, { withFileTypes: true });
1993
+ for (const name of tooOld(entries.filter(e => e.isFile()).map(e => e.name))) {
1994
+ await (0, promises_1.unlink)((0, node_path_1.join)(dir, name));
1995
+ }
1996
+ }
1997
+ catch (error) {
1998
+ if (error.code !== 'ENOENT') {
1999
+ this.log.debug(`Cannot delete old videos of the assistant in ${dir}: ${error}`);
2000
+ }
2001
+ }
2002
+ }
2003
+ try {
2004
+ const files = await this.readDirAsync(this.namespace, 'assistant');
2005
+ for (const file of tooOld(files.filter(f => !f.isDir).map(f => f.file))) {
2006
+ await this.delFileAsync(this.namespace, `assistant/${file}`);
2007
+ }
2008
+ }
2009
+ catch (error) {
2010
+ this.log.debug(`Cannot delete old videos of the assistant: ${error}`);
2011
+ }
2012
+ }
1665
2013
  /**
1666
2014
  * Store a downloaded file where `saveFilesTo` says (file system or ioBroker file storage).
1667
2015
  *
@@ -1678,6 +2026,7 @@ class Telegram extends adapter_core_1.Adapter {
1678
2026
  info: `media file has been saved to "${this.config.saveFilesTo}": ${fileLocation}`,
1679
2027
  location: this.config.saveFilesTo,
1680
2028
  path: fileLocation,
2029
+ url: this.getReceivedFileUrl(fileLocation),
1681
2030
  });
1682
2031
  }
1683
2032
  else if (this.config.saveFilesTo == 'iobroker') {
@@ -1736,6 +2085,10 @@ class Telegram extends adapter_core_1.Adapter {
1736
2085
  ack: true,
1737
2086
  });
1738
2087
  }
2088
+ // Photos and videos (with their caption) to the assistant; saved below as before
2089
+ if (this.forwardsMediaToAssistant(msg)) {
2090
+ this.queueAssistantMedia(msg);
2091
+ }
1739
2092
  if (msg.voice) {
1740
2093
  // Downloaded once: stored as before (communicate.pathFile) and, with an assistant instance, recognised
1741
2094
  // and answered there. A voice message with a caption is answered by its caption (text pipeline) instead.
@@ -1746,7 +2099,7 @@ class Telegram extends adapter_core_1.Adapter {
1746
2099
  download
1747
2100
  .then(content => this.storeFile(this.config.saveFiles ? `/voice/${date}.ogg` : '/voice/temp.ogg', content, res => {
1748
2101
  this.log.info(res.info);
1749
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2102
+ this.setReceivedFile(res);
1750
2103
  }))
1751
2104
  .catch(err => this.log.debug(`Error saving voice file: ${err}`));
1752
2105
  }
@@ -1801,7 +2154,7 @@ class Telegram extends adapter_core_1.Adapter {
1801
2154
  this.saveFile(item.file_id, fileName, res => {
1802
2155
  if (!res.error) {
1803
2156
  this.log.info(res.info);
1804
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2157
+ this.setReceivedFile(res);
1805
2158
  }
1806
2159
  else {
1807
2160
  this.log.debug(res.error);
@@ -1818,7 +2171,7 @@ class Telegram extends adapter_core_1.Adapter {
1818
2171
  this.saveFile(msg.video.file_id, `/video/${date}.mp4`, res => {
1819
2172
  if (!res.error) {
1820
2173
  this.log.info(res.info);
1821
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2174
+ this.setReceivedFile(res);
1822
2175
  }
1823
2176
  else {
1824
2177
  this.log.debug(res.error);
@@ -1834,7 +2187,7 @@ class Telegram extends adapter_core_1.Adapter {
1834
2187
  this.saveFile(msg.video_note.file_id, `/video/${date}.mp4`, res => {
1835
2188
  if (!res.error) {
1836
2189
  this.log.info(res.info);
1837
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2190
+ this.setReceivedFile(res);
1838
2191
  }
1839
2192
  else {
1840
2193
  this.log.debug(res.error);
@@ -1850,7 +2203,7 @@ class Telegram extends adapter_core_1.Adapter {
1850
2203
  this.saveFile(msg.audio.file_id, `/audio/${date}.mp3`, res => {
1851
2204
  if (!res.error) {
1852
2205
  this.log.info(res.info);
1853
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2206
+ this.setReceivedFile(res);
1854
2207
  }
1855
2208
  else {
1856
2209
  this.log.debug(res.error);
@@ -1866,7 +2219,7 @@ class Telegram extends adapter_core_1.Adapter {
1866
2219
  this.saveFile(msg.document.file_id, `/document/${msg.document.file_name}`, res => {
1867
2220
  if (!res.error) {
1868
2221
  this.log.info(res.info);
1869
- this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
2222
+ this.setReceivedFile(res);
1870
2223
  }
1871
2224
  else {
1872
2225
  this.log.debug(res.error);
@@ -2286,7 +2639,15 @@ class Telegram extends adapter_core_1.Adapter {
2286
2639
  * @param command the `sendTo` command
2287
2640
  * @param message the payload to forward
2288
2641
  */
2289
- async sendToIfAlive(instance, command, message) {
2642
+ /**
2643
+ * `sendTo` an instance that is running; a stopped one is only logged.
2644
+ *
2645
+ * @param instance the instance, short (`assistant.0`) or long (`system.adapter.assistant.0`)
2646
+ * @param command the command
2647
+ * @param message the message
2648
+ * @param timeoutMs if set, rejects with a `SendToTimeoutError` when there is no answer by then
2649
+ */
2650
+ async sendToIfAlive(instance, command, message, timeoutMs) {
2290
2651
  // depending on the admin version the configured instance is stored as `text2command.0` or as
2291
2652
  // `system.adapter.text2command.0`, so normalize it to the short form
2292
2653
  const instanceId = instance.startsWith('system.adapter.')
@@ -2303,7 +2664,24 @@ class Telegram extends adapter_core_1.Adapter {
2303
2664
  this.log.warn(`Cannot check if "${instanceId}" is alive: ${err instanceof Error ? err.message : err}`);
2304
2665
  return;
2305
2666
  }
2306
- return await this.sendToAsync(instanceId, command, message);
2667
+ if (!timeoutMs) {
2668
+ return await this.sendToAsync(instanceId, command, message);
2669
+ }
2670
+ let timer;
2671
+ try {
2672
+ return await Promise.race([
2673
+ // The controller gets a timeout too, a bit later, only so that it forgets the callback.
2674
+ this.sendToAsync(instanceId, command, message, { timeout: timeoutMs + 5000 }),
2675
+ new Promise((_, reject) => {
2676
+ timer = this.setTimeout(() => reject(new SendToTimeoutError(`${instanceId} did not answer "${command}" within ${Math.round(timeoutMs / 1000)} s`)), timeoutMs);
2677
+ }),
2678
+ ]);
2679
+ }
2680
+ finally {
2681
+ if (timer) {
2682
+ this.clearTimeout(timer);
2683
+ }
2684
+ }
2307
2685
  }
2308
2686
  async processTelegramText(msg) {
2309
2687
  this.connectionState(true);
@@ -2620,8 +2998,8 @@ class Telegram extends adapter_core_1.Adapter {
2620
2998
  }
2621
2999
  // Forward messages that no internal rule/command matched to the ioBroker.assistant instance and
2622
3000
  // 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) {
3001
+ // goes back to the right chat/thread. The caption of a photo or video goes there with the media instead.
3002
+ if (this.config.assistantInstance && !this.forwardsMediaToAssistant(msg)) {
2625
3003
  this.sendToIfAlive(this.config.assistantInstance, 'ask', {
2626
3004
  text: msgText,
2627
3005
  source: `telegram:${user}`,
@@ -2629,7 +3007,7 @@ class Telegram extends adapter_core_1.Adapter {
2629
3007
  chatId: msg.chat.id,
2630
3008
  userId: from.id.toString(),
2631
3009
  messageThreadId: msg.is_topic_message ? msg.message_thread_id : 0,
2632
- })
3010
+ }, this.assistantTimeoutMs)
2633
3011
  // @ts-expect-error types fixed in js-controller
2634
3012
  .then((response) => {
2635
3013
  const text = response && (response.answer || response.error);
@@ -2641,7 +3019,7 @@ class Telegram extends adapter_core_1.Adapter {
2641
3019
  .catch(error => this.log.error(`send Message Error: ${error}`));
2642
3020
  }
2643
3021
  })
2644
- .catch(err => this.log.error(`Cannot send message to ${this.config.assistantInstance}: ${err}`));
3022
+ .catch(err => this.assistantFailed(msg, err));
2645
3023
  }
2646
3024
  this.setStateSafe('communicate.requestChatId', { val: msg.chat.id, ack: true });
2647
3025
  this.setStateSafe('communicate.requestMessageId', { val: msg.message_id, ack: true });
@@ -3078,6 +3456,7 @@ class Telegram extends adapter_core_1.Adapter {
3078
3456
  await this.setState('communicate.responseSilentJson', { val: '', ack: true });
3079
3457
  await this.setState('communicate.requestResponse', { val: '', ack: true });
3080
3458
  await this.setState('communicate.pathFile', { val: '', ack: true });
3459
+ await this.setState('communicate.pathFileUrl', { val: '', ack: true });
3081
3460
  this.config.password ||= '';
3082
3461
  this.config.keyboard ||= '/cmds';
3083
3462
  await this.updateUsers();