iobroker.telegram 4.1.0 → 5.0.2

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 (127) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +39 -6
  3. package/admin/blockly.js +9 -1
  4. package/admin/custom/assets/Components-BPb4U2ux.js +1 -0
  5. package/admin/custom/assets/TelegramComponent-B2NWSbGI.js +1 -0
  6. package/admin/custom/assets/_virtual_mf-localSharedImportMap___mfe_internal__ConfigCustomTelegramSet__mf_owner__1-C5FjfPSF.js +1 -0
  7. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__1__loadShare___mf_0_emotion_mf_1_react__loadShare__.js-ffNJqDHH.js +1 -0
  8. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__1__loadShare___mf_0_emotion_mf_1_styled__loadShare__.js-DljvyjSM.js +1 -0
  9. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BPr09WB7.js +1243 -0
  10. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_json_mf_2_config__loadShare__.js-7tOzTXDd.js +1494 -0
  11. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomTelegramSet__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-DTpb_EpK.js +9 -0
  12. package/admin/custom/assets/hostInit-CA0CeAYu.js +1 -0
  13. package/admin/custom/assets/index-mc307YJJ.js +1 -0
  14. package/admin/custom/assets/lib-DrMMUYBG.js +3 -0
  15. package/admin/custom/assets/mf-entry-bootstrap-0-7aced7b2.js +36 -0
  16. package/admin/custom/assets/rolldown-runtime-C0FnF6B9.js +1 -0
  17. package/admin/custom/assets/virtualExposes-B2RF6pfj.js +1 -0
  18. package/admin/custom/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__ConfigCustomTelegramSet__customComponents_js-Bvox5IIB.js +1 -0
  19. package/admin/custom/assets/virtual_mf-exposes-ssr___mfe_internal__ConfigCustomTelegramSet__customComponents_js-EnDnmCdS.js +2 -0
  20. package/admin/custom/assets/virtual_mf-exposes___mfe_internal__ConfigCustomTelegramSet__customComponents_js-CVmxheYM.js +2 -0
  21. package/admin/custom/assets/vite-preload-helper-B7qeedMF.js +1 -0
  22. package/admin/custom/customComponents.js +1 -2
  23. package/admin/i18n/{de/translations.json → de.json} +25 -13
  24. package/admin/i18n/{en/translations.json → en.json} +24 -12
  25. package/admin/i18n/{es/translations.json → es.json} +34 -22
  26. package/admin/i18n/{fr/translations.json → fr.json} +24 -12
  27. package/admin/i18n/{it/translations.json → it.json} +24 -12
  28. package/admin/i18n/{nl/translations.json → nl.json} +24 -12
  29. package/admin/i18n/{pl/translations.json → pl.json} +24 -12
  30. package/admin/i18n/{pt/translations.json → pt.json} +24 -12
  31. package/admin/i18n/{ru/translations.json → ru.json} +24 -12
  32. package/admin/i18n/{uk/translations.json → uk.json} +23 -11
  33. package/admin/i18n/{zh-cn/translations.json → zh-cn.json} +24 -12
  34. package/admin/jsonConfig.json +359 -344
  35. package/admin/rules/@mf-types/ActionTelegram.d.ts +2 -0
  36. package/admin/rules/@mf-types/compiled-types/ActionTelegram.d.ts +30 -0
  37. package/admin/rules/@mf-types.d.ts +3 -0
  38. package/admin/rules/@mf-types.zip +0 -0
  39. package/admin/rules/assets/ActionTelegram-DT4ZdmnH.js +5 -0
  40. package/admin/rules/assets/_virtual_mf-localSharedImportMap___mfe_internal__ActionTelegram__mf_owner__1-BlWjokQ7.js +1 -0
  41. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BMRgH2Bz.js +1213 -0
  42. package/admin/rules/assets/_virtual_mf___mfe_internal__ActionTelegram__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-CL8n1_X7.js +9 -0
  43. package/admin/rules/assets/bootstrap-DkRK1rmm.js +1 -0
  44. package/admin/rules/assets/dist-PnYvbzKY.js +4 -0
  45. package/admin/rules/assets/hostInit-CZrk7GFX.js +1 -0
  46. package/admin/rules/assets/index-CSUxJu3H.js +2 -0
  47. package/admin/rules/assets/mf-entry-bootstrap-0-e99f43b5.js +36 -0
  48. package/admin/rules/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  49. package/admin/rules/assets/virtualExposes-oJO8jZih.js +1 -0
  50. package/admin/rules/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__ActionTelegram__customRuleBlocks_js-CbJMsNQ0.js +1 -0
  51. package/admin/rules/assets/virtual_mf-exposes-ssr___mfe_internal__ActionTelegram__customRuleBlocks_js-CbR3ExBo.js +2 -0
  52. package/admin/rules/assets/virtual_mf-exposes___mfe_internal__ActionTelegram__customRuleBlocks_js-BEjoGfOy.js +2 -0
  53. package/admin/rules/assets/vite-preload-helper-B7qeedMF.js +1 -0
  54. package/admin/rules/customRuleBlocks.js +1 -2
  55. package/admin/rules/customRuleBlocks.ssr.js +1 -0
  56. package/admin/rules/index.html +2 -6
  57. package/admin/rules/mf-manifest.json +1 -1
  58. package/admin/rules/mf-stats.json +1 -0
  59. package/build/iobUri.d.ts +38 -0
  60. package/build/iobUri.js +131 -0
  61. package/build/iobUri.js.map +1 -0
  62. package/build/main.d.ts +1 -0
  63. package/build/main.js +2713 -0
  64. package/build/main.js.map +1 -0
  65. package/build/types.d.ts +214 -0
  66. package/build/types.js +4 -0
  67. package/build/types.js.map +1 -0
  68. package/i18n/de.json +23 -0
  69. package/i18n/en.json +23 -0
  70. package/i18n/es.json +23 -0
  71. package/i18n/fr.json +23 -0
  72. package/i18n/it.json +23 -0
  73. package/i18n/nl.json +23 -0
  74. package/i18n/pl.json +23 -0
  75. package/i18n/pt.json +23 -0
  76. package/i18n/ru.json +23 -0
  77. package/i18n/uk.json +23 -0
  78. package/i18n/zh-cn.json +23 -0
  79. package/io-package.json +75 -33
  80. package/package.json +33 -53
  81. package/admin/custom/assets/Components-D2wD0zbe.js +0 -1
  82. package/admin/custom/assets/ConfigCustomTelegramSet__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__-Ci6Xy-GH.js +0 -1
  83. package/admin/custom/assets/ConfigCustomTelegramSet__loadShare___mf_0_mui_mf_1_icons_mf_2_material__loadShare__-DsvMV1W3.js +0 -1
  84. package/admin/custom/assets/ConfigCustomTelegramSet__loadShare__react__loadShare__-xs2vjw5Y.js +0 -1
  85. package/admin/custom/assets/ConfigCustomTelegramSet__mf_v__runtimeInit__mf_v__-J6gnGK7T.js +0 -10
  86. package/admin/custom/assets/DefaultPropsProvider-DmEC3G80.js +0 -1
  87. package/admin/custom/assets/TelegramComponent-DCLCOges.js +0 -1
  88. package/admin/custom/assets/TextField-bqxvaxBf.js +0 -102
  89. package/admin/custom/assets/ThemeProvider-BRixW8Ci.js +0 -29
  90. package/admin/custom/assets/_commonjsHelpers-D6-XlEtG.js +0 -1
  91. package/admin/custom/assets/createSvgIcon-BzWD3ACi.js +0 -7
  92. package/admin/custom/assets/createTheme-CfKVAAx0.js +0 -16
  93. package/admin/custom/assets/defaultTheme-DCM5Nrg_.js +0 -1
  94. package/admin/custom/assets/hostInit-DAQ2zgXM.js +0 -2
  95. package/admin/custom/assets/index-BY-bILJE.js +0 -1397
  96. package/admin/custom/assets/index-BYe_R7Ws.js +0 -8
  97. package/admin/custom/assets/index-BgKfcD1A.js +0 -24
  98. package/admin/custom/assets/index-BpXXtf3y.js +0 -1
  99. package/admin/custom/assets/index-CI-xWTov.js +0 -91
  100. package/admin/custom/assets/index-Co3YA5NW.js +0 -9
  101. package/admin/custom/assets/index-DFNeivSO.js +0 -1
  102. package/admin/custom/assets/index-DS28Nms8.js +0 -1
  103. package/admin/custom/assets/index-Doac_TLQ.js +0 -779
  104. package/admin/custom/assets/index-_YNjWM7c.js +0 -31
  105. package/admin/custom/assets/jsx-runtime-DscBPJdh.js +0 -9
  106. package/admin/custom/assets/preload-helper-C1FmrZbK.js +0 -1
  107. package/admin/custom/assets/useTheme-DhBqOhQ3.js +0 -1
  108. package/admin/custom/assets/useThemeWithoutDefault-BKCaHj9c.js +0 -1
  109. package/admin/custom/assets/virtualExposes-D2gQfgfw.js +0 -2
  110. package/admin/rules/assets/ActionTelegram-DYJUMFCx.js +0 -5
  111. package/admin/rules/assets/ActionTelegram__loadShare__react__loadShare__-Ccaej0ya.js +0 -1
  112. package/admin/rules/assets/ActionTelegram__loadShare__react_mf_2_dom__loadShare__-CgzDrK9W.js +0 -9
  113. package/admin/rules/assets/ActionTelegram__mf_v__runtimeInit__mf_v__-DxlLd_3A.js +0 -10
  114. package/admin/rules/assets/_commonjsHelpers-Cpj98o6Y.js +0 -1
  115. package/admin/rules/assets/bootstrap-DXJ-CBj3.js +0 -1
  116. package/admin/rules/assets/hostInit-CUxlaMpR.js +0 -2
  117. package/admin/rules/assets/index-BrA2IcWW.js +0 -9
  118. package/admin/rules/assets/index-C9A6m5GR.js +0 -1026
  119. package/admin/rules/assets/index-DQiceR5U.js +0 -1
  120. package/admin/rules/assets/index-XCGquB1p.js +0 -2
  121. package/admin/rules/assets/index-hSC67Jtf.js +0 -24
  122. package/admin/rules/assets/preload-helper-C1FmrZbK.js +0 -1
  123. package/admin/rules/assets/virtualExposes-D_O17Ipe.js +0 -2
  124. package/admin/words.js +0 -98
  125. package/lib/adapter-config.d.ts +0 -17
  126. package/lib/words.js +0 -270
  127. package/main.js +0 -2460
package/build/main.js ADDED
@@ -0,0 +1,2713 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const node_fs_1 = require("node:fs");
7
+ const node_path_1 = require("node:path");
8
+ const node_https_1 = require("node:https");
9
+ const axios_1 = __importDefault(require("axios"));
10
+ const node_telegram_bot_api_1 = __importDefault(require("node-telegram-bot-api"));
11
+ const adapter_core_1 = require("@iobroker/adapter-core");
12
+ const webserver_1 = require("@iobroker/webserver");
13
+ const iobUri_1 = require("./iobUri");
14
+ const systemLang2CallMe = {
15
+ en: 'en-GB-Standard-A',
16
+ de: 'de-DE-Standard-A',
17
+ ru: 'ru-RU-Standard-A',
18
+ pt: 'pt-BR-Standard-A',
19
+ nl: 'nl-NL-Standard-A',
20
+ fr: 'fr-FR-Standard-A',
21
+ it: 'it-IT-Standard-A',
22
+ es: 'es-ES-Standard-A',
23
+ pl: 'pl-PL-Standard-A',
24
+ uk: 'uk-UA-Standard-A',
25
+ 'zh-cn': 'en-GB-Standard-A',
26
+ };
27
+ const actions = [
28
+ 'typing',
29
+ 'upload_photo',
30
+ 'upload_video',
31
+ 'record_video',
32
+ 'record_audio',
33
+ 'upload_document',
34
+ 'find_location',
35
+ ];
36
+ class Telegram extends adapter_core_1.Adapter {
37
+ bot;
38
+ storedUsers = {};
39
+ storedChats = {};
40
+ systemLang = 'en';
41
+ reconnectTimer;
42
+ pollConnectionStatus;
43
+ isConnected = null;
44
+ lastMessageTime = 0;
45
+ lastMessageText = '';
46
+ enumsCache = { rooms: {} };
47
+ protection = {};
48
+ gcInterval;
49
+ commands = {};
50
+ callbackQueryId = {};
51
+ mediaGroupExport = {};
52
+ tmpDirName = '';
53
+ questions = [];
54
+ garbageCollectorInterval;
55
+ isServer = false;
56
+ /**
57
+ * In-memory queue of outgoing sends that failed because telegram was unreachable. They are resent (FIFO)
58
+ * as soon as the connection is re-established. See issue #839. The queue is intentionally NOT persisted,
59
+ * so an adapter restart clears it.
60
+ */
61
+ sendQueue = [];
62
+ sendQueueFlushing = false;
63
+ sendQueueRetryTimer;
64
+ static MAX_SEND_QUEUE_LENGTH = 100;
65
+ static SEND_QUEUE_RETRY_MS = 30000;
66
+ static MAX_SEND_QUEUE_AGE_MS = 24 * 60 * 60 * 1000; // 24 h
67
+ static MAX_SEND_ATTEMPTS = 10;
68
+ server = {
69
+ server: null,
70
+ settings: null,
71
+ };
72
+ constructor(options = {}) {
73
+ super({
74
+ ...options,
75
+ name: 'telegram',
76
+ error: (err) => {
77
+ // Identify unhandled errors originating from callbacks in scripts
78
+ // These are not caught by wrapping the execution code in try-catch
79
+ if (err) {
80
+ const errStr = err.toString();
81
+ if (errStr.includes('getaddrinfo') ||
82
+ errStr.includes('api.telegram.org') ||
83
+ errStr.includes('EAI_AGAIN')) {
84
+ return true;
85
+ }
86
+ }
87
+ return false;
88
+ },
89
+ ready: () => this.onReady(),
90
+ message: obj => this.onMessage(obj),
91
+ unload: callback => this.onUnload(callback),
92
+ stateChange: (id, state) => this.onStateChange(id, state),
93
+ objectChange: (id, obj) => this.onObjectChange(id, obj),
94
+ });
95
+ this.server.settings = this.config;
96
+ }
97
+ onMessage(obj) {
98
+ if (obj) {
99
+ if (obj.command === 'adminuser') {
100
+ let adminUserData;
101
+ this.getState('communicate.users', (err, state) => {
102
+ if (err) {
103
+ this.log.error(err.toString());
104
+ }
105
+ if (state?.val) {
106
+ try {
107
+ adminUserData = JSON.parse(state.val);
108
+ this.sendTo(obj.from, obj.command, adminUserData, obj.callback);
109
+ }
110
+ catch (err) {
111
+ this.log.error(err);
112
+ this.log.error('Cannot parse stored user IDs!');
113
+ }
114
+ }
115
+ });
116
+ }
117
+ else if (obj.command === 'delUser') {
118
+ const userID = obj.message;
119
+ let userObj = {};
120
+ this.getState('communicate.users', (err, state) => {
121
+ if (err) {
122
+ this.log.error(err.toString());
123
+ }
124
+ if (state?.val) {
125
+ try {
126
+ userObj = JSON.parse(state.val);
127
+ delete userObj[userID];
128
+ this.setState('communicate.users', JSON.stringify(userObj), true)
129
+ .then(() => {
130
+ this.sendTo(obj.from, obj.command, userID, obj.callback);
131
+ void this.updateUsers();
132
+ this.log.warn(`User ${userID} has been deleted!`);
133
+ })
134
+ .catch(e => this.log.error(`Cannot set state communicate.users: ${e}`));
135
+ }
136
+ catch (err) {
137
+ this.log.error(err);
138
+ this.log.error(`Cannot delete user ${userID}!`);
139
+ }
140
+ }
141
+ });
142
+ }
143
+ else if (obj.command === 'systemMessages') {
144
+ const userID = obj.message.itemId;
145
+ const checked = obj.message.checked;
146
+ let userObj = {};
147
+ this.getState('communicate.users', (err, state) => {
148
+ if (err) {
149
+ this.log.error(err.toString());
150
+ }
151
+ if (state?.val) {
152
+ try {
153
+ userObj = JSON.parse(state.val);
154
+ userObj[userID].sysMessages = checked;
155
+ this.setState('communicate.users', JSON.stringify(userObj), true)
156
+ .then(() => {
157
+ this.sendTo(obj.from, obj.command, userID, obj.callback);
158
+ void this.updateUsers();
159
+ this.log.info(`Receiving of system messages for user "${userID}" has been changed to ${checked}!`);
160
+ })
161
+ .catch(e => this.log.error(`Cannot set state communicate.users: ${e}`));
162
+ }
163
+ catch (err) {
164
+ this.log.error(err);
165
+ this.log.error(`Cannot change user ${userID}!`);
166
+ }
167
+ }
168
+ });
169
+ }
170
+ else if (obj.command === 'delAllUser') {
171
+ try {
172
+ this.setState('communicate.users', '{}', true)
173
+ .then(() => {
174
+ this.sendTo(obj.from, obj.command, true, obj.callback);
175
+ void this.updateUsers();
176
+ this.log.warn('List of saved users has been wiped. Every User has to reauthenticate with the new password!');
177
+ })
178
+ .catch(e => this.log.error(`Cannot set state communicate.users: ${e}`));
179
+ }
180
+ catch (err) {
181
+ this.log.error(err);
182
+ this.log.error('Cannot wipe list of saved users!');
183
+ }
184
+ }
185
+ else if (obj.command === 'sendNotification') {
186
+ this.processNotification(obj).catch(err => this.log.error(err));
187
+ }
188
+ else {
189
+ this.processMessage(obj).catch(err => this.log.error(err));
190
+ }
191
+ }
192
+ }
193
+ async onReady() {
194
+ this.isServer = this.config.server === 'true';
195
+ // i18n JSON files live in `<packageRoot>/i18n`; main.js runs from `<packageRoot>/build`
196
+ await adapter_core_1.I18n.init((0, node_path_1.join)(__dirname, '..'), this);
197
+ this.questions = [];
198
+ this.garbageCollectorInterval = this.setInterval(() => {
199
+ const now = Date.now();
200
+ Object.keys(this.callbackQueryId).forEach(id => {
201
+ if (now - this.callbackQueryId[id].ts > 120000) {
202
+ delete this.callbackQueryId[id];
203
+ }
204
+ });
205
+ }, 10000);
206
+ this.tmpDirName = (0, node_path_1.join)((0, adapter_core_1.getAbsoluteDefaultDataDir)(), this.namespace.replace('.', '_'));
207
+ // Create file system directories for media files
208
+ if (this.config.saveFilesTo == 'filesystem') {
209
+ try {
210
+ if (!(0, node_fs_1.existsSync)(this.tmpDirName)) {
211
+ (0, node_fs_1.mkdirSync)(this.tmpDirName);
212
+ }
213
+ const subDirectories = ['voice'];
214
+ if (this.config.saveFiles) {
215
+ // Create subdirs for other attachment types
216
+ subDirectories.push('photo', 'video', 'audio', 'document');
217
+ }
218
+ for (const subDir of subDirectories) {
219
+ const subDirPath = (0, node_path_1.join)(this.tmpDirName, subDir);
220
+ if (!(0, node_fs_1.existsSync)(subDirPath)) {
221
+ (0, node_fs_1.mkdirSync)(subDirPath);
222
+ }
223
+ }
224
+ }
225
+ catch (err) {
226
+ this.log.error(`Cannot create tmp directory: ${this.tmpDirName}: ${err}`);
227
+ }
228
+ }
229
+ if (this.isServer) {
230
+ this.config.port = parseInt(String(this.config.port), 10);
231
+ // Load certificates
232
+ this.getCertificates(undefined, undefined, undefined, async (err, certificates, leConfig) => {
233
+ this.config.certificates = certificates;
234
+ this.config.leConfig = leConfig;
235
+ this.config.secure = true;
236
+ try {
237
+ const webserver = new webserver_1.WebServer({
238
+ app: (req, res) => this.handleWebHook(req, res),
239
+ adapter: this,
240
+ secure: this.config.secure,
241
+ });
242
+ this.server.server = (await webserver.init());
243
+ }
244
+ catch (err) {
245
+ this.log.error(`Cannot create webserver: ${err}`);
246
+ this.terminate(adapter_core_1.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
247
+ return;
248
+ }
249
+ if (this.server.server) {
250
+ this.server.server.__server = this.server;
251
+ let serverListening = false;
252
+ let serverPort = this.config.port;
253
+ this.server.server.on('error', (e) => {
254
+ if (e.toString().includes('EACCES') && serverPort <= 1024) {
255
+ this.log.error(`node.js process has no rights to start server on the port ${serverPort}.\n` +
256
+ `Do you know that on linux you need special permissions for ports under 1024?\n` +
257
+ `You can call in shell following scrip to allow it for node.js: "iobroker fix"`);
258
+ }
259
+ else {
260
+ this.log.error(`Cannot start server on ${this.config.bind || '0.0.0.0'}:${serverPort}: ${e}`);
261
+ }
262
+ if (!serverListening) {
263
+ this.terminate
264
+ ? this.terminate(adapter_core_1.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION)
265
+ : process.exit(adapter_core_1.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
266
+ }
267
+ });
268
+ this.getPort(this.config.port, !this.config.bind || this.config.bind === '0.0.0.0' ? undefined : this.config.bind || undefined, port => {
269
+ if (parseInt(String(port), 10) !== this.config.port && !this.config.findNextPort) {
270
+ this.log.error(`port ${this.config.port} already in use`);
271
+ this.terminate ? this.terminate() : process.exit(1);
272
+ }
273
+ serverPort = port;
274
+ this.server.server?.listen(port, !this.config.bind || this.config.bind === '0.0.0.0'
275
+ ? undefined
276
+ : this.config.bind || undefined, () => (serverListening = true));
277
+ this.log.info(`https server listening on port ${port}`);
278
+ this.main().catch(e => this.log.error(`Cannot start adapter: ${e}`));
279
+ });
280
+ }
281
+ });
282
+ }
283
+ else {
284
+ this.main().catch(e => this.log.error(`Cannot start adapter: ${e}`));
285
+ }
286
+ }
287
+ onUnload(callback) {
288
+ if (this.reconnectTimer) {
289
+ this.clearInterval(this.reconnectTimer);
290
+ this.reconnectTimer = undefined;
291
+ }
292
+ if (this.gcInterval) {
293
+ this.clearInterval(this.gcInterval);
294
+ this.gcInterval = undefined;
295
+ }
296
+ if (this.pollConnectionStatus) {
297
+ this.clearTimeout(this.pollConnectionStatus);
298
+ this.pollConnectionStatus = undefined;
299
+ }
300
+ if (this.sendQueueRetryTimer) {
301
+ this.clearTimeout(this.sendQueueRetryTimer);
302
+ this.sendQueueRetryTimer = undefined;
303
+ }
304
+ if (this.garbageCollectorInterval) {
305
+ this.clearInterval(this.garbageCollectorInterval);
306
+ this.garbageCollectorInterval = undefined;
307
+ }
308
+ // cancel any pending question answer-timeouts so they cannot fire after unload
309
+ this.questions?.forEach(q => q.timeout && this.clearTimeout(q.timeout));
310
+ this.questions = [];
311
+ if (this.config) {
312
+ if (this.config.restarting !== '') {
313
+ // default text
314
+ if (this.config.restarting === '_' ||
315
+ this.config.restarting === null ||
316
+ this.config.restarting === undefined) {
317
+ this.sendSystemMessage(this.config.rememberUsers
318
+ ? adapter_core_1.I18n.translate('Restarting...')
319
+ : adapter_core_1.I18n.translate('Restarting... Reauthenticate!')).catch(err => this.log.error(err));
320
+ }
321
+ else {
322
+ this.sendSystemMessage(this.config.restarting).catch(err => this.log.error(err));
323
+ }
324
+ }
325
+ try {
326
+ if (this.server.server) {
327
+ this.server.server.close();
328
+ }
329
+ }
330
+ catch (e) {
331
+ console.error(`Cannot close server: ${e}`);
332
+ }
333
+ }
334
+ if (this.isConnected && this.setState) {
335
+ this.setState('info.connection', false, true).catch(e => this.log.error(`Cannot set state: ${e}`));
336
+ }
337
+ this.isConnected = false;
338
+ callback();
339
+ }
340
+ // This handler is called if a subscribed state changes
341
+ async onStateChange(id, state) {
342
+ if (state) {
343
+ if (!state.ack) {
344
+ if (id.endsWith('communicate.response')) {
345
+ if (typeof state.val === 'object') {
346
+ this.log.error(`communicate.response only supports passing a message to send as string. You provided ${JSON.stringify(state.val)}. Please use "communicate.responseJson" instead with a stringified JSON object!`);
347
+ return;
348
+ }
349
+ // Send to someone this message
350
+ await this.sendMessage(state.val);
351
+ await this.setState('communicate.response', { val: state.val, ack: true });
352
+ }
353
+ else if (id.endsWith('communicate.responseSilent')) {
354
+ if (typeof state.val === 'object') {
355
+ this.log.error(`communicate.responseSilent only supports passing a message to send as string. You provided ${JSON.stringify(state.val)}. Please use "communicate.responseSilentJson" instead with a stringified JSON object!`);
356
+ return;
357
+ }
358
+ // Send to someone this message
359
+ await this.sendMessage(state.val, null, null, { disable_notification: true });
360
+ await this.setState('communicate.responseSilent', { val: state.val, ack: true });
361
+ }
362
+ else if (id.endsWith('communicate.responseJson')) {
363
+ try {
364
+ const val = JSON.parse(state.val);
365
+ let options;
366
+ let text;
367
+ let chatId;
368
+ let user;
369
+ if (val && typeof val === 'object' && val.text !== undefined && typeof val.text === 'string') {
370
+ options = val;
371
+ text = options.text;
372
+ if (options.chatId) {
373
+ chatId = options.chatId;
374
+ }
375
+ if (options.user) {
376
+ user = options.user;
377
+ }
378
+ }
379
+ else {
380
+ text = val;
381
+ }
382
+ if (text) {
383
+ // Send to someone this message
384
+ await this.sendMessage(text, user, chatId, options);
385
+ }
386
+ else {
387
+ this.log.warn(`Invalid message: no text found: ${JSON.stringify(state.val)}`);
388
+ }
389
+ await this.setState('communicate.responseJson', { val: state.val, ack: true });
390
+ }
391
+ catch (err) {
392
+ this.log.error(`could not parse Json in communicate.responseJon state: ${err instanceof Error ? err.message : err}`);
393
+ }
394
+ }
395
+ else if (id.endsWith('communicate.responseSilentJson')) {
396
+ try {
397
+ const val = JSON.parse(state.val);
398
+ let options;
399
+ let text;
400
+ let chatId;
401
+ let user;
402
+ if (val && typeof val === 'object' && val.text !== undefined && typeof val.text === 'string') {
403
+ options = val;
404
+ text = options.text;
405
+ if (options.chatId) {
406
+ chatId = options.chatId;
407
+ }
408
+ if (options.user) {
409
+ user = options.user;
410
+ }
411
+ }
412
+ else {
413
+ text = val;
414
+ }
415
+ if (text) {
416
+ // Send to someone this message
417
+ await this.sendMessage(text, user, chatId, { disable_notification: true, ...options });
418
+ }
419
+ else {
420
+ this.log.warn(`Invalid message: no text found: ${JSON.stringify(state.val)}`);
421
+ }
422
+ await this.setState('communicate.responseSilentJson', { val: state.val, ack: true });
423
+ }
424
+ catch (err) {
425
+ this.log.error(`could not parse Json in communicate.responseSilentJon state: ${err instanceof Error ? err.message : err}`);
426
+ }
427
+ }
428
+ else if (id.endsWith('communicate.requestResponse')) {
429
+ try {
430
+ const text = state.val;
431
+ const chatIdState = await this.getStateAsync('communicate.requestChatId');
432
+ const threadIdState = await this.getStateAsync('communicate.requestMessageThreadId');
433
+ const options = {};
434
+ if (threadIdState && threadIdState.val > 0) {
435
+ options.message_thread_id = threadIdState.val;
436
+ }
437
+ // Send to someone this message
438
+ await this.sendMessage(text, null, chatIdState ? chatIdState.val : null, options);
439
+ await this.setState('communicate.requestResponse', { val: state.val, ack: true });
440
+ }
441
+ catch (err) {
442
+ this.log.error(`could not parse Json in communicate.requestResponse state: ${err instanceof Error ? err.message : err}`);
443
+ }
444
+ }
445
+ }
446
+ else if (this.commands[id]?.report) {
447
+ this.log.debug(`reporting state change of ${id}: ${JSON.stringify(this.commands[id])}`);
448
+ const options = this.commands[id].reportSilent == true ? { disable_notification: true } : {};
449
+ let users = null;
450
+ if (this.commands[id]?.recipients) {
451
+ users = this.commands[id].recipients;
452
+ }
453
+ if (this.commands[id].reportChanges) {
454
+ if (state.val !== this.commands[id].lastState) {
455
+ this.commands[id].lastState = state.val;
456
+ await this.sendMessage(this.getStatus(id, state), users, null, options);
457
+ }
458
+ }
459
+ else {
460
+ await this.sendMessage(this.getStatus(id, state), users, null, options);
461
+ }
462
+ }
463
+ }
464
+ }
465
+ onObjectChange(id, obj) {
466
+ if (obj?.common?.custom?.[this.namespace]?.enabled) {
467
+ const stateObj = obj;
468
+ const alias = this.getName(stateObj);
469
+ if (!this.commands[id]) {
470
+ this.log.info(`enabled logging of ${id}, Alias=${alias}`);
471
+ setImmediate(() => this.subscribeForeignStates(id));
472
+ }
473
+ this.commands[id] = stateObj.common.custom?.[this.namespace];
474
+ this.commands[id].type = stateObj.common.type;
475
+ this.commands[id].states = this.parseStates(stateObj.common?.states);
476
+ this.commands[id].unit = stateObj.common?.unit;
477
+ this.commands[id].min = stateObj.common?.min;
478
+ this.commands[id].max = stateObj.common?.max;
479
+ this.commands[id].alias = alias;
480
+ // read actual state to detect changes
481
+ if (this.commands[id].reportChanges) {
482
+ this.getForeignStateAsync(id)
483
+ .then(state => (this.commands[id].lastState = state ? state.val : undefined))
484
+ .catch(err => this.log.error(err));
485
+ }
486
+ }
487
+ else if (this.commands[id]) {
488
+ this.log.debug(`Removed command: ${id}`);
489
+ delete this.commands[id];
490
+ setImmediate(() => this.unsubscribeForeignStates(id));
491
+ }
492
+ else if (id.startsWith('enum.rooms') && this.config.rooms) {
493
+ if (obj?.common?.members?.length) {
494
+ this.enumsCache.rooms[id] = obj.common;
495
+ }
496
+ else if (this.enumsCache.rooms[id]) {
497
+ delete this.enumsCache.rooms[id];
498
+ }
499
+ }
500
+ }
501
+ /**
502
+ * Send a message to all system users
503
+ *
504
+ * @param text text to send
505
+ * @param options additional options, e.g. parse_mode
506
+ */
507
+ async sendSystemMessage(text, options = {}) {
508
+ const _users = Object.keys(this.storedUsers)
509
+ .filter(id => this.storedUsers[id].sysMessages !== false)
510
+ .map(id => (this.config.useUsername ? this.storedUsers[id].userName : this.storedUsers[id].firstName));
511
+ await this.sendMessage(text, _users, null, { ...options, disable_notification: true });
512
+ }
513
+ getStatus(id, state) {
514
+ const cmd = this.commands[id];
515
+ // If the state has no value yet, we cannot tell ON from OFF - report it as uncertain instead of
516
+ // rendering a not-set boolean as "ON" (falsy 'State not set' string used to leak through here).
517
+ if (state?.val == null) {
518
+ return `${cmd.alias} => ${adapter_core_1.I18n.translate('uncertain')}`;
519
+ }
520
+ let val = state.val;
521
+ if (cmd.type === 'boolean') {
522
+ return `${cmd.alias} => ${val ? cmd.onStatus || adapter_core_1.I18n.translate('ON-Status') : cmd.offStatus || adapter_core_1.I18n.translate('OFF-Status')}`;
523
+ }
524
+ if (cmd.states?.[String(val)] !== undefined) {
525
+ val = cmd.states[String(val)];
526
+ }
527
+ return `${cmd.alias} => ${val}${cmd.unit ? ` ${cmd.unit}` : ''}`;
528
+ }
529
+ /**
530
+ * Fire-and-forget `setState` that never rejects: a failure is logged instead of surfacing as an
531
+ * unhandled promise rejection (which would otherwise terminate the adapter).
532
+ *
533
+ * @param id the (namespaced) state id
534
+ * @param value the value or a settable-state object (e.g. `{ val, ack: true }`)
535
+ */
536
+ setStateSafe(id, value) {
537
+ this.setState(id, value).catch(e => this.log.error(`Cannot set state "${id}": ${e}`));
538
+ }
539
+ connectionState(connected, logSuccess) {
540
+ let errorCounter = 0;
541
+ const checkConnection = () => {
542
+ this.pollConnectionStatus = undefined;
543
+ this.bot
544
+ ?.getMe?.()
545
+ .then(data => {
546
+ this.log.debug(`getMe (reconnect): ${JSON.stringify(data)}`);
547
+ this.connectionState(true, errorCounter > 0);
548
+ })
549
+ .catch(error => {
550
+ if (errorCounter % 10 === 0) {
551
+ this.log.error(`getMe (reconnect #${errorCounter}) Error:${error}`);
552
+ }
553
+ errorCounter++;
554
+ if (this.pollConnectionStatus) {
555
+ this.clearTimeout(this.pollConnectionStatus);
556
+ }
557
+ this.pollConnectionStatus = this.setTimeout(checkConnection, 1000);
558
+ });
559
+ };
560
+ if (connected && logSuccess) {
561
+ this.log.info('getMe (reconnect): Success');
562
+ }
563
+ if (this.isConnected !== connected) {
564
+ this.isConnected = connected;
565
+ this.setStateSafe('info.connection', { val: this.isConnected, ack: true });
566
+ if (this.isConnected) {
567
+ if (this.pollConnectionStatus) {
568
+ this.clearTimeout(this.pollConnectionStatus);
569
+ this.pollConnectionStatus = undefined;
570
+ }
571
+ // Connection (re)established: resend everything that piled up while telegram was unreachable.
572
+ void this.flushSendQueue();
573
+ }
574
+ else {
575
+ checkConnection();
576
+ }
577
+ }
578
+ }
579
+ /**
580
+ * Whether a failed send is worth retrying. Only transient/network problems are retried; permanent
581
+ * telegram errors (e.g. 400 "chat not found", 403 "bot was blocked") must not be requeued, otherwise
582
+ * they would be retried forever. See issue #839.
583
+ *
584
+ * @param error the error thrown by the telegram API call
585
+ * @returns true if the send should be queued and retried later
586
+ */
587
+ isRetryableSendError(error) {
588
+ const code = error?.code;
589
+ // EFATAL: network/connection problem (e.g. no internet); EPARSE: telegram answered with a
590
+ // non-JSON body, typically a transient 5xx gateway error.
591
+ if (code === 'EFATAL' || code === 'EPARSE') {
592
+ return true;
593
+ }
594
+ if (code === 'ETELEGRAM') {
595
+ // the Bot API replied with ok:false - retry only on rate limit (429) or server errors (5xx)
596
+ const status = error?.response?.body?.error_code ?? error?.response?.statusCode;
597
+ if (status === 429 || (typeof status === 'number' && status >= 500 && status < 600)) {
598
+ return true;
599
+ }
600
+ const m = /ETELEGRAM:\s*(\d{3})/.exec(String(error?.message ?? error));
601
+ if (m) {
602
+ const s = parseInt(m[1], 10);
603
+ return s === 429 || (s >= 500 && s < 600);
604
+ }
605
+ return false;
606
+ }
607
+ // unknown error shape - be conservative and do not retry
608
+ return false;
609
+ }
610
+ /**
611
+ * Queue a send that failed because telegram was unreachable, so it can be resent on reconnect. The
612
+ * queue is bounded: when it is full the oldest entry is dropped. See issue #839.
613
+ *
614
+ * @param action the telegram API call to repeat later
615
+ * @param label a human-readable recipient label for logging
616
+ * @param error the error that caused the enqueue (for the log message)
617
+ */
618
+ enqueueFailedSend(action, label, error) {
619
+ if (this.sendQueue.length >= Telegram.MAX_SEND_QUEUE_LENGTH) {
620
+ this.sendQueue.shift();
621
+ this.log.warn(`Outgoing message queue is full (${Telegram.MAX_SEND_QUEUE_LENGTH}); dropped the oldest queued message`);
622
+ }
623
+ this.sendQueue.push({ action, label, ts: Date.now(), attempts: 1 });
624
+ this.log.info(`Telegram not reachable - queued message for "${label}" to resend on reconnect (queue size: ${this.sendQueue.length}). Reason: ${String(error)}`);
625
+ // Safety net for transient failures that do not trigger a full disconnect/reconnect cycle: keep
626
+ // retrying the queue periodically until it is empty (see flushSendQueue).
627
+ this.scheduleSendQueueRetry();
628
+ }
629
+ /** Schedule a delayed flush of the send queue (once), unless one is already pending. */
630
+ scheduleSendQueueRetry() {
631
+ if (this.sendQueueRetryTimer || !this.sendQueue.length) {
632
+ return;
633
+ }
634
+ this.sendQueueRetryTimer = this.setTimeout(() => {
635
+ this.sendQueueRetryTimer = undefined;
636
+ void this.flushSendQueue();
637
+ }, Telegram.SEND_QUEUE_RETRY_MS);
638
+ }
639
+ /**
640
+ * Resend all queued messages (FIFO) once the connection is back. Entries older than the max age are
641
+ * dropped; if a resend fails again with a retryable error, the queue is kept and the flush stops (the
642
+ * server is probably down again) to be retried on the next reconnect. See issue #839.
643
+ */
644
+ async flushSendQueue() {
645
+ if (this.sendQueueFlushing || !this.sendQueue.length) {
646
+ return;
647
+ }
648
+ this.sendQueueFlushing = true;
649
+ try {
650
+ // drop messages that are too old to be worth sending
651
+ const now = Date.now();
652
+ for (let i = this.sendQueue.length - 1; i >= 0; i--) {
653
+ if (now - this.sendQueue[i].ts >= Telegram.MAX_SEND_QUEUE_AGE_MS) {
654
+ const [dropped] = this.sendQueue.splice(i, 1);
655
+ this.log.warn(`Dropped queued message for "${dropped.label}" (older than 24 h)`);
656
+ }
657
+ }
658
+ if (this.sendQueue.length) {
659
+ this.log.info(`Connection restored - resending ${this.sendQueue.length} queued message(s)`);
660
+ }
661
+ while (this.sendQueue.length) {
662
+ const item = this.sendQueue[0];
663
+ try {
664
+ const response = await item.action();
665
+ this.saveSendRequest(response);
666
+ this.sendQueue.shift();
667
+ this.log.debug(`Resent queued message for "${item.label}"`);
668
+ }
669
+ catch (error) {
670
+ item.attempts++;
671
+ if (this.isRetryableSendError(error) &&
672
+ item.attempts <= Telegram.MAX_SEND_ATTEMPTS &&
673
+ Date.now() - item.ts < Telegram.MAX_SEND_QUEUE_AGE_MS) {
674
+ // still unreachable: keep the queue and wait for the next reconnect
675
+ this.log.warn(`Resending queued message for "${item.label}" failed again (attempt ${item.attempts}); will retry on next reconnect: ${error}`);
676
+ break;
677
+ }
678
+ // permanent error or too many attempts: give up on this message and continue with the rest
679
+ this.sendQueue.shift();
680
+ this.log.error(`Giving up on queued message for "${item.label}" after ${item.attempts} attempt(s): ${error}`);
681
+ }
682
+ }
683
+ }
684
+ finally {
685
+ this.sendQueueFlushing = false;
686
+ // if anything is still queued (server still down), make sure we try again later
687
+ this.scheduleSendQueueRetry();
688
+ }
689
+ }
690
+ parseStates(states) {
691
+ if (!states) {
692
+ return undefined;
693
+ }
694
+ if (Array.isArray(states)) {
695
+ const obj = {};
696
+ states.forEach(value => (obj[value] = value));
697
+ return obj;
698
+ }
699
+ if (typeof states === 'string') {
700
+ const parts = states.split(';');
701
+ const obj = {};
702
+ parts.forEach(value => (obj[value] = value));
703
+ return obj;
704
+ }
705
+ return states;
706
+ }
707
+ getName(obj) {
708
+ const custom = obj.common.custom;
709
+ if (custom[this.namespace].alias) {
710
+ return custom[this.namespace].alias;
711
+ }
712
+ let name = obj.common.name;
713
+ if (typeof name === 'object') {
714
+ name = name[this.systemLang] || name.en;
715
+ }
716
+ return name || obj._id;
717
+ }
718
+ handleWebHook(req, res) {
719
+ if (req.method === 'POST' && req.url === `/${this.config.token}`) {
720
+ let body = '';
721
+ req.on('data', data => {
722
+ body += data;
723
+ if (body.length > 100_000) {
724
+ res.writeHead(413, 'Request Entity Too Large', {
725
+ 'Content-Type': 'text/html',
726
+ });
727
+ res.end('<!doctype html><html><head><title>413</title></head><body>413: Request Entity Too Large</body></html>');
728
+ }
729
+ });
730
+ req.on('end', () => {
731
+ let msg;
732
+ try {
733
+ msg = JSON.parse(body);
734
+ }
735
+ catch (e) {
736
+ this.log.error(`Cannot parse webhook response!: ${e}`);
737
+ return;
738
+ }
739
+ res.end('OK');
740
+ this.bot.processUpdate(msg);
741
+ });
742
+ }
743
+ else {
744
+ res.writeHead(404, 'Resource Not Found', {
745
+ 'Content-Type': 'text/html',
746
+ });
747
+ res.end('<!doctype html><html><head><title>404</title></head><body>404: Resource Not Found</body></html>');
748
+ }
749
+ }
750
+ saveSendRequest(msg) {
751
+ this.log.debug(`Request [saveSendRequest]: ${JSON.stringify(msg)}`);
752
+ if (typeof msg === 'object') {
753
+ if (this.config.storeRawRequest) {
754
+ this.setState('communicate.botSendRaw', JSON.stringify(msg, null, 2), true).catch(err => this.log.error(err.message));
755
+ }
756
+ if (msg?.message_id) {
757
+ this.setState('communicate.botSendMessageId', msg.message_id, true).catch(err => this.log.error(err.message));
758
+ }
759
+ if (msg?.message_thread_id) {
760
+ this.setState('communicate.botSendMessageThreadId', msg.message_thread_id, true).catch(err => this.log.error(err.message));
761
+ }
762
+ if (msg?.chat?.id) {
763
+ this.setState('communicate.botSendChatId', msg.chat.id.toString(), true).catch(err => this.log.error(err.message));
764
+ }
765
+ }
766
+ }
767
+ /**
768
+ * Resolve an ioBroker URI to a payload that can be handed to the telegram send functions.
769
+ *
770
+ * File and (base64) object/state content is returned as a Buffer, so that it can be uploaded even when
771
+ * the file is not present on the local filesystem. `http(s)` URLs and filesystem paths are returned as a
772
+ * string and forwarded as-is (telegram / the bot library fetch them).
773
+ *
774
+ * @param uri the ioBroker URI (string or already parsed)
775
+ * @param depth internal recursion guard (a state may reference another URI)
776
+ * @returns the resolved payload or null if it could not be resolved
777
+ */
778
+ async resolveIobUri(uri, depth = 0) {
779
+ if (depth > 5) {
780
+ this.log.warn('Too many nested ioBroker URI references');
781
+ return null;
782
+ }
783
+ const parsed = typeof uri === 'string' ? (0, iobUri_1.iobUriFromString)(uri) : uri;
784
+ if (parsed.type === 'http') {
785
+ return { content: parsed.address, type: (0, iobUri_1.detectMediaTypeFromName)(parsed.address) };
786
+ }
787
+ if (parsed.type === 'file') {
788
+ const result = await this.readFileAsync(parsed.address, parsed.path || '');
789
+ const file = result?.file;
790
+ if (file === undefined || file === null) {
791
+ return null;
792
+ }
793
+ const content = Buffer.isBuffer(file) ? file : Buffer.from(file, 'binary');
794
+ const fileName = (parsed.path || '').split('/').pop() || undefined;
795
+ let type = (0, iobUri_1.detectMediaTypeFromName)(parsed.path || '');
796
+ if (!type && result?.mimeType) {
797
+ type = (0, iobUri_1.mimeToMediaType)(result.mimeType);
798
+ }
799
+ return { content, type: type || 'document', fileName };
800
+ }
801
+ if (parsed.type === 'state') {
802
+ const state = await this.getForeignStateAsync(parsed.address);
803
+ return this.valueToPayload(state ? state.val : null, depth);
804
+ }
805
+ // parsed.type === 'object'
806
+ const obj = await this.getForeignObjectAsync(parsed.address);
807
+ let value = obj;
808
+ if (parsed.path) {
809
+ for (const key of parsed.path.split('/')) {
810
+ if (value && typeof value === 'object') {
811
+ value = value[key];
812
+ }
813
+ else {
814
+ value = undefined;
815
+ break;
816
+ }
817
+ }
818
+ }
819
+ return this.valueToPayload(value, depth);
820
+ }
821
+ /**
822
+ * Convert an ioBroker state/object value into a send payload. Data URLs are decoded to a Buffer, nested
823
+ * ioBroker/http URIs are resolved recursively, everything else is returned as a string.
824
+ *
825
+ * @param value the raw value
826
+ * @param depth current recursion depth (see {@link resolveIobUri})
827
+ * @returns the resolved payload or null
828
+ */
829
+ async valueToPayload(value, depth) {
830
+ if (value === undefined || value === null) {
831
+ return null;
832
+ }
833
+ if (typeof value === 'string') {
834
+ const dataUrl = value.match(/^data:([^;]+);base64,(.*)$/s);
835
+ if (dataUrl) {
836
+ const mime = dataUrl[1];
837
+ return {
838
+ content: Buffer.from(dataUrl[2], 'base64'),
839
+ type: (0, iobUri_1.mimeToMediaType)(mime),
840
+ fileName: `data.${mime.split('/')[1] || 'bin'}`,
841
+ };
842
+ }
843
+ if ((0, iobUri_1.isIobUri)(value) || /^https?:\/\//i.test(value)) {
844
+ return this.resolveIobUri(value, depth + 1);
845
+ }
846
+ return { content: value, type: (0, iobUri_1.detectMediaTypeFromName)(value) };
847
+ }
848
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
849
+ return { content: String(value) };
850
+ }
851
+ if (typeof value === 'object') {
852
+ return { content: JSON.stringify(value) };
853
+ }
854
+ return null;
855
+ }
856
+ async sendMessageHelper(dest, name, text, options) {
857
+ const bot = this.bot;
858
+ // Resolve ioBroker URIs (iobfile://, iobobject://, iobstate://) to their content before dispatching.
859
+ // This allows sending files that live in the ioBroker file storage (e.g. behind Redis/jsonl) and are
860
+ // therefore not accessible through the local filesystem. See issue #907.
861
+ if (typeof text === 'string' && (0, iobUri_1.isIobUri)(text)) {
862
+ try {
863
+ const resolved = await this.resolveIobUri(text);
864
+ if (!resolved) {
865
+ this.log.error(`Cannot resolve ioBroker URI: ${text}`);
866
+ return JSON.stringify({
867
+ error: { [String(options.chatId ?? dest)]: 'Cannot resolve ioBroker URI' },
868
+ });
869
+ }
870
+ text = resolved.content;
871
+ if (resolved.type && !options.type) {
872
+ options.type = resolved.type;
873
+ }
874
+ if (resolved.fileName && !options.fileName) {
875
+ options.fileName = resolved.fileName;
876
+ }
877
+ }
878
+ catch (err) {
879
+ this.log.error(`Cannot resolve ioBroker URI "${text}": ${err instanceof Error ? err.message : err}`);
880
+ return JSON.stringify({ error: { [String(options.chatId ?? dest)]: String(err) } });
881
+ }
882
+ }
883
+ return new Promise(resolve => {
884
+ const messageIds = {};
885
+ if (options?.chatId !== undefined && options.user === undefined) {
886
+ options.user = this.config.useUsername
887
+ ? this.storedUsers[options.chatId].userName
888
+ : this.storedUsers[options.chatId].firstName;
889
+ }
890
+ // to push chatId value for the group chats - useful to process the errors, and list of processed messages.
891
+ if (options.chatId === undefined && options.user === undefined && name === 'chat' && dest) {
892
+ options.chatId = dest;
893
+ }
894
+ if (options?.editMessageReplyMarkup !== undefined) {
895
+ this.log.debug(`Send editMessageReplyMarkup to "${name}"`);
896
+ if (bot) {
897
+ this.executeSending(() => bot.editMessageReplyMarkup(options.editMessageReplyMarkup.reply_markup, options.editMessageReplyMarkup.options), options, resolve);
898
+ }
899
+ }
900
+ else if (options?.editMessageText !== undefined) {
901
+ this.log.debug(`Send editMessageText to "${name}"`);
902
+ if (bot) {
903
+ this.executeSending(() => bot.editMessageText({ ...options.editMessageText.options, text }), options, resolve);
904
+ }
905
+ }
906
+ else if (options?.editMessageMedia !== undefined) {
907
+ this.log.debug(`Send editMessageMedia to "${name}"`);
908
+ if (text) {
909
+ let mediaInput;
910
+ if ((typeof text === 'string' &&
911
+ text.match(/\.(jpg|png|jpeg|bmp|gif)$/i) &&
912
+ ((0, node_fs_1.existsSync)(text) || text.match(/^(https|http)/i))) ||
913
+ options?.type === 'photo') {
914
+ mediaInput = {
915
+ type: 'photo',
916
+ media: text,
917
+ };
918
+ }
919
+ else if ((typeof text === 'string' && text.match(/\.(gif)/i) && (0, node_fs_1.existsSync)(text)) ||
920
+ options?.type === 'animation') {
921
+ mediaInput = {
922
+ type: 'animation',
923
+ media: text,
924
+ };
925
+ }
926
+ else if ((typeof text === 'string' && text.match(/\.(mp4)$/i) && (0, node_fs_1.existsSync)(text)) ||
927
+ options?.type === 'video') {
928
+ mediaInput = {
929
+ type: 'video',
930
+ media: text,
931
+ };
932
+ }
933
+ else if ((typeof text === 'string' && text.match(/\.(wav|mp3|ogg)$/i) && (0, node_fs_1.existsSync)(text)) ||
934
+ options?.type === 'audio') {
935
+ mediaInput = {
936
+ type: 'audio',
937
+ media: text,
938
+ };
939
+ }
940
+ else if ((typeof text === 'string' &&
941
+ text.match(/\.(txt|doc|docx|csv|pdf|xls|xlsx)$/i) &&
942
+ (0, node_fs_1.existsSync)(text)) ||
943
+ options?.type === 'document') {
944
+ mediaInput = {
945
+ type: 'document',
946
+ media: text,
947
+ };
948
+ }
949
+ if (mediaInput) {
950
+ // The library resolves the file itself (local path / Buffer / stream / URL /
951
+ // file_id) and builds the multipart form + `attach://` reference internally.
952
+ // We only pass the InputMedia object and the extra form fields.
953
+ const inputMedia = {
954
+ type: mediaInput.type,
955
+ media: mediaInput.media,
956
+ };
957
+ if (options.editMessageMedia.options?.caption) {
958
+ inputMedia.caption = options.editMessageMedia.options.caption;
959
+ }
960
+ if (options.editMessageMedia.options?.parse_mode) {
961
+ inputMedia.parse_mode = options.editMessageMedia.options.parse_mode;
962
+ }
963
+ const form = {};
964
+ if (options.editMessageMedia.options?.chat_id !== undefined) {
965
+ form.chat_id = options.editMessageMedia.options.chat_id;
966
+ }
967
+ if (options.editMessageMedia.options?.message_id !== undefined) {
968
+ form.message_id = options.editMessageMedia.options.message_id;
969
+ }
970
+ if (options.editMessageMedia.options?.reply_markup) {
971
+ form.reply_markup = options.editMessageMedia.options.reply_markup;
972
+ }
973
+ if (bot) {
974
+ this.executeSending(() => bot.editMessageMedia(inputMedia, form), options, resolve);
975
+ }
976
+ }
977
+ else {
978
+ this.log.error(`Cannot send editMessageMedia [chatId - ${options.chatId}]: unsupported media type`);
979
+ resolve(JSON.stringify(messageIds));
980
+ }
981
+ }
982
+ else {
983
+ this.log.error(`Cannot send editMessageMedia [chatId - ${options.chatId}]: no media found. "text" may not be empty`);
984
+ resolve(JSON.stringify(messageIds));
985
+ }
986
+ }
987
+ else if (options?.editMessageCaption !== undefined) {
988
+ this.log.debug(`Send editMessageCaption to "${name}"`);
989
+ if (bot) {
990
+ this.executeSending(() => bot.editMessageCaption(text, options.editMessageCaption.options), options, resolve);
991
+ }
992
+ }
993
+ else if (options?.deleteMessage !== undefined) {
994
+ this.log.debug(`Send deleteMessage to "${name}"`);
995
+ if (bot) {
996
+ this.executeSending(() => bot.deleteMessage(options.deleteMessage.options.chat_id, options.deleteMessage.options.message_id), options, resolve);
997
+ }
998
+ }
999
+ else if (options &&
1000
+ options.latitude !== undefined &&
1001
+ options.longitude !== undefined &&
1002
+ options.title !== undefined &&
1003
+ options.address !== undefined) {
1004
+ this.log.debug(`Send venue to "${name}": ${options.latitude},${options.longitude}`);
1005
+ if (bot) {
1006
+ this.executeSending(() => bot.sendVenue(dest, parseFloat(String(options.latitude)), parseFloat(String(options.longitude)), options.title, options.address, options), options, resolve);
1007
+ }
1008
+ }
1009
+ else if (options?.latitude !== undefined && options.longitude !== undefined) {
1010
+ this.log.debug(`Send location to "${name}": ${options.latitude},${options.longitude}`);
1011
+ if (bot) {
1012
+ this.executeSending(() => bot.sendLocation(dest, parseFloat(String(options.latitude)), parseFloat(String(options.longitude)), options), options, resolve);
1013
+ }
1014
+ }
1015
+ else if (options?.type === 'mediagroup') {
1016
+ this.log.debug(`Send media group to "${name}": `);
1017
+ if (bot) {
1018
+ const { media: fileNames } = options;
1019
+ if (fileNames instanceof Array) {
1020
+ bot.sendChatAction(dest, 'upload_photo')
1021
+ .then(() => {
1022
+ if (fileNames.every((name) => (0, node_fs_1.existsSync)(name))) {
1023
+ const filesAsArray = fileNames
1024
+ .map((element) => {
1025
+ try {
1026
+ return { type: 'photo', media: (0, node_fs_1.readFileSync)(element) };
1027
+ }
1028
+ catch (err) {
1029
+ this.log.error(`Cannot read file ${element}: ${err}`);
1030
+ return undefined;
1031
+ }
1032
+ })
1033
+ .filter(element => element !== undefined);
1034
+ const size = filesAsArray
1035
+ .map(element => element.media.length)
1036
+ .reduce((acc, val) => acc + val);
1037
+ this.log.info(`Send media group to "${name}": ${size} bytes`);
1038
+ if (filesAsArray.length > 0) {
1039
+ this.executeSending(() => bot.sendMediaGroup(dest, filesAsArray), options, resolve);
1040
+ }
1041
+ }
1042
+ else {
1043
+ this.log.debug('files must exists');
1044
+ resolve(JSON.stringify(messageIds));
1045
+ }
1046
+ })
1047
+ .catch(error => {
1048
+ this.log.error(`upload Error: ${error}`);
1049
+ });
1050
+ }
1051
+ else {
1052
+ this.log.debug('option media should be an array');
1053
+ resolve(JSON.stringify(messageIds));
1054
+ }
1055
+ }
1056
+ else {
1057
+ this.log.debug('no files added!');
1058
+ resolve(JSON.stringify(messageIds));
1059
+ }
1060
+ }
1061
+ else if (text && typeof text === 'string' && actions.includes(text)) {
1062
+ this.log.debug(`Send action to "${name}": ${text}`);
1063
+ if (bot) {
1064
+ this.executeSending(() => bot.sendChatAction(dest, text), options, resolve);
1065
+ }
1066
+ }
1067
+ else if (text &&
1068
+ ((typeof text === 'string' && text.match(/\.webp$/i) && (0, node_fs_1.existsSync)(text)) ||
1069
+ options?.type === 'sticker')) {
1070
+ if (typeof text === 'string') {
1071
+ this.log.debug(`Send sticker to "${name}": ${text}`);
1072
+ }
1073
+ else {
1074
+ this.log.debug(`Send sticker to "${name}": ${text.length} bytes`);
1075
+ }
1076
+ if (bot) {
1077
+ this.executeSending(() => bot.sendSticker(dest, text, options, { filename: options.fileName }), options, resolve);
1078
+ }
1079
+ }
1080
+ else if (text &&
1081
+ ((typeof text === 'string' && text.match(/\.(gif)/i) && (0, node_fs_1.existsSync)(text)) ||
1082
+ options?.type === 'animation')) {
1083
+ if (typeof text === 'string') {
1084
+ this.log.debug(`Send animation to "${name}": ${text}`);
1085
+ }
1086
+ else {
1087
+ this.log.debug(`Send animation to "${name}": ${text.length} bytes`);
1088
+ }
1089
+ if (bot) {
1090
+ this.executeSending(() => bot.sendAnimation(dest, text, options, { filename: options.fileName }), options, resolve);
1091
+ }
1092
+ }
1093
+ else if (text &&
1094
+ ((typeof text === 'string' && text.match(/\.(mp4)$/i) && (0, node_fs_1.existsSync)(text)) || options?.type === 'video')) {
1095
+ if (typeof text === 'string') {
1096
+ this.log.debug(`Send video to "${name}": ${text}`);
1097
+ }
1098
+ else {
1099
+ this.log.debug(`Send video to "${name}": ${text.length} bytes`);
1100
+ }
1101
+ if (bot) {
1102
+ this.executeSending(() => bot.sendVideo(dest, text, options, { filename: options.fileName }), options, resolve);
1103
+ }
1104
+ }
1105
+ else if (text &&
1106
+ ((typeof text === 'string' && text.match(/\.(txt|doc|docx|csv|pdf|xls|xlsx)$/i) && (0, node_fs_1.existsSync)(text)) ||
1107
+ options?.type === 'document')) {
1108
+ this.log.debug(`Send document to "${name}": ${typeof text === 'string' ? text : text.length}`);
1109
+ if (bot) {
1110
+ this.executeSending(() => bot.sendDocument(dest, text, options, { filename: options.fileName }), options, resolve);
1111
+ }
1112
+ }
1113
+ else if (text &&
1114
+ ((typeof text === 'string' && text.match(/\.(wav|mp3|ogg)$/i) && (0, node_fs_1.existsSync)(text)) ||
1115
+ (options && options?.type === 'audio'))) {
1116
+ this.log.debug(`Send audio to "${name}": ${typeof text === 'string' ? text : text.length}`);
1117
+ if (bot) {
1118
+ this.executeSending(() => bot.sendAudio(dest, text, options, { filename: options.fileName }), options, resolve);
1119
+ }
1120
+ }
1121
+ else if (text &&
1122
+ ((typeof text === 'string' && // if the message is a string, and it is a path to file or URL
1123
+ text.match(/\.(jpg|png|jpeg|bmp|gif)$/i) &&
1124
+ ((0, node_fs_1.existsSync)(text) || text.match(/^(https|http)/i))) ||
1125
+ options?.type === 'photo') // if the type of message is photo
1126
+ ) {
1127
+ this.log.debug(`Send photo to "${name}": ${typeof text === 'string' ? text : text.length}`);
1128
+ if (bot) {
1129
+ this.executeSending(() => bot.sendPhoto(dest, text, options, { filename: options.fileName }), options, resolve);
1130
+ }
1131
+ }
1132
+ else if (options?.answerCallbackQuery !== undefined) {
1133
+ this.log.debug(`Send answerCallbackQuery to "${name}"`);
1134
+ if (options.answerCallbackQuery.showAlert === undefined) {
1135
+ options.answerCallbackQuery.showAlert = false;
1136
+ }
1137
+ if (bot && this.callbackQueryId[String(options.chatId)]) {
1138
+ const originalChatId = this.callbackQueryId[String(options.chatId)].id;
1139
+ delete this.callbackQueryId[String(options.chatId)];
1140
+ this.executeSending(() => bot.answerCallbackQuery(originalChatId, {
1141
+ text: options.answerCallbackQuery.text,
1142
+ show_alert: options.answerCallbackQuery.showAlert,
1143
+ }), options, resolve);
1144
+ }
1145
+ }
1146
+ else {
1147
+ this.log.debug(`Send message to [${name}]: "${text}"`);
1148
+ if (text && typeof text === 'string') {
1149
+ options ||= {};
1150
+ if (text.startsWith('<MarkdownV2>') && text.endsWith('</MarkdownV2>')) {
1151
+ options.parse_mode = 'MarkdownV2';
1152
+ text = text.substring(12, text.length - 13);
1153
+ }
1154
+ else if (text.startsWith('<HTML>') && text.endsWith('</HTML>')) {
1155
+ options.parse_mode = 'HTML';
1156
+ text = text.substring(6, text.length - 7);
1157
+ }
1158
+ else if (text.startsWith('<Markdown>') && text.endsWith('</Markdown>')) {
1159
+ options.parse_mode = 'Markdown';
1160
+ text = text.substring(10, text.length - 11);
1161
+ }
1162
+ }
1163
+ if (bot) {
1164
+ this.executeSending(() => bot.sendMessage(dest, text || '', options), options, resolve);
1165
+ }
1166
+ }
1167
+ });
1168
+ }
1169
+ /**
1170
+ * executes the given method and handles, what to do next
1171
+ *
1172
+ * @param action the telegram API call to execute
1173
+ * @param options the send options bag
1174
+ * @param resolve resolves the surrounding promise with the collected message ids
1175
+ */
1176
+ executeSending(action, options, resolve) {
1177
+ // create an empty object, to store chat id and message id of successfully sent messages
1178
+ const messageIds = {};
1179
+ action()
1180
+ .then(response => {
1181
+ // put chat id and message id to the object, that will be returned
1182
+ // delete message command return only true in response,
1183
+ // to return deleted message id and chat id the next if construction is used:
1184
+ if (response?.message_id) {
1185
+ // The chatId is mostly used in code, instead of chat_id.
1186
+ messageIds[String(options.chat_id ?? options.chatId)] = response.message_id;
1187
+ }
1188
+ else if (typeof response === 'boolean' &&
1189
+ options?.deleteMessage?.options?.chat_id &&
1190
+ options?.deleteMessage?.options?.message_id) {
1191
+ messageIds[options.deleteMessage.options.chat_id] = options.deleteMessage.options.message_id;
1192
+ }
1193
+ // puts ids to the ioBroker database
1194
+ this.saveSendRequest(response);
1195
+ })
1196
+ .then(() => {
1197
+ this.log.debug('Message sent');
1198
+ // return all the collected message ids to the callback
1199
+ resolve(JSON.stringify(messageIds));
1200
+ })
1201
+ .catch(error => {
1202
+ // add the error to the message ids object
1203
+ messageIds.error = { [String(options.chat_id ?? options.chatId)]: error };
1204
+ // log error to the system
1205
+ this.log.error(`Failed sending [${options.chatId ? 'chatId' : 'user'} - ${options.chatId ? options.chatId : options.user}]: ${error}`);
1206
+ // If telegram was unreachable, queue the send so it can be retried on reconnect (issue #839).
1207
+ // The original promise is still resolved right away so callers never block on the retry.
1208
+ if (this.isRetryableSendError(error)) {
1209
+ const label = String(options.chat_id ?? options.chatId ?? options.user ?? 'all');
1210
+ this.enqueueFailedSend(action, label, error);
1211
+ }
1212
+ // send the successfully sent messages as callback
1213
+ resolve(JSON.stringify(messageIds));
1214
+ });
1215
+ }
1216
+ // https://core.telegram.org/bots/api
1217
+ sendMessage(text, user, chatId, options) {
1218
+ if (!text && typeof options !== 'object' && text !== 0 && (!options || !options.latitude)) {
1219
+ this.log.warn('Invalid text: null');
1220
+ return Promise.resolve([]);
1221
+ }
1222
+ if (options && typeof options === 'object') {
1223
+ if (options.chatId !== undefined) {
1224
+ delete options.chatId;
1225
+ }
1226
+ if (options.text !== undefined) {
1227
+ delete options.text;
1228
+ }
1229
+ if (options.user !== undefined) {
1230
+ delete options.user;
1231
+ }
1232
+ }
1233
+ options ||= {};
1234
+ if (text && typeof text === 'string') {
1235
+ if (text && text.startsWith('<MarkdownV2>') && text.endsWith('</MarkdownV2>')) {
1236
+ options.parse_mode = 'MarkdownV2';
1237
+ text = text.substring(12, text.length - 13);
1238
+ }
1239
+ else if (text && text.startsWith('<HTML>') && text.endsWith('</HTML>')) {
1240
+ options.parse_mode = 'HTML';
1241
+ text = text.substring(6, text.length - 7);
1242
+ }
1243
+ else if (text && text.startsWith('<Markdown>') && text.endsWith('</Markdown>')) {
1244
+ options.parse_mode = 'Markdown';
1245
+ text = text.substring(10, text.length - 11);
1246
+ }
1247
+ }
1248
+ // deleteMessage / editMessage* already carry their target chat in their own options. If the caller
1249
+ // did not address a specific recipient, dispatch the operation exactly once to that chat instead of
1250
+ // broadcasting it to every stored user (which made all but the first recipient fail, see
1251
+ // https://github.com/iobroker-community-adapters/ioBroker.telegram/issues/885).
1252
+ if (!chatId && !user) {
1253
+ const targetedChatId = options.deleteMessage?.options?.chat_id ??
1254
+ options.editMessageText?.options?.chat_id ??
1255
+ options.editMessageCaption?.options?.chat_id ??
1256
+ options.editMessageMedia?.options?.chat_id ??
1257
+ options.editMessageReplyMarkup?.options?.chat_id;
1258
+ if (targetedChatId !== undefined && targetedChatId !== null) {
1259
+ chatId = targetedChatId;
1260
+ }
1261
+ }
1262
+ const tPromiseList = [];
1263
+ // convert
1264
+ if (text !== undefined && text !== null && typeof text !== 'object') {
1265
+ text = text.toString();
1266
+ }
1267
+ if (chatId) {
1268
+ tPromiseList.push(this.sendMessageHelper(chatId, 'chat', text, options));
1269
+ return Promise.all(tPromiseList).catch(e => e);
1270
+ }
1271
+ else if (user) {
1272
+ if (typeof user !== 'string' && !(user instanceof Array)) {
1273
+ this.log.warn(`Invalid type of user parameter: ${typeof user}. Expected is string or array.`);
1274
+ }
1275
+ const userArray = Array.isArray(user)
1276
+ ? user
1277
+ : (user || '')
1278
+ .toString()
1279
+ .split(/[,;\s]/)
1280
+ .map(u => u.trim())
1281
+ .filter(u => !!u);
1282
+ let matches = 0;
1283
+ userArray.forEach(userName => {
1284
+ for (const id in this.storedUsers) {
1285
+ if (!Object.prototype.hasOwnProperty.call(this.storedUsers, id)) {
1286
+ continue;
1287
+ }
1288
+ if (
1289
+ // allow addressing a recipient by its numeric user/chat id (storedUsers is keyed by id)
1290
+ id === userName ||
1291
+ // Match by username when one is stored, otherwise fall back to the first name. A
1292
+ // recipient without a public telegram username is stored with an empty userName, so
1293
+ // usernames and first names can be mixed in one recipient list. See issue #854.
1294
+ (this.config.useUsername && this.storedUsers[id].userName
1295
+ ? this.storedUsers[id].userName === userName
1296
+ : this.storedUsers[id].firstName === userName)) {
1297
+ if (options) {
1298
+ options.chatId = id;
1299
+ }
1300
+ matches++;
1301
+ tPromiseList.push(this.sendMessageHelper(id, userName, text, options));
1302
+ break;
1303
+ }
1304
+ }
1305
+ });
1306
+ if (userArray.length !== matches) {
1307
+ this.log.warn(`${userArray.length - matches} of ${userArray.length} recipients are unknown!`);
1308
+ }
1309
+ return Promise.all(tPromiseList).catch(e => e);
1310
+ }
1311
+ const m = typeof text === 'string' ? text.match(/^@(.+?)\b/) : null;
1312
+ if (m) {
1313
+ text = (text || '').toString();
1314
+ text = text.replace(`@${m[1]}`, '').trim().replace(/\s\s/g, ' ');
1315
+ const re = new RegExp(m[1], 'i');
1316
+ let id = '';
1317
+ for (const id_t in this.storedUsers) {
1318
+ if (!Object.prototype.hasOwnProperty.call(this.storedUsers, id_t)) {
1319
+ continue;
1320
+ }
1321
+ if (
1322
+ // Match by username when one is stored, otherwise fall back to the first name (see #854).
1323
+ this.config.useUsername && this.storedUsers[id_t].userName
1324
+ ? this.storedUsers[id_t].userName.match(re)
1325
+ : this.storedUsers[id_t].firstName.match(re)) {
1326
+ id = id_t;
1327
+ break;
1328
+ }
1329
+ }
1330
+ if (id) {
1331
+ if (options) {
1332
+ options.chatId = id;
1333
+ }
1334
+ tPromiseList.push(this.sendMessageHelper(id, m[1], text, options));
1335
+ }
1336
+ }
1337
+ else {
1338
+ // Send to all users
1339
+ Object.keys(this.storedUsers).forEach(id => {
1340
+ if (options) {
1341
+ options.chatId = id;
1342
+ }
1343
+ tPromiseList.push(this.sendMessageHelper(id, this.config.useUsername && this.storedUsers[id].userName
1344
+ ? this.storedUsers[id].userName
1345
+ : this.storedUsers[id].firstName, text, options));
1346
+ });
1347
+ }
1348
+ return Promise.all(tPromiseList).catch(e => e);
1349
+ }
1350
+ saveFile(fileID, fileName, callback) {
1351
+ this.log.debug(`Saving media file ${fileID} to ${fileName} (location = ${this.config.saveFilesTo})`);
1352
+ this.bot.getFileLink(fileID)
1353
+ .then(url => {
1354
+ this.log.debug(`Received message: ${url}`);
1355
+ (0, node_https_1.get)(url, res => {
1356
+ if (res.statusCode === 200) {
1357
+ const buf = [];
1358
+ res.on('data', data => buf.push(data));
1359
+ res.on('end', () => {
1360
+ if (this.config.saveFilesTo == 'filesystem') {
1361
+ const fileLocation = (0, node_path_1.join)(this.tmpDirName, fileName);
1362
+ try {
1363
+ (0, node_fs_1.writeFileSync)(fileLocation, Buffer.concat(buf));
1364
+ callback({
1365
+ info: `media file has been saved to "${this.config.saveFilesTo}": ${fileLocation}`,
1366
+ location: this.config.saveFilesTo,
1367
+ path: fileLocation,
1368
+ });
1369
+ }
1370
+ catch (err) {
1371
+ return callback({ error: `Error: ${err}` });
1372
+ }
1373
+ }
1374
+ else if (this.config.saveFilesTo == 'iobroker') {
1375
+ try {
1376
+ const fileLocation = (0, node_path_1.join)(this.tmpDirName, fileName); // TODO: check new urn format https://github.com/ioBroker/ioBroker.js-controller/issues/2710
1377
+ this.writeFileAsync(this.namespace, fileName, Buffer.concat(buf))
1378
+ .then(() => {
1379
+ callback({
1380
+ info: `media file has been saved to "${this.config.saveFilesTo}": ${fileLocation}`,
1381
+ location: this.config.saveFilesTo,
1382
+ path: fileLocation,
1383
+ });
1384
+ })
1385
+ .catch(err => this.log.error(err));
1386
+ }
1387
+ catch (err) {
1388
+ return callback({ error: `Error: ${err}` });
1389
+ }
1390
+ }
1391
+ });
1392
+ res.on('error', err => callback({ error: `Error: ${err}` }));
1393
+ }
1394
+ else {
1395
+ callback({ error: 'Error: statusCode !== 200' });
1396
+ }
1397
+ });
1398
+ })
1399
+ .catch(err => callback({ error: `Error bot.getFileLink: ${err}` }));
1400
+ }
1401
+ getMessage(msg) {
1402
+ const date = new Date().toISOString().replace(/T/, '_').replace(/\..+/, '').replace(/:/g, '-');
1403
+ this.log.debug(`Received message: ${JSON.stringify(msg)}`);
1404
+ // Remember the chat/group so other adapters can pick it by id (issue #312).
1405
+ this.storeChat(msg.chat);
1406
+ // Media messages (photo, document, voice, ...) do not contain `msg.text`, so they are not handled
1407
+ // by `processTelegramText` (which is bound via `bot.onText`). As a result the request metadata
1408
+ // (chat id, message id, user id) would stay empty for received files. Populate it here so the
1409
+ // sender can be identified. See https://github.com/iobroker-community-adapters/ioBroker.telegram/issues/1043
1410
+ if (msg.voice ||
1411
+ msg.photo ||
1412
+ msg.video ||
1413
+ msg.video_note ||
1414
+ msg.audio ||
1415
+ msg.document ||
1416
+ msg.location ||
1417
+ msg.venue) {
1418
+ this.setStateSafe('communicate.requestChatId', { val: msg.chat.id, ack: true });
1419
+ this.setStateSafe('communicate.requestMessageId', { val: msg.message_id, ack: true });
1420
+ this.setStateSafe('communicate.requestMessageThreadId', {
1421
+ val: msg.is_topic_message ? msg.message_thread_id : 0,
1422
+ ack: true,
1423
+ });
1424
+ if (msg.from) {
1425
+ this.setStateSafe('communicate.requestUserId', { val: msg.from.id.toString(), ack: true });
1426
+ }
1427
+ }
1428
+ // A shared location (paperclip -> location) or a venue (location + title/address) carries a
1429
+ // latitude/longitude. Expose it as a "latitude;longitude" GPS string so it can be shown e.g. on a
1430
+ // vis/jarvis map. See https://github.com/iobroker-community-adapters/ioBroker.telegram/issues/853
1431
+ const location = msg.venue?.location || msg.location;
1432
+ if (location) {
1433
+ this.setStateSafe('communicate.requestLocation', {
1434
+ val: `${location.latitude};${location.longitude}`,
1435
+ ack: true,
1436
+ });
1437
+ }
1438
+ if (msg.voice) {
1439
+ try {
1440
+ this.saveFile(msg.voice.file_id, this.config.saveFiles ? `/voice/${date}.ogg` : '/voice/temp.ogg', res => {
1441
+ if (!res.error) {
1442
+ this.log.info(res.info);
1443
+ this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
1444
+ }
1445
+ else {
1446
+ this.log.debug(res.error);
1447
+ }
1448
+ });
1449
+ }
1450
+ catch (err) {
1451
+ this.log.error(`Error saving voice file: ${err}`);
1452
+ }
1453
+ }
1454
+ else if (this.config.saveFiles && msg.photo) {
1455
+ try {
1456
+ const qualityMap = {
1457
+ 0: 'low',
1458
+ 1: 'med',
1459
+ 2: 'high',
1460
+ 3: 'highdef',
1461
+ };
1462
+ let saveOnlyQuality = this.config.saveFilesQuality;
1463
+ if (saveOnlyQuality) {
1464
+ const saveOnlyQualityNum = parseInt(saveOnlyQuality, 10);
1465
+ if (msg.photo.length <= saveOnlyQualityNum) {
1466
+ saveOnlyQuality = null;
1467
+ }
1468
+ else {
1469
+ saveOnlyQuality = saveOnlyQualityNum.toString();
1470
+ }
1471
+ }
1472
+ msg.photo.forEach((item, i) => {
1473
+ // skip if quality is set and not equal
1474
+ if (saveOnlyQuality && i.toString() !== saveOnlyQuality) {
1475
+ return;
1476
+ }
1477
+ const quality = qualityMap[i] || 'none';
1478
+ let fileName = '';
1479
+ if (msg.media_group_id) {
1480
+ if (!Object.prototype.hasOwnProperty.call(this.mediaGroupExport, msg.media_group_id)) {
1481
+ const id = Object.keys(this.mediaGroupExport).length;
1482
+ this.mediaGroupExport[msg.media_group_id] = {
1483
+ id,
1484
+ count: 0,
1485
+ };
1486
+ }
1487
+ else {
1488
+ this.mediaGroupExport[msg.media_group_id].count++;
1489
+ }
1490
+ fileName = `/photo/${date}_grpID_${this.mediaGroupExport[msg.media_group_id].id}_${this.mediaGroupExport[msg.media_group_id].count}_${quality}.jpg`;
1491
+ }
1492
+ else {
1493
+ fileName = `/photo/${date}_${quality}.jpg`;
1494
+ if ((0, node_fs_1.existsSync)((0, node_path_1.join)(this.tmpDirName, fileName))) {
1495
+ let tIdx = 0;
1496
+ do {
1497
+ fileName = `/photo/${date}_${tIdx}_${quality}.jpg`;
1498
+ tIdx++;
1499
+ } while ((0, node_fs_1.existsSync)((0, node_path_1.join)(this.tmpDirName, fileName)));
1500
+ }
1501
+ }
1502
+ this.saveFile(item.file_id, fileName, res => {
1503
+ if (!res.error) {
1504
+ this.log.info(res.info);
1505
+ this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
1506
+ }
1507
+ else {
1508
+ this.log.debug(res.error);
1509
+ }
1510
+ });
1511
+ });
1512
+ }
1513
+ catch (err) {
1514
+ this.log.error(`Error saving photo file: ${err}`);
1515
+ }
1516
+ }
1517
+ else if (this.config.saveFiles && msg.video) {
1518
+ try {
1519
+ this.saveFile(msg.video.file_id, `/video/${date}.mp4`, res => {
1520
+ if (!res.error) {
1521
+ this.log.info(res.info);
1522
+ this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
1523
+ }
1524
+ else {
1525
+ this.log.debug(res.error);
1526
+ }
1527
+ });
1528
+ }
1529
+ catch (err) {
1530
+ this.log.error(`Error saving video file: ${err}`);
1531
+ }
1532
+ }
1533
+ else if (this.config.saveFiles && msg.video_note) {
1534
+ try {
1535
+ this.saveFile(msg.video_note.file_id, `/video/${date}.mp4`, res => {
1536
+ if (!res.error) {
1537
+ this.log.info(res.info);
1538
+ this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
1539
+ }
1540
+ else {
1541
+ this.log.debug(res.error);
1542
+ }
1543
+ });
1544
+ }
1545
+ catch (err) {
1546
+ this.log.error(`Error saving video file: ${err}`);
1547
+ }
1548
+ }
1549
+ else if (this.config.saveFiles && msg.audio) {
1550
+ try {
1551
+ this.saveFile(msg.audio.file_id, `/audio/${date}.mp3`, res => {
1552
+ if (!res.error) {
1553
+ this.log.info(res.info);
1554
+ this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
1555
+ }
1556
+ else {
1557
+ this.log.debug(res.error);
1558
+ }
1559
+ });
1560
+ }
1561
+ catch (err) {
1562
+ this.log.error(`Error saving audio file: ${err}`);
1563
+ }
1564
+ }
1565
+ else if (this.config.saveFiles && msg.document) {
1566
+ try {
1567
+ this.saveFile(msg.document.file_id, `/document/${msg.document.file_name}`, res => {
1568
+ if (!res.error) {
1569
+ this.log.info(res.info);
1570
+ this.setStateSafe('communicate.pathFile', { val: res.path, ack: true });
1571
+ }
1572
+ else {
1573
+ this.log.debug(res.error);
1574
+ }
1575
+ });
1576
+ }
1577
+ catch (err) {
1578
+ this.log.error(`Error saving document file: ${err}`);
1579
+ }
1580
+ }
1581
+ }
1582
+ async processMessage(obj) {
1583
+ if (!obj?.command) {
1584
+ return;
1585
+ }
1586
+ // Ignore own answers
1587
+ if (obj.message?.response) {
1588
+ return;
1589
+ }
1590
+ // filter out the double messages
1591
+ const json = JSON.stringify(obj);
1592
+ if (this.lastMessageTime && this.lastMessageText === json && Date.now() - this.lastMessageTime < 1200) {
1593
+ return this.log.debug(`Filter out double message [first was for ${Date.now() - this.lastMessageTime}ms]: ${json}`);
1594
+ }
1595
+ this.lastMessageTime = Date.now();
1596
+ this.lastMessageText = json;
1597
+ this.log.debug(`Received command "${obj.command}": ${JSON.stringify(obj.message)}`);
1598
+ switch (obj.command) {
1599
+ case 'send':
1600
+ if (obj.message) {
1601
+ let tPromise;
1602
+ if (typeof obj.message === 'object') {
1603
+ tPromise = this.sendMessage(obj.message.text, obj.message?.user, obj.message?.chatId, obj.message);
1604
+ }
1605
+ else {
1606
+ tPromise = this.sendMessage(obj.message);
1607
+ }
1608
+ tPromise
1609
+ .then(results => obj.callback && this.sendTo(obj.from, obj.command, results.length, obj.callback))
1610
+ .catch(e => this.log.error(`Cannot send command: ${e}`));
1611
+ }
1612
+ break;
1613
+ case 'ask':
1614
+ if (obj.message) {
1615
+ const question = {
1616
+ cb: obj.callback,
1617
+ from: obj.from,
1618
+ ts: Date.now(),
1619
+ };
1620
+ if (typeof obj.message === 'object') {
1621
+ const messages = await this.sendMessage(obj.message.text, obj.message.user, obj.message.chatId, obj.message);
1622
+ const msgIds = messages.length > 0 ? messages.map(m => JSON.parse(m))[0] : {};
1623
+ question.chatId = obj.message.chatId;
1624
+ question.user = obj.message.user;
1625
+ question.msgId = msgIds?.[String(question.chatId)];
1626
+ }
1627
+ else {
1628
+ await this.sendMessage(obj.message);
1629
+ }
1630
+ if (obj.callback) {
1631
+ this.questions.push(question);
1632
+ this.log.debug(`added question: ${JSON.stringify(question)} - answer timeout: ${this.config.answerTimeoutSec}`);
1633
+ question.timeout = this.setTimeout((q) => {
1634
+ q.timeout = null;
1635
+ this.sendTo(q.from, 'ask', '__timeout__', q.cb);
1636
+ this.log.info(`question timeout for: ${JSON.stringify(q)}`);
1637
+ // Remove keyboard
1638
+ if (this.bot && q?.chatId && q?.msgId) {
1639
+ // Catch the rejection: if the message was already deleted/edited or is too
1640
+ // old, telegram answers "message to edit not found". Without a catch this
1641
+ // rejection is unhandled and terminates the whole adapter. See
1642
+ // https://github.com/iobroker-community-adapters/ioBroker.telegram/issues/879
1643
+ this.bot
1644
+ .editMessageReplyMarkup({ inline_keyboard: [] }, {
1645
+ chat_id: q.chatId,
1646
+ message_id: q.msgId,
1647
+ })
1648
+ .then(() => this.log.debug(`removed inline_keyboard for msg ${q.msgId}: ${JSON.stringify(q)}`))
1649
+ .catch(error => this.log.warn(`Cannot remove inline_keyboard for msg ${q.msgId}: ${error}`));
1650
+ }
1651
+ const pos = this.questions.indexOf(q);
1652
+ pos !== -1 && this.questions.splice(pos, 1);
1653
+ }, this.config.answerTimeoutSec + 1000, question);
1654
+ }
1655
+ }
1656
+ break;
1657
+ case 'call':
1658
+ if (obj.message) {
1659
+ let call = {};
1660
+ if (typeof obj.message === 'object') {
1661
+ call = obj.message;
1662
+ }
1663
+ else {
1664
+ call.message = obj.message;
1665
+ }
1666
+ if (call.users && call.user) {
1667
+ this.log.error(`Please provide only user or users as array. Attribute user will be ignored!`);
1668
+ }
1669
+ if (!call.users && call.user) {
1670
+ call.users = [call.user];
1671
+ }
1672
+ if (!call.users && !call.user) {
1673
+ call.users = Object.keys(this.storedUsers)
1674
+ .filter(id => this.storedUsers[id] && this.storedUsers[id].userName)
1675
+ .map(id => this.storedUsers[id].userName.startsWith('@')
1676
+ ? this.storedUsers[id].userName
1677
+ : `@${this.storedUsers[id].userName}`);
1678
+ }
1679
+ if (!(call.users instanceof Array)) {
1680
+ call.users = [call.users];
1681
+ }
1682
+ // set language
1683
+ call.lang ||= systemLang2CallMe[this.systemLang] || systemLang2CallMe.en;
1684
+ if (!call.file) {
1685
+ // Set message
1686
+ call.message = call.message || call.text || adapter_core_1.I18n.translate('Call text');
1687
+ }
1688
+ else {
1689
+ call.message = '';
1690
+ }
1691
+ if (!call.users || !call.users.length) {
1692
+ this.log.error(`Cannot make a call, because no users stored in ${this.namespace}.communicate.users`);
1693
+ }
1694
+ else {
1695
+ this.callUsers(call.users, call.message, call.lang, call.file, call.repeats);
1696
+ }
1697
+ }
1698
+ break;
1699
+ }
1700
+ }
1701
+ callUsers(users, text, lang, file, repeats, cb) {
1702
+ if (!users || !users.length) {
1703
+ cb && cb();
1704
+ }
1705
+ else {
1706
+ let user = users.shift();
1707
+ if (!user.startsWith('@') && !user.startsWith('+') && !user.startsWith('00')) {
1708
+ user = `@${user}`;
1709
+ }
1710
+ let url = 'http://api.callmebot.com/start.php?source=iobroker&';
1711
+ const params = [`user=${encodeURIComponent(user)}`];
1712
+ if (file) {
1713
+ params.push(`file=${encodeURIComponent(file)}`);
1714
+ }
1715
+ else {
1716
+ params.push(`text=${encodeURIComponent(text)}`);
1717
+ }
1718
+ if (repeats !== undefined) {
1719
+ params.push(`rpt=${parseInt(String(repeats), 10) || 0}`);
1720
+ }
1721
+ params.push(`lang=${lang || systemLang2CallMe[this.systemLang]}`);
1722
+ url += params.join('&');
1723
+ this.log.debug(`CALL: ${url}`);
1724
+ axios_1.default
1725
+ .get(url)
1726
+ .then(response => {
1727
+ const body = response && response.data;
1728
+ if (!body || !response || response.status !== 200) {
1729
+ this.log.error(`Cannot make a call to ${user}: ${body || (response && response.status) || 'Unknown error'}`);
1730
+ }
1731
+ else {
1732
+ this.log.debug(`Call to ${user} was made: ${body.substring(body.indexOf('<p>')).replace(/<p>/g, ' ')}`);
1733
+ }
1734
+ setImmediate(() => this.callUsers(users, text, lang, file, repeats, cb));
1735
+ })
1736
+ .catch(err => {
1737
+ this.log.error(`Cannot make a call to ${user}: ${err || 'Unknown error'}`);
1738
+ setImmediate(() => this.callUsers(users, text, lang, file, repeats, cb));
1739
+ });
1740
+ }
1741
+ }
1742
+ storeUser(id, firstName, userName) {
1743
+ if (!this.storedUsers[id] ||
1744
+ this.storedUsers[id].firstName !== firstName ||
1745
+ this.storedUsers[id].userName !== userName) {
1746
+ Object.keys(this.storedUsers).forEach(uid => {
1747
+ if (userName && this.storedUsers[uid].userName === userName) {
1748
+ delete this.storedUsers[uid];
1749
+ }
1750
+ if (!userName && !this.storedUsers[uid].userName && this.storedUsers[uid].firstName === firstName) {
1751
+ delete this.storedUsers[uid];
1752
+ }
1753
+ });
1754
+ this.storedUsers[id] = { firstName, userName, sysMessages: false };
1755
+ if (this.config.rememberUsers) {
1756
+ this.setStateSafe('communicate.users', { val: JSON.stringify(this.storedUsers), ack: true });
1757
+ }
1758
+ }
1759
+ }
1760
+ /**
1761
+ * Remember a chat the bot has seen (private chat, group, supergroup or channel) in `communicate.chats`,
1762
+ * so other adapters can offer a chat/group picker (e.g. to address a group by id). See issue #312.
1763
+ *
1764
+ * @param chat the `msg.chat` object of a received message
1765
+ */
1766
+ storeChat(chat) {
1767
+ if (chat?.id == null) {
1768
+ return;
1769
+ }
1770
+ const id = String(chat.id);
1771
+ const title = chat.title || [chat.first_name, chat.last_name].filter(n => !!n).join(' ') || chat.username || id;
1772
+ const type = chat.type || 'private';
1773
+ if (!this.storedChats[id] || this.storedChats[id].title !== title || this.storedChats[id].type !== type) {
1774
+ this.storedChats[id] = { title, type };
1775
+ this.setStateSafe('communicate.chats', { val: JSON.stringify(this.storedChats), ack: true });
1776
+ }
1777
+ }
1778
+ getListOfCommands() {
1779
+ const ids = Object.keys(this.commands).sort((a, b) => this.commands[b].alias - this.commands[a].alias);
1780
+ const lines = [];
1781
+ ids.forEach(id => {
1782
+ if (!this.commands[id].readOnly) {
1783
+ if (this.commands[id].type === 'boolean') {
1784
+ if (this.commands[id].writeOnly) {
1785
+ lines.push(`${this.commands[id].alias} ${this.commands[id].onCommand || adapter_core_1.I18n.translate('ON-Command')}|${this.commands[id].offCommand || adapter_core_1.I18n.translate('OFF-Command')}`);
1786
+ }
1787
+ else {
1788
+ lines.push(`${this.commands[id].alias} ${this.commands[id].onCommand || adapter_core_1.I18n.translate('ON-Command')}|${this.commands[id].offCommand || adapter_core_1.I18n.translate('OFF-Command')}|?`);
1789
+ }
1790
+ }
1791
+ else {
1792
+ if (this.commands[id].writeOnly) {
1793
+ lines.push(`${this.commands[id].alias} ${adapter_core_1.I18n.translate(`value as ${this.commands[id].type}`)}`);
1794
+ }
1795
+ else {
1796
+ lines.push(`${this.commands[id].alias} ${adapter_core_1.I18n.translate(`value as ${this.commands[id].type}`)}|?`);
1797
+ }
1798
+ }
1799
+ }
1800
+ });
1801
+ if (!lines.length) {
1802
+ lines.push(adapter_core_1.I18n.translate('No commands found.'));
1803
+ }
1804
+ return lines.join('\n');
1805
+ }
1806
+ getCommandsKeyboard(chatId) {
1807
+ const ids = Object.keys(this.commands).sort((a, b) => this.commands[b].alias - this.commands[a].alias);
1808
+ const keyboard = [];
1809
+ ids.forEach(id => {
1810
+ const cmd = this.commands[id];
1811
+ if (!cmd.readOnly) {
1812
+ if (cmd.type === 'boolean') {
1813
+ if (cmd.onlyTrue) {
1814
+ if (cmd.buttons === 1) {
1815
+ keyboard.push([`${cmd.alias} ${cmd.onCommand || adapter_core_1.I18n.translate('ON-Command')}`]);
1816
+ !cmd.writeOnly && keyboard.push([`${cmd.alias} ?`]);
1817
+ }
1818
+ else {
1819
+ cmd.writeOnly
1820
+ ? keyboard.push([`${cmd.alias} ${cmd.onCommand || adapter_core_1.I18n.translate('ON-Command')}`])
1821
+ : keyboard.push([
1822
+ `${cmd.alias} ${cmd.onCommand || adapter_core_1.I18n.translate('ON-Command')}`,
1823
+ `${cmd.alias} ?`,
1824
+ ]);
1825
+ }
1826
+ }
1827
+ else {
1828
+ if (cmd.buttons === 1) {
1829
+ keyboard.push([`${cmd.alias} ${cmd.onCommand || adapter_core_1.I18n.translate('ON-Command')}`]);
1830
+ keyboard.push([`${cmd.alias} ${cmd.offCommand || adapter_core_1.I18n.translate('OFF-Command')}`]);
1831
+ !cmd.writeOnly && keyboard.push([`${cmd.alias} ?`]);
1832
+ }
1833
+ else if (cmd.buttons === 2) {
1834
+ keyboard.push([
1835
+ `${cmd.alias} ${cmd.onCommand || adapter_core_1.I18n.translate('ON-Command')}`,
1836
+ `${cmd.alias} ${cmd.offCommand || adapter_core_1.I18n.translate('OFF-Command')}`,
1837
+ ]);
1838
+ !cmd.writeOnly && keyboard.push([`${cmd.alias} ?`]);
1839
+ }
1840
+ else {
1841
+ cmd.writeOnly
1842
+ ? keyboard.push([
1843
+ `${cmd.alias} ${cmd.onCommand || adapter_core_1.I18n.translate('ON-Command')}`,
1844
+ `${cmd.alias} ${cmd.offCommand || adapter_core_1.I18n.translate('OFF-Command')}`,
1845
+ ])
1846
+ : keyboard.push([
1847
+ `${cmd.alias} ${cmd.onCommand || adapter_core_1.I18n.translate('ON-Command')}`,
1848
+ `${cmd.alias} ${cmd.offCommand || adapter_core_1.I18n.translate('OFF-Command')}`,
1849
+ `${cmd.alias} ?`,
1850
+ ]);
1851
+ }
1852
+ }
1853
+ }
1854
+ else if (cmd.states) {
1855
+ let s = [];
1856
+ const stat = Object.keys(cmd.states);
1857
+ for (let i = 0; i < stat.length; i++) {
1858
+ s.push(`${cmd.alias} ${cmd.states[stat[i]]}`);
1859
+ if (s.length >= (cmd.buttons || 3)) {
1860
+ keyboard.push(s);
1861
+ s = [];
1862
+ }
1863
+ }
1864
+ !cmd.writeOnly && s.push(`${cmd.alias} ?`);
1865
+ keyboard.push(s);
1866
+ }
1867
+ else if (cmd.type === 'number' && cmd.unit === '%') {
1868
+ let s = [];
1869
+ const step = ((cmd.max || 100) - (cmd.min || 0)) / 4;
1870
+ for (let i = cmd.min || 0; i <= (cmd.max || 100); i += step) {
1871
+ s.push(`${cmd.alias} ${i}%`);
1872
+ if (s.length >= (cmd.buttons || 3)) {
1873
+ keyboard.push(s);
1874
+ s = [];
1875
+ }
1876
+ }
1877
+ !cmd.writeOnly && s.push(`${cmd.alias} ?`);
1878
+ keyboard.push(s);
1879
+ }
1880
+ else {
1881
+ this.log.warn(`Unsupported state type for keyboard: ${cmd.type}. Only numbers and booleans are supported`);
1882
+ }
1883
+ }
1884
+ else {
1885
+ keyboard.push([`${cmd.alias} ?`]);
1886
+ }
1887
+ });
1888
+ this.bot.sendMessage(chatId, adapter_core_1.I18n.translate('Select option'), {
1889
+ reply_markup: {
1890
+ keyboard: keyboard.map(row => row.map(text => ({ text }))),
1891
+ resize_keyboard: true,
1892
+ one_time_keyboard: true,
1893
+ },
1894
+ })
1895
+ .then(() => {
1896
+ this.log.debug('Message sent');
1897
+ })
1898
+ .catch(error => {
1899
+ this.log.error(`Send message error: ${error}`);
1900
+ });
1901
+ }
1902
+ isAnswerForQuestion(msg) {
1903
+ if (this.questions?.length) {
1904
+ const now = Date.now();
1905
+ const chatId = 'chat' in msg ? msg.chat?.id : undefined;
1906
+ const fromId = msg.from?.id;
1907
+ let question = chatId &&
1908
+ this.questions.find(q => q.chatId === chatId && q.user === fromId && now - q.ts < this.config.answerTimeoutSec);
1909
+ question ||=
1910
+ chatId && this.questions.find(q => q.chatId === chatId && now - q.ts < this.config.answerTimeoutSec);
1911
+ question ||= this.questions.find(q => now - q.ts < this.config.answerTimeoutSec);
1912
+ // user have 60 seconds for answer
1913
+ if (question && Date.now() - question.ts < this.config.answerTimeoutSec) {
1914
+ if (question.timeout) {
1915
+ this.clearTimeout(question.timeout);
1916
+ question.timeout = null;
1917
+ this.sendTo(question.from, 'ask', msg, question.cb);
1918
+ // Remove the inline keyboard. For a broadcast question `question.chatId`/`msgId` are
1919
+ // empty (the question was not tied to a single chat), so prefer the chat/message the
1920
+ // button was actually pressed on - it is carried by the incoming CallbackQuery. Fall back
1921
+ // to the stored question for text-message answers.
1922
+ const callbackMessage = 'data' in msg ? msg.message : undefined;
1923
+ const answeredChatId = callbackMessage?.chat.id ?? question.chatId;
1924
+ const answeredMsgId = callbackMessage?.message_id ?? question.msgId;
1925
+ if (this.bot && answeredChatId && answeredMsgId) {
1926
+ // Catch the rejection: if the message was already deleted/edited or is too old,
1927
+ // telegram answers "message to edit not found". Without a catch this rejection is
1928
+ // unhandled and terminates the whole adapter. See
1929
+ // https://github.com/iobroker-community-adapters/ioBroker.telegram/issues/879
1930
+ this.bot
1931
+ .editMessageReplyMarkup({ inline_keyboard: [] }, {
1932
+ chat_id: answeredChatId,
1933
+ message_id: answeredMsgId,
1934
+ })
1935
+ .then(() => this.log.debug(`removed inline_keyboard for msg ${answeredMsgId}`))
1936
+ .catch(error => this.log.warn(`Cannot remove inline_keyboard for msg ${answeredMsgId}: ${error}`));
1937
+ }
1938
+ }
1939
+ this.questions.splice(this.questions.indexOf(question), 1);
1940
+ }
1941
+ // remove old questions
1942
+ this.questions = this.questions.filter(q => now - q.ts < this.config.answerTimeoutSec);
1943
+ }
1944
+ }
1945
+ garbageCollector() {
1946
+ const now = Date.now() - 5 * 60000; // last 5 minutes
1947
+ Object.keys(this.protection).forEach(user => {
1948
+ let a;
1949
+ for (a = 0; a < this.protection[user].length; a++) {
1950
+ // find first entry newer than 5 minutes
1951
+ if (this.protection[user][a] > now) {
1952
+ break;
1953
+ }
1954
+ }
1955
+ // remove all old entries
1956
+ if (a < this.protection[user].length && a) {
1957
+ this.protection[user].splice(0, a);
1958
+ }
1959
+ if (!this.protection[user].length) {
1960
+ delete this.protection[user];
1961
+ }
1962
+ });
1963
+ if (!Object.keys(this.protection).length) {
1964
+ this.gcInterval && this.clearInterval(this.gcInterval);
1965
+ this.gcInterval = undefined;
1966
+ }
1967
+ }
1968
+ /**
1969
+ * Forward a message to another instance, but only if that instance is currently alive. If the
1970
+ * target is not running, `sendTo` would queue the message unanswered and the callback would never
1971
+ * fire, so we skip it (and log) instead.
1972
+ *
1973
+ * @param instance target instance id, e.g. `assistant.0`
1974
+ * @param command the `sendTo` command
1975
+ * @param message the payload to forward
1976
+ */
1977
+ async sendToIfAlive(instance, command, message) {
1978
+ try {
1979
+ const aliveState = await this.getForeignStateAsync(`system.adapter.${instance}.alive`);
1980
+ if (!aliveState?.val) {
1981
+ this.log.warn(`Cannot forward message to "${instance}": instance is not running`);
1982
+ return;
1983
+ }
1984
+ }
1985
+ catch (err) {
1986
+ this.log.warn(`Cannot check if "${instance}" is alive: ${err instanceof Error ? err.message : err}`);
1987
+ return;
1988
+ }
1989
+ return await this.sendToAsync(instance, command, message);
1990
+ }
1991
+ async processTelegramText(msg) {
1992
+ this.connectionState(true);
1993
+ const bot = this.bot;
1994
+ const from = msg.from;
1995
+ let msgText = msg.text ?? '';
1996
+ // see https://core.telegram.org/bots/api#message
1997
+ this.log.debug(JSON.stringify(msg));
1998
+ const user = !this.config.useUsername ? from.first_name : !from.username ? from.first_name : from.username;
1999
+ const now = Date.now();
2000
+ let pollingInterval = 0;
2001
+ if (this.config && this.config.pollingInterval !== undefined) {
2002
+ pollingInterval = parseInt(String(this.config.pollingInterval), 10) || 0;
2003
+ }
2004
+ // ignore all messages older than 30 seconds + polling interval
2005
+ if (now - msg.date * 1000 > pollingInterval + 30000) {
2006
+ this.log.warn(`Message from ${from.first_name} ignored, because too old: (${pollingInterval + 30000}) ${msgText}`);
2007
+ return bot
2008
+ .sendMessage(from.id, adapter_core_1.I18n.translate('Message ignored: ') + msgText)
2009
+ .catch(error => this.log.error(`send Message Error: ${error}`));
2010
+ }
2011
+ msgText = (msgText || '').trim();
2012
+ // sometimes telegram sends messages like "message@user_name"
2013
+ const pos = msgText.lastIndexOf('@');
2014
+ if (pos !== -1) {
2015
+ msgText = msgText.substring(0, pos);
2016
+ }
2017
+ if (msgText === '/password' && !this.config.doNotAcceptNewUser) {
2018
+ return bot
2019
+ .sendMessage(from.id, adapter_core_1.I18n.translate('Please enter password in form "/password phrase"'))
2020
+ .catch(error => this.log.error(`send Message Error:${error}`));
2021
+ }
2022
+ if (this.config.password && !this.config.doNotAcceptNewUsers) {
2023
+ // if user sent password
2024
+ let m = msgText.match(/^\/password (.+)$/);
2025
+ m ||= msgText.match(/^\/p (.+)$/);
2026
+ if (m) {
2027
+ this.garbageCollector();
2028
+ if (this.protection[user] && this.protection[user].length >= 5) {
2029
+ return bot
2030
+ .sendMessage(from.id, `${adapter_core_1.I18n.translate('Too many attempts. Blocked for')} ${Math.round((now - this.protection[user][this.protection[user].length - 1]) / 1000)} ${adapter_core_1.I18n.translate('seconds')}`)
2031
+ .catch(error => this.log.error(`send Message Error: ${error}`));
2032
+ }
2033
+ if (this.config.password === m[1]) {
2034
+ if (this.protection[user]) {
2035
+ delete this.protection[user];
2036
+ }
2037
+ this.storeUser(from.id, from.first_name, from.username ?? '');
2038
+ if (!from.username) {
2039
+ this.log.warn(`User ${from.first_name} hast not set an username in the Telegram App!!`);
2040
+ }
2041
+ // delete the message that contains the password, so the passphrase is not left in the chat
2042
+ await bot
2043
+ .deleteMessage(msg.chat.id, msg.message_id)
2044
+ .catch(error => this.log.warn(`Cannot delete password message: ${error}`));
2045
+ return bot
2046
+ .sendMessage(from.id, adapter_core_1.I18n.translate('Welcome ') + user)
2047
+ .catch(error => this.log.error(`send Message Error: ${error}`));
2048
+ }
2049
+ this.protection[user] ||= [];
2050
+ this.protection[user].push(Date.now());
2051
+ this.gcInterval ||= this.setInterval(() => this.garbageCollector(), 60000);
2052
+ this.log.warn(`Got invalid password from ${user}: ${m[1]}`);
2053
+ bot.sendMessage(from.id, adapter_core_1.I18n.translate('Invalid password')).catch(error => this.log.error(`send Message Error: ${error}`));
2054
+ if (this.storedUsers[from.id]) {
2055
+ delete this.storedUsers[from.id];
2056
+ }
2057
+ }
2058
+ }
2059
+ // todo support commands: instances, running, restart
2060
+ // If a user is not in the trusted list
2061
+ if ((this.config.password || this.config.doNotAcceptNewUsers) && !this.storedUsers[from.id]) {
2062
+ return bot
2063
+ .sendMessage(from.id, adapter_core_1.I18n.translate(this.config.doNotAcceptNewUsers
2064
+ ? 'User is not in the list'
2065
+ : 'Please enter password in form "/password phrase"'))
2066
+ .catch(error => this.log.error(`send Message Error: ${error}`));
2067
+ }
2068
+ if (msgText === '/help') {
2069
+ return bot
2070
+ .sendMessage(from.id, this.getListOfCommands())
2071
+ .catch(error => this.log.error(`send Message Error: ${error}`));
2072
+ }
2073
+ this.isAnswerForQuestion(msg);
2074
+ if (msgText === this.config.keyboard || msgText === '/commands') {
2075
+ this.log.debug('Response keyboard');
2076
+ if (this.config.rooms) {
2077
+ this.getCommandsKeyboard(msg.chat.id);
2078
+ //getRoomsKeyboard(msg.chat.id)
2079
+ }
2080
+ else {
2081
+ this.getCommandsKeyboard(msg.chat.id);
2082
+ }
2083
+ return;
2084
+ }
2085
+ if (this.config.rooms) {
2086
+ // detect if some room is selected
2087
+ }
2088
+ // Search all user's states and try to detect something like "device-alias on"
2089
+ let found = false;
2090
+ for (const id in this.commands) {
2091
+ if (Object.prototype.hasOwnProperty.call(this.commands, id)) {
2092
+ if (msgText.startsWith(`${this.commands[id].alias} `)) {
2093
+ let sValue = msgText.substring(this.commands[id].alias.length + 1);
2094
+ found = true;
2095
+ if (sValue === '?') {
2096
+ const state = await this.getForeignStateAsync(id);
2097
+ bot.sendMessage(msg.chat.id, this.getStatus(id, state)).catch(error => this.log.error(`send Message Error: ${error}`));
2098
+ }
2099
+ else {
2100
+ let value;
2101
+ if (this.commands[id].states) {
2102
+ const sState = Object.keys(this.commands[id].states).find(val => this.commands[id].states[val] === sValue);
2103
+ if (sState !== null && sState !== undefined) {
2104
+ sValue = sState;
2105
+ }
2106
+ }
2107
+ if (this.commands[id].type === 'boolean') {
2108
+ value = this.commands[id].onCommand
2109
+ ? sValue === this.commands[id].onCommand
2110
+ : sValue === adapter_core_1.I18n.translate('ON-Command') ||
2111
+ sValue === 'true' ||
2112
+ sValue.toLowerCase() === 'on' ||
2113
+ sValue === '1';
2114
+ }
2115
+ else if (this.commands[id].type === 'number') {
2116
+ sValue = sValue.replace('%', '').trim();
2117
+ value = parseFloat(sValue);
2118
+ if (sValue !== value.toString()) {
2119
+ bot.sendMessage(msg.chat.id, adapter_core_1.I18n.translate('Invalid number %s', sValue)).catch(error => this.log.error(`send Message Error: ${error}`));
2120
+ continue;
2121
+ }
2122
+ }
2123
+ else {
2124
+ value = sValue;
2125
+ }
2126
+ this.setForeignStateAsync(id, value, false, () => bot
2127
+ .sendMessage(msg.chat.id, adapter_core_1.I18n.translate('Done'))
2128
+ .catch(error => this.log.error(`send Message Error: ${error}`)))?.catch(error => this.log.error(`setForeignState Error: ${error}`));
2129
+ }
2130
+ }
2131
+ }
2132
+ }
2133
+ if (found) {
2134
+ return;
2135
+ }
2136
+ this.storeUser(from.id, from.first_name, from.username ?? '');
2137
+ if (!from.username) {
2138
+ this.log.warn(`User ${from.first_name} hast not set an username in the Telegram App!!`);
2139
+ }
2140
+ if (this.config.allowStates) {
2141
+ // Check set state
2142
+ let m = msgText.match(/^\/state (.+) (.+)$/);
2143
+ if (m) {
2144
+ let id1 = m[1];
2145
+ let val1 = m[2];
2146
+ let currentMsg = msg;
2147
+ // clear by timeout id
2148
+ let memoryLeak1 = this.setTimeout(() => {
2149
+ currentMsg = null;
2150
+ memoryLeak1 = undefined;
2151
+ id1 = null;
2152
+ val1 = null;
2153
+ }, 1000);
2154
+ let state = null;
2155
+ try {
2156
+ state = await this.getForeignStateAsync(id1);
2157
+ }
2158
+ catch (err) {
2159
+ bot.sendMessage(from.id, err.message).catch(error => this.log.error(`send Message Error: ${error}`));
2160
+ }
2161
+ if (memoryLeak1) {
2162
+ this.clearTimeout(memoryLeak1);
2163
+ memoryLeak1 = undefined;
2164
+ m = null;
2165
+ }
2166
+ if (currentMsg) {
2167
+ if (state) {
2168
+ try {
2169
+ await this.setForeignStateAsync(id1, val1, false);
2170
+ if (currentMsg) {
2171
+ bot.sendMessage(from.id, adapter_core_1.I18n.translate('Done')).catch(error => this.log.error(`send Message Error: ${error}`));
2172
+ }
2173
+ }
2174
+ catch (err) {
2175
+ if (currentMsg) {
2176
+ bot.sendMessage(from.id, err.message).catch(error => this.log.error(`send Message Error: ${error}`));
2177
+ }
2178
+ }
2179
+ }
2180
+ else {
2181
+ try {
2182
+ await bot.sendMessage(from.id, adapter_core_1.I18n.translate('ID "%s" not found.', id1));
2183
+ }
2184
+ catch (err) {
2185
+ this.log.error(`send Message Error: ${err}`);
2186
+ }
2187
+ }
2188
+ }
2189
+ return;
2190
+ }
2191
+ // Check get state
2192
+ m = msgText.match(/^\/state (.+)$/);
2193
+ if (m) {
2194
+ let id2 = m[1];
2195
+ let currentMsg = msg;
2196
+ // clear by timeout id
2197
+ let memoryLeak2 = this.setTimeout(() => {
2198
+ id2 = null;
2199
+ currentMsg = null;
2200
+ memoryLeak2 = undefined;
2201
+ }, 1000);
2202
+ let state = null;
2203
+ try {
2204
+ state = await this.getForeignStateAsync(id2);
2205
+ }
2206
+ catch (err) {
2207
+ if (currentMsg) {
2208
+ bot.sendMessage(from.id, err.message).catch(error => this.log.error(`send Message Error: ${error}`));
2209
+ }
2210
+ }
2211
+ if (memoryLeak2) {
2212
+ this.clearTimeout(memoryLeak2);
2213
+ memoryLeak2 = undefined;
2214
+ m = null;
2215
+ }
2216
+ if (currentMsg) {
2217
+ if (state) {
2218
+ try {
2219
+ await bot.sendMessage(from.id, String(state.val));
2220
+ }
2221
+ catch (error) {
2222
+ this.log.error(`send Message Error: ${error}`);
2223
+ }
2224
+ }
2225
+ else {
2226
+ try {
2227
+ await bot.sendMessage(from.id, adapter_core_1.I18n.translate('ID "%s" not found.', id2));
2228
+ }
2229
+ catch (error) {
2230
+ this.log.error(`send Message Error: ${error}`);
2231
+ }
2232
+ }
2233
+ }
2234
+ return;
2235
+ }
2236
+ }
2237
+ this.log.debug(`Got message from ${user}: ${msgText}`);
2238
+ // Send to text2command
2239
+ if (this.config.text2command) {
2240
+ this.sendToIfAlive(this.config.text2command, 'send', {
2241
+ text: msgText.replace(/\//g, '#').replace(/_/g, ' '),
2242
+ id: msg.chat.id,
2243
+ user,
2244
+ })
2245
+ // @ts-expect-error types fixed in js-controller
2246
+ .then((response) => {
2247
+ if (response?.response) {
2248
+ let text = response.response;
2249
+ let options;
2250
+ if (text && typeof text === 'string') {
2251
+ if (text.startsWith('<MarkdownV2>') && text.endsWith('</MarkdownV2>')) {
2252
+ options = { parse_mode: 'MarkdownV2' };
2253
+ text = text.substring(12, text.length - 13);
2254
+ }
2255
+ else if (text.startsWith('<HTML>') && text.endsWith('</HTML>')) {
2256
+ options = { parse_mode: 'HTML' };
2257
+ text = text.substring(6, text.length - 7);
2258
+ }
2259
+ else if (text.startsWith('<Markdown>') && text.endsWith('</Markdown>')) {
2260
+ options = { parse_mode: 'Markdown' };
2261
+ text = text.substring(10, text.length - 11);
2262
+ }
2263
+ }
2264
+ this.log.debug(`Send response: ${text}`);
2265
+ bot.sendMessage(response.id, text, options).catch(error => this.log.error(`send Message Error: ${error}`));
2266
+ }
2267
+ })
2268
+ .catch(err => this.log.error(`Cannot send message to ${this.config.text2command}: ${err}`));
2269
+ }
2270
+ // Forward messages that no internal rule/command matched to the ioBroker.assistant instance and
2271
+ // reply with its answer. The reply is routed via this closure (msg.chat.id), so the answer always
2272
+ // goes back to the right chat/thread.
2273
+ if (this.config.assistantInstance) {
2274
+ this.sendToIfAlive(this.config.assistantInstance, 'ask', {
2275
+ text: msgText,
2276
+ source: `telegram:${user}`,
2277
+ user,
2278
+ chatId: msg.chat.id,
2279
+ userId: from.id.toString(),
2280
+ messageThreadId: msg.is_topic_message ? msg.message_thread_id : 0,
2281
+ })
2282
+ // @ts-expect-error types fixed in js-controller
2283
+ .then((response) => {
2284
+ const text = response && (response.answer || response.error);
2285
+ if (text) {
2286
+ this.log.debug(`Assistant response: ${text}`);
2287
+ const options = msg.is_topic_message ? { message_thread_id: msg.message_thread_id } : undefined;
2288
+ bot.sendMessage(msg.chat.id, text, options).catch(error => this.log.error(`send Message Error: ${error}`));
2289
+ }
2290
+ })
2291
+ .catch(err => this.log.error(`Cannot send message to ${this.config.assistantInstance}: ${err}`));
2292
+ }
2293
+ this.setStateSafe('communicate.requestChatId', { val: msg.chat.id, ack: true });
2294
+ this.setStateSafe('communicate.requestMessageId', { val: msg.message_id, ack: true });
2295
+ this.setStateSafe('communicate.requestMessageThreadId', {
2296
+ val: msg.is_topic_message ? msg.message_thread_id : 0,
2297
+ ack: true,
2298
+ });
2299
+ this.setStateSafe('communicate.requestUserId', {
2300
+ val: from.id.toString(),
2301
+ ack: true,
2302
+ });
2303
+ this.setStateSafe('communicate.request', { val: `[${user}]${msgText}`, ack: true });
2304
+ }
2305
+ connect() {
2306
+ if (this.bot) {
2307
+ const bot = this.bot;
2308
+ if (!this.isServer) {
2309
+ try {
2310
+ if (bot.isPolling()) {
2311
+ this.log.debug('bot polling OK');
2312
+ }
2313
+ else {
2314
+ this.log.debug('bot restarting...');
2315
+ bot.stopPolling().then(() => {
2316
+ this.log.debug('Start Polling');
2317
+ bot.startPolling().catch(error => this.log.error(`Error start polling: ${error}`));
2318
+ }, error => {
2319
+ this.log.error(`Error stop polling: ${error}`);
2320
+ });
2321
+ }
2322
+ }
2323
+ catch {
2324
+ // looks empty
2325
+ }
2326
+ }
2327
+ // Check connection
2328
+ bot.getMe()
2329
+ .then(data => {
2330
+ this.log.debug(`getMe (reconnect): ${JSON.stringify(data)}`);
2331
+ this.connectionState(true);
2332
+ })
2333
+ .catch(error => this.log.error(`getMe (reconnect) Error:${error}`));
2334
+ }
2335
+ else {
2336
+ if (this.isServer) {
2337
+ // Setup server way
2338
+ const serverOptions = {
2339
+ polling: false,
2340
+ filepath: true,
2341
+ baseApiUrl: this.config.baseApiUrl,
2342
+ };
2343
+ this.bot = new node_telegram_bot_api_1.default(this.config.token, serverOptions);
2344
+ if (this.config.url[this.config.url.length - 1] === '/') {
2345
+ this.config.url = this.config.url.substring(0, this.config.url.length - 1);
2346
+ }
2347
+ this.bot
2348
+ .setWebhook(`${this.config.url}/${this.config.token}`)
2349
+ .catch(error => this.log.error(`setWebhook Error: ${error}`));
2350
+ }
2351
+ else {
2352
+ // Setup polling way
2353
+ const pollingOptions = {
2354
+ polling: {
2355
+ interval: parseInt(String(this.config.pollingInterval), 10) || 300,
2356
+ },
2357
+ filepath: true,
2358
+ baseApiUrl: this.config.baseApiUrl,
2359
+ };
2360
+ this.log.debug(`Start polling with: ${pollingOptions.polling.interval}(${typeof pollingOptions.polling.interval}) ms interval`);
2361
+ this.bot = new node_telegram_bot_api_1.default(this.config.token, pollingOptions);
2362
+ this.bot.setWebhook('').catch(error => {
2363
+ this.log.error(`setWebhook Error:${error}`);
2364
+ });
2365
+ }
2366
+ const bot = this.bot;
2367
+ // Check connection
2368
+ bot.getMe()
2369
+ .then(data => {
2370
+ this.log.debug(`getMe: ${JSON.stringify(data)}`);
2371
+ this.connectionState(true);
2372
+ if (this.config.restarted !== '') {
2373
+ // default text
2374
+ if (this.config.restarted === '_' ||
2375
+ this.config.restarted === null ||
2376
+ this.config.restarted === undefined) {
2377
+ this.sendSystemMessage(adapter_core_1.I18n.translate('Started!')).catch(err => this.log.error(err));
2378
+ }
2379
+ else {
2380
+ this.sendSystemMessage(this.config.restarted).catch(err => this.log.error(err));
2381
+ }
2382
+ }
2383
+ })
2384
+ .catch(error => {
2385
+ this.log.error(`getMe Error:${error}`);
2386
+ this.connectionState(false);
2387
+ });
2388
+ // Matches /echo [whatever]
2389
+ bot.onText(/(.+)/, msg => this.processTelegramText(msg));
2390
+ bot.on('message', msg => {
2391
+ this.connectionState(true);
2392
+ if (this.config.storeRawRequest) {
2393
+ this.setStateSafe('communicate.requestRaw', { val: JSON.stringify(msg, null, 2), ack: true });
2394
+ }
2395
+ this.getMessage(msg);
2396
+ // Media messages (photo, video, document, ...) carry their text in `msg.caption`, not in
2397
+ // `msg.text`, so `bot.onText` never fires for them and the caption would be lost. Route the
2398
+ // caption through the same text pipeline (auth check, command handling, communicate.request)
2399
+ // by treating it as the message text.
2400
+ if (!msg.text && msg.caption) {
2401
+ void this.processTelegramText({ ...msg, text: msg.caption });
2402
+ }
2403
+ });
2404
+ // Channel posts (in a channel where the bot is an admin) are delivered as a separate event, not
2405
+ // as `message`, so they were ignored before. They are anonymous (no `msg.from`), therefore the
2406
+ // auth/command pipeline cannot run; instead expose the post text and metadata so scripts can
2407
+ // react. See https://github.com/iobroker-community-adapters/ioBroker.telegram/issues/289
2408
+ bot.on('channel_post', msg => {
2409
+ this.connectionState(true);
2410
+ if (this.config.storeRawRequest) {
2411
+ this.setStateSafe('communicate.requestRaw', { val: JSON.stringify(msg, null, 2), ack: true });
2412
+ }
2413
+ // stores the channel in communicate.chats and handles/saves any attached media
2414
+ this.getMessage(msg);
2415
+ const text = msg.text ?? msg.caption;
2416
+ if (text !== undefined) {
2417
+ const name = msg.chat.title || String(msg.chat.id);
2418
+ this.setStateSafe('communicate.requestChatId', { val: msg.chat.id, ack: true });
2419
+ this.setStateSafe('communicate.requestMessageId', { val: msg.message_id, ack: true });
2420
+ this.setStateSafe('communicate.requestMessageThreadId', {
2421
+ val: msg.is_topic_message ? msg.message_thread_id : 0,
2422
+ ack: true,
2423
+ });
2424
+ this.setStateSafe('communicate.request', { val: `[${name}]${text}`, ack: true });
2425
+ }
2426
+ });
2427
+ // callback InlineKeyboardButton
2428
+ bot.on('callback_query', (callbackQuery) => {
2429
+ this.connectionState(true);
2430
+ // write received answer into variable
2431
+ this.log.debug(`callback_query: ${JSON.stringify(callbackQuery)}`);
2432
+ this.callbackQueryId[callbackQuery.from.id] = { id: callbackQuery.id, ts: Date.now() };
2433
+ if (this.config.storeRawRequest) {
2434
+ this.setStateSafe('communicate.requestRaw', { val: JSON.stringify(callbackQuery), ack: true });
2435
+ }
2436
+ this.setStateSafe('communicate.requestMessageId', {
2437
+ val: callbackQuery.message.message_id,
2438
+ ack: true,
2439
+ });
2440
+ this.setStateSafe('communicate.requestChatId', { val: callbackQuery.message.chat.id, ack: true });
2441
+ this.setStateSafe('communicate.request', {
2442
+ val: `[${!this.config.useUsername
2443
+ ? callbackQuery.from.first_name
2444
+ : !callbackQuery.from.username
2445
+ ? callbackQuery.from.first_name
2446
+ : callbackQuery.from.username}]${callbackQuery.data}`,
2447
+ ack: true,
2448
+ });
2449
+ this.isAnswerForQuestion(callbackQuery);
2450
+ });
2451
+ bot.on('polling_error', (error) => {
2452
+ if (this.isConnected) {
2453
+ this.log.warn(`polling_error: ${error.code}, ${error.message.replace(/<[^>]+>/g, '')}`); // => 'EFATAL'
2454
+ this.connectionState(false);
2455
+ }
2456
+ });
2457
+ bot.on('webhook_error', (error) => {
2458
+ this.log.error(`webhook_error:${error.code}, ${error.message.replace(/<[^>]+>/g, '')}`); // => 'EPARSE'
2459
+ this.log.debug('bot restarting...');
2460
+ bot.stopPolling().then(() => {
2461
+ this.log.debug('Start Polling');
2462
+ void bot.startPolling();
2463
+ }, error => {
2464
+ this.log.error(`Error stop polling: ${error}`);
2465
+ });
2466
+ });
2467
+ }
2468
+ }
2469
+ async updateUsers() {
2470
+ if (this.config.rememberUsers) {
2471
+ try {
2472
+ const state = await this.getStateAsync('communicate.users');
2473
+ if (state?.val) {
2474
+ try {
2475
+ this.storedUsers = JSON.parse(state.val);
2476
+ // convert old format to new format
2477
+ Object.keys(this.storedUsers).forEach(id => {
2478
+ if (typeof this.storedUsers[id] !== 'object') {
2479
+ if (this.config.useUsername) {
2480
+ this.storedUsers[id] = {
2481
+ userName: this.storedUsers[id],
2482
+ firstName: this.storedUsers[id],
2483
+ sysMessages: this.storedUsers[id]
2484
+ .sysMessages !== false,
2485
+ };
2486
+ }
2487
+ else {
2488
+ this.storedUsers[id] = {
2489
+ firstName: this.storedUsers[id],
2490
+ userName: '',
2491
+ sysMessages: this.storedUsers[id]
2492
+ .sysMessages !== false,
2493
+ };
2494
+ }
2495
+ }
2496
+ });
2497
+ }
2498
+ catch (err) {
2499
+ if (err) {
2500
+ this.log.error(err);
2501
+ }
2502
+ this.log.error('Cannot parse stored user IDs!');
2503
+ }
2504
+ }
2505
+ }
2506
+ catch (err) {
2507
+ this.log.error(err);
2508
+ }
2509
+ }
2510
+ }
2511
+ /** Restore the list of known chats/groups from `communicate.chats` on startup. See issue #312. */
2512
+ async updateChats() {
2513
+ try {
2514
+ const state = await this.getStateAsync('communicate.chats');
2515
+ if (state?.val) {
2516
+ try {
2517
+ this.storedChats = JSON.parse(state.val);
2518
+ }
2519
+ catch (err) {
2520
+ this.log.error(`Cannot parse stored chat IDs: ${err instanceof Error ? err.message : err}`);
2521
+ }
2522
+ }
2523
+ }
2524
+ catch (err) {
2525
+ this.log.error(err);
2526
+ }
2527
+ }
2528
+ // Read all Object names sequentially, that do not have aliases
2529
+ async readAllNames(ids) {
2530
+ for (let i = 0; i < ids.length; i++) {
2531
+ try {
2532
+ const obj = await this.getForeignObjectAsync(ids[i]);
2533
+ if (obj) {
2534
+ this.commands[ids[i]].alias = this.getName(obj);
2535
+ this.commands[ids[i]].type = obj.common?.type;
2536
+ this.commands[ids[i]].states = this.parseStates(obj.common?.states);
2537
+ this.commands[ids[i]].unit = obj.common?.unit;
2538
+ this.commands[ids[i]].min = obj.common?.min;
2539
+ this.commands[ids[i]].max = obj.common?.max;
2540
+ // read actual state to detect changes
2541
+ if (this.commands[ids[i]].reportChanges) {
2542
+ const state = await this.getForeignStateAsync(ids[i]);
2543
+ this.commands[ids[i]].lastState = state ? state.val : undefined;
2544
+ }
2545
+ await this.subscribeForeignStatesAsync(ids[i]);
2546
+ }
2547
+ }
2548
+ catch (err) {
2549
+ this.log.error(`Cannot process object "${ids[i]}": ${err}`);
2550
+ }
2551
+ }
2552
+ }
2553
+ async readStatesCommands() {
2554
+ const doc = await this.getObjectViewAsync('system', 'custom', {});
2555
+ const readNames = [];
2556
+ if (doc && doc.rows) {
2557
+ for (let i = 0, l = doc.rows.length; i < l; i++) {
2558
+ if (doc.rows[i].value) {
2559
+ const id = doc.rows[i].id;
2560
+ const obj = doc.rows[i].value;
2561
+ if (obj[this.namespace] && obj[this.namespace].enabled) {
2562
+ this.commands[id] = obj[this.namespace];
2563
+ readNames.push(id);
2564
+ }
2565
+ }
2566
+ }
2567
+ }
2568
+ await this.readAllNames(readNames);
2569
+ }
2570
+ async readEnums(name) {
2571
+ name ||= 'rooms';
2572
+ this.enumsCache[name] = {};
2573
+ try {
2574
+ const doc = await this.getObjectViewAsync('system', 'enum', {
2575
+ startkey: `enum.${name}.`,
2576
+ endkey: `enum.${name}.香`,
2577
+ });
2578
+ if (doc && doc.rows) {
2579
+ for (let i = 0, l = doc.rows.length; i < l; i++) {
2580
+ if (doc.rows[i].value) {
2581
+ const id = doc.rows[i].id;
2582
+ const obj = doc.rows[i].value;
2583
+ if (obj && obj.common && obj.common.members && obj.common.members.length) {
2584
+ this.enumsCache[name][id] = obj.common;
2585
+ }
2586
+ }
2587
+ }
2588
+ }
2589
+ }
2590
+ catch (err) {
2591
+ this.log.error(`Cannot read enum ${name}: ${err}`);
2592
+ }
2593
+ return this.enumsCache;
2594
+ }
2595
+ async main() {
2596
+ if (!this.config.token) {
2597
+ this.log.error('Token is not set!');
2598
+ return;
2599
+ }
2600
+ await this.setState('info.connection', false, true);
2601
+ await this.subscribeStatesAsync('communicate.request');
2602
+ await this.subscribeStatesAsync('communicate.response');
2603
+ await this.subscribeStatesAsync('communicate.responseSilent');
2604
+ await this.subscribeStatesAsync('communicate.responseJson');
2605
+ await this.subscribeStatesAsync('communicate.responseSilentJson');
2606
+ await this.subscribeStatesAsync('communicate.requestResponse');
2607
+ // clear states
2608
+ await this.setState('communicate.request', { val: '', ack: true });
2609
+ await this.setState('communicate.response', { val: '', ack: true });
2610
+ await this.setState('communicate.responseSilent', { val: '', ack: true });
2611
+ await this.setState('communicate.responseJson', { val: '', ack: true });
2612
+ await this.setState('communicate.responseSilentJson', { val: '', ack: true });
2613
+ await this.setState('communicate.requestResponse', { val: '', ack: true });
2614
+ await this.setState('communicate.pathFile', { val: '', ack: true });
2615
+ this.config.password ||= '';
2616
+ this.config.keyboard ||= '/cmds';
2617
+ await this.updateUsers();
2618
+ await this.updateChats();
2619
+ // Default to enabled only when the option is missing (old configs); respect an explicit `false`.
2620
+ if (this.config.allowStates == null) {
2621
+ this.config.allowStates = true;
2622
+ }
2623
+ this.config.answerTimeoutSec = parseInt(String(this.config.answerTimeoutSec), 10) || 60;
2624
+ this.config.answerTimeoutSec *= 1000;
2625
+ this.config.rememberUsers =
2626
+ this.config.rememberUsers === 'true' || this.config.rememberUsers === true;
2627
+ try {
2628
+ const obj = await this.getForeignObjectAsync('system.config');
2629
+ if (obj) {
2630
+ this.systemLang = obj.common.language || 'en';
2631
+ }
2632
+ await this.readStatesCommands();
2633
+ if (this.config.rooms) {
2634
+ await this.readEnums();
2635
+ }
2636
+ // init polling every hour
2637
+ this.reconnectTimer = this.setInterval(() => this.connect(), 3600000);
2638
+ this.connect();
2639
+ // detect changes of objects
2640
+ await this.subscribeForeignObjectsAsync('*');
2641
+ }
2642
+ catch (err) {
2643
+ this.log.error(err);
2644
+ }
2645
+ }
2646
+ /**
2647
+ * Process a `sendNotification` request
2648
+ *
2649
+ * @param obj the message object with the notification payload
2650
+ */
2651
+ async processNotification(obj) {
2652
+ this.log.info(`New notification received from ${obj.from}`);
2653
+ const notificationMessage = this.buildMessageFromNotification(obj.message);
2654
+ try {
2655
+ await this.sendSystemMessage(notificationMessage, { parse_mode: 'MarkdownV2' });
2656
+ if (obj.callback) {
2657
+ this.sendTo(obj.from, 'sendNotification', { sent: true }, obj.callback);
2658
+ }
2659
+ }
2660
+ catch {
2661
+ if (obj.callback) {
2662
+ this.sendTo(obj.from, 'sendNotification', { sent: false }, obj.callback);
2663
+ }
2664
+ }
2665
+ }
2666
+ /**
2667
+ * Build up a mail object from the notification message
2668
+ *
2669
+ * @param message the notification message payload
2670
+ * @returns the formatted, character-escaped message text
2671
+ */
2672
+ buildMessageFromNotification(message) {
2673
+ const subject = message.category.name;
2674
+ const { instances } = message.category;
2675
+ const readableInstances = Object.entries(instances).map(([instance, entry]) => `${instance.substring('system.adapter.'.length)}: ${this.getNewestMessage(entry.messages)}`);
2676
+ const text = `${message.category.description}
2677
+ ${message.host}:
2678
+ ${readableInstances.join('\n')}
2679
+ `;
2680
+ return this.replaceReservedCharacters(`*${subject}*\n\n${text}`);
2681
+ }
2682
+ /**
2683
+ * Replace reserved characters in outgoing message
2684
+ *
2685
+ * @param text string to sanitize
2686
+ * @returns the sanitized string
2687
+ */
2688
+ replaceReservedCharacters(text) {
2689
+ return text.replace(/([.!()\-_*[\]~`><&#+=|{}])/g, '\\$1');
2690
+ }
2691
+ /**
2692
+ * Extract the newest message out of a notification messages together with the localized date
2693
+ *
2694
+ * @param messages the list of notification messages
2695
+ * @returns the formatted newest message
2696
+ */
2697
+ getNewestMessage(messages) {
2698
+ if (!messages?.length) {
2699
+ return '';
2700
+ }
2701
+ const newestMessage = messages.sort((a, b) => (a.ts < b.ts ? 1 : -1))[0];
2702
+ return `${new Date(newestMessage.ts).toLocaleString()} ${newestMessage.message}`;
2703
+ }
2704
+ }
2705
+ if (require.main !== module) {
2706
+ // Export the constructor in compact mode
2707
+ module.exports = (options) => new Telegram(options);
2708
+ }
2709
+ else {
2710
+ // otherwise start the instance directly
2711
+ (() => new Telegram())();
2712
+ }
2713
+ //# sourceMappingURL=main.js.map