iobroker.telegram 1.15.6 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/main.js CHANGED
@@ -48,7 +48,7 @@ let tmpDirName;
48
48
  const server = {
49
49
  app: null,
50
50
  server: null,
51
- settings: null
51
+ settings: null,
52
52
  };
53
53
 
54
54
  let adapter;
@@ -63,7 +63,7 @@ const systemLang2CallMe = {
63
63
  it: 'it-IT-Standard-A',
64
64
  es: 'es-ES-Standard-A',
65
65
  pl: 'pl-PL-Standard-A',
66
- 'zh-cn': 'en-GB-Standard-A'
66
+ 'zh-cn': 'en-GB-Standard-A',
67
67
  };
68
68
 
69
69
  function startAdapter(options) {
@@ -164,7 +164,9 @@ function startAdapter(options) {
164
164
  err && adapter.log.error(err);
165
165
  adapter.log.error('Cannot wipe list of saved users!');
166
166
  }
167
- } else {
167
+ } else if(obj.command === 'sendNotification') {
168
+ processNotification(obj);
169
+ } else{
168
170
  processMessage(obj);
169
171
  }
170
172
  }
@@ -234,13 +236,13 @@ function startAdapter(options) {
234
236
  adapter.log.info(`https server listening on port ${port}`);
235
237
 
236
238
  main()
237
- .then(() => {});
239
+ .catch(e => adapter.log.error(`Cannot start adapter: ${e}`));
238
240
  });
239
241
  }
240
242
  });
241
243
  } else {
242
244
  main()
243
- .then(() => {});
245
+ .catch(e => adapter.log.error(`Cannot start adapter: ${e}`));
244
246
  }
245
247
  });
246
248
 
@@ -291,35 +293,35 @@ function startAdapter(options) {
291
293
  sendMessage(state.val)
292
294
  .then(data => adapter.setState('communicate.response', state.val, true));
293
295
  } else
294
- if (id.endsWith('communicate.responseSilent')) {
295
- if (typeof state.val === 'object') {
296
- 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!`);
297
- return;
298
- }
299
- // Send to someone this message
300
- sendMessage(state.val, null, null, {disable_notification: true})
301
- .then(data => adapter.setState('communicate.responseSilent', state.val, true));
302
- } else
303
- if (id.endsWith('communicate.responseJson')) {
304
- try {
305
- const val = JSON.parse(state.val);
306
- // Send to someone this message
307
- sendMessage(val)
308
- .then(data => adapter.setState('communicate.responseJson', state.val, true));
309
- } catch (err) {
310
- adapter.log.error(`could not parse Json in communicate.responseJon state: ${err.message}`);
311
- }
312
- } else
313
- if (id.endsWith('communicate.responseSilentJson')) {
314
- try {
315
- const val = JSON.parse(state.val);
296
+ if (id.endsWith('communicate.responseSilent')) {
297
+ if (typeof state.val === 'object') {
298
+ 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!`);
299
+ return;
300
+ }
316
301
  // Send to someone this message
317
- sendMessage(val, null, null, {disable_notification: true})
302
+ sendMessage(state.val, null, null, {disable_notification: true})
318
303
  .then(data => adapter.setState('communicate.responseSilent', state.val, true));
319
- } catch (err) {
320
- adapter.log.error(`could not parse Json in communicate.responseSilentJon state: ${err.message}`);
321
- }
322
- }
304
+ } else
305
+ if (id.endsWith('communicate.responseJson')) {
306
+ try {
307
+ const val = JSON.parse(state.val);
308
+ // Send to someone this message
309
+ sendMessage(val)
310
+ .then(data => adapter.setState('communicate.responseJson', state.val, true));
311
+ } catch (err) {
312
+ adapter.log.error(`could not parse Json in communicate.responseJon state: ${err.message}`);
313
+ }
314
+ } else
315
+ if (id.endsWith('communicate.responseSilentJson')) {
316
+ try {
317
+ const val = JSON.parse(state.val);
318
+ // Send to someone this message
319
+ sendMessage(val, null, null, {disable_notification: true})
320
+ .then(data => adapter.setState('communicate.responseSilent', state.val, true));
321
+ } catch (err) {
322
+ adapter.log.error(`could not parse Json in communicate.responseSilentJon state: ${err.message}`);
323
+ }
324
+ }
323
325
  } else {
324
326
  if (commands[id] && commands[id].report) {
325
327
  if (commands[id].reportChanges) {
@@ -351,6 +353,11 @@ function startAdapter(options) {
351
353
  commands[id].min = obj.common && obj.common.min;
352
354
  commands[id].max = obj.common && obj.common.max;
353
355
  commands[id].alias = alias;
356
+ // read actual state to detect changes
357
+ if (commands[id].reportChanges) {
358
+ adapter.getForeignStateAsync(id)
359
+ .then(state => commands[id].lastState = state ? state.val : undefined);
360
+ }
354
361
  } else if (commands[id]) {
355
362
  adapter.log.debug(`Removed command: ${id}`);
356
363
  delete commands[id];
@@ -376,12 +383,19 @@ function startAdapter(options) {
376
383
  return adapter;
377
384
  }
378
385
 
379
- function sendSystemMessage(text) {
386
+ /**
387
+ * Send message to all system users
388
+ *
389
+ * @param {string} text text to send
390
+ * @param {Record<string, any>} options additional options, e.g. parse_mode
391
+ * @returns {Promise<void>}
392
+ */
393
+ async function sendSystemMessage(text, options= {}) {
380
394
  const _users = Object.keys(users)
381
395
  .filter(id => users[id].sysMessages !== false)
382
396
  .map(id => adapter.config.useUsername ? users[id].userName : users[id].firstName);
383
397
 
384
- sendMessage(text, _users, null, {disable_notification: true});
398
+ await sendMessage(text, _users, null, {...options, disable_notification: true});
385
399
  }
386
400
 
387
401
  function getStatus(id, state) {
@@ -449,7 +463,7 @@ function getName(obj) {
449
463
  }
450
464
 
451
465
  const actions = [
452
- 'typing', 'upload_photo', 'upload_video', 'record_video', 'record_audio', 'upload_document', 'find_location'
466
+ 'typing', 'upload_photo', 'upload_video', 'record_video', 'record_audio', 'upload_document', 'find_location',
453
467
  ];
454
468
 
455
469
  function handleWebHook(req, res) {
@@ -478,7 +492,7 @@ function handleWebHook(req, res) {
478
492
  let body = '';
479
493
  req.on('data', data => {
480
494
  body += data;
481
- if (body.length > 100000) {
495
+ if (body.length > 100_000) {
482
496
  res.writeHead(413, 'Request Entity Too Large', {
483
497
  'Content-Type': 'text/html'
484
498
  });
@@ -498,7 +512,7 @@ function handleWebHook(req, res) {
498
512
  });
499
513
  } else {
500
514
  res.writeHead(404, 'Resource Not Found', {
501
- 'Content-Type': 'text/html'
515
+ 'Content-Type': 'text/html',
502
516
  });
503
517
  res.end('<!doctype html><html><head><title>404</title></head><body>404: Resource Not Found</body></html>');
504
518
  }
@@ -525,85 +539,69 @@ function saveSendRequest(msg) {
525
539
 
526
540
  function _sendMessageHelper(dest, name, text, options) {
527
541
  return new Promise((resolve, reject) => {
528
- let count = 0;
542
+ const messageIds = {};
529
543
  if (options && options.chatId !== undefined && options.user === undefined) {
530
544
  options.user = adapter.config.useUsername ? users[options.chatId].userName : users[options.chatId].firstName;
531
545
  }
532
546
 
533
547
  if (options && options.editMessageReplyMarkup !== undefined) {
534
548
  adapter.log.debug(`Send editMessageReplyMarkup to "${name}"`);
535
- bot && bot.editMessageReplyMarkup(options.editMessageReplyMarkup.reply_markup, options.editMessageReplyMarkup.options)
536
- .then(response => saveSendRequest(response))
537
- .then(() => {
538
- options = null;
539
- count++;
540
- resolve(count);
541
- })
542
- .catch(error => {
543
- if (options.chatId) {
544
- adapter.log.error(`Cannot send editMessageReplyMarkup [chatId - ${options.chatId}]: ${error}`);
545
- } else {
546
- adapter.log.error(`Cannot send editMessageReplyMarkup [user - ${options.user}]: ${error}`);
547
- }
548
- options = null;
549
- resolve(count);
550
- });
549
+ bot && executeSending(() => bot.editMessageReplyMarkup(options.editMessageReplyMarkup.reply_markup, options.editMessageReplyMarkup.options), options, resolve);
551
550
  } else if (options && options.editMessageText !== undefined) {
552
551
  adapter.log.debug(`Send editMessageText to "${name}"`);
553
- bot && bot.editMessageText(text, options.editMessageText.options)
554
- .then(response => saveSendRequest(response))
555
- .then(() => {
556
- options = null;
557
- count++;
558
- resolve(count);
559
- })
560
- .catch(error => {
561
- if (options.chatId) {
562
- adapter.log.error(`Cannot send editMessageText [chatId - ${options.chatId}]: ${error}`);
563
- } else {
564
- adapter.log.error(`Cannot send editMessageText [user - ${options.user}]: ${error}`);
565
- }
566
- options = null;
567
- resolve(count);
568
- });
552
+ bot && executeSending(() => bot.editMessageText(text, options.editMessageText.options), options, resolve);
569
553
  } else if (options && options.editMessageMedia !== undefined) {
570
554
  adapter.log.debug(`Send editMessageMedia to "${name}"`);
571
555
  if (text) {
572
556
  let mediaInput;
573
- if ((typeof text === 'string' && text.match(/\.(jpg|png|jpeg|bmp|gif)$/i) && (fs.existsSync(text) || text.match(/^(https|http)/i))) || (options && options.type === 'photo')) {
557
+ if (
558
+ (typeof text === 'string' &&
559
+ text.match(/\.(jpg|png|jpeg|bmp|gif)$/i) &&
560
+ (fs.existsSync(text) || text.match(/^(https|http)/i))
561
+ ) ||
562
+ (options && options.type === 'photo')
563
+ ) {
574
564
  mediaInput = {
575
565
  type: 'photo',
576
- media: text
566
+ media: text,
577
567
  };
578
- } else
579
- if ((typeof text === 'string' && text.match(/\.(gif)/i) && fs.existsSync(text)) || (options && options.type === 'animation')) {
568
+ } else if (
569
+ (typeof text === 'string' && text.match(/\.(gif)/i) && fs.existsSync(text)) ||
570
+ (options && options.type === 'animation')
571
+ ) {
580
572
  mediaInput = {
581
573
  type: 'animation',
582
- media: text
574
+ media: text,
583
575
  };
584
- } else
585
- if ((typeof text === 'string' && text.match(/\.(mp4)$/i) && fs.existsSync(text)) || (options && options.type === 'video')) {
576
+ } else if (
577
+ (typeof text === 'string' && text.match(/\.(mp4)$/i) && fs.existsSync(text)) ||
578
+ (options && options.type === 'video')
579
+ ) {
586
580
  mediaInput = {
587
581
  type: 'video',
588
- media: text
582
+ media: text,
589
583
  };
590
- } else
591
- if ((typeof text === 'string' && text.match(/\.(wav|mp3|ogg)$/i) && fs.existsSync(text)) || (options && options.type === 'audio')) {
584
+ } else if (
585
+ (typeof text === 'string' && text.match(/\.(wav|mp3|ogg)$/i) && fs.existsSync(text)) ||
586
+ (options && options.type === 'audio')
587
+ ) {
592
588
  mediaInput = {
593
589
  type: 'audio',
594
- media: text
590
+ media: text,
595
591
  };
596
- } else
597
- if ((typeof text === 'string' && text.match(/\.(txt|doc|docx|csv|pdf|xls|xlsx)$/i) && fs.existsSync(text)) || (options && options.type === 'document')) {
592
+ } else if (
593
+ (typeof text === 'string' && text.match(/\.(txt|doc|docx|csv|pdf|xls|xlsx)$/i) && fs.existsSync(text)) ||
594
+ (options && options.type === 'document')
595
+ ) {
598
596
  mediaInput = {
599
597
  type: 'document',
600
- media: text
598
+ media: text,
601
599
  };
602
600
  }
603
601
 
604
602
  if (mediaInput) {
605
603
  const opts = {
606
- qs: options.editMessageMedia.options,
604
+ qs: options.editMessageMedia.options,
607
605
  };
608
606
  opts.formData = {};
609
607
 
@@ -626,376 +624,188 @@ function _sendMessageHelper(dest, name, text, options) {
626
624
  }
627
625
 
628
626
  opts.qs.media = JSON.stringify(payload);
629
- bot && bot._request('editMessageMedia', opts)
630
- .then(response => saveSendRequest(response))
631
- .then(() => {
632
- options = null;
633
- count++;
634
- resolve(count);
635
- })
636
- .catch(error => {
637
- if (options.chatId) {
638
- adapter.log.error(`Cannot send editMessageMedia [chatId - ${options.chatId}]: ${error}`);
639
- } else {
640
- adapter.log.error(`Cannot send editMessageMedia [user - ${options.user}]: ${error}`);
641
- }
642
- options = null;
643
- resolve(count);
644
- });
627
+ bot && executeSending(() => bot._request('editMessageMedia', opts), options, resolve);
645
628
  } else {
646
629
  adapter.log.error(`Cannot send editMessageMedia [chatId - ${options.chatId}]: unsupported media type`);
647
630
  options = null;
648
- resolve(count);
631
+ resolve(JSON.stringify(messageIds));
649
632
  }
650
633
  } else {
651
634
  adapter.log.error(`Cannot send editMessageMedia [chatId - ${options.chatId}]: no media found. "text" may not be empty`);
652
635
  options = null;
653
- resolve(count);
636
+ resolve(JSON.stringify(messageIds));
654
637
  }
655
638
  } else if (options && options.editMessageCaption !== undefined) {
656
639
  adapter.log.debug(`Send editMessageCaption to "${name}"`);
657
- bot && bot.editMessageCaption(text, options.editMessageCaption.options)
658
- .then(response => saveSendRequest(response))
659
- .then(() => {
660
- options = null;
661
- count++;
662
- resolve(count);
663
- })
664
- .catch(error => {
665
- if (options.chatId) {
666
- adapter.log.error(`Cannot send editMessageCaption [chatId - ${options.chatId}]: ${error}`);
667
- } else {
668
- adapter.log.error(`Cannot send editMessageCaption [user - ${options.user}]: ${error}`);
669
- }
670
- options = null;
671
- resolve(count);
672
- });
640
+ bot && executeSending(() => bot.editMessageCaption(text, options.editMessageCaption.options), options, resolve);
673
641
  } else if (options && options.deleteMessage !== undefined) {
674
642
  adapter.log.debug(`Send deleteMessage to "${name}"`);
675
- bot && bot.deleteMessage(options.deleteMessage.options.chat_id, options.deleteMessage.options.message_id)
676
- .then(response => saveSendRequest(response))
677
- .then(() => {
678
- options = null;
679
- count++;
680
- resolve(count);
681
- })
682
- .catch(error => {
683
- if (options.chatId) {
684
- adapter.log.error(`Cannot send deleteMessage [chatId - ${options.chatId}]: ${error}`);
685
- } else {
686
- adapter.log.error(`Cannot send deleteMessage [user - ${options.user}]: ${error}`);
687
- }
688
- options = null;
689
- resolve(count);
690
- });
643
+ bot && executeSending(() => bot.deleteMessage(options.deleteMessage.options.chat_id, options.deleteMessage.options.message_id), options, resolve);
691
644
  } else
692
- if (options && options.latitude !== undefined) {
693
- adapter.log.debug(`Send location to "${name}": ${text}`);
694
- if (bot) {
695
- bot.sendLocation(dest, parseFloat(options.latitude), parseFloat(options.longitude), options)
696
- .then(response => saveSendRequest(response))
697
- .then(() => {
698
- adapter.log.debug('Location sent');
699
- options = null;
700
- count++;
701
- resolve(count);
702
- })
703
- .catch(error => {
704
- if (options.chatId) {
705
- adapter.log.error(`Cannot send location [chatId - ${options.chatId}]: ${error}`);
706
- } else {
707
- adapter.log.error(`Cannot send location [user - ${options.user}]: ${error}`);
708
- }
709
- options = null;
710
- reject(error);
711
- });
712
- }
713
- } else if (options && options.type === 'mediagroup') {
714
- adapter.log.debug(`Send media group to "${name}": `);
715
- if (bot) {
716
- const {media: fileNames} = options;
717
- if (fileNames instanceof Array) {
718
- bot.sendChatAction(dest, 'upload_photo')
719
- .then(param => {
720
- if (fileNames.every(name => fs.existsSync(name))) {
721
- const filesAsArray = fileNames
722
- .map(element => {
723
- try {
724
- return {type: 'photo', media: fs.readFileSync(element)}
725
- } catch (error) {
726
- adapter.log.error(`Cannot read file${element}`);
727
- return undefined;
728
- }
729
- })
730
- .filter(element => element !== undefined);
731
-
732
- const size = filesAsArray
733
- .map(element => element.media.length)
734
- .reduce((acc, val) => acc + val);
735
-
736
- adapter.log.info(`Send media group to "${name}": ${size} bytes`);
737
- if (filesAsArray.length > 0) {
738
- bot.sendMediaGroup(dest, filesAsArray)
739
- .then((response) => saveSendRequest(response))
740
- .then(() => {
741
- adapter.log.debug('photos sent');
742
- count++;
743
- resolve(count);
744
- options = null;
745
- })
746
- .catch(error => {
747
- if (options.chatId) {
748
- adapter.log.error(`Cannot send media group [chatId - ${options.chatId}]: ${error}`);
749
- } else {
750
- adapter.log.error(`Cannot send media group [user - ${options.user}]: ${error}`);
645
+ if (options && options.latitude !== undefined) {
646
+ adapter.log.debug(`Send location to "${name}": ${text}`);
647
+ bot && executeSending(() => bot.sendLocation(dest, parseFloat(options.latitude), parseFloat(options.longitude), options), options, resolve);
648
+ } else if (options && options.type === 'mediagroup') {
649
+ adapter.log.debug(`Send media group to "${name}": `);
650
+ if (bot) {
651
+ const {media: fileNames} = options;
652
+ if (fileNames instanceof Array) {
653
+ bot.sendChatAction(dest, 'upload_photo')
654
+ .then(param => {
655
+ if (fileNames.every(name => fs.existsSync(name))) {
656
+ const filesAsArray = fileNames
657
+ .map(element => {
658
+ try {
659
+ return {type: 'photo', media: fs.readFileSync(element)};
660
+ } catch (error) {
661
+ adapter.log.error(`Cannot read file${element}`);
662
+ return undefined;
751
663
  }
752
- options = null;
753
- resolve(count);
754
- });
664
+ })
665
+ .filter(element => element !== undefined);
666
+
667
+ const size = filesAsArray
668
+ .map(element => element.media.length)
669
+ .reduce((acc, val) => acc + val);
670
+
671
+ adapter.log.info(`Send media group to "${name}": ${size} bytes`);
672
+ if (filesAsArray.length > 0) {
673
+ executeSending(() => bot.sendMediaGroup(dest, filesAsArray), options, resolve);
674
+ }
675
+ } else {
676
+ adapter.log.debug('files must exists');
677
+ options = null;
678
+ resolve(JSON.stringify(messageIds));
755
679
  }
756
- } else {
757
- adapter.log.debug('files must exists');
758
- options = null;
759
- resolve(count);
760
- }
761
- })
762
- .catch(error => {
763
- adapter.log.error(`upload Error:${error}`);
764
- });
765
- } else {
766
- adapter.log.debug('option media should be an array');
767
- resolve(count);
768
- }
769
- } else {
770
- adapter.log.debug('no files added!');
771
- options = null;
772
- resolve(count);
773
- }
774
- } else if (text && typeof text === 'string' && actions.includes(text)) {
775
- adapter.log.debug(`Send action to "${name}": ${text}`);
776
- bot && bot.sendChatAction(dest, text)
777
- .then(response => saveSendRequest(response))
778
- .then(() => {
779
- adapter.log.debug('Action sent');
780
- options = null;
781
- count++;
782
- resolve(count);
783
- })
784
- .catch(error => {
785
- if (options.chatId) {
786
- adapter.log.error(`Cannot send action [chatId - ${options.chatId}]: ${error}`);
787
- } else {
788
- adapter.log.error(`Cannot send action [user - ${options.user}]: ${error}`);
789
- }
790
- options = null;
791
- resolve(count);
792
- });
793
- } else if (text && ((typeof text === 'string' && text.match(/\.webp$/i) && fs.existsSync(text)) || (options && options.type === 'sticker'))) {
794
- if (typeof text === 'string') {
795
- adapter.log.debug(`Send sticker to "${name}": ${text}`);
796
- } else {
797
- adapter.log.debug(`Send sticker to "${name}": ${text.length} bytes`);
798
- }
799
- bot && bot.sendSticker(dest, text, options)
800
- .then(response => saveSendRequest(response))
801
- .then(() => {
802
- adapter.log.debug('Sticker sent');
803
- count++;
804
- resolve(count);
805
- options = null;
806
- })
807
- .catch(error => {
808
- if (options.chatId) {
809
- adapter.log.error(`Cannot send sticker [chatId - ${options.chatId}]: ${error}`);
810
- } else {
811
- adapter.log.error(`Cannot send sticker [user - ${options.user}]: ${error}`);
812
- }
813
- options = null;
814
- resolve(count);
815
- });
816
- } else if (text && ((typeof text === 'string' && text.match(/\.(gif)/i) && fs.existsSync(text)) || (options && options.type === 'animation'))) {
817
- if (typeof text === 'string') {
818
- adapter.log.debug(`Send animation to "${name}": ${text}`);
819
- } else {
820
- adapter.log.debug(`Send animation to "${name}": ${text.length} bytes`);
821
- }
822
- bot && bot.sendAnimation(dest, text, options)
823
- .then(response => saveSendRequest(response))
824
- .then(() => {
825
- adapter.log.debug('animation sent');
826
- options = null;
827
- count++;
828
- resolve(count);
829
- })
830
- .catch(error => {
831
- if (options.chatId) {
832
- adapter.log.error(`Cannot send animation [chatId - ${options.chatId}]: ${error}`);
833
- } else {
834
- adapter.log.error(`Cannot send animation [user - ${options.user}]: ${error}`);
835
- }
836
- options = null;
837
- resolve(count);
838
- });
839
- } else if (text && ((typeof text === 'string' && text.match(/\.(mp4)$/i) && fs.existsSync(text)) || (options && options.type === 'video'))) {
840
- if (typeof text === 'string') {
841
- adapter.log.debug(`Send video to "${name}": ${text}`);
842
- } else {
843
- adapter.log.debug(`Send video to "${name}": ${text.length} bytes`);
844
- }
845
- bot && bot.sendVideo(dest, text, options)
846
- .then(response => saveSendRequest(response))
847
- .then(() => {
848
- adapter.log.debug('Video sent');
849
- count++;
850
- resolve(count);
851
- options = null;
852
- })
853
- .catch(error => {
854
- if (options.chatId) {
855
- adapter.log.error(`Cannot send video [chatId - ${options.chatId}]: ${error}`);
856
- } else {
857
- adapter.log.error(`Cannot send video [user - ${options.user}]: ${error}`);
858
- }
859
- options = null;
860
- resolve(count);
861
- });
862
- } else if (text && ((typeof text === 'string' && text.match(/\.(txt|doc|docx|csv|pdf|xls|xlsx)$/i) && fs.existsSync(text)) || (options && options.type === 'document'))) {
863
- if (typeof text === 'string') {
864
- adapter.log.debug(`Send document to "${name}": ${text}`);
865
- } else {
866
- adapter.log.debug(`Send document to "${name}": ${text.length} bytes`);
867
- }
868
- bot && bot.sendDocument(dest, text, options)
869
- .then(response => saveSendRequest(response))
870
- .then(() => {
871
- adapter.log.debug('Document sent');
872
- options = null;
873
- count++;
874
- resolve(count);
875
- })
876
- .catch(error => {
877
- if (options.chatId) {
878
- adapter.log.error(`Cannot send document [chatId - ${options.chatId}]: ${error}`);
879
- } else {
880
- adapter.log.error(`Cannot send document [user - ${options.user}]: ${error}`);
881
- }
882
- options = null;
883
- resolve(count);
884
- });
885
- } else if (text && ((typeof text === 'string' && text.match(/\.(wav|mp3|ogg)$/i) && fs.existsSync(text)) || (options && options.type === 'audio'))) {
886
- if (typeof text === 'string') {
887
- adapter.log.debug(`Send audio to "${name}": ${text}`);
888
- } else {
889
- adapter.log.debug(`Send audio to "${name}": ${text.length} bytes`);
890
- }
891
- bot && bot.sendAudio(dest, text, options)
892
- .then(response => saveSendRequest(response))
893
- .then(() => {
894
- adapter.log.debug('Audio sent');
895
- options = null;
896
- count++;
897
- resolve(count);
898
- })
899
- .catch(error => {
900
- if (options.chatId) {
901
- adapter.log.error(`Cannot send audio [chatId - ${options.chatId}]: ${error}`);
680
+ })
681
+ .catch(error => {
682
+ adapter.log.error(`upload Error:${error}`);
683
+ });
902
684
  } else {
903
- adapter.log.error(`Cannot send audio [user - ${options.user}]: ${error}`);
685
+ adapter.log.debug('option media should be an array');
686
+ resolve(JSON.stringify(messageIds));
904
687
  }
688
+ } else {
689
+ adapter.log.debug('no files added!');
905
690
  options = null;
906
- resolve(count);
907
- });
908
- } else if (text && ((typeof text === 'string' && text.match(/\.(jpg|png|jpeg|bmp|gif)$/i) && (fs.existsSync(text) || text.match(/^(https|http)/i))) || (options && options.type === 'photo'))) {
909
- if (typeof text === 'string') {
910
- adapter.log.debug(`Send photo to "${name}": ${text}`);
691
+ resolve(JSON.stringify(messageIds));
692
+ }
693
+ } else if (text && typeof text === 'string' && actions.includes(text)) {
694
+ adapter.log.debug(`Send action to "${name}": ${text}`);
695
+ bot && executeSending(() => bot.sendChatAction(dest, text), options, resolve);
696
+ } else if (text && ((typeof text === 'string' && text.match(/\.webp$/i) && fs.existsSync(text)) || (options && options.type === 'sticker'))) {
697
+ if (typeof text === 'string') {
698
+ adapter.log.debug(`Send sticker to "${name}": ${text}`);
699
+ } else {
700
+ adapter.log.debug(`Send sticker to "${name}": ${text.length} bytes`);
701
+ }
702
+ bot && executeSending(() => bot.sendSticker(dest, text, options), options, resolve);
703
+ } else if (text && ((typeof text === 'string' && text.match(/\.(gif)/i) && fs.existsSync(text)) || (options && options.type === 'animation'))) {
704
+ if (typeof text === 'string') {
705
+ adapter.log.debug(`Send animation to "${name}": ${text}`);
706
+ } else {
707
+ adapter.log.debug(`Send animation to "${name}": ${text.length} bytes`);
708
+ }
709
+ bot && executeSending(() => bot.sendAnimation(dest, text, options), options, resolve);
710
+ } else if (text && ((typeof text === 'string' && text.match(/\.(mp4)$/i) && fs.existsSync(text)) || (options && options.type === 'video'))) {
711
+ if (typeof text === 'string') {
712
+ adapter.log.debug(`Send video to "${name}": ${text}`);
713
+ } else {
714
+ adapter.log.debug(`Send video to "${name}": ${text.length} bytes`);
715
+ }
716
+ bot && executeSending(() => bot.sendVideo(dest, text, options), options, resolve);
717
+ } else if (text && ((typeof text === 'string' && text.match(/\.(txt|doc|docx|csv|pdf|xls|xlsx)$/i) && fs.existsSync(text)) || (options && options.type === 'document'))) {
718
+ adapter.log.debug(`Send document to "${name}": ${(typeof text === 'string') ? text : text.length}`);
719
+ bot && executeSending(() => bot.sendDocument(dest, text, options), options, resolve);
720
+ } else if (
721
+ text &&
722
+ (
723
+ (typeof text === 'string' &&
724
+ text.match(/\.(wav|mp3|ogg)$/i) &&
725
+ fs.existsSync(text)
726
+ ) ||
727
+ (options && options?.type === 'audio')
728
+ )
729
+ ) {
730
+ adapter.log.debug(`Send audio to "${name}": ${(typeof text === 'string') ? text : text.length}`);
731
+
732
+ bot && executeSending(() => bot.sendAudio(dest, text, options), options, resolve);
733
+
734
+ } else if (
735
+ text &&
736
+ (
737
+ (
738
+ typeof text === 'string' && // if the message is a string, and it is a path to file or URL
739
+ text.match(/\.(jpg|png|jpeg|bmp|gif)$/i) &&
740
+ (fs.existsSync(text) || text.match(/^(https|http)/i))
741
+ ) ||
742
+ (options && options.type === 'photo') // if the type of message is photo
743
+ )
744
+ ) {
745
+ adapter.log.debug(`Send photo to "${name}": ${(typeof text === 'string') ? text : text.length}`);
746
+
747
+ bot && executeSending(() => bot.sendPhoto(dest, text, options), options, resolve);
748
+ } else if (options && options.answerCallbackQuery !== undefined) {
749
+ adapter.log.debug(`Send answerCallbackQuery to "${name}"`);
750
+ if (options.answerCallbackQuery.showAlert === undefined) {
751
+ options.answerCallbackQuery.showAlert = false;
752
+ }
753
+ if (bot && callbackQueryId[options.chatId]) {
754
+ const originalChatId = callbackQueryId[options.chatId].id;
755
+ delete callbackQueryId[options.chatId];
756
+ executeSending(() => bot.answerCallbackQuery(originalChatId, options.answerCallbackQuery.text, options.answerCallbackQuery.showAlert), options, resolve);
757
+ }
911
758
  } else {
912
- adapter.log.debug(`Send photo to "${name}": ${text.length} bytes`);
913
- }
914
- bot && bot.sendPhoto(dest, text, options)
915
- .then(response => saveSendRequest(response))
916
- .then(() => {
917
- adapter.log.debug('Photo sent');
918
- options = null;
919
- count++;
920
- resolve(count);
921
- })
922
- .catch(error => {
923
- if (options.chatId) {
924
- adapter.log.error(`Cannot send photo [chatId - ${options.chatId}]: ${error}`);
925
- } else {
926
- adapter.log.error(`Cannot send photo [user - ${options.user}]: ${error}`);
927
- }
928
- options = null;
929
- resolve(count);
930
- });
931
- } else if (options && options.answerCallbackQuery !== undefined) {
932
- adapter.log.debug(`Send answerCallbackQuery to "${name}"`);
933
- if (options.answerCallbackQuery.showAlert === undefined) {
934
- options.answerCallbackQuery.showAlert = false;
935
- }
936
- if (bot && callbackQueryId[options.chatId]) {
937
- const originalChatId = callbackQueryId[options.chatId].id;
938
- delete callbackQueryId[options.chatId];
939
- bot.answerCallbackQuery(originalChatId, options.answerCallbackQuery.text, options.answerCallbackQuery.showAlert)
940
- .then(() => {
941
- options = null;
942
- count++;
943
- resolve(count);
944
- })
945
- .catch(error => {
946
- if (options.chatId) {
947
- adapter.log.error(`Cannot send answerCallbackQuery [chatId - ${options.chatId}]: ${error}`);
948
- } else {
949
- adapter.log.error(`Cannot send answerCallbackQuery [user - ${options.user}]: ${error}`);
950
- }
951
- options = null;
952
- resolve(count);
953
- });
954
- }
955
- } else {
956
- adapter.log.debug(`Send message to [${name}]: "${text}"`);
957
- if (text && typeof text === 'string') {
958
- if (text.startsWith('<MarkdownV2>') && text.endsWith('</MarkdownV2>')) {
959
- options = options || {};
960
- options.parse_mode = 'MarkdownV2';
961
- text = text.substring(12, text.length - 13);
962
- } else if (text.startsWith('<HTML>') && text.endsWith('</HTML>')) {
963
- options = options || {};
964
- options.parse_mode = 'HTML';
965
- text = text.substring(6, text.length - 7);
966
- } else if (text.startsWith('<Markdown>') && text.endsWith('</Markdown>')) {
759
+ adapter.log.debug(`Send message to [${name}]: "${text}"`);
760
+ if (text && typeof text === 'string') {
967
761
  options = options || {};
968
- options.parse_mode = 'Markdown';
969
- text = text.substring(10, text.length - 11);
762
+ if (text.startsWith('<MarkdownV2>') && text.endsWith('</MarkdownV2>')) {
763
+ options.parse_mode = 'MarkdownV2';
764
+ text = text.substring(12, text.length - 13);
765
+ } else if (text.startsWith('<HTML>') && text.endsWith('</HTML>')) {
766
+ options.parse_mode = 'HTML';
767
+ text = text.substring(6, text.length - 7);
768
+ } else if (text.startsWith('<Markdown>') && text.endsWith('</Markdown>')) {
769
+ options.parse_mode = 'Markdown';
770
+ text = text.substring(10, text.length - 11);
771
+ }
970
772
  }
773
+ bot && executeSending(() => bot.sendMessage(dest, text || '', options), options, resolve);
971
774
  }
972
-
973
- bot && bot.sendMessage(dest, text || '', options)
974
- .then(response => saveSendRequest(response))
975
- .then(() => {
976
- adapter.log.debug('Message sent');
977
- options = null;
978
- count++;
979
- resolve(count);
980
- })
981
- .catch(error => {
982
- if (options && options.chatId) {
983
- adapter.log.error(`Cannot send message [chatId - ${options.chatId}]: ${error}`);
984
- } else {
985
- adapter.log.error(`Cannot send message [user - ${options && options.user}]: ${error}`);
986
- }
987
- options = null;
988
- resolve(count);
989
- });
990
-
991
- }
992
775
  });
993
776
  }
994
777
 
778
+ /**
779
+ * executes the given method and handles, what to do next
780
+ */
781
+ function executeSending(action, options, resolve){
782
+ // create an empty object, to store chat id and message id of successfully sent messages
783
+ const messageIds = {};
784
+ action()
785
+ .then(response => {
786
+ // put chat id and message id to the object, that will be returned
787
+ messageIds[options.chat_id] = response.message_id;
788
+ // puts ids to the ioBroker database
789
+ saveSendRequest(response);
790
+ })
791
+ .then(() => {
792
+ adapter.log.debug('Message sent');
793
+ options = null;
794
+ // return all the collected message ids to the callback
795
+ resolve(JSON.stringify(messageIds));
796
+ }).catch(error => {
797
+ // log error to the system
798
+ adapter.log.error(`Failed sending [${options.chatId ? 'chatId' : 'user'} - ${options.chatId ? options.chatId : options.user}]: ${error}`);
799
+ options = null;
800
+ // send the succesfully send messages as callback
801
+ resolve(JSON.stringify(messageIds));
802
+ });
803
+ }
804
+
995
805
  function sendMessage(text, user, chatId, options) {
996
806
  if (!text && typeof options !== 'object' && text !== 0 && (!options || !options.latitude)) {
997
- adapter.log.warn('Invalid text: null');
998
- return Promise.resolve(0);
807
+ adapter.log.warn('Invalid text: null');
808
+ return Promise.resolve({});
999
809
  }
1000
810
 
1001
811
  if (text && typeof text === 'object' && text.text !== undefined && typeof text.text === 'string' && options === undefined) {
@@ -1027,18 +837,16 @@ function sendMessage(text, user, chatId, options) {
1027
837
  if (text && text.startsWith('<MarkdownV2>') && text.endsWith('</MarkdownV2>')) {
1028
838
  options.parse_mode = 'MarkdownV2';
1029
839
  text = text.substring(12, text.length - 13);
1030
- } else
1031
- if (text && text.startsWith('<HTML>') && text.endsWith('</HTML>')) {
840
+ } else if (text && text.startsWith('<HTML>') && text.endsWith('</HTML>')) {
1032
841
  options.parse_mode = 'HTML';
1033
842
  text = text.substring(6, text.length - 7);
1034
- } else
1035
- if (text && text.startsWith('<Markdown>') && text.endsWith('</Markdown>')) {
843
+ } else if (text && text.startsWith('<Markdown>') && text.endsWith('</Markdown>')) {
1036
844
  options.parse_mode = 'Markdown';
1037
845
  text = text.substring(10, text.length - 11);
1038
846
  }
1039
847
  }
1040
848
 
1041
- let tPromiseList = [];
849
+ const tPromiseList = [];
1042
850
  // convert
1043
851
  if (text !== undefined && text !== null && typeof text !== 'object') {
1044
852
  text = text.toString();
@@ -1095,7 +903,7 @@ function sendMessage(text, user, chatId, options) {
1095
903
  continue;
1096
904
  }
1097
905
  if ((adapter.config.useUsername && users[id_t].userName.match(re)) || (!adapter.config.useUsername && users[id_t].firstName.match(re))) {
1098
- id = id_t
906
+ id = id_t;
1099
907
  break;
1100
908
  }
1101
909
  }
@@ -1168,7 +976,7 @@ function getMessage(msg) {
1168
976
  } else {
1169
977
  adapter.log.debug(res.error);
1170
978
  }
1171
- })
979
+ });
1172
980
  } catch (err) {
1173
981
  adapter.log.error(`Error saving voice file: ${err}`);
1174
982
  }
@@ -1764,7 +1572,7 @@ function processTelegramText(msg) {
1764
1572
  continue;
1765
1573
  }
1766
1574
  } else {
1767
- value = sValue
1575
+ value = sValue;
1768
1576
  }
1769
1577
 
1770
1578
  adapter.setForeignState(id, value, false, err =>
@@ -1926,7 +1734,7 @@ function connect() {
1926
1734
  );
1927
1735
  }
1928
1736
  } catch (e) {
1929
-
1737
+ // looks empty
1930
1738
  }
1931
1739
  }
1932
1740
  // Check connection
@@ -2005,7 +1813,7 @@ function connect() {
2005
1813
  adapter.log.debug(`Start polling with: ${pollingOptions.polling.interval}(${typeof pollingOptions.polling.interval}) ms interval`);
2006
1814
  bot = new TelegramBot(adapter.config.token, pollingOptions);
2007
1815
  bot.setWebHook('').catch(error => {
2008
- adapter.log.error(`setWebHook Error:${error}`)
1816
+ adapter.log.error(`setWebHook Error:${error}`);
2009
1817
  });
2010
1818
  }
2011
1819
 
@@ -2023,7 +1831,7 @@ function connect() {
2023
1831
  }
2024
1832
  }
2025
1833
  }).catch(error => {
2026
- adapter.log.error(`getMe Error:${error}`)
1834
+ adapter.log.error(`getMe Error:${error}`);
2027
1835
  connectionState(false);
2028
1836
  });
2029
1837
 
@@ -2155,11 +1963,11 @@ async function readStatesCommands() {
2155
1963
  if (doc && doc.rows) {
2156
1964
  for (let i = 0, l = doc.rows.length; i < l; i++) {
2157
1965
  if (doc.rows[i].value) {
2158
- let id = doc.rows[i].id;
2159
- let obj = doc.rows[i].value;
1966
+ const id = doc.rows[i].id;
1967
+ const obj = doc.rows[i].value;
2160
1968
  if (obj[adapter.namespace] && obj[adapter.namespace].enabled) {
2161
1969
  commands[id] = obj[adapter.namespace];
2162
- readNames.push(id)
1970
+ readNames.push(id);
2163
1971
  }
2164
1972
  }
2165
1973
  }
@@ -2176,8 +1984,8 @@ async function readEnums(name) {
2176
1984
  if (doc && doc.rows) {
2177
1985
  for (let i = 0, l = doc.rows.length; i < l; i++) {
2178
1986
  if (doc.rows[i].value) {
2179
- let id = doc.rows[i].id;
2180
- let obj = doc.rows[i].value;
1987
+ const id = doc.rows[i].id;
1988
+ const obj = doc.rows[i].value;
2181
1989
  if (obj && obj.common && obj.common.members && obj.common.members.length) {
2182
1990
  enums[name][id] = obj.common;
2183
1991
  }
@@ -2230,7 +2038,7 @@ async function main() {
2230
2038
  systemLang = obj.common.language || 'en';
2231
2039
  }
2232
2040
 
2233
- await readStatesCommands()
2041
+ await readStatesCommands();
2234
2042
  if (adapter.config.rooms) {
2235
2043
  await readEnums();
2236
2044
  }
@@ -2246,10 +2054,75 @@ async function main() {
2246
2054
  }
2247
2055
  }
2248
2056
 
2057
+
2058
+ /**
2059
+ * Process a `sendNotification` request
2060
+ *
2061
+ * @param {ioBroker.Message} obj
2062
+ */
2063
+ async function processNotification( obj) {
2064
+ adapter.log.info(`New notification received from ${obj.from}`);
2065
+
2066
+ const notificationMessage = buildMessageFromNotification(obj.message);
2067
+ try {
2068
+ await sendSystemMessage(notificationMessage, { parse_mode: 'MarkdownV2' });
2069
+ if (obj.callback) {
2070
+ adapter.sendTo(obj.from, 'sendNotification', { sent: true }, obj.callback);
2071
+ }
2072
+ } catch {
2073
+ if (obj.callback) {
2074
+ adapter.sendTo(obj.from, 'sendNotification', { sent: false }, obj.callback);
2075
+ }
2076
+ }
2077
+
2078
+ }
2079
+
2080
+ /**
2081
+ * Build up a mail object from the notification message
2082
+ *
2083
+ * @param {Record<string, any>} message
2084
+ * @returns {string}
2085
+ */
2086
+ function buildMessageFromNotification(message) {
2087
+ const subject = message.category.name;
2088
+ const { instances } = message.category;
2089
+
2090
+ const readableInstances = Object.entries(instances).map(([instance, entry]) => `${instance.substring('system.adapter.'.length)}: ${getNewestDate(entry.messages)}`);
2091
+
2092
+ const text = `${message.category.description}
2093
+ ${message.host}:
2094
+ ${readableInstances.join('\n')}
2095
+ `;
2096
+
2097
+ return replaceReservedCharacters(`*${subject}*\n\n${text}`);
2098
+ }
2099
+
2100
+ /**
2101
+ * Replace reserved characters in outgoing message
2102
+ *
2103
+ * @param {string} text string to sanitize
2104
+ * @returns {string}
2105
+ */
2106
+ function replaceReservedCharacters(text) {
2107
+ return text.replace(/\./g, '\\.').replace(/-/g, '\\-');
2108
+ }
2109
+
2110
+ /**
2111
+ * Extract the newest date out of a notification messages array as local date
2112
+ *
2113
+ * @param {{ ts: number, message: string }[]} messages
2114
+ * @return string
2115
+ */
2116
+ function getNewestDate(messages) {
2117
+ const newestTs = messages.sort((a, b) => a.ts < b.ts ? 1 : -1)[0].ts;
2118
+
2119
+ return new Date(newestTs).toLocaleString();
2120
+ }
2121
+
2249
2122
  // If started as allInOne/compact mode => return function to create instance
2250
2123
  if (module && module.parent) {
2251
2124
  module.exports = startAdapter;
2252
2125
  } else {
2253
2126
  // or start the instance directly
2254
2127
  startAdapter();
2255
- }
2128
+ }