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/main.js DELETED
@@ -1,2460 +0,0 @@
1
- 'use strict';
2
-
3
- // https://github.com/yagop/node-telegram-bot-api/issues/319 (because of bluebird)
4
- process.env.NTBA_FIX_319 = 1;
5
-
6
- const TelegramBot = require('node-telegram-bot-api');
7
- const utils = require('@iobroker/adapter-core'); // Get common adapter utils
8
- const adapterName = require('./package.json').name.split('.').pop();
9
- const _ = require('./lib/words.js');
10
- const fs = require('node:fs');
11
- const path = require('node:path');
12
- const { WebServer } = require('@iobroker/webserver');
13
- const https = require('node:https');
14
- const axios = require('axios').default;
15
-
16
- let bot;
17
- let users = {};
18
- let systemLang = 'en';
19
- let reconnectTimer = null;
20
- let pollConnectionStatus = null;
21
- let isConnected = null;
22
- let lastMessageTime = 0;
23
- let lastMessageText = '';
24
- const enums = {};
25
- const protection = {};
26
- let gcInterval = null;
27
-
28
- const commands = {};
29
- const callbackQueryId = {};
30
- const mediaGroupExport = {};
31
- let tmpDirName;
32
-
33
- const server = {
34
- app: null,
35
- server: null,
36
- settings: null,
37
- };
38
-
39
- let adapter;
40
-
41
- const systemLang2CallMe = {
42
- en: 'en-GB-Standard-A',
43
- de: 'de-DE-Standard-A',
44
- ru: 'ru-RU-Standard-A',
45
- pt: 'pt-BR-Standard-A',
46
- nl: 'nl-NL-Standard-A',
47
- fr: 'fr-FR-Standard-A',
48
- it: 'it-IT-Standard-A',
49
- es: 'es-ES-Standard-A',
50
- pl: 'pl-PL-Standard-A',
51
- uk: 'uk-UA-Standard-A',
52
- 'zh-cn': 'en-GB-Standard-A',
53
- };
54
-
55
- function startAdapter(options) {
56
- options = options || {};
57
- Object.assign(options, {
58
- name: adapterName,
59
- error: err => {
60
- // Identify unhandled errors originating from callbacks in scripts
61
- // These are not caught by wrapping the execution code in try-catch
62
- if (err) {
63
- const errStr = err.toString();
64
- if (
65
- errStr.includes('getaddrinfo') ||
66
- errStr.includes('api.telegram.org') ||
67
- errStr.includes('EAI_AGAIN')
68
- ) {
69
- return true;
70
- }
71
- }
72
- return false;
73
- },
74
- });
75
-
76
- adapter = new utils.Adapter(options);
77
-
78
- adapter.on('message', obj => {
79
- if (obj) {
80
- if (obj.command === 'adminuser') {
81
- let adminUserData;
82
- adapter.getState('communicate.users', (err, state) => {
83
- err && adapter.log.error(err);
84
- if (state && state.val) {
85
- try {
86
- adminUserData = JSON.parse(state.val);
87
- adapter.sendTo(obj.from, obj.command, adminUserData, obj.callback);
88
- } catch (err) {
89
- err && adapter.log.error(err);
90
- adapter.log.error('Cannot parse stored user IDs!');
91
- }
92
- }
93
- });
94
- } else if (obj.command === 'delUser') {
95
- const userID = obj.message;
96
- let userObj = {};
97
- adapter.getState('communicate.users', (err, state) => {
98
- err && adapter.log.error(err);
99
- if (state && state.val) {
100
- try {
101
- userObj = JSON.parse(state.val);
102
- delete userObj[userID];
103
- adapter.setState('communicate.users', JSON.stringify(userObj), true, err => {
104
- if (!err) {
105
- adapter.sendTo(obj.from, obj.command, userID, obj.callback);
106
- updateUsers();
107
- adapter.log.warn(`User ${userID} has been deleted!`);
108
- }
109
- });
110
- } catch (err) {
111
- err && adapter.log.error(err);
112
- adapter.log.error(`Cannot delete user ${userID}!`);
113
- }
114
- }
115
- });
116
- } else if (obj.command === 'systemMessages') {
117
- const userID = obj.message.itemId;
118
- const checked = obj.message.checked;
119
- let userObj = {};
120
- adapter.getState('communicate.users', (err, state) => {
121
- err && adapter.log.error(err);
122
- if (state && state.val) {
123
- try {
124
- userObj = JSON.parse(state.val);
125
- userObj[userID].sysMessages = checked;
126
- adapter.setState('communicate.users', JSON.stringify(userObj), true, err => {
127
- if (!err) {
128
- adapter.sendTo(obj.from, obj.command, userID, obj.callback);
129
- updateUsers();
130
- adapter.log.info(
131
- `Receiving of system messages for user "${userID}" has been changed to ${checked}!`,
132
- );
133
- }
134
- });
135
- } catch (err) {
136
- err && adapter.log.error(err);
137
- adapter.log.error(`Cannot change user ${userID}!`);
138
- }
139
- }
140
- });
141
- } else if (obj.command === 'delAllUser') {
142
- try {
143
- adapter.setState('communicate.users', '{}', true, err => {
144
- if (!err) {
145
- adapter.sendTo(obj.from, obj.command, true, obj.callback);
146
- updateUsers();
147
- adapter.log.warn(
148
- 'List of saved users has been wiped. Every User has to reauthenticate with the new password!',
149
- );
150
- }
151
- });
152
- } catch (err) {
153
- err && adapter.log.error(err);
154
- adapter.log.error('Cannot wipe list of saved users!');
155
- }
156
- } else if (obj.command === 'sendNotification') {
157
- processNotification(obj);
158
- } else {
159
- processMessage(obj);
160
- }
161
- }
162
- });
163
-
164
- adapter.on('ready', () => {
165
- adapter.config.server = adapter.config.server === 'true';
166
-
167
- adapter._questions = [];
168
- adapter.garbageCollectorinterval = setInterval(() => {
169
- const now = Date.now();
170
- Object.keys(callbackQueryId).forEach(id => {
171
- if (now - callbackQueryId[id].ts > 120000) {
172
- delete callbackQueryId[id];
173
- }
174
- });
175
- }, 10000);
176
-
177
- tmpDirName = path.join(utils.getAbsoluteDefaultDataDir(), adapter.namespace.replace('.', '_'));
178
-
179
- // Create file system directories for media files
180
- if (adapter.config.saveFilesTo == 'filesystem') {
181
- try {
182
- !fs.existsSync(tmpDirName) && fs.mkdirSync(tmpDirName);
183
-
184
- const subDirectories = ['voice'];
185
- if (adapter.config.saveFiles) {
186
- // Create subdirs for other attachment types
187
- subDirectories.push('photo', 'video', 'audio', 'document');
188
- }
189
-
190
- for (const subDir of subDirectories) {
191
- const subDirPath = path.join(tmpDirName, subDir);
192
- !fs.existsSync(subDirPath) && fs.mkdirSync(subDirPath);
193
- }
194
- } catch (err) {
195
- adapter.log.error(`Cannot create tmp directory: ${tmpDirName}: ${err}`);
196
- }
197
- }
198
-
199
- if (adapter.config.server) {
200
- adapter.config.port = parseInt(adapter.config.port, 10);
201
-
202
- // Load certificates
203
- adapter.getCertificates(async (err, certificates, leConfig) => {
204
- adapter.config.certificates = certificates;
205
- adapter.config.leConfig = leConfig;
206
- adapter.config.secure = true;
207
-
208
- try {
209
- const webserver = new WebServer({
210
- app: handleWebHook,
211
- adapter,
212
- secure: adapter.config.secure,
213
- });
214
-
215
- server.server = await webserver.init();
216
- } catch (err) {
217
- adapter.log.error(`Cannot create webserver: ${err}`);
218
- adapter.terminate
219
- ? adapter.terminate(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION)
220
- : process.exit(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
221
- return;
222
- }
223
- if (server.server) {
224
- server.server.__server = server;
225
-
226
- let serverListening = false;
227
- let serverPort = adapter.config.port;
228
- server.server.on('error', e => {
229
- if (e.toString().includes('EACCES') && serverPort <= 1024) {
230
- adapter.log.error(
231
- `node.js process has no rights to start server on the port ${serverPort}.\n` +
232
- `Do you know that on linux you need special permissions for ports under 1024?\n` +
233
- `You can call in shell following scrip to allow it for node.js: "iobroker fix"`,
234
- );
235
- } else {
236
- adapter.log.error(
237
- `Cannot start server on ${adapter.config.bind || '0.0.0.0'}:${serverPort}: ${e}`,
238
- );
239
- }
240
- if (!serverListening) {
241
- adapter.terminate
242
- ? adapter.terminate(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION)
243
- : process.exit(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
244
- }
245
- });
246
-
247
- adapter.getPort(
248
- adapter.config.port,
249
- !adapter.config.bind || adapter.config.bind === '0.0.0.0'
250
- ? undefined
251
- : adapter.config.bind || undefined,
252
- port => {
253
- if (parseInt(port, 10) !== adapter.config.port && !adapter.config.findNextPort) {
254
- adapter.log.error(`port ${adapter.config.port} already in use`);
255
- adapter.terminate ? adapter.terminate() : process.exit(1);
256
- }
257
- serverPort = port;
258
-
259
- server.server.listen(
260
- port,
261
- !adapter.config.bind || adapter.config.bind === '0.0.0.0'
262
- ? undefined
263
- : adapter.config.bind || undefined,
264
- () => (serverListening = true),
265
- );
266
- adapter.log.info(`https server listening on port ${port}`);
267
-
268
- main().catch(e => adapter.log.error(`Cannot start adapter: ${e}`));
269
- },
270
- );
271
- }
272
- });
273
- } else {
274
- main().catch(e => adapter.log.error(`Cannot start adapter: ${e}`));
275
- }
276
- });
277
-
278
- adapter.on('unload', () => {
279
- reconnectTimer && clearInterval(reconnectTimer);
280
- reconnectTimer = null;
281
-
282
- gcInterval && clearInterval(gcInterval);
283
- gcInterval = null;
284
-
285
- pollConnectionStatus && clearInterval(pollConnectionStatus);
286
- pollConnectionStatus = null;
287
-
288
- adapter.garbageCollectorinterval && clearInterval(adapter.garbageCollectorinterval);
289
- adapter.garbageCollectorinterval = null;
290
-
291
- if (adapter && adapter.config) {
292
- if (adapter.config.restarting !== '') {
293
- // default text
294
- if (
295
- adapter.config.restarting === '_' ||
296
- adapter.config.restarting === null ||
297
- adapter.config.restarting === undefined
298
- ) {
299
- sendSystemMessage(
300
- adapter.config.rememberUsers ? _('Restarting...') : _('Restarting... Reauthenticate!'),
301
- );
302
- } else {
303
- sendSystemMessage(adapter.config.restarting);
304
- }
305
- }
306
- try {
307
- if (server.server) {
308
- server.server.close();
309
- }
310
- } catch (e) {
311
- console.error(`Cannot close server: ${e}`);
312
- }
313
- }
314
-
315
- isConnected && adapter && adapter.setState && adapter.setState('info.connection', false, true);
316
- isConnected = false;
317
- });
318
-
319
- // This handler is called if a subscribed state changes
320
- adapter.on('stateChange', async (id, state) => {
321
- if (state) {
322
- if (!state.ack) {
323
- if (id.endsWith('communicate.response')) {
324
- if (typeof state.val === 'object') {
325
- adapter.log.error(
326
- `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!`,
327
- );
328
- return;
329
- }
330
-
331
- // Send to someone this message
332
- await sendMessage(state.val);
333
- await adapter.setStateAsync('communicate.response', { val: state.val, ack: true });
334
- } else if (id.endsWith('communicate.responseSilent')) {
335
- if (typeof state.val === 'object') {
336
- adapter.log.error(
337
- `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!`,
338
- );
339
- return;
340
- }
341
- // Send to someone this message
342
- await sendMessage(state.val, null, null, { disable_notification: true });
343
- await adapter.setStateAsync('communicate.responseSilent', { val: state.val, ack: true });
344
- } else if (id.endsWith('communicate.responseJson')) {
345
- try {
346
- const val = JSON.parse(state.val);
347
-
348
- // Send to someone this message
349
- await sendMessage(val);
350
- await adapter.setStateAsync('communicate.responseJson', { val: state.val, ack: true });
351
- } catch (err) {
352
- adapter.log.error(`could not parse Json in communicate.responseJon state: ${err.message}`);
353
- }
354
- } else if (id.endsWith('communicate.responseSilentJson')) {
355
- try {
356
- const val = JSON.parse(state.val);
357
-
358
- // Send to someone this message
359
- await sendMessage(val, null, null, { disable_notification: true });
360
- await adapter.setStateAsync('communicate.responseSilent', { val: state.val, ack: true });
361
- } catch (err) {
362
- adapter.log.error(
363
- `could not parse Json in communicate.responseSilentJon state: ${err.message}`,
364
- );
365
- }
366
- } else if (id.endsWith('communicate.requestResponse')) {
367
- try {
368
- const text = state.val;
369
- const chatIdState = await adapter.getStateAsync('communicate.requestChatId');
370
- const threadIdState = await adapter.getStateAsync('communicate.requestMessageThreadId');
371
-
372
- const options = {};
373
-
374
- if (threadIdState && threadIdState.val > 0) {
375
- options.message_thread_id = threadIdState.val;
376
- }
377
-
378
- // Send to someone this message
379
- await sendMessage(text, null, chatIdState ? chatIdState.val : null, options);
380
- await adapter.setStateAsync('communicate.requestResponse', { val: state.val, ack: true });
381
- } catch (err) {
382
- adapter.log.error(
383
- `could not parse Json in communicate.responseSilentJon state: ${err.message}`,
384
- );
385
- }
386
- }
387
- } else if (commands[id] && commands[id].report) {
388
- adapter.log.debug(`reporting state change of ${id}: ${JSON.stringify(commands[id])}`);
389
-
390
- const options = commands[id].reportSilent == true ? { disable_notification: true } : {};
391
- let users = null;
392
-
393
- if (commands[id]?.recipients && commands[id].recipients !== '') {
394
- users = commands[id].recipients;
395
- }
396
-
397
- if (commands[id].reportChanges) {
398
- if (state.val !== commands[id].lastState) {
399
- commands[id].lastState = state.val;
400
- sendMessage(getStatus(id, state), users, null, options);
401
- }
402
- } else {
403
- sendMessage(getStatus(id, state), users, null, options);
404
- }
405
- }
406
- }
407
- });
408
-
409
- adapter.on('objectChange', (id, obj) => {
410
- if (
411
- obj &&
412
- obj.common &&
413
- obj.common.custom &&
414
- obj.common.custom[adapter.namespace] &&
415
- obj.common.custom[adapter.namespace].enabled
416
- ) {
417
- const alias = getName(obj);
418
- if (!commands[id]) {
419
- adapter.log.info(`enabled logging of ${id}, Alias=${alias}`);
420
- setImmediate(() => adapter.subscribeForeignStates(id));
421
- }
422
-
423
- commands[id] = obj.common.custom[adapter.namespace];
424
- commands[id].type = obj.common.type;
425
- commands[id].states = parseStates(obj.common.states);
426
- commands[id].unit = obj.common && obj.common.unit;
427
- commands[id].min = obj.common && obj.common.min;
428
- commands[id].max = obj.common && obj.common.max;
429
- commands[id].recipients = obj.common && obj.common.recipients;
430
- commands[id].alias = alias;
431
-
432
- // read actual state to detect changes
433
- if (commands[id].reportChanges) {
434
- adapter
435
- .getForeignStateAsync(id)
436
- .then(state => (commands[id].lastState = state ? state.val : undefined));
437
- }
438
- } else if (commands[id]) {
439
- adapter.log.debug(`Removed command: ${id}`);
440
- delete commands[id];
441
- setImmediate(() => adapter.unsubscribeForeignStates(id));
442
- } else if (id.startsWith('enum.rooms') && adapter.config.rooms) {
443
- if (obj && obj.common && obj.common.members && obj.common.members.length) {
444
- enums.rooms[id] = obj.common;
445
- } else if (enums.rooms[id]) {
446
- delete enums.rooms[id];
447
- }
448
- }
449
- });
450
-
451
- server.settings = adapter.config;
452
-
453
- return adapter;
454
- }
455
-
456
- /**
457
- * Send a message to all system users
458
- *
459
- * @param text text to send
460
- * @param options additional options, e.g. parse_mode
461
- * @returns
462
- */
463
- async function sendSystemMessage(text, options = {}) {
464
- const _users = Object.keys(users)
465
- .filter(id => users[id].sysMessages !== false)
466
- .map(id => (adapter.config.useUsername ? users[id].userName : users[id].firstName));
467
-
468
- await sendMessage(text, _users, null, { ...options, disable_notification: true });
469
- }
470
-
471
- function getStatus(id, state) {
472
- if (!state) {
473
- state = { val: 'State not set' };
474
- }
475
- if (commands[id].type === 'boolean') {
476
- return `${commands[id].alias} => ${state.val ? commands[id].onStatus || _('ON-Status') : commands[id].offStatus || _('OFF-Status')}`;
477
- }
478
- if (commands[id].states && commands[id].states[state.val] !== undefined) {
479
- state.val = commands[id].states[state.val];
480
- }
481
- return `${commands[id].alias} => ${state.val}${commands[id].unit ? ` ${commands[id].unit}` : ''}`;
482
- }
483
-
484
- function connectionState(connected, logSuccess) {
485
- let errorCounter = 0;
486
-
487
- function checkConnection() {
488
- pollConnectionStatus = null;
489
- bot &&
490
- bot.getMe &&
491
- bot
492
- .getMe()
493
- .then(data => {
494
- adapter.log.debug(`getMe (reconnect): ${JSON.stringify(data)}`);
495
- connectionState(true, errorCounter > 0);
496
- })
497
- .catch(error => {
498
- errorCounter % 10 === 0 && adapter.log.error(`getMe (reconnect #${errorCounter}) Error:${error}`);
499
- errorCounter++;
500
- pollConnectionStatus && clearTimeout(pollConnectionStatus);
501
- pollConnectionStatus = setTimeout(checkConnection, 1000);
502
- });
503
- }
504
-
505
- if (connected && logSuccess) {
506
- adapter.log.info('getMe (reconnect): Success');
507
- }
508
- if (isConnected !== connected) {
509
- isConnected = connected;
510
- adapter.setState('info.connection', isConnected, true);
511
- if (isConnected && pollConnectionStatus) {
512
- clearTimeout(pollConnectionStatus);
513
- pollConnectionStatus = null;
514
- } else if (!isConnected) {
515
- checkConnection();
516
- }
517
- }
518
- }
519
-
520
- function parseStates(states) {
521
- // todo
522
- return states;
523
- }
524
-
525
- function getName(obj) {
526
- if (obj.common.custom[adapter.namespace].alias) {
527
- return obj.common.custom[adapter.namespace].alias;
528
- }
529
- let name = obj.common.name;
530
- if (typeof name === 'object') {
531
- name = name[systemLang] || name.en;
532
- }
533
- return name || obj._id;
534
- }
535
-
536
- const actions = [
537
- 'typing',
538
- 'upload_photo',
539
- 'upload_video',
540
- 'record_video',
541
- 'record_audio',
542
- 'upload_document',
543
- 'find_location',
544
- ];
545
-
546
- function handleWebHook(req, res) {
547
- if (req.method === 'POST' && req.url === `/${adapter.config.token}`) {
548
- //
549
- //{
550
- // "update_id":10000,
551
- // "message":{
552
- // "date":1441645532,
553
- // "chat":{
554
- // "last_name":"Test Lastname",
555
- // "id":1111111,
556
- // "first_name":"Test",
557
- // "username":"Test"
558
- // },
559
- // "message_id":1365,
560
- // "from": {
561
- // "last_name":"Test Lastname",
562
- // "id":1111111,
563
- // "first_name":"Test",
564
- // "username":"Test"
565
- // },
566
- // "text":"/start"
567
- // }
568
- //}
569
- let body = '';
570
- req.on('data', data => {
571
- body += data;
572
- if (body.length > 100_000) {
573
- res.writeHead(413, 'Request Entity Too Large', {
574
- 'Content-Type': 'text/html',
575
- });
576
- res.end(
577
- '<!doctype html><html><head><title>413</title></head><body>413: Request Entity Too Large</body></html>',
578
- );
579
- }
580
- });
581
- req.on('end', () => {
582
- let msg;
583
- try {
584
- msg = JSON.parse(body);
585
- } catch (e) {
586
- adapter.log.error(`Cannot parse webhook response!: ${e}`);
587
- return;
588
- }
589
- res.end('OK');
590
- bot.processUpdate(msg);
591
- });
592
- } else {
593
- res.writeHead(404, 'Resource Not Found', {
594
- 'Content-Type': 'text/html',
595
- });
596
- res.end('<!doctype html><html><head><title>404</title></head><body>404: Resource Not Found</body></html>');
597
- }
598
- }
599
-
600
- function saveSendRequest(msg) {
601
- adapter.log.debug(`Request [saveSendRequest]: ${JSON.stringify(msg)}`);
602
-
603
- if (typeof msg === 'object') {
604
- if (adapter.config.storeRawRequest) {
605
- adapter.setState(
606
- 'communicate.botSendRaw',
607
- JSON.stringify(msg, null, 2),
608
- true,
609
- err => err && adapter.log.error(err),
610
- );
611
- }
612
-
613
- if (msg?.message_id) {
614
- adapter.setState(
615
- 'communicate.botSendMessageId',
616
- msg.message_id,
617
- true,
618
- err => err && adapter.log.error(err),
619
- );
620
- }
621
-
622
- if (msg?.message_thread_id) {
623
- adapter.setState(
624
- 'communicate.botSendMessageThreadId',
625
- msg.message_thread_id,
626
- true,
627
- err => err && adapter.log.error(err),
628
- );
629
- }
630
-
631
- if (msg?.chat && msg.chat.id) {
632
- adapter.setState(
633
- 'communicate.botSendChatId',
634
- msg.chat.id.toString(),
635
- true,
636
- err => err && adapter.log.error(err),
637
- );
638
- }
639
- }
640
- }
641
-
642
- function _sendMessageHelper(dest, name, text, options) {
643
- return new Promise(resolve => {
644
- const messageIds = {};
645
- if (options && options.chatId !== undefined && options.user === undefined) {
646
- options.user = adapter.config.useUsername
647
- ? users[options.chatId].userName
648
- : users[options.chatId].firstName;
649
- }
650
- // to push chatId value for the group chats - useful to process the errors, and list of processed messages.
651
- if (options.chatId === undefined && options.user === undefined && name === 'chat' && dest) {
652
- options.chatId = dest;
653
- }
654
- if (options && options.editMessageReplyMarkup !== undefined) {
655
- adapter.log.debug(`Send editMessageReplyMarkup to "${name}"`);
656
- bot &&
657
- executeSending(
658
- () =>
659
- bot.editMessageReplyMarkup(
660
- options.editMessageReplyMarkup.reply_markup,
661
- options.editMessageReplyMarkup.options,
662
- ),
663
- options,
664
- resolve,
665
- );
666
- } else if (options && options.editMessageText !== undefined) {
667
- adapter.log.debug(`Send editMessageText to "${name}"`);
668
- bot && executeSending(() => bot.editMessageText(text, options.editMessageText.options), options, resolve);
669
- } else if (options && options.editMessageMedia !== undefined) {
670
- adapter.log.debug(`Send editMessageMedia to "${name}"`);
671
- if (text) {
672
- let mediaInput;
673
- if (
674
- (typeof text === 'string' &&
675
- text.match(/\.(jpg|png|jpeg|bmp|gif)$/i) &&
676
- (fs.existsSync(text) || text.match(/^(https|http)/i))) ||
677
- (options && options.type === 'photo')
678
- ) {
679
- mediaInput = {
680
- type: 'photo',
681
- media: text,
682
- };
683
- } else if (
684
- (typeof text === 'string' && text.match(/\.(gif)/i) && fs.existsSync(text)) ||
685
- (options && options.type === 'animation')
686
- ) {
687
- mediaInput = {
688
- type: 'animation',
689
- media: text,
690
- };
691
- } else if (
692
- (typeof text === 'string' && text.match(/\.(mp4)$/i) && fs.existsSync(text)) ||
693
- (options && options.type === 'video')
694
- ) {
695
- mediaInput = {
696
- type: 'video',
697
- media: text,
698
- };
699
- } else if (
700
- (typeof text === 'string' && text.match(/\.(wav|mp3|ogg)$/i) && fs.existsSync(text)) ||
701
- (options && options.type === 'audio')
702
- ) {
703
- mediaInput = {
704
- type: 'audio',
705
- media: text,
706
- };
707
- } else if (
708
- (typeof text === 'string' &&
709
- text.match(/\.(txt|doc|docx|csv|pdf|xls|xlsx)$/i) &&
710
- fs.existsSync(text)) ||
711
- (options && options.type === 'document')
712
- ) {
713
- mediaInput = {
714
- type: 'document',
715
- media: text,
716
- };
717
- }
718
-
719
- if (mediaInput) {
720
- const opts = {
721
- qs: options.editMessageMedia.options,
722
- };
723
- opts.formData = {};
724
-
725
- const payload = Object.assign({}, mediaInput);
726
-
727
- delete payload.media;
728
- delete payload.fileOptions;
729
-
730
- try {
731
- const attachName = String(0);
732
- const [formData, fileId] = bot._formatSendData(
733
- attachName,
734
- mediaInput.media,
735
- mediaInput.fileOptions,
736
- );
737
- if (formData) {
738
- opts.formData[attachName] = formData[attachName];
739
- payload.media = `attach://${attachName}`;
740
- } else {
741
- payload.media = fileId;
742
- }
743
- } catch (ex) {
744
- return Promise.reject(ex);
745
- }
746
-
747
- opts.qs.media = JSON.stringify(payload);
748
- bot && executeSending(() => bot._request('editMessageMedia', opts), options, resolve);
749
- } else {
750
- adapter.log.error(
751
- `Cannot send editMessageMedia [chatId - ${options.chatId}]: unsupported media type`,
752
- );
753
- options = null;
754
- resolve(JSON.stringify(messageIds));
755
- }
756
- } else {
757
- adapter.log.error(
758
- `Cannot send editMessageMedia [chatId - ${options.chatId}]: no media found. "text" may not be empty`,
759
- );
760
- options = null;
761
- resolve(JSON.stringify(messageIds));
762
- }
763
- } else if (options && options.editMessageCaption !== undefined) {
764
- adapter.log.debug(`Send editMessageCaption to "${name}"`);
765
- bot &&
766
- executeSending(
767
- () => bot.editMessageCaption(text, options.editMessageCaption.options),
768
- options,
769
- resolve,
770
- );
771
- } else if (options && options.deleteMessage !== undefined) {
772
- adapter.log.debug(`Send deleteMessage to "${name}"`);
773
- bot &&
774
- executeSending(
775
- () =>
776
- bot.deleteMessage(
777
- options.deleteMessage.options.chat_id,
778
- options.deleteMessage.options.message_id,
779
- ),
780
- options,
781
- resolve,
782
- );
783
- } else if (
784
- options &&
785
- options.latitude !== undefined &&
786
- options.longitude !== undefined &&
787
- options.title !== undefined &&
788
- options.address !== undefined
789
- ) {
790
- adapter.log.debug(`Send venue to "${name}": ${options.latitude},${options.longitude}`);
791
- bot &&
792
- executeSending(
793
- () =>
794
- bot.sendVenue(
795
- dest,
796
- parseFloat(options.latitude),
797
- parseFloat(options.longitude),
798
- options.title,
799
- options.address,
800
- options,
801
- ),
802
- options,
803
- resolve,
804
- );
805
- } else if (options && options.latitude !== undefined && options.longitude !== undefined) {
806
- adapter.log.debug(`Send location to "${name}": ${options.latitude},${options.longitude}`);
807
- bot &&
808
- executeSending(
809
- () => bot.sendLocation(dest, parseFloat(options.latitude), parseFloat(options.longitude), options),
810
- options,
811
- resolve,
812
- );
813
- } else if (options && options.type === 'mediagroup') {
814
- adapter.log.debug(`Send media group to "${name}": `);
815
- if (bot) {
816
- const { media: fileNames } = options;
817
- if (fileNames instanceof Array) {
818
- bot.sendChatAction(dest, 'upload_photo')
819
- .then(() => {
820
- if (fileNames.every(name => fs.existsSync(name))) {
821
- const filesAsArray = fileNames
822
- .map(element => {
823
- try {
824
- return { type: 'photo', media: fs.readFileSync(element) };
825
- } catch (err) {
826
- adapter.log.error(`Cannot read file ${element}: ${err}`);
827
- return undefined;
828
- }
829
- })
830
- .filter(element => element !== undefined);
831
-
832
- const size = filesAsArray
833
- .map(element => element.media.length)
834
- .reduce((acc, val) => acc + val);
835
-
836
- adapter.log.info(`Send media group to "${name}": ${size} bytes`);
837
- if (filesAsArray.length > 0) {
838
- executeSending(() => bot.sendMediaGroup(dest, filesAsArray), options, resolve);
839
- }
840
- } else {
841
- adapter.log.debug('files must exists');
842
- options = null;
843
- resolve(JSON.stringify(messageIds));
844
- }
845
- })
846
- .catch(error => {
847
- adapter.log.error(`upload Error: ${error}`);
848
- });
849
- } else {
850
- adapter.log.debug('option media should be an array');
851
- resolve(JSON.stringify(messageIds));
852
- }
853
- } else {
854
- adapter.log.debug('no files added!');
855
- options = null;
856
- resolve(JSON.stringify(messageIds));
857
- }
858
- } else if (text && typeof text === 'string' && actions.includes(text)) {
859
- adapter.log.debug(`Send action to "${name}": ${text}`);
860
- bot && executeSending(() => bot.sendChatAction(dest, text), options, resolve);
861
- } else if (
862
- text &&
863
- ((typeof text === 'string' && text.match(/\.webp$/i) && fs.existsSync(text)) ||
864
- (options && options.type === 'sticker'))
865
- ) {
866
- if (typeof text === 'string') {
867
- adapter.log.debug(`Send sticker to "${name}": ${text}`);
868
- } else {
869
- adapter.log.debug(`Send sticker to "${name}": ${text.length} bytes`);
870
- }
871
- bot && executeSending(() => bot.sendSticker(dest, text, options), options, resolve);
872
- } else if (
873
- text &&
874
- ((typeof text === 'string' && text.match(/\.(gif)/i) && fs.existsSync(text)) ||
875
- (options && options.type === 'animation'))
876
- ) {
877
- if (typeof text === 'string') {
878
- adapter.log.debug(`Send animation to "${name}": ${text}`);
879
- } else {
880
- adapter.log.debug(`Send animation to "${name}": ${text.length} bytes`);
881
- }
882
- bot && executeSending(() => bot.sendAnimation(dest, text, options), options, resolve);
883
- } else if (
884
- text &&
885
- ((typeof text === 'string' && text.match(/\.(mp4)$/i) && fs.existsSync(text)) ||
886
- (options && options.type === 'video'))
887
- ) {
888
- if (typeof text === 'string') {
889
- adapter.log.debug(`Send video to "${name}": ${text}`);
890
- } else {
891
- adapter.log.debug(`Send video to "${name}": ${text.length} bytes`);
892
- }
893
- bot && executeSending(() => bot.sendVideo(dest, text, options), options, resolve);
894
- } else if (
895
- text &&
896
- ((typeof text === 'string' && text.match(/\.(txt|doc|docx|csv|pdf|xls|xlsx)$/i) && fs.existsSync(text)) ||
897
- (options && options.type === 'document'))
898
- ) {
899
- adapter.log.debug(`Send document to "${name}": ${typeof text === 'string' ? text : text.length}`);
900
- bot && executeSending(() => bot.sendDocument(dest, text, options), options, resolve);
901
- } else if (
902
- text &&
903
- ((typeof text === 'string' && text.match(/\.(wav|mp3|ogg)$/i) && fs.existsSync(text)) ||
904
- (options && options?.type === 'audio'))
905
- ) {
906
- adapter.log.debug(`Send audio to "${name}": ${typeof text === 'string' ? text : text.length}`);
907
-
908
- bot && executeSending(() => bot.sendAudio(dest, text, options), options, resolve);
909
- } else if (
910
- text &&
911
- ((typeof text === 'string' && // if the message is a string, and it is a path to file or URL
912
- text.match(/\.(jpg|png|jpeg|bmp|gif)$/i) &&
913
- (fs.existsSync(text) || text.match(/^(https|http)/i))) ||
914
- (options && options.type === 'photo')) // if the type of message is photo
915
- ) {
916
- adapter.log.debug(`Send photo to "${name}": ${typeof text === 'string' ? text : text.length}`);
917
-
918
- bot && executeSending(() => bot.sendPhoto(dest, text, options), options, resolve);
919
- } else if (options && options.answerCallbackQuery !== undefined) {
920
- adapter.log.debug(`Send answerCallbackQuery to "${name}"`);
921
- if (options.answerCallbackQuery.showAlert === undefined) {
922
- options.answerCallbackQuery.showAlert = false;
923
- }
924
- if (bot && callbackQueryId[options.chatId]) {
925
- const originalChatId = callbackQueryId[options.chatId].id;
926
- delete callbackQueryId[options.chatId];
927
- executeSending(
928
- () =>
929
- bot.answerCallbackQuery(
930
- originalChatId,
931
- options.answerCallbackQuery.text,
932
- options.answerCallbackQuery.showAlert,
933
- ),
934
- options,
935
- resolve,
936
- );
937
- }
938
- } else {
939
- adapter.log.debug(`Send message to [${name}]: "${text}"`);
940
- if (text && typeof text === 'string') {
941
- options = options || {};
942
- if (text.startsWith('<MarkdownV2>') && text.endsWith('</MarkdownV2>')) {
943
- options.parse_mode = 'MarkdownV2';
944
- text = text.substring(12, text.length - 13);
945
- } else if (text.startsWith('<HTML>') && text.endsWith('</HTML>')) {
946
- options.parse_mode = 'HTML';
947
- text = text.substring(6, text.length - 7);
948
- } else if (text.startsWith('<Markdown>') && text.endsWith('</Markdown>')) {
949
- options.parse_mode = 'Markdown';
950
- text = text.substring(10, text.length - 11);
951
- }
952
- }
953
- bot && executeSending(() => bot.sendMessage(dest, text || '', options), options, resolve);
954
- }
955
- });
956
- }
957
-
958
- /**
959
- * executes the given method and handles, what to do next
960
- *
961
- * @param action
962
- * @param options
963
- * @param resolve
964
- */
965
- function executeSending(action, options, resolve) {
966
- // create an empty object, to store chat id and message id of successfully sent messages
967
- const messageIds = {};
968
- action()
969
- .then(response => {
970
- // put chat id and message id to the object, that will be returned
971
- // delete message command return only true in response,
972
- // to return deleted message id and chat id the next if construction is used:
973
- if (response?.message_id) {
974
- // The chatId is mostly used in code, instead of chat_id.
975
- messageIds[options.chat_id ? options.chat_id : options.chatId] = response.message_id;
976
- } else if (
977
- typeof response === 'boolean' &&
978
- options?.deleteMessage?.options?.chat_id &&
979
- options?.deleteMessage?.options?.message_id
980
- ) {
981
- messageIds[options.deleteMessage.options.chat_id] = options.deleteMessage.options.message_id;
982
- }
983
- // puts ids to the ioBroker database
984
- saveSendRequest(response);
985
- })
986
- .then(() => {
987
- adapter.log.debug('Message sent');
988
- options = null;
989
- // return all the collected message ids to the callback
990
- resolve(JSON.stringify(messageIds));
991
- })
992
- .catch(error => {
993
- // add the error to the message ids object
994
- messageIds.error = { [options.chat_id ? options.chat_id : options.chatId]: error };
995
- // log error to the system
996
- adapter.log.error(
997
- `Failed sending [${options.chatId ? 'chatId' : 'user'} - ${options.chatId ? options.chatId : options.user}]: ${error}`,
998
- );
999
- options = null;
1000
- // send the successfully sent messages as callback
1001
- resolve(JSON.stringify(messageIds));
1002
- });
1003
- }
1004
-
1005
- // https://core.telegram.org/bots/api
1006
- function sendMessage(text, user, chatId, options) {
1007
- if (!text && typeof options !== 'object' && text !== 0 && (!options || !options.latitude)) {
1008
- adapter.log.warn('Invalid text: null');
1009
- return Promise.resolve({});
1010
- }
1011
-
1012
- if (
1013
- text &&
1014
- typeof text === 'object' &&
1015
- text.text !== undefined &&
1016
- typeof text.text === 'string' &&
1017
- options === undefined
1018
- ) {
1019
- options = text;
1020
- text = options.text;
1021
- if (options.chatId) {
1022
- chatId = options.chatId;
1023
- }
1024
- if (options.user) {
1025
- user = options.user;
1026
- }
1027
- }
1028
-
1029
- if (options && typeof options === 'object') {
1030
- if (options.chatId !== undefined) {
1031
- delete options.chatId;
1032
- }
1033
- if (options.text !== undefined) {
1034
- delete options.text;
1035
- }
1036
- if (options.user !== undefined) {
1037
- delete options.user;
1038
- }
1039
- }
1040
-
1041
- options = options || {};
1042
-
1043
- if (text && typeof text === 'string') {
1044
- if (text && text.startsWith('<MarkdownV2>') && text.endsWith('</MarkdownV2>')) {
1045
- options.parse_mode = 'MarkdownV2';
1046
- text = text.substring(12, text.length - 13);
1047
- } else if (text && text.startsWith('<HTML>') && text.endsWith('</HTML>')) {
1048
- options.parse_mode = 'HTML';
1049
- text = text.substring(6, text.length - 7);
1050
- } else if (text && text.startsWith('<Markdown>') && text.endsWith('</Markdown>')) {
1051
- options.parse_mode = 'Markdown';
1052
- text = text.substring(10, text.length - 11);
1053
- }
1054
- }
1055
-
1056
- const tPromiseList = [];
1057
- // convert
1058
- if (text !== undefined && text !== null && typeof text !== 'object') {
1059
- text = text.toString();
1060
- }
1061
- if (chatId) {
1062
- tPromiseList.push(_sendMessageHelper(chatId, 'chat', text, options));
1063
- return Promise.all(tPromiseList).catch(e => e);
1064
- } else if (user) {
1065
- if (typeof user !== 'string' && !(user instanceof Array)) {
1066
- adapter.log.warn(`Invalid type of user parameter: ${typeof user}. Expected is string or array.`);
1067
- }
1068
-
1069
- const userArray = Array.isArray(user)
1070
- ? user
1071
- : (user || '')
1072
- .toString()
1073
- .split(/[,;\s]/)
1074
- .map(u => u.trim())
1075
- .filter(u => !!u);
1076
- let matches = 0;
1077
- userArray.forEach(userName => {
1078
- for (const id in users) {
1079
- if (!Object.prototype.hasOwnProperty.call(users, id)) {
1080
- continue;
1081
- }
1082
-
1083
- if (
1084
- (adapter.config.useUsername && users[id].userName === userName) ||
1085
- (!adapter.config.useUsername && users[id].firstName === userName)
1086
- ) {
1087
- if (options) {
1088
- options.chatId = id;
1089
- }
1090
- matches++;
1091
- tPromiseList.push(_sendMessageHelper(id, userName, text, options));
1092
- break;
1093
- }
1094
- }
1095
- });
1096
-
1097
- if (userArray.length !== matches) {
1098
- adapter.log.warn(`${userArray.length - matches} of ${userArray.length} recipients are unknown!`);
1099
- }
1100
-
1101
- return Promise.all(tPromiseList).catch(e => e);
1102
- }
1103
-
1104
- const m = typeof text === 'string' ? text.match(/^@(.+?)\b/) : null;
1105
-
1106
- if (m) {
1107
- text = (text || '').toString();
1108
- text = text.replace(`@${m[1]}`, '').trim().replace(/\s\s/g, ' ');
1109
- const re = new RegExp(m[1], 'i');
1110
- let id = '';
1111
- for (const id_t in users) {
1112
- if (!Object.prototype.hasOwnProperty.call(users, id_t)) {
1113
- continue;
1114
- }
1115
- if (
1116
- (adapter.config.useUsername && users[id_t].userName.match(re)) ||
1117
- (!adapter.config.useUsername && users[id_t].firstName.match(re))
1118
- ) {
1119
- id = id_t;
1120
- break;
1121
- }
1122
- }
1123
- if (id) {
1124
- if (options) {
1125
- options.chatId = id;
1126
- }
1127
- tPromiseList.push(_sendMessageHelper(id, m[1], text, options));
1128
- }
1129
- } else {
1130
- // Send to all users
1131
- Object.keys(users).forEach(id => {
1132
- if (options) {
1133
- options.chatId = id;
1134
- }
1135
- tPromiseList.push(
1136
- _sendMessageHelper(
1137
- id,
1138
- adapter.config.useUsername ? users[id].userName : users[id].firstName,
1139
- text,
1140
- options,
1141
- ),
1142
- );
1143
- });
1144
- }
1145
-
1146
- return Promise.all(tPromiseList).catch(e => e);
1147
- }
1148
-
1149
- function saveFile(fileID, fileName, callback) {
1150
- adapter.log.debug(`Saving media file ${fileID} to ${fileName} (location = ${adapter.config.saveFilesTo})`);
1151
-
1152
- bot.getFileLink(fileID)
1153
- .then(url => {
1154
- adapter.log.debug(`Received message: ${url}`);
1155
- https.get(url, res => {
1156
- if (res.statusCode === 200) {
1157
- const buf = [];
1158
- res.on('data', data => buf.push(data));
1159
- res.on('end', () => {
1160
- if (adapter.config.saveFilesTo == 'filesystem') {
1161
- const fileLocation = path.join(tmpDirName, fileName);
1162
- try {
1163
- fs.writeFileSync(fileLocation, Buffer.concat(buf));
1164
-
1165
- callback({
1166
- info: `media file has been saved to "${adapter.config.saveFilesTo}": ${fileLocation}`,
1167
- location: adapter.config.saveFilesTo,
1168
- path: fileLocation,
1169
- });
1170
- } catch (err) {
1171
- return callback({ error: `Error: ${err}` });
1172
- }
1173
- } else if (adapter.config.saveFilesTo == 'iobroker') {
1174
- try {
1175
- const fileLocation = path.join(tmpDirName, fileName); // TODO: check new urn format https://github.com/ioBroker/ioBroker.js-controller/issues/2710
1176
-
1177
- adapter.writeFileAsync(adapter.namespace, fileName, Buffer.concat(buf)).then(() => {
1178
- callback({
1179
- info: `media file has been saved to "${adapter.config.saveFilesTo}": ${fileLocation}`,
1180
- location: adapter.config.saveFilesTo,
1181
- path: fileLocation,
1182
- });
1183
- });
1184
- } catch (err) {
1185
- return callback({ error: `Error: ${err}` });
1186
- }
1187
- }
1188
- });
1189
-
1190
- res.on('error', err => callback({ error: `Error: ${err}` }));
1191
- } else {
1192
- callback({ error: 'Error: statusCode !== 200' });
1193
- }
1194
- });
1195
- })
1196
- .catch(err => callback({ error: `Error bot.getFileLink: ${err}` }));
1197
- }
1198
-
1199
- function getMessage(msg) {
1200
- const date = new Date().toISOString().replace(/T/, '_').replace(/\..+/, '').replace(/:/g, '-');
1201
- adapter.log.debug(`Received message: ${JSON.stringify(msg)}`);
1202
-
1203
- if (msg.voice) {
1204
- try {
1205
- saveFile(msg.voice.file_id, adapter.config.saveFiles ? `/voice/${date}.ogg` : '/voice/temp.ogg', res => {
1206
- if (!res.error) {
1207
- adapter.log.info(res.info);
1208
- adapter.setState('communicate.pathFile', res.path, true, err => err && adapter.log.error(err));
1209
- } else {
1210
- adapter.log.debug(res.error);
1211
- }
1212
- });
1213
- } catch (err) {
1214
- adapter.log.error(`Error saving voice file: ${err}`);
1215
- }
1216
- } else if (adapter.config.saveFiles && msg.photo) {
1217
- try {
1218
- const qualityMap = {
1219
- 0: 'low',
1220
- 1: 'med',
1221
- 2: 'high',
1222
- 3: 'highdef',
1223
- };
1224
-
1225
- let saveOnlyQuality = adapter.config.saveFilesQuality;
1226
- if (saveOnlyQuality) {
1227
- saveOnlyQuality = parseInt(saveOnlyQuality, 10);
1228
- if (msg.photo.length <= saveOnlyQuality) {
1229
- saveOnlyQuality = null;
1230
- } else {
1231
- saveOnlyQuality = saveOnlyQuality.toString();
1232
- }
1233
- }
1234
-
1235
- msg.photo.forEach((item, i) => {
1236
- // skip if quality is set and not equal
1237
- if (saveOnlyQuality && i.toString() !== saveOnlyQuality) {
1238
- return;
1239
- }
1240
- const quality = qualityMap[i] || 'none';
1241
-
1242
- let fileName = '';
1243
- if (msg.media_group_id) {
1244
- if (!Object.prototype.hasOwnProperty.call(mediaGroupExport, msg.media_group_id)) {
1245
- const id = Object.keys(mediaGroupExport).length;
1246
- mediaGroupExport[msg.media_group_id] = {
1247
- id,
1248
- count: 0,
1249
- };
1250
- } else {
1251
- mediaGroupExport[msg.media_group_id].count++;
1252
- }
1253
- fileName = `/photo/${date}_grpID_${mediaGroupExport[msg.media_group_id].id}_${mediaGroupExport[msg.media_group_id].count}_${quality}.jpg`;
1254
- } else {
1255
- fileName = `/photo/${date}_${quality}.jpg`;
1256
- if (fs.existsSync(path.join(tmpDirName, fileName))) {
1257
- let tIdx = 0;
1258
- do {
1259
- fileName = `/photo/${date}_${tIdx}_${quality}.jpg`;
1260
- tIdx++;
1261
- } while (fs.existsSync(path.join(tmpDirName, fileName)));
1262
- }
1263
- }
1264
-
1265
- saveFile(item.file_id, fileName, res => {
1266
- if (!res.error) {
1267
- adapter.log.info(res.info);
1268
- adapter.setState('communicate.pathFile', res.path, true, err => err && adapter.log.error(err));
1269
- } else {
1270
- adapter.log.debug(res.error);
1271
- }
1272
- });
1273
- });
1274
- } catch (err) {
1275
- adapter.log.error(`Error saving photo file: ${err}`);
1276
- }
1277
- } else if (adapter.config.saveFiles && msg.video) {
1278
- try {
1279
- saveFile(msg.video.file_id, `/video/${date}.mp4`, res => {
1280
- if (!res.error) {
1281
- adapter.log.info(res.info);
1282
- adapter.setState('communicate.pathFile', res.path, true, err => err && adapter.log.error(err));
1283
- } else {
1284
- adapter.log.debug(res.error);
1285
- }
1286
- });
1287
- } catch (err) {
1288
- adapter.log.error(`Error saving video file: ${err}`);
1289
- }
1290
- } else if (adapter.config.saveFiles && msg.video_note) {
1291
- try {
1292
- saveFile(msg.video_note.file_id, `/video/${date}.mp4`, res => {
1293
- if (!res.error) {
1294
- adapter.log.info(res.info);
1295
- adapter.setState('communicate.pathFile', res.path, true, err => err && adapter.log.error(err));
1296
- } else {
1297
- adapter.log.debug(res.error);
1298
- }
1299
- });
1300
- } catch (err) {
1301
- adapter.log.error(`Error saving video file: ${err}`);
1302
- }
1303
- } else if (adapter.config.saveFiles && msg.audio) {
1304
- try {
1305
- saveFile(msg.audio.file_id, `/audio/${date}.mp3`, res => {
1306
- if (!res.error) {
1307
- adapter.log.info(res.info);
1308
- adapter.setState('communicate.pathFile', res.path, true, err => err && adapter.log.error(err));
1309
- } else {
1310
- adapter.log.debug(res.error);
1311
- }
1312
- });
1313
- } catch (err) {
1314
- adapter.log.error(`Error saving audio file: ${err}`);
1315
- }
1316
- } else if (adapter.config.saveFiles && msg.document) {
1317
- try {
1318
- saveFile(msg.document.file_id, `/document/${msg.document.file_name}`, res => {
1319
- if (!res.error) {
1320
- adapter.log.info(res.info);
1321
- adapter.setState('communicate.pathFile', res.path, true, err => err && adapter.log.error(err));
1322
- } else {
1323
- adapter.log.debug(res.error);
1324
- }
1325
- });
1326
- } catch (err) {
1327
- adapter.log.error(`Error saving document file: ${err}`);
1328
- }
1329
- }
1330
- }
1331
-
1332
- async function processMessage(obj) {
1333
- if (!obj || !obj.command) {
1334
- return;
1335
- }
1336
- // Ignore own answers
1337
- if (obj.message && obj.message.response) {
1338
- return;
1339
- }
1340
-
1341
- // filter out the double messages
1342
- const json = JSON.stringify(obj);
1343
- if (lastMessageTime && lastMessageText === JSON.stringify(obj) && Date.now() - lastMessageTime < 1200) {
1344
- return adapter.log.debug(
1345
- `Filter out double message [first was for ${Date.now() - lastMessageTime}ms]: ${json}`,
1346
- );
1347
- }
1348
-
1349
- lastMessageTime = Date.now();
1350
- lastMessageText = json;
1351
-
1352
- adapter.log.debug(`Received command "${obj.command}": ${JSON.stringify(obj.message)}`);
1353
-
1354
- switch (obj.command) {
1355
- case 'send':
1356
- if (obj.message) {
1357
- let tPromise;
1358
- if (typeof obj.message === 'object') {
1359
- tPromise = sendMessage(obj.message.text, obj.message?.user, obj.message?.chatId, obj.message);
1360
- } else {
1361
- tPromise = sendMessage(obj.message);
1362
- }
1363
-
1364
- tPromise
1365
- .then(count => obj.callback && adapter.sendTo(obj.from, obj.command, count, obj.callback))
1366
- .catch(e => adapter.log.error(`Cannot send command: ${e}`));
1367
- }
1368
- break;
1369
-
1370
- case 'ask':
1371
- if (obj.message) {
1372
- const question = {
1373
- cb: obj.callback,
1374
- from: obj.from,
1375
- ts: Date.now(),
1376
- };
1377
-
1378
- if (typeof obj.message === 'object') {
1379
- const messages = await sendMessage(
1380
- obj.message.text,
1381
- obj.message.user,
1382
- obj.message.chatId,
1383
- obj.message,
1384
- );
1385
- const msgIds = messages.length > 0 ? messages.map(JSON.parse)[0] : {};
1386
-
1387
- question.chatId = obj.message.chatId;
1388
- question.user = obj.message.user;
1389
- question.msgId = msgIds?.[question.chatId];
1390
- } else {
1391
- sendMessage(obj.message);
1392
- }
1393
-
1394
- if (obj.callback) {
1395
- adapter._questions.push(question);
1396
- adapter.log.debug(
1397
- `added question: ${JSON.stringify(question)} - answer timeout: ${adapter.config.answerTimeoutSec}`,
1398
- );
1399
-
1400
- question.timeout = setTimeout(
1401
- q => {
1402
- q.timeout = null;
1403
- adapter.sendTo(q.from, 'ask', '__timeout__', q.callback);
1404
-
1405
- adapter.log.info(`question timeout for: ${JSON.stringify(q)}`);
1406
-
1407
- // Remove keyboard
1408
- if (bot && q?.chatId && q?.msgId) {
1409
- bot.editMessageReplyMarkup(
1410
- { inline_keyboard: [] },
1411
- { chat_id: q.chatId, message_id: q.msgId },
1412
- );
1413
- adapter.log.debug(`removed inline_keyboard for msg ${q.msgId}: ${JSON.stringify(q)}`);
1414
- }
1415
-
1416
- const pos = adapter._questions.indexOf(q);
1417
- pos !== -1 && adapter._questions.splice(pos);
1418
- },
1419
- adapter.config.answerTimeoutSec + 1000,
1420
- question,
1421
- );
1422
- }
1423
- }
1424
- break;
1425
-
1426
- case 'call':
1427
- if (obj.message) {
1428
- let call = {};
1429
- if (typeof obj.message === 'object') {
1430
- call = obj.message;
1431
- } else {
1432
- call.message = obj.message;
1433
- }
1434
-
1435
- if (call.users && call.user) {
1436
- adapter.log.error(`Please provide only user or users as array. Attribute user will be ignored!`);
1437
- }
1438
- if (!call.users && call.user) {
1439
- call.users = [call.user];
1440
- }
1441
- if (!call.users && !call.user) {
1442
- call.users = Object.keys(users)
1443
- .filter(id => users[id] && users[id].userName)
1444
- .map(id =>
1445
- users[id].userName.startsWith('@') ? users[id].userName : `@${users[id].userName}`,
1446
- );
1447
- }
1448
- if (!(call.users instanceof Array)) {
1449
- call.users = [call.users];
1450
- }
1451
- // set language
1452
- call.lang = call.lang || systemLang2CallMe[systemLang] || systemLang2CallMe.en;
1453
- if (!call.file) {
1454
- // Set message
1455
- call.message = call.message || call.text || _('Call text', call.lang || systemLang);
1456
- } else {
1457
- call.message = '';
1458
- }
1459
-
1460
- //
1461
- if (!call.users || !call.users.length) {
1462
- adapter.log.error(
1463
- `Cannot make a call, because no users stored in ${adapter.namespace}.communicate.users`,
1464
- );
1465
- } else {
1466
- callUsers(call.users, call.message, call.lang, call.file, call.repeats);
1467
- }
1468
- }
1469
- break;
1470
- }
1471
- }
1472
-
1473
- function callUsers(users, text, lang, file, repeats, cb) {
1474
- if (!users || !users.length) {
1475
- cb && cb();
1476
- } else {
1477
- let user = users.shift();
1478
- if (!user.startsWith('@') && !user.startsWith('+') && !user.startsWith('00')) {
1479
- user = `@${user}`;
1480
- }
1481
-
1482
- let url = 'http://api.callmebot.com/start.php?source=iobroker&';
1483
- const params = [`user=${encodeURIComponent(user)}`];
1484
- if (file) {
1485
- params.push(`file=${encodeURIComponent(file)}`);
1486
- } else {
1487
- params.push(`text=${encodeURIComponent(text)}`);
1488
- }
1489
- if (repeats !== undefined) {
1490
- params.push(`rpt=${parseInt(repeats, 10) || 0}`);
1491
- }
1492
-
1493
- params.push(`lang=${lang || systemLang2CallMe[systemLang]}`);
1494
- url += params.join('&');
1495
- adapter.log.debug(`CALL: ${url}`);
1496
-
1497
- axios
1498
- .get(url)
1499
- .then(response => {
1500
- const body = response && response.data;
1501
- if (!body || !response || response.status !== 200) {
1502
- adapter.log.error(
1503
- `Cannot make a call to ${user}: ${body || (response && response.status) || 'Unknown error'}`,
1504
- );
1505
- } else {
1506
- adapter.log.debug(
1507
- `Call to ${user} was made: ${body.substring(body.indexOf('<p>')).replace(/<p>/g, ' ')}`,
1508
- );
1509
- }
1510
- setImmediate(callUsers, users, text, lang, file, repeats, cb);
1511
- })
1512
- .catch(err => {
1513
- adapter.log.error(`Cannot make a call to ${user}: ${err || 'Unknown error'}`);
1514
- setImmediate(callUsers, users, text, lang, file, repeats, cb);
1515
- });
1516
- }
1517
- }
1518
-
1519
- function storeUser(id, firstName, userName) {
1520
- if (!users[id] || users[id].firstName !== firstName || users[id].userName !== userName) {
1521
- Object.keys(users).forEach(id => {
1522
- if (userName && users[id].userName === userName) {
1523
- delete users[id];
1524
- }
1525
- if (!userName && !users[id].userName && users[id].firstName === firstName) {
1526
- delete users[id];
1527
- }
1528
- });
1529
-
1530
- users[id] = { firstName, userName, sysMessages: false };
1531
-
1532
- if (adapter.config.rememberUsers) {
1533
- adapter.setState('communicate.users', JSON.stringify(users), true);
1534
- }
1535
- }
1536
- }
1537
-
1538
- function getListOfCommands() {
1539
- const ids = Object.keys(commands).sort((a, b) => commands[b].alias - commands[a].alias);
1540
- const lines = [];
1541
-
1542
- ids.forEach(id => {
1543
- if (!commands[id].readOnly) {
1544
- if (commands[id].type === 'boolean') {
1545
- if (commands[id].writeOnly) {
1546
- lines.push(
1547
- `${commands[id].alias} ${commands[id].onCommand || _('ON-Command')}|${commands[id].offCommand || _('OFF-Command')}`,
1548
- );
1549
- } else {
1550
- lines.push(
1551
- `${commands[id].alias} ${commands[id].onCommand || _('ON-Command')}|${commands[id].offCommand || _('OFF-Command')}|?`,
1552
- );
1553
- }
1554
- } else {
1555
- if (commands[id].writeOnly) {
1556
- lines.push(`${commands[id].alias} ${_(`value as ${commands[id].type}`)}`);
1557
- } else {
1558
- lines.push(`${commands[id].alias} ${_(`value as ${commands[id].type}`)}|?`);
1559
- }
1560
- }
1561
- }
1562
- });
1563
-
1564
- if (!lines.length) {
1565
- lines.push(_('No commands found.'));
1566
- }
1567
-
1568
- return lines.join('\n');
1569
- }
1570
-
1571
- function getCommandsKeyboard(chatId) {
1572
- const ids = Object.keys(commands).sort((a, b) => commands[b].alias - commands[a].alias);
1573
- const keyboard = [];
1574
-
1575
- ids.forEach(id => {
1576
- if (!commands[id].readOnly) {
1577
- if (commands[id].type === 'boolean') {
1578
- if (commands[id].onlyTrue) {
1579
- if (commands[id].buttons === 1) {
1580
- keyboard.push([`${commands[id].alias} ${commands[id].onCommand || _('ON-Command')}`]);
1581
- !commands[id].writeOnly && keyboard.push([`${commands[id].alias} ?`]);
1582
- } else {
1583
- commands[id].writeOnly
1584
- ? keyboard.push([`${commands[id].alias} ${commands[id].onCommand || _('ON-Command')}`])
1585
- : keyboard.push([
1586
- `${commands[id].alias} ${commands[id].onCommand || _('ON-Command')}`,
1587
- `${commands[id].alias} ?`,
1588
- ]);
1589
- }
1590
- } else {
1591
- if (commands[id].buttons === 1) {
1592
- keyboard.push([`${commands[id].alias} ${commands[id].onCommand || _('ON-Command')}`]);
1593
- keyboard.push([`${commands[id].alias} ${commands[id].offCommand || _('OFF-Command')}`]);
1594
- !commands[id].writeOnly && keyboard.push([`${commands[id].alias} ?`]);
1595
- } else if (commands[id].buttons === 2) {
1596
- keyboard.push([
1597
- `${commands[id].alias} ${commands[id].onCommand || _('ON-Command')}`,
1598
- `${commands[id].alias} ${commands[id].offCommand || _('OFF-Command')}`,
1599
- ]);
1600
- !commands[id].writeOnly && keyboard.push([`${commands[id].alias} ?`]);
1601
- } else {
1602
- commands[id].writeOnly
1603
- ? keyboard.push([
1604
- `${commands[id].alias} ${commands[id].onCommand || _('ON-Command')}`,
1605
- `${commands[id].alias} ${commands[id].offCommand || _('OFF-Command')}`,
1606
- ])
1607
- : keyboard.push([
1608
- `${commands[id].alias} ${commands[id].onCommand || _('ON-Command')}`,
1609
- `${commands[id].alias} ${commands[id].offCommand || _('OFF-Command')}`,
1610
- `${commands[id].alias} ?`,
1611
- ]);
1612
- }
1613
- }
1614
- } else if (commands[id].states) {
1615
- let s = [];
1616
- const stat = Object.keys(commands[id].states);
1617
- for (let i = 0; i <= stat.length; i++) {
1618
- s.push(`${commands[id].alias} ${commands[id].states[stat[i]]}`);
1619
- if (s.length >= (commands[id].buttons || 3)) {
1620
- keyboard.push(s);
1621
- s = [];
1622
- }
1623
- }
1624
- !commands[id].writeOnly && s.push(`${commands[id].alias} ?`);
1625
- keyboard.push(s);
1626
- } else if (commands[id].type === 'number' && commands[id].unit === '%') {
1627
- let s = [];
1628
- const step = ((commands[id].max || 100) - (commands[id].min || 0)) / 4;
1629
- for (let i = commands[id].min || 0; i <= (commands[id].max || 100); i += step) {
1630
- s.push(`${commands[id].alias} ${i}%`);
1631
- if (s.length >= (commands[id].buttons || 3)) {
1632
- keyboard.push(s);
1633
- s = [];
1634
- }
1635
- }
1636
- !commands[id].writeOnly && s.push(`${commands[id].alias} ?`);
1637
- keyboard.push(s);
1638
- } else {
1639
- adapter.log.warn(
1640
- `Unsupported state type for keyboard: ${commands[id].type}. Only numbers and booleans are supported`,
1641
- );
1642
- }
1643
- } else {
1644
- keyboard.push([`${commands[id].alias} ?`]);
1645
- }
1646
- });
1647
-
1648
- bot.sendMessage(chatId, _('Select option'), {
1649
- reply_markup: {
1650
- keyboard,
1651
- resize_keyboard: true,
1652
- one_time_keyboard: true,
1653
- },
1654
- chatId,
1655
- })
1656
- .then(() => {
1657
- adapter.log.debug('Message sent');
1658
- })
1659
- .catch(error => {
1660
- adapter.log.error(`Send message error: ${error}`);
1661
- });
1662
- }
1663
-
1664
- function isAnswerForQuestion(adapter, msg) {
1665
- if (adapter._questions && adapter._questions.length) {
1666
- const now = Date.now();
1667
- const chatId = msg.chat && msg.chat.id;
1668
-
1669
- let question =
1670
- chatId &&
1671
- adapter._questions.find(
1672
- q => q.chatId === chatId && q.user === msg.from.id && now - q.ts < adapter.config.answerTimeoutSec,
1673
- );
1674
- question =
1675
- question ||
1676
- (chatId &&
1677
- adapter._questions.find(q => q.chatId === chatId && now - q.ts < adapter.config.answerTimeoutSec));
1678
- question = question || adapter._questions.find(q => now - q.ts < adapter.config.answerTimeoutSec);
1679
-
1680
- // user have 60 seconds for answer
1681
- if (question && Date.now() - question.ts < adapter.config.answerTimeoutSec) {
1682
- if (question.timeout) {
1683
- clearTimeout(question.timeout);
1684
- question.timeout = null;
1685
- adapter.sendTo(question.from, 'ask', msg, question.cb);
1686
-
1687
- // Remove keyboard
1688
- if (bot && question?.chatId && question?.msgId) {
1689
- bot.editMessageReplyMarkup(
1690
- { inline_keyboard: [] },
1691
- { chat_id: question.chatId, message_id: question.msgId },
1692
- );
1693
- adapter.log.debug(`removed inline_keyboard for msg ${question.msgId}: ${JSON.stringify(question)}`);
1694
- }
1695
- }
1696
- adapter._questions.splice(adapter._questions.indexOf(question), 1);
1697
- }
1698
-
1699
- // remove old questions
1700
- adapter._questions = adapter._questions.filter(q => now - q.ts < adapter.config.answerTimeoutSec);
1701
- }
1702
- }
1703
-
1704
- function garbageCollector() {
1705
- const now = Date.now() - 5 * 60000; // last 5 minutes
1706
-
1707
- Object.keys(protection).forEach(user => {
1708
- let a;
1709
- for (a = 0; a < protection[user].length; a++) {
1710
- // find first entry newer than 5 minutes
1711
- if (protection[user][a] > now) {
1712
- break;
1713
- }
1714
- }
1715
- // remove all old entries
1716
- if (a < protection[user].length && a) {
1717
- protection[user].splice(0, a);
1718
- }
1719
- if (!protection[user].length) {
1720
- delete protection[user];
1721
- }
1722
- });
1723
-
1724
- if (!Object.keys(protection).length) {
1725
- gcInterval && clearInterval(gcInterval);
1726
- gcInterval = null;
1727
- }
1728
- }
1729
-
1730
- function processTelegramText(msg) {
1731
- connectionState(true);
1732
-
1733
- // see https://core.telegram.org/bots/api#message
1734
- adapter.log.debug(JSON.stringify(msg));
1735
-
1736
- const user = !adapter.config.useUsername
1737
- ? msg.from.first_name
1738
- : !msg.from.username
1739
- ? msg.from.first_name
1740
- : msg.from.username;
1741
-
1742
- const now = Date.now();
1743
- let pollingInterval = 0;
1744
- if (adapter.config && adapter.config.pollingInterval !== undefined) {
1745
- pollingInterval = parseInt(adapter.config.pollingInterval, 10) || 0;
1746
- }
1747
-
1748
- // ignore all messages older than 30 seconds + polling interval
1749
- if (now - msg.date * 1000 > pollingInterval + 30000) {
1750
- adapter.log.warn(
1751
- `Message from ${msg.from.name} ignored, because too old: (${pollingInterval + 30000}) ${msg.text}`,
1752
- );
1753
- return bot
1754
- .sendMessage(msg.from.id, _('Message ignored: ', systemLang) + msg.text)
1755
- .catch(error => adapter.log.error(`send Message Error: ${error}`));
1756
- }
1757
-
1758
- msg.text = (msg.text || '').trim();
1759
-
1760
- // sometimes telegram sends messages like "message@user_name"
1761
- const pos = msg.text.lastIndexOf('@');
1762
- if (pos !== -1) {
1763
- msg.text = msg.text.substring(0, pos);
1764
- }
1765
-
1766
- if (msg.text === '/password' && !adapter.config.doNotAcceptNewUser) {
1767
- return bot
1768
- .sendMessage(msg.from.id, _('Please enter password in form "/password phrase"', systemLang))
1769
- .catch(error => adapter.log.error(`send Message Error:${error}`));
1770
- }
1771
-
1772
- if (adapter.config.password && !adapter.config.doNotAcceptNewUsers) {
1773
- // if user sent password
1774
- let m = msg.text.match(/^\/password (.+)$/);
1775
- m = m || msg.text.match(/^\/p (.+)$/);
1776
-
1777
- if (m) {
1778
- garbageCollector();
1779
-
1780
- if (protection[user] && protection[user].length >= 5) {
1781
- return bot
1782
- .sendMessage(
1783
- msg.from.id,
1784
- `${_('Too many attempts. Blocked for', systemLang)} ${Math.round((now - protection[user][protection[user].length - 1]) / 1000)} ${_('seconds', systemLang)}`,
1785
- )
1786
- .catch(error => adapter.log.error(`send Message Error: ${error}`));
1787
- }
1788
-
1789
- if (adapter.config.password === m[1]) {
1790
- if (protection[user]) {
1791
- delete protection[user];
1792
- }
1793
- storeUser(msg.from.id, msg.from.first_name, msg.from.username);
1794
-
1795
- if (!msg.from.username) {
1796
- adapter.log.warn(`User ${msg.from.first_name} hast not set an username in the Telegram App!!`);
1797
- }
1798
-
1799
- return bot
1800
- .sendMessage(msg.from.id, _('Welcome ', systemLang) + user)
1801
- .catch(error => adapter.log.error(`send Message Error: ${error}`));
1802
- }
1803
- protection[user] = protection[user] || [];
1804
- protection[user].push(Date.now());
1805
-
1806
- gcInterval = gcInterval || setInterval(() => garbageCollector(), 60000);
1807
-
1808
- adapter.log.warn(`Got invalid password from ${user}: ${m[1]}`);
1809
-
1810
- bot.sendMessage(msg.from.id, _('Invalid password', systemLang)).catch(error =>
1811
- adapter.log.error(`send Message Error: ${error}`),
1812
- );
1813
-
1814
- if (users[msg.from.id]) {
1815
- delete users[msg.from.id];
1816
- }
1817
- }
1818
- }
1819
-
1820
- // todo support commands: instances, running, restart
1821
-
1822
- // If a user is not in the trusted list
1823
- if ((adapter.config.password || adapter.config.doNotAcceptNewUsers) && !users[msg.from.id]) {
1824
- return bot
1825
- .sendMessage(
1826
- msg.from.id,
1827
- _(
1828
- adapter.config.doNotAcceptNewUsers
1829
- ? 'User is not in the list'
1830
- : 'Please enter password in form "/password phrase"',
1831
- systemLang,
1832
- ),
1833
- )
1834
- .catch(error => adapter.log.error(`send Message Error: ${error}`));
1835
- }
1836
-
1837
- if (msg.text === '/help') {
1838
- return bot
1839
- .sendMessage(msg.from.id, getListOfCommands())
1840
- .catch(error => adapter.log.error(`send Message Error: ${error}`));
1841
- }
1842
-
1843
- isAnswerForQuestion(adapter, msg);
1844
-
1845
- if (msg.text === adapter.config.keyboard || msg.text === '/commands') {
1846
- adapter.log.debug('Response keyboard');
1847
- if (adapter.config.rooms) {
1848
- getCommandsKeyboard(msg.chat.id);
1849
- //getRoomsKeyboard(msg.chat.id)
1850
- } else {
1851
- getCommandsKeyboard(msg.chat.id);
1852
- }
1853
- return;
1854
- }
1855
-
1856
- if (adapter.config.rooms) {
1857
- // detect if some room is selected
1858
- }
1859
-
1860
- // Search all user's states and try to detect something like "device-alias on"
1861
- let found = false;
1862
- for (const id in commands) {
1863
- if (Object.prototype.hasOwnProperty.call(commands, id)) {
1864
- if (msg.text.startsWith(`${commands[id].alias} `)) {
1865
- let sValue = msg.text.substring(commands[id].alias.length + 1);
1866
- found = true;
1867
- if (sValue === '?') {
1868
- adapter.getForeignState(id, (err, state) =>
1869
- bot
1870
- .sendMessage(msg.chat.id, getStatus(id, state))
1871
- .catch(error => adapter.log.error(`send Message Error: ${error}`)),
1872
- );
1873
- } else {
1874
- let value;
1875
- if (commands[id].states) {
1876
- const sState = Object.keys(commands[id].states).find(
1877
- val => commands[id].states[val] === sValue,
1878
- );
1879
- if (sState !== null && sState !== undefined) {
1880
- sValue = sState;
1881
- }
1882
- }
1883
-
1884
- if (commands[id].type === 'boolean') {
1885
- value = commands[id].onCommand
1886
- ? sValue === commands[id].onCommand
1887
- : sValue === _('ON-Command') ||
1888
- sValue === 'true' ||
1889
- sValue.toLowerCase() === 'on' ||
1890
- sValue === '1';
1891
- } else if (commands[id].type === 'number') {
1892
- sValue = sValue.replace('%', '').trim();
1893
- value = parseFloat(sValue);
1894
- if (sValue !== value.toString()) {
1895
- bot.sendMessage(msg.chat.id, _('Invalid number %s', sValue)).catch(error =>
1896
- adapter.log.error(`send Message Error: ${error}`),
1897
- );
1898
- continue;
1899
- }
1900
- } else {
1901
- value = sValue;
1902
- }
1903
-
1904
- adapter
1905
- .setForeignState(id, value, false, () => bot.sendMessage(msg.chat.id, _('Done')))
1906
- .catch(error => adapter.log.error(`send Message Error: ${error}`));
1907
- }
1908
- }
1909
- }
1910
- }
1911
- if (found) {
1912
- return;
1913
- }
1914
-
1915
- storeUser(msg.from.id, msg.from.first_name, msg.from.username);
1916
-
1917
- if (!msg.from.username) {
1918
- adapter.log.warn(`User ${msg.from.first_name} hast not set an username in the Telegram App!!`);
1919
- }
1920
-
1921
- if (adapter.config.allowStates) {
1922
- // Check set state
1923
- let m = msg.text.match(/^\/state (.+) (.+)$/);
1924
- if (m) {
1925
- let id1 = m[1];
1926
- let val1 = m[2];
1927
-
1928
- // clear by timeout id
1929
- let memoryLeak1 = setTimeout(() => {
1930
- msg = null;
1931
- memoryLeak1 = null;
1932
- id1 = null;
1933
- val1 = null;
1934
- }, 1000);
1935
-
1936
- adapter.getForeignState(id1, (err, state) => {
1937
- if (memoryLeak1) {
1938
- clearTimeout(memoryLeak1);
1939
- memoryLeak1 = null;
1940
- m = null;
1941
- }
1942
- if (msg) {
1943
- if (err) {
1944
- bot.sendMessage(msg.from.id, err).catch(error =>
1945
- adapter.log.error(`send Message Error: ${error}`),
1946
- );
1947
- }
1948
- if (state) {
1949
- adapter.setForeignState(id1, val1, false, err => {
1950
- if (msg) {
1951
- if (err) {
1952
- bot.sendMessage(msg.from.id, err).catch(error =>
1953
- adapter.log.error(`send Message Error: ${error}`),
1954
- );
1955
- } else {
1956
- bot.sendMessage(msg.from.id, _('Done', systemLang)).catch(error =>
1957
- adapter.log.error(`send Message Error: ${error}`),
1958
- );
1959
- }
1960
- }
1961
- });
1962
- } else {
1963
- bot.sendMessage(msg.from.id, _('ID "%s" not found.', systemLang).replace('%s', id1)).catch(
1964
- error => adapter.log.error(`send Message Error: ${error}`),
1965
- );
1966
- }
1967
- }
1968
- });
1969
- return;
1970
- }
1971
-
1972
- // Check get state
1973
- m = msg.text.match(/^\/state (.+)$/);
1974
- if (m) {
1975
- let id2 = m[1];
1976
-
1977
- // clear by timeout id
1978
- let memoryLeak2 = setTimeout(() => {
1979
- id2 = null;
1980
- msg = null;
1981
- memoryLeak2 = null;
1982
- }, 1000);
1983
-
1984
- adapter.getForeignState(id2, (err, state) => {
1985
- if (memoryLeak2) {
1986
- clearTimeout(memoryLeak2);
1987
- memoryLeak2 = null;
1988
- m = null;
1989
- }
1990
- if (msg) {
1991
- if (err) {
1992
- bot.sendMessage(msg.from.id, err).catch(error =>
1993
- adapter.log.error(`send Message Error: ${error}`),
1994
- );
1995
- }
1996
- if (state) {
1997
- bot.sendMessage(msg.from.id, state.val.toString()).catch(error =>
1998
- adapter.log.error(`send Message Error: ${error}`),
1999
- );
2000
- } else {
2001
- bot.sendMessage(msg.from.id, _('ID "%s" not found.', systemLang).replace('%s', id2)).catch(
2002
- error => adapter.log.error(`send Message Error: ${error}`),
2003
- );
2004
- }
2005
- }
2006
- });
2007
- return;
2008
- }
2009
- }
2010
-
2011
- adapter.log.debug(`Got message from ${user}: ${msg.text}`);
2012
-
2013
- // Send to text2command
2014
- if (adapter.config.text2command) {
2015
- adapter.sendTo(
2016
- adapter.config.text2command,
2017
- 'send',
2018
- {
2019
- text: msg.text.replace(/\//g, '#').replace(/_/g, ' '),
2020
- id: msg.chat.id,
2021
- user,
2022
- },
2023
- response => {
2024
- if (response && response.response) {
2025
- let text = response.response;
2026
- let options;
2027
- if (text && typeof text === 'string') {
2028
- if (text.startsWith('<MarkdownV2>') && text.endsWith('</MarkdownV2>')) {
2029
- options = { parse_mode: 'MarkdownV2' };
2030
- text = text.substring(12, text.length - 13);
2031
- } else if (text.startsWith('<HTML>') && text.endsWith('</HTML>')) {
2032
- options = { parse_mode: 'HTML' };
2033
- text = text.substring(6, text.length - 7);
2034
- } else if (text.startsWith('<Markdown>') && text.endsWith('</Markdown>')) {
2035
- options = { parse_mode: 'Markdown' };
2036
- text = text.substring(10, text.length - 11);
2037
- }
2038
- }
2039
-
2040
- adapter.log.debug(`Send response: ${text}`);
2041
- bot.sendMessage(response.id, text, options).catch(error =>
2042
- adapter.log.error(`send Message Error: ${error}`),
2043
- );
2044
- }
2045
- },
2046
- );
2047
- }
2048
-
2049
- adapter.setState('communicate.requestChatId', { val: msg.chat.id, ack: true });
2050
- adapter.setState('communicate.requestMessageId', { val: msg.message_id, ack: true });
2051
- adapter.setState('communicate.requestMessageThreadId', {
2052
- val: msg?.is_topic_message ? msg.message_thread_id : 0,
2053
- ack: true,
2054
- });
2055
- adapter.setState('communicate.requestUserId', {
2056
- val: msg.from && msg.from.id !== undefined && msg.from.id !== null ? msg.from.id.toString() : '',
2057
- ack: true,
2058
- });
2059
- adapter.setState('communicate.request', { val: `[${user}]${msg.text}`, ack: true });
2060
- }
2061
-
2062
- function connect() {
2063
- if (bot) {
2064
- if (!adapter.config.server) {
2065
- try {
2066
- if (bot.isPolling()) {
2067
- adapter.log.debug('bot polling OK');
2068
- } else {
2069
- adapter.log.debug('bot restarting...');
2070
- bot.stopPolling().then(
2071
- () => {
2072
- adapter.log.debug('Start Polling');
2073
- bot.startPolling();
2074
- },
2075
- error => {
2076
- adapter.log.error(`Error stop polling: ${error}`);
2077
- },
2078
- );
2079
- }
2080
- } catch {
2081
- // looks empty
2082
- }
2083
- }
2084
- // Check connection
2085
- bot.getMe()
2086
- .then(data => {
2087
- adapter.log.debug(`getMe (reconnect): ${JSON.stringify(data)}`);
2088
- connectionState(true);
2089
- })
2090
- .catch(error => adapter.log.error(`getMe (reconnect) Error:${error}`));
2091
- } else {
2092
- if (adapter.config.server) {
2093
- // Setup server way
2094
- const serverOptions = {
2095
- polling: false,
2096
- filepath: true,
2097
- baseApiUrl: adapter.config.baseApiUrl,
2098
- };
2099
- bot = new TelegramBot(adapter.config.token, serverOptions);
2100
- if (adapter.config.url[adapter.config.url.length - 1] === '/') {
2101
- adapter.config.url = adapter.config.url.substring(0, adapter.config.url.length - 1);
2102
- }
2103
- bot.setWebHook(`${adapter.config.url}/${adapter.config.token}`);
2104
- } else {
2105
- // Setup polling way
2106
- const pollingOptions = {
2107
- polling: {
2108
- interval: parseInt(adapter.config.pollingInterval, 10) || 300,
2109
- },
2110
- filepath: true,
2111
- baseApiUrl: adapter.config.baseApiUrl,
2112
- };
2113
- adapter.log.debug(
2114
- `Start polling with: ${pollingOptions.polling.interval}(${typeof pollingOptions.polling.interval}) ms interval`,
2115
- );
2116
- bot = new TelegramBot(adapter.config.token, pollingOptions);
2117
- bot.setWebHook('').catch(error => {
2118
- adapter.log.error(`setWebHook Error:${error}`);
2119
- });
2120
- }
2121
-
2122
- // Check connection
2123
- bot.getMe()
2124
- .then(data => {
2125
- adapter.log.debug(`getMe: ${JSON.stringify(data)}`);
2126
- connectionState(true);
2127
-
2128
- if (adapter.config.restarted !== '') {
2129
- // default text
2130
- if (
2131
- adapter.config.restarted === '_' ||
2132
- adapter.config.restarted === null ||
2133
- adapter.config.restarted === undefined
2134
- ) {
2135
- sendSystemMessage(_('Started!'));
2136
- } else {
2137
- sendSystemMessage(adapter.config.restarted);
2138
- }
2139
- }
2140
- })
2141
- .catch(error => {
2142
- adapter.log.error(`getMe Error:${error}`);
2143
- connectionState(false);
2144
- });
2145
-
2146
- // Matches /echo [whatever]
2147
- bot.onText(/(.+)/, processTelegramText);
2148
- bot.on('message', msg => {
2149
- connectionState(true);
2150
-
2151
- if (adapter.config.storeRawRequest) {
2152
- adapter.setState('communicate.requestRaw', { val: JSON.stringify(msg, null, 2), ack: true });
2153
- }
2154
-
2155
- getMessage(msg);
2156
- });
2157
-
2158
- // callback InlineKeyboardButton
2159
- bot.on('callback_query', callbackQuery => {
2160
- connectionState(true);
2161
-
2162
- // write received answer into variable
2163
- adapter.log.debug(`callback_query: ${JSON.stringify(callbackQuery)}`);
2164
- callbackQueryId[callbackQuery.from.id] = { id: callbackQuery.id, ts: Date.now() };
2165
-
2166
- if (adapter.config.storeRawRequest) {
2167
- adapter.setState(
2168
- 'communicate.requestRaw',
2169
- JSON.stringify(callbackQuery),
2170
- true,
2171
- err => err && adapter.log.error(err),
2172
- );
2173
- }
2174
-
2175
- adapter.setState(
2176
- 'communicate.requestMessageId',
2177
- callbackQuery.message.message_id,
2178
- true,
2179
- err => err && adapter.log.error(err),
2180
- );
2181
- adapter.setState(
2182
- 'communicate.requestChatId',
2183
- callbackQuery.message.chat.id,
2184
- true,
2185
- err => err && adapter.log.error(err),
2186
- );
2187
- adapter.setState(
2188
- 'communicate.request',
2189
- `[${
2190
- !adapter.config.useUsername
2191
- ? callbackQuery.from.first_name
2192
- : !callbackQuery.from.username
2193
- ? callbackQuery.from.first_name
2194
- : callbackQuery.from.username
2195
- }]${callbackQuery.data}`,
2196
- true,
2197
- err => err && adapter.log.error(err),
2198
- );
2199
-
2200
- isAnswerForQuestion(adapter, callbackQuery);
2201
- });
2202
-
2203
- bot.on('polling_error', error => {
2204
- if (isConnected) {
2205
- adapter.log.warn(`polling_error: ${error.code}, ${error.message.replace(/<[^>]+>/g, '')}`); // => 'EFATAL'
2206
- connectionState(false);
2207
- }
2208
- });
2209
-
2210
- bot.on('webhook_error', error => {
2211
- adapter.log.error(`webhook_error:${error.code}, ${error.message.replace(/<[^>]+>/g, '')}`); // => 'EPARSE'
2212
- adapter.log.debug('bot restarting...');
2213
-
2214
- bot.stopPolling().then(
2215
- () => {
2216
- adapter.log.debug('Start Polling');
2217
- bot.startPolling();
2218
- },
2219
- error => {
2220
- adapter.log.error(`Error stop polling: ${error}`);
2221
- },
2222
- );
2223
- });
2224
- }
2225
- }
2226
-
2227
- async function updateUsers() {
2228
- if (adapter.config.rememberUsers) {
2229
- try {
2230
- const state = await adapter.getStateAsync('communicate.users');
2231
- if (state && state.val) {
2232
- try {
2233
- users = JSON.parse(state.val);
2234
-
2235
- // convert old format to new format
2236
- Object.keys(users).forEach(id => {
2237
- if (typeof users[id] !== 'object') {
2238
- if (adapter.config.useUsername) {
2239
- users[id] = {
2240
- userName: users[id],
2241
- firstName: users[id],
2242
- sysMessages: users[id].sysMessages !== false,
2243
- };
2244
- } else {
2245
- users[id] = {
2246
- firstName: users[id],
2247
- userName: '',
2248
- sysMessages: users[id].sysMessages !== false,
2249
- };
2250
- }
2251
- }
2252
- });
2253
- } catch (err) {
2254
- err && adapter.log.error(err);
2255
- adapter.log.error('Cannot parse stored user IDs!');
2256
- }
2257
- }
2258
- } catch (err) {
2259
- adapter.log.error(err);
2260
- }
2261
- }
2262
- }
2263
-
2264
- // Read all Object names sequentially, that do not have aliases
2265
- async function readAllNames(ids) {
2266
- for (let i = 0; i < ids.length; i++) {
2267
- try {
2268
- const obj = await adapter.getForeignObjectAsync(ids[i]);
2269
- if (obj) {
2270
- commands[ids[i]].alias = getName(obj);
2271
- commands[ids[i]].type = obj.common && obj.common.type;
2272
- commands[ids[i]].states = obj.common && parseStates(obj.common.states || undefined);
2273
- commands[ids[i]].unit = obj.common && obj.common.unit;
2274
- commands[ids[i]].min = obj.common && obj.common.min;
2275
- commands[ids[i]].max = obj.common && obj.common.max;
2276
- // read actual state to detect changes
2277
- if (commands[ids[i]].reportChanges) {
2278
- const state = await adapter.getForeignStateAsync(ids[i]);
2279
- commands[ids[i]].lastState = state ? state.val : undefined;
2280
- }
2281
- await adapter.subscribeForeignStatesAsync(ids[i]);
2282
- }
2283
- } catch (err) {
2284
- adapter.log.error(`Cannot process object "${ids[i]}": ${err}`);
2285
- }
2286
- }
2287
- }
2288
-
2289
- async function readStatesCommands() {
2290
- const doc = await adapter.getObjectViewAsync('system', 'custom', {});
2291
- const readNames = [];
2292
- if (doc && doc.rows) {
2293
- for (let i = 0, l = doc.rows.length; i < l; i++) {
2294
- if (doc.rows[i].value) {
2295
- const id = doc.rows[i].id;
2296
- const obj = doc.rows[i].value;
2297
- if (obj[adapter.namespace] && obj[adapter.namespace].enabled) {
2298
- commands[id] = obj[adapter.namespace];
2299
- readNames.push(id);
2300
- }
2301
- }
2302
- }
2303
- }
2304
-
2305
- await readAllNames(readNames);
2306
- }
2307
-
2308
- async function readEnums(name) {
2309
- name = name || 'rooms';
2310
- enums[name] = {};
2311
- try {
2312
- const doc = await adapter.getObjectViewAsync('system', 'enum', {
2313
- startkey: `enum.${name}.`,
2314
- endkey: `enum.${name}.\u9999`,
2315
- });
2316
- if (doc && doc.rows) {
2317
- for (let i = 0, l = doc.rows.length; i < l; i++) {
2318
- if (doc.rows[i].value) {
2319
- const id = doc.rows[i].id;
2320
- const obj = doc.rows[i].value;
2321
- if (obj && obj.common && obj.common.members && obj.common.members.length) {
2322
- enums[name][id] = obj.common;
2323
- }
2324
- }
2325
- }
2326
- }
2327
- } catch (err) {
2328
- adapter.log.error(`Cannot read enum ${name}: ${err}`);
2329
- }
2330
-
2331
- return enums;
2332
- }
2333
-
2334
- async function main() {
2335
- if (!adapter.config.token) {
2336
- return adapter.log.error('Token is not set!');
2337
- }
2338
-
2339
- await adapter.setStateAsync('info.connection', false, true);
2340
-
2341
- await adapter.subscribeStatesAsync('communicate.request');
2342
- await adapter.subscribeStatesAsync('communicate.response');
2343
- await adapter.subscribeStatesAsync('communicate.responseSilent');
2344
- await adapter.subscribeStatesAsync('communicate.responseJson');
2345
- await adapter.subscribeStatesAsync('communicate.responseSilentJson');
2346
- await adapter.subscribeStatesAsync('communicate.requestResponse');
2347
-
2348
- // clear states
2349
- await adapter.setStateAsync('communicate.request', { val: '', ack: true });
2350
- await adapter.setStateAsync('communicate.response', { val: '', ack: true });
2351
- await adapter.setStateAsync('communicate.responseSilent', { val: '', ack: true });
2352
- await adapter.setStateAsync('communicate.responseJson', { val: '', ack: true });
2353
- await adapter.setStateAsync('communicate.responseSilentJson', { val: '', ack: true });
2354
- await adapter.setStateAsync('communicate.requestResponse', { val: '', ack: true });
2355
- await adapter.setStateAsync('communicate.pathFile', { val: '', ack: true });
2356
-
2357
- adapter.config.password = adapter.config.password || '';
2358
- adapter.config.keyboard = adapter.config.keyboard || '/cmds';
2359
-
2360
- await updateUsers();
2361
- if (adapter.config.allowStates !== undefined) {
2362
- adapter.config.allowStates = true;
2363
- }
2364
- adapter.config.answerTimeoutSec = parseInt(adapter.config.answerTimeoutSec, 10) || 60;
2365
- adapter.config.answerTimeoutSec *= 1000;
2366
- adapter.config.rememberUsers = adapter.config.rememberUsers === 'true' || adapter.config.rememberUsers === true;
2367
-
2368
- try {
2369
- const obj = await adapter.getForeignObjectAsync('system.config');
2370
-
2371
- if (obj) {
2372
- systemLang = obj.common.language || 'en';
2373
- }
2374
-
2375
- await readStatesCommands();
2376
- if (adapter.config.rooms) {
2377
- await readEnums();
2378
- }
2379
- // init polling every hour
2380
- reconnectTimer = setInterval(connect, 3600000);
2381
-
2382
- connect();
2383
-
2384
- // detect changes of objects
2385
- await adapter.subscribeForeignObjectsAsync('*');
2386
- } catch (err) {
2387
- adapter.log.error(err);
2388
- }
2389
- }
2390
-
2391
- /**
2392
- * Process a `sendNotification` request
2393
- *
2394
- * @param obj
2395
- */
2396
- async function processNotification(obj) {
2397
- adapter.log.info(`New notification received from ${obj.from}`);
2398
-
2399
- const notificationMessage = buildMessageFromNotification(obj.message);
2400
- try {
2401
- await sendSystemMessage(notificationMessage, { parse_mode: 'MarkdownV2' });
2402
- if (obj.callback) {
2403
- adapter.sendTo(obj.from, 'sendNotification', { sent: true }, obj.callback);
2404
- }
2405
- } catch {
2406
- if (obj.callback) {
2407
- adapter.sendTo(obj.from, 'sendNotification', { sent: false }, obj.callback);
2408
- }
2409
- }
2410
- }
2411
-
2412
- /**
2413
- * Build up a mail object from the notification message
2414
- *
2415
- * @param message
2416
- * @returns
2417
- */
2418
- function buildMessageFromNotification(message) {
2419
- const subject = message.category.name;
2420
- const { instances } = message.category;
2421
-
2422
- const readableInstances = Object.entries(instances).map(
2423
- ([instance, entry]) => `${instance.substring('system.adapter.'.length)}: ${getNewestMessage(entry.messages)}`,
2424
- );
2425
-
2426
- const text = `${message.category.description}
2427
- ${message.host}:
2428
- ${readableInstances.join('\n')}
2429
- `;
2430
-
2431
- return replaceReservedCharacters(`*${subject}*\n\n${text}`);
2432
- }
2433
-
2434
- /**
2435
- * Replace reserved characters in outgoing message
2436
- *
2437
- * @param text string to sanitize
2438
- * @returns
2439
- */
2440
- function replaceReservedCharacters(text) {
2441
- return text.replace(/([.!()-_*[\]~`><&#+=|{}])/g, '\\$1');
2442
- }
2443
-
2444
- /**
2445
- * Extract the newest message out of a notification messages together with the localized date
2446
- *
2447
- * @param messages
2448
- * @returns string
2449
- */
2450
- function getNewestMessage(messages) {
2451
- const newestMessage = messages.sort((a, b) => (a.ts < b.ts ? 1 : -1))[0];
2452
-
2453
- return `${new Date(newestMessage.ts).toLocaleString()} ${newestMessage.message}`;
2454
- }
2455
-
2456
- if (require.main === module) {
2457
- startAdapter();
2458
- } else {
2459
- module.exports = startAdapter;
2460
- }