-
Notifications
You must be signed in to change notification settings - Fork 44
/
main.js
2168 lines (1950 loc) · 90.6 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
// https://github.com/yagop/node-telegram-bot-api/issues/319 (because of bluebird)
process.env.NTBA_FIX_319 = 1;
const TelegramBot = require('node-telegram-bot-api');
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const adapterName = require('./package.json').name.split('.').pop();
const _ = require('./lib/words.js');
const fs = require('node:fs');
const path = require('node:path');
const { WebServer } = require('@iobroker/webserver');
const https = require('node:https');
const axios = require('axios').default;
let bot;
let users = {};
let systemLang = 'en';
let reconnectTimer = null;
let pollConnectionStatus = null;
let isConnected = null;
let lastMessageTime = 0;
let lastMessageText = '';
const enums = {};
const protection = {};
let gcInterval = null;
const commands = {};
const callbackQueryId = {};
const mediaGroupExport = {};
let tmpDirName;
const server = {
app: null,
server: null,
settings: null,
};
let adapter;
const systemLang2CallMe = {
en: 'en-GB-Standard-A',
de: 'de-DE-Standard-A',
ru: 'ru-RU-Standard-A',
pt: 'pt-BR-Standard-A',
nl: 'nl-NL-Standard-A',
fr: 'fr-FR-Standard-A',
it: 'it-IT-Standard-A',
es: 'es-ES-Standard-A',
pl: 'pl-PL-Standard-A',
uk: 'uk-UA-Standard-A',
'zh-cn': 'en-GB-Standard-A',
};
function startAdapter(options) {
options = options || {};
Object.assign(options, {
name: adapterName,
/**
* If the JS-Controller catches an unhandled error, this will be called
* so we have a chance to handle it ourselves.
* @param {Error} err
*/
error: (err) => {
// Identify unhandled errors originating from callbacks in scripts
// These are not caught by wrapping the execution code in try-catch
if (err ) {
const errStr = err.toString();
if (errStr.includes('getaddrinfo') || errStr.includes('api.telegram.org') || errStr.includes('EAI_AGAIN')) {
return true;
}
}
return false;
}
});
adapter = new utils.Adapter(options);
adapter.on('message', obj => {
if (obj) {
if (obj.command === 'adminuser') {
let adminUserData;
adapter.getState('communicate.users', (err, state) => {
err && adapter.log.error(err);
if (state && state.val) {
try {
adminUserData = JSON.parse(state.val);
adapter.sendTo(obj.from, obj.command, adminUserData, obj.callback);
} catch (err) {
err && adapter.log.error(err);
adapter.log.error('Cannot parse stored user IDs!');
}
}
});
} else if (obj.command === 'delUser') {
const userID = obj.message;
let userObj = {};
adapter.getState('communicate.users', (err, state) => {
err && adapter.log.error(err);
if (state && state.val) {
try {
userObj = JSON.parse(state.val);
delete userObj[userID];
adapter.setState('communicate.users', JSON.stringify(userObj), true, err => {
if (!err) {
adapter.sendTo(obj.from, obj.command, userID, obj.callback);
updateUsers();
adapter.log.warn(`User ${userID} has been deleted!`);
}
});
} catch (err) {
err && adapter.log.error(err);
adapter.log.error(`Cannot delete user ${userID}!`);
}
}
});
} else if (obj.command === 'systemMessages') {
const userID = obj.message.itemId;
const checked = obj.message.checked;
let userObj = {};
adapter.getState('communicate.users', (err, state) => {
err && adapter.log.error(err);
if (state && state.val) {
try {
userObj = JSON.parse(state.val);
userObj[userID].sysMessages = checked;
adapter.setState('communicate.users', JSON.stringify(userObj), true, err => {
if (!err) {
adapter.sendTo(obj.from, obj.command, userID, obj.callback);
updateUsers();
adapter.log.info(`Receiving of system messages for user "${userID}" has been changed to ${checked}!`);
}
});
} catch (err) {
err && adapter.log.error(err);
adapter.log.error(`Cannot change user ${userID}!`);
}
}
});
} else if (obj.command === 'delAllUser') {
try {
adapter.setState('communicate.users', '{}', true, err => {
if (!err) {
adapter.sendTo(obj.from, obj.command, true, obj.callback);
updateUsers();
adapter.log.warn('List of saved users has been wiped. Every User has to reauthenticate with the new password!');
}
});
} catch (err) {
err && adapter.log.error(err);
adapter.log.error('Cannot wipe list of saved users!');
}
} else if (obj.command === 'sendNotification') {
processNotification(obj);
} else{
processMessage(obj);
}
}
});
adapter.on('ready', () => {
adapter.config.server = adapter.config.server === 'true';
adapter._questions = [];
adapter.garbageCollectorinterval = setInterval(() => {
const now = Date.now();
Object.keys(callbackQueryId).forEach(id => {
if (now - callbackQueryId[id].ts > 120000) {
delete callbackQueryId[id];
}
});
}, 10000);
tmpDirName = path.join(utils.getAbsoluteDefaultDataDir(), adapter.namespace.replace('.', '_'));
// Create file system directories for media files
if (adapter.config.saveFilesTo == 'filesystem') {
try {
!fs.existsSync(tmpDirName) && fs.mkdirSync(tmpDirName);
const subDirectories = ['voice'];
if (adapter.config.saveFiles) {
// Create subdirs for other attachment types
subDirectories.push('photo', 'video', 'audio', 'document');
}
for (const subDir of subDirectories) {
const subDirPath = path.join(tmpDirName, subDir);
!fs.existsSync(subDirPath) && fs.mkdirSync(subDirPath);
}
} catch (err) {
adapter.log.error(`Cannot create tmp directory: ${tmpDirName}: ${err}`);
}
}
if (adapter.config.server) {
adapter.config.port = parseInt(adapter.config.port, 10);
// Load certificates
adapter.getCertificates(async (err, certificates, leConfig) => {
adapter.config.certificates = certificates;
adapter.config.leConfig = leConfig;
adapter.config.secure = true;
try {
const webserver = new WebServer({
app: handleWebHook,
adapter,
secure: adapter.config.secure
});
server.server = await webserver.init();
} catch (err) {
adapter.log.error(`Cannot create webserver: ${err}`);
adapter.terminate ? adapter.terminate(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION) : process.exit(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
return;
}
if (server.server) {
server.server.__server = server;
let serverListening = false;
let serverPort = adapter.config.port;
server.server.on('error', e => {
if (e.toString().includes('EACCES') && serverPort <= 1024) {
adapter.log.error(`node.js process has no rights to start server on the port ${serverPort}.\n` +
`Do you know that on linux you need special permissions for ports under 1024?\n` +
`You can call in shell following scrip to allow it for node.js: "iobroker fix"`
);
} else {
adapter.log.error(`Cannot start server on ${adapter.config.bind || '0.0.0.0'}:${serverPort}: ${e}`);
}
if (!serverListening) {
adapter.terminate ? adapter.terminate(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION) : process.exit(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
}
});
adapter.getPort(adapter.config.port, (!adapter.config.bind || adapter.config.bind === '0.0.0.0') ? undefined : adapter.config.bind || undefined, port => {
if (parseInt(port, 10) !== adapter.config.port && !adapter.config.findNextPort) {
adapter.log.error(`port ${adapter.config.port} already in use`);
adapter.terminate ? adapter.terminate() : process.exit(1);
}
serverPort = port;
server.server.listen(port, (!adapter.config.bind || adapter.config.bind === '0.0.0.0') ? undefined : adapter.config.bind || undefined, () =>
serverListening = true);
adapter.log.info(`https server listening on port ${port}`);
main()
.catch(e => adapter.log.error(`Cannot start adapter: ${e}`));
});
}
});
} else {
main()
.catch(e => adapter.log.error(`Cannot start adapter: ${e}`));
}
});
adapter.on('unload', () => {
reconnectTimer && clearInterval(reconnectTimer);
reconnectTimer = null;
gcInterval && clearInterval(gcInterval);
gcInterval = null;
pollConnectionStatus && clearInterval(pollConnectionStatus);
pollConnectionStatus = null;
adapter.garbageCollectorinterval && clearInterval(adapter.garbageCollectorinterval);
adapter.garbageCollectorinterval = null;
if (adapter && adapter.config) {
if (adapter.config.restarting !== '') {
// default text
if (adapter.config.restarting === '_' || adapter.config.restarting === null || adapter.config.restarting === undefined) {
sendSystemMessage(adapter.config.rememberUsers ? _('Restarting...') : _('Restarting... Reauthenticate!'));
} else {
sendSystemMessage(adapter.config.restarting);
}
}
try {
if (server.server) {
server.server.close();
}
} catch (e) {
console.error(`Cannot close server: ${e}`);
}
}
isConnected && adapter && adapter.setState && adapter.setState('info.connection', false, true);
isConnected = false;
});
// This handler is called if a subscribed state changes
adapter.on('stateChange', async (id, state) => {
if (state) {
if (!state.ack) {
if (id.endsWith('communicate.response')) {
if (typeof state.val === 'object') {
adapter.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!`);
return;
}
// Send to someone this message
await sendMessage(state.val);
await adapter.setStateAsync('communicate.response', { val: state.val, ack: true });
} else if (id.endsWith('communicate.responseSilent')) {
if (typeof state.val === 'object') {
adapter.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!`);
return;
}
// Send to someone this message
await sendMessage(state.val, null, null, { disable_notification: true });
await adapter.setStateAsync('communicate.responseSilent', { val: state.val, ack: true });
} else if (id.endsWith('communicate.responseJson')) {
try {
const val = JSON.parse(state.val);
// Send to someone this message
await sendMessage(val);
await adapter.setStateAsync('communicate.responseJson', { val: state.val, ack: true });
} catch (err) {
adapter.log.error(`could not parse Json in communicate.responseJon state: ${err.message}`);
}
} else if (id.endsWith('communicate.responseSilentJson')) {
try {
const val = JSON.parse(state.val);
// Send to someone this message
await sendMessage(val, null, null, { disable_notification: true });
await adapter.setStateAsync('communicate.responseSilent', { val: state.val, ack: true });
} catch (err) {
adapter.log.error(`could not parse Json in communicate.responseSilentJon state: ${err.message}`);
}
} else if (id.endsWith('communicate.requestResponse')) {
try {
const text = state.val;
const chatIdState = await adapter.getStateAsync('communicate.requestChatId');
const threadIdState = await adapter.getStateAsync('communicate.requestMessageThreadId');
const options = {};
if (threadIdState && threadIdState.val > 0) {
options.message_thread_id = threadIdState.val;
}
// Send to someone this message
await sendMessage(
text,
null,
chatIdState ? chatIdState.val : null,
options,
);
await adapter.setStateAsync('communicate.requestResponse', { val: state.val, ack: true });
} catch (err) {
adapter.log.error(`could not parse Json in communicate.responseSilentJon state: ${err.message}`);
}
}
} else if (commands[id] && commands[id].report) {
adapter.log.debug(`reporting state change of ${id}: ${JSON.stringify(commands[id])}`);
const options = commands[id].reportSilent == true ? { disable_notification: true } : {};
let users = null;
if (commands[id]?.recipients && commands[id].recipients !== '') {
users = commands[id].recipients;
}
if (commands[id].reportChanges) {
if (state.val !== commands[id].lastState) {
commands[id].lastState = state.val;
sendMessage(getStatus(id, state), users, null, options);
}
} else {
sendMessage(getStatus(id, state), users, null, options);
}
}
}
});
adapter.on('objectChange', (id, obj) => {
if (obj && obj.common && obj.common.custom &&
obj.common.custom[adapter.namespace] && obj.common.custom[adapter.namespace].enabled
) {
const alias = getName(obj);
if (!commands[id]) {
adapter.log.info(`enabled logging of ${id}, Alias=${alias}`);
setImmediate(() => adapter.subscribeForeignStates(id));
}
commands[id] = obj.common.custom[adapter.namespace];
commands[id].type = obj.common.type;
commands[id].states = parseStates(obj.common.states);
commands[id].unit = obj.common && obj.common.unit;
commands[id].min = obj.common && obj.common.min;
commands[id].max = obj.common && obj.common.max;
commands[id].recipients = obj.common && obj.common.recipients;
commands[id].alias = alias;
// read actual state to detect changes
if (commands[id].reportChanges) {
adapter.getForeignStateAsync(id)
.then(state => commands[id].lastState = state ? state.val : undefined);
}
} else if (commands[id]) {
adapter.log.debug(`Removed command: ${id}`);
delete commands[id];
setImmediate(() => adapter.unsubscribeForeignStates(id));
} else if (id.startsWith('enum.rooms') && adapter.config.rooms) {
if (obj && obj.common && obj.common.members && obj.common.members.length) {
enums.rooms[id] = obj.common;
} else if (enums.rooms[id]) {
delete enums.rooms[id];
}
}
});
server.settings = adapter.config;
return adapter;
}
/**
* Send message to all system users
*
* @param {string} text text to send
* @param {Record<string, any>} options additional options, e.g. parse_mode
* @returns {Promise<void>}
*/
async function sendSystemMessage(text, options= {}) {
const _users = Object.keys(users)
.filter(id => users[id].sysMessages !== false)
.map(id => adapter.config.useUsername ? users[id].userName : users[id].firstName);
await sendMessage(text, _users, null, {...options, disable_notification: true});
}
function getStatus(id, state) {
if (!state) {
state = {val: 'State not set'};
}
if (commands[id].type === 'boolean') {
return `${commands[id].alias} => ${state.val ? commands[id].onStatus || _('ON-Status') : commands[id].offStatus || _('OFF-Status')}`;
} else {
if (commands[id].states && commands[id].states[state.val] !== undefined) {
state.val = commands[id].states[state.val];
}
return `${commands[id].alias} => ${state.val}${commands[id].unit ? ` ${commands[id].unit}` : ''}`;
}
}
function connectionState(connected, logSuccess) {
let errorCounter = 0;
function checkConnection() {
pollConnectionStatus = null;
bot && bot.getMe && bot.getMe()
.then(data => {
adapter.log.debug(`getMe (reconnect): ${JSON.stringify(data)}`);
connectionState(true, errorCounter > 0);
})
.catch(error => {
(errorCounter % 10 === 0) && adapter.log.error(`getMe (reconnect #${errorCounter}) Error:${error}`);
errorCounter++;
pollConnectionStatus && clearTimeout(pollConnectionStatus);
pollConnectionStatus = setTimeout(checkConnection, 1000);
});
}
if (connected && logSuccess) {
adapter.log.info('getMe (reconnect): Success');
}
if (isConnected !== connected) {
isConnected = connected;
adapter.setState('info.connection', isConnected, true);
if (isConnected && pollConnectionStatus) {
clearTimeout(pollConnectionStatus);
pollConnectionStatus = null;
} else if (!isConnected) {
checkConnection();
}
}
}
function parseStates(states) {
// todo
return states;
}
function getName(obj) {
if (obj.common.custom[adapter.namespace].alias) {
return obj.common.custom[adapter.namespace].alias;
} else {
let name = obj.common.name;
if (typeof name === 'object') {
name = name[systemLang] || name.en;
}
return name || obj._id;
}
}
const actions = [
'typing', 'upload_photo', 'upload_video', 'record_video', 'record_audio', 'upload_document', 'find_location',
];
function handleWebHook(req, res) {
if (req.method === 'POST' && req.url === `/${adapter.config.token}`) {
//
//{
// "update_id":10000,
// "message":{
// "date":1441645532,
// "chat":{
// "last_name":"Test Lastname",
// "id":1111111,
// "first_name":"Test",
// "username":"Test"
// },
// "message_id":1365,
// "from": {
// "last_name":"Test Lastname",
// "id":1111111,
// "first_name":"Test",
// "username":"Test"
// },
// "text":"/start"
// }
//}
let body = '';
req.on('data', data => {
body += data;
if (body.length > 100_000) {
res.writeHead(413, 'Request Entity Too Large', {
'Content-Type': 'text/html'
});
res.end('<!doctype html><html><head><title>413</title></head><body>413: Request Entity Too Large</body></html>');
}
});
req.on('end', () => {
let msg;
try {
msg = JSON.parse(body);
} catch (e) {
adapter.log.error(`Cannot parse webhook response!: ${e}`);
return;
}
res.end('OK');
bot.processUpdate(msg);
});
} else {
res.writeHead(404, 'Resource Not Found', {
'Content-Type': 'text/html',
});
res.end('<!doctype html><html><head><title>404</title></head><body>404: Resource Not Found</body></html>');
}
}
function saveSendRequest(msg) {
adapter.log.debug(`Request [saveSendRequest]: ${JSON.stringify(msg)}`);
if (typeof msg === 'object'){
if (adapter.config.storeRawRequest) {
adapter.setState('communicate.botSendRaw', JSON.stringify(msg, null, 2), true, err =>
err && adapter.log.error(err));
}
if (msg?.message_id) {
adapter.setState('communicate.botSendMessageId', msg.message_id, true, err =>
err && adapter.log.error(err));
}
if (msg?.message_thread_id) {
adapter.setState('communicate.botSendMessageThreadId', msg.message_thread_id, true, err =>
err && adapter.log.error(err));
}
if (msg?.chat && msg.chat.id) {
adapter.setState('communicate.botSendChatId', msg.chat.id.toString(), true, err =>
err && adapter.log.error(err));
}
}
}
function _sendMessageHelper(dest, name, text, options) {
return new Promise((resolve) => {
const messageIds = {};
if (options && options.chatId !== undefined && options.user === undefined) {
options.user = adapter.config.useUsername ? users[options.chatId].userName : users[options.chatId].firstName;
}
// to push chatId value for the group chats - useful to process the errors, and list of processed messages.
if (options.chatId === undefined && options.user === undefined && name === 'chat' && dest) {
options.chatId = dest;
}
if (options && options.editMessageReplyMarkup !== undefined) {
adapter.log.debug(`Send editMessageReplyMarkup to "${name}"`);
bot && executeSending(() => bot.editMessageReplyMarkup(options.editMessageReplyMarkup.reply_markup, options.editMessageReplyMarkup.options), options, resolve);
} else if (options && options.editMessageText !== undefined) {
adapter.log.debug(`Send editMessageText to "${name}"`);
bot && executeSending(() => bot.editMessageText(text, options.editMessageText.options), options, resolve);
} else if (options && options.editMessageMedia !== undefined) {
adapter.log.debug(`Send editMessageMedia to "${name}"`);
if (text) {
let mediaInput;
if (
(typeof text === 'string' &&
text.match(/\.(jpg|png|jpeg|bmp|gif)$/i) &&
(fs.existsSync(text) || text.match(/^(https|http)/i))
) ||
(options && options.type === 'photo')
) {
mediaInput = {
type: 'photo',
media: text,
};
} else if (
(typeof text === 'string' && text.match(/\.(gif)/i) && fs.existsSync(text)) ||
(options && options.type === 'animation')
) {
mediaInput = {
type: 'animation',
media: text,
};
} else if (
(typeof text === 'string' && text.match(/\.(mp4)$/i) && fs.existsSync(text)) ||
(options && options.type === 'video')
) {
mediaInput = {
type: 'video',
media: text,
};
} else if (
(typeof text === 'string' && text.match(/\.(wav|mp3|ogg)$/i) && fs.existsSync(text)) ||
(options && options.type === 'audio')
) {
mediaInput = {
type: 'audio',
media: text,
};
} else if (
(typeof text === 'string' && text.match(/\.(txt|doc|docx|csv|pdf|xls|xlsx)$/i) && fs.existsSync(text)) ||
(options && options.type === 'document')
) {
mediaInput = {
type: 'document',
media: text,
};
}
if (mediaInput) {
const opts = {
qs: options.editMessageMedia.options,
};
opts.formData = {};
const payload = Object.assign({}, mediaInput);
delete payload.media;
delete payload.fileOptions;
try {
const attachName = String(0);
const [formData, fileId] = bot._formatSendData(attachName, mediaInput.media, mediaInput.fileOptions);
if (formData) {
opts.formData[attachName] = formData[attachName];
payload.media = `attach://${attachName}`;
} else {
payload.media = fileId;
}
} catch (ex) {
return Promise.reject(ex);
}
opts.qs.media = JSON.stringify(payload);
bot && executeSending(() => bot._request('editMessageMedia', opts), options, resolve);
} else {
adapter.log.error(`Cannot send editMessageMedia [chatId - ${options.chatId}]: unsupported media type`);
options = null;
resolve(JSON.stringify(messageIds));
}
} else {
adapter.log.error(`Cannot send editMessageMedia [chatId - ${options.chatId}]: no media found. "text" may not be empty`);
options = null;
resolve(JSON.stringify(messageIds));
}
} else if (options && options.editMessageCaption !== undefined) {
adapter.log.debug(`Send editMessageCaption to "${name}"`);
bot && executeSending(() => bot.editMessageCaption(text, options.editMessageCaption.options), options, resolve);
} else if (options && options.deleteMessage !== undefined) {
adapter.log.debug(`Send deleteMessage to "${name}"`);
bot && executeSending(() => bot.deleteMessage(options.deleteMessage.options.chat_id, options.deleteMessage.options.message_id), options, resolve);
} else if (options && options.latitude !== undefined && options.longitude !== undefined && options.title !== undefined && options.address !== undefined) {
adapter.log.debug(`Send venue to "${name}": ${options.latitude},${options.longitude}`);
bot && executeSending(() => bot.sendVenue(dest, parseFloat(options.latitude), parseFloat(options.longitude), options.title, options.address, options), options, resolve);
} else if (options && options.latitude !== undefined && options.longitude !== undefined) {
adapter.log.debug(`Send location to "${name}": ${options.latitude},${options.longitude}`);
bot && executeSending(() => bot.sendLocation(dest, parseFloat(options.latitude), parseFloat(options.longitude), options), options, resolve);
} else if (options && options.type === 'mediagroup') {
adapter.log.debug(`Send media group to "${name}": `);
if (bot) {
const {media: fileNames} = options;
if (fileNames instanceof Array) {
bot.sendChatAction(dest, 'upload_photo')
.then(() => {
if (fileNames.every(name => fs.existsSync(name))) {
const filesAsArray = fileNames
.map(element => {
try {
return {type: 'photo', media: fs.readFileSync(element)};
} catch (err) {
adapter.log.error(`Cannot read file ${element}: ${err}`);
return undefined;
}
})
.filter(element => element !== undefined);
const size = filesAsArray
.map(element => element.media.length)
.reduce((acc, val) => acc + val);
adapter.log.info(`Send media group to "${name}": ${size} bytes`);
if (filesAsArray.length > 0) {
executeSending(() => bot.sendMediaGroup(dest, filesAsArray), options, resolve);
}
} else {
adapter.log.debug('files must exists');
options = null;
resolve(JSON.stringify(messageIds));
}
})
.catch(error => {
adapter.log.error(`upload Error: ${error}`);
});
} else {
adapter.log.debug('option media should be an array');
resolve(JSON.stringify(messageIds));
}
} else {
adapter.log.debug('no files added!');
options = null;
resolve(JSON.stringify(messageIds));
}
} else if (text && typeof text === 'string' && actions.includes(text)) {
adapter.log.debug(`Send action to "${name}": ${text}`);
bot && executeSending(() => bot.sendChatAction(dest, text), options, resolve);
} else if (text && ((typeof text === 'string' && text.match(/\.webp$/i) && fs.existsSync(text)) || (options && options.type === 'sticker'))) {
if (typeof text === 'string') {
adapter.log.debug(`Send sticker to "${name}": ${text}`);
} else {
adapter.log.debug(`Send sticker to "${name}": ${text.length} bytes`);
}
bot && executeSending(() => bot.sendSticker(dest, text, options), options, resolve);
} else if (text && ((typeof text === 'string' && text.match(/\.(gif)/i) && fs.existsSync(text)) || (options && options.type === 'animation'))) {
if (typeof text === 'string') {
adapter.log.debug(`Send animation to "${name}": ${text}`);
} else {
adapter.log.debug(`Send animation to "${name}": ${text.length} bytes`);
}
bot && executeSending(() => bot.sendAnimation(dest, text, options), options, resolve);
} else if (text && ((typeof text === 'string' && text.match(/\.(mp4)$/i) && fs.existsSync(text)) || (options && options.type === 'video'))) {
if (typeof text === 'string') {
adapter.log.debug(`Send video to "${name}": ${text}`);
} else {
adapter.log.debug(`Send video to "${name}": ${text.length} bytes`);
}
bot && executeSending(() => bot.sendVideo(dest, text, options), options, resolve);
} else if (text && ((typeof text === 'string' && text.match(/\.(txt|doc|docx|csv|pdf|xls|xlsx)$/i) && fs.existsSync(text)) || (options && options.type === 'document'))) {
adapter.log.debug(`Send document to "${name}": ${(typeof text === 'string') ? text : text.length}`);
bot && executeSending(() => bot.sendDocument(dest, text, options), options, resolve);
} else if (
text &&
(
(typeof text === 'string' &&
text.match(/\.(wav|mp3|ogg)$/i) &&
fs.existsSync(text)
) ||
(options && options?.type === 'audio')
)
) {
adapter.log.debug(`Send audio to "${name}": ${(typeof text === 'string') ? text : text.length}`);
bot && executeSending(() => bot.sendAudio(dest, text, options), options, resolve);
} else if (
text &&
(
(
typeof text === 'string' && // if the message is a string, and it is a path to file or URL
text.match(/\.(jpg|png|jpeg|bmp|gif)$/i) &&
(fs.existsSync(text) || text.match(/^(https|http)/i))
) ||
(options && options.type === 'photo') // if the type of message is photo
)
) {
adapter.log.debug(`Send photo to "${name}": ${(typeof text === 'string') ? text : text.length}`);
bot && executeSending(() => bot.sendPhoto(dest, text, options), options, resolve);
} else if (options && options.answerCallbackQuery !== undefined) {
adapter.log.debug(`Send answerCallbackQuery to "${name}"`);
if (options.answerCallbackQuery.showAlert === undefined) {
options.answerCallbackQuery.showAlert = false;
}
if (bot && callbackQueryId[options.chatId]) {
const originalChatId = callbackQueryId[options.chatId].id;
delete callbackQueryId[options.chatId];
executeSending(() => bot.answerCallbackQuery(originalChatId, options.answerCallbackQuery.text, options.answerCallbackQuery.showAlert), options, resolve);
}
} else {
adapter.log.debug(`Send message to [${name}]: "${text}"`);
if (text && typeof text === 'string') {
options = options || {};
if (text.startsWith('<MarkdownV2>') && text.endsWith('</MarkdownV2>')) {
options.parse_mode = 'MarkdownV2';
text = text.substring(12, text.length - 13);
} else if (text.startsWith('<HTML>') && text.endsWith('</HTML>')) {
options.parse_mode = 'HTML';
text = text.substring(6, text.length - 7);
} else if (text.startsWith('<Markdown>') && text.endsWith('</Markdown>')) {
options.parse_mode = 'Markdown';
text = text.substring(10, text.length - 11);
}
}
bot && executeSending(() => bot.sendMessage(dest, text || '', options), options, resolve);
}
});
}
/**
* executes the given method and handles, what to do next
*/
function executeSending(action, options, resolve){
// create an empty object, to store chat id and message id of successfully sent messages
const messageIds = {};
action()
.then(response => {
// put chat id and message id to the object, that will be returned
// delete message command return only true in response,
// to return deleted message id and chat id the next if construction is used:
if (response?.message_id) {
// The chatId is mostly used in code, instead of chat_id.
messageIds[options.chat_id ? options.chat_id : options.chatId] = response.message_id;
} else if (typeof response === 'boolean' && options?.deleteMessage?.options?.chat_id && options?.deleteMessage?.options?.message_id) {
messageIds[options.deleteMessage.options.chat_id] = options.deleteMessage.options.message_id;
}
// puts ids to the ioBroker database
saveSendRequest(response);
})
.then(() => {
adapter.log.debug('Message sent');
options = null;
// return all the collected message ids to the callback
resolve(JSON.stringify(messageIds));
})
.catch(error => {
// add the error to the message ids object
messageIds.error = {[options.chat_id ? options.chat_id : options.chatId] : error};
// log error to the system
adapter.log.error(`Failed sending [${options.chatId ? 'chatId' : 'user'} - ${options.chatId ? options.chatId : options.user}]: ${error}`);
options = null;
// send the successfully sent messages as callback
resolve(JSON.stringify(messageIds));
});
}
// https://core.telegram.org/bots/api
function sendMessage(text, user, chatId, options) {
if (!text && typeof options !== 'object' && text !== 0 && (!options || !options.latitude)) {
adapter.log.warn('Invalid text: null');
return Promise.resolve({});
}
if (text && typeof text === 'object' && text.text !== undefined && typeof text.text === 'string' && options === undefined) {
options = text;
text = options.text;
if (options.chatId) {
chatId = options.chatId;
}
if (options.user) {
user = options.user;
}
}
if (options && typeof options === 'object') {
if (options.chatId !== undefined) {
delete options.chatId;
}
if (options.text !== undefined) {
delete options.text;
}
if (options.user !== undefined) {
delete options.user;
}
}
options = options || {};
if (text && typeof text === 'string') {
if (text && text.startsWith('<MarkdownV2>') && text.endsWith('</MarkdownV2>')) {
options.parse_mode = 'MarkdownV2';
text = text.substring(12, text.length - 13);
} else if (text && text.startsWith('<HTML>') && text.endsWith('</HTML>')) {
options.parse_mode = 'HTML';
text = text.substring(6, text.length - 7);
} else if (text && text.startsWith('<Markdown>') && text.endsWith('</Markdown>')) {
options.parse_mode = 'Markdown';
text = text.substring(10, text.length - 11);
}
}
const tPromiseList = [];
// convert
if (text !== undefined && text !== null && typeof text !== 'object') {
text = text.toString();
}
if (chatId) {
tPromiseList.push(_sendMessageHelper(chatId, 'chat', text, options));
return Promise.all(tPromiseList)
.catch(e => e);
} else if (user) {
if (typeof user !== 'string' && !(user instanceof Array)) {
adapter.log.warn(`Invalid type of user parameter: ${typeof user}. Expected is string or array.`);
}
const userArray = Array.isArray(user) ? user : (user || '').toString().split(/[,;\s]/).map(u => u.trim()).filter(u => !!u);
let matches = 0;
userArray.forEach(userName => {
for (const id in users) {
if (!Object.prototype.hasOwnProperty.call(users, id)) {
continue;
}
if ((adapter.config.useUsername && users[id].userName === userName) ||
(!adapter.config.useUsername && users[id].firstName === userName)) {
if (options) {
options.chatId = id;
}
matches++;
tPromiseList.push(_sendMessageHelper(id, userName, text, options));
break;
}
}
});
if (userArray.length !== matches) {
adapter.log.warn(`${userArray.length - matches} of ${userArray.length} recipients are unknown!`);
}
return Promise.all(tPromiseList)
.catch(e => e);
}
const m = typeof text === 'string' ? text.match(/^@(.+?)\b/) : null;
if (m) {
text = (text || '').toString();
text = text.replace(`@${m[1]}`, '').trim().replace(/\s\s/g, ' ');
const re = new RegExp(m[1], 'i');
let id = '';
for (const id_t in users) {
if (!Object.prototype.hasOwnProperty.call(users, id_t)) {
continue;
}
if ((adapter.config.useUsername && users[id_t].userName.match(re)) || (!adapter.config.useUsername && users[id_t].firstName.match(re))) {
id = id_t;
break;
}
}
if (id) {
if (options) {
options.chatId = id;
}
tPromiseList.push(_sendMessageHelper(id, m[1], text, options));
}
} else {
// Send to all users
Object.keys(users).forEach(id => {
if (options) {
options.chatId = id;
}
tPromiseList.push(_sendMessageHelper(id, adapter.config.useUsername ? users[id].userName : users[id].firstName, text, options));
});
}
return Promise.all(tPromiseList)
.catch(e => e);
}
function saveFile(fileID, fileName, callback) {
adapter.log.debug(`Saving media file ${fileID} to ${fileName} (location = ${adapter.config.saveFilesTo})`);
bot.getFileLink(fileID)
.then(url => {
adapter.log.debug(`Received message: ${url}`);
https.get(url, res => {
if (res.statusCode === 200) {
const buf = [];
res.on('data', data => buf.push(data));
res.on('end', () => {
if (adapter.config.saveFilesTo == 'filesystem') {
const fileLocation = path.join(tmpDirName, fileName);
try {
fs.writeFileSync(fileLocation, Buffer.concat(buf));