iobroker.telegram 5.0.5 → 6.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/README.md +10 -6
- package/admin/i18n/de.json +10 -1
- package/admin/i18n/en.json +10 -1
- package/admin/i18n/es.json +10 -1
- package/admin/i18n/fr.json +10 -1
- package/admin/i18n/it.json +10 -1
- package/admin/i18n/nl.json +10 -1
- package/admin/i18n/pl.json +10 -1
- package/admin/i18n/pt.json +10 -1
- package/admin/i18n/ru.json +10 -1
- package/admin/i18n/uk.json +10 -1
- package/admin/i18n/zh-cn.json +10 -1
- package/admin/jsonConfig.json +76 -10
- package/admin/rules/@mf-types.zip +0 -0
- package/build/main.js +522 -299
- package/build/main.js.map +1 -1
- package/build/proxy.d.ts +32 -0
- package/build/proxy.js +66 -0
- package/build/proxy.js.map +1 -0
- package/build/types.d.ts +2 -0
- package/io-package.json +94 -15
- package/package.json +4 -3
package/build/main.js
CHANGED
|
@@ -5,12 +5,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
const node_fs_1 = require("node:fs");
|
|
7
7
|
const node_path_1 = require("node:path");
|
|
8
|
-
const node_https_1 = require("node:https");
|
|
9
8
|
const axios_1 = __importDefault(require("axios"));
|
|
10
|
-
const node_telegram_bot_api_1 =
|
|
9
|
+
const node_telegram_bot_api_1 = require("node-telegram-bot-api");
|
|
10
|
+
const node_1 = require("node-telegram-bot-api/node");
|
|
11
11
|
const adapter_core_1 = require("@iobroker/adapter-core");
|
|
12
12
|
const webserver_1 = require("@iobroker/webserver");
|
|
13
13
|
const iobUri_1 = require("./iobUri");
|
|
14
|
+
const proxy_1 = require("./proxy");
|
|
14
15
|
const systemLang2CallMe = {
|
|
15
16
|
en: 'en-GB-Standard-A',
|
|
16
17
|
de: 'de-DE-Standard-A',
|
|
@@ -33,13 +34,69 @@ const actions = [
|
|
|
33
34
|
'upload_document',
|
|
34
35
|
'find_location',
|
|
35
36
|
];
|
|
37
|
+
/**
|
|
38
|
+
* Keys of the `SendOptions` bag that steer the adapter itself (recipient selection, media type detection,
|
|
39
|
+
* the edit/delete/answer sub-commands, ...). Everything else is forwarded to the Bot API unchanged, so callers
|
|
40
|
+
* can pass any documented parameter of the underlying method (e.g. `parse_mode`, `reply_markup`,
|
|
41
|
+
* `protect_content`, `message_thread_id`).
|
|
42
|
+
*/
|
|
43
|
+
const INTERNAL_OPTION_KEYS = new Set([
|
|
44
|
+
'chatId',
|
|
45
|
+
'user',
|
|
46
|
+
'text',
|
|
47
|
+
'type',
|
|
48
|
+
'fileName',
|
|
49
|
+
'media',
|
|
50
|
+
'latitude',
|
|
51
|
+
'longitude',
|
|
52
|
+
'title',
|
|
53
|
+
'address',
|
|
54
|
+
'editMessageReplyMarkup',
|
|
55
|
+
'editMessageText',
|
|
56
|
+
'editMessageMedia',
|
|
57
|
+
'editMessageCaption',
|
|
58
|
+
'deleteMessage',
|
|
59
|
+
'answerCallbackQuery',
|
|
60
|
+
]);
|
|
61
|
+
/**
|
|
62
|
+
* Pick the Bot API parameters out of the option bag, dropping the adapter-internal keys.
|
|
63
|
+
*
|
|
64
|
+
* @param options the option bag of a send request
|
|
65
|
+
* @returns the parameters to forward to the Bot API method
|
|
66
|
+
*/
|
|
67
|
+
function toApiParams(options) {
|
|
68
|
+
const params = {};
|
|
69
|
+
if (options) {
|
|
70
|
+
for (const [key, value] of Object.entries(options)) {
|
|
71
|
+
if (!INTERNAL_OPTION_KEYS.has(key) && value !== undefined) {
|
|
72
|
+
params[key] = value;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return params;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* File names telegram gets to see when raw bytes are uploaded and the caller did not provide one. The extension
|
|
80
|
+
* matters: the library does no content sniffing, so the name decides how telegram treats the upload.
|
|
81
|
+
*/
|
|
82
|
+
const DEFAULT_FILE_NAMES = {
|
|
83
|
+
photo: 'photo.jpg',
|
|
84
|
+
animation: 'animation.gif',
|
|
85
|
+
video: 'video.mp4',
|
|
86
|
+
audio: 'audio.mp3',
|
|
87
|
+
document: 'document.bin',
|
|
88
|
+
sticker: 'sticker.webp',
|
|
89
|
+
};
|
|
36
90
|
class Telegram extends adapter_core_1.Adapter {
|
|
37
91
|
bot;
|
|
92
|
+
/** The fetch used by the Bot API client and for media downloads - bound to the proxy when one is configured */
|
|
93
|
+
fetchImpl = globalThis.fetch;
|
|
38
94
|
storedUsers = {};
|
|
39
95
|
storedChats = {};
|
|
40
96
|
systemLang = 'en';
|
|
41
97
|
reconnectTimer;
|
|
42
98
|
pollConnectionStatus;
|
|
99
|
+
pollingRestartTimer;
|
|
43
100
|
isConnected = null;
|
|
44
101
|
lastMessageTime = 0;
|
|
45
102
|
lastMessageText = '';
|
|
@@ -65,6 +122,8 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
65
122
|
static SEND_QUEUE_RETRY_MS = 30000;
|
|
66
123
|
static MAX_SEND_QUEUE_AGE_MS = 24 * 60 * 60 * 1000; // 24 h
|
|
67
124
|
static MAX_SEND_ATTEMPTS = 10;
|
|
125
|
+
/** Delay before the long-poll loop is restarted after it ended with a fatal error */
|
|
126
|
+
static POLLING_RESTART_MS = 30000;
|
|
68
127
|
server = {
|
|
69
128
|
server: null,
|
|
70
129
|
settings: null,
|
|
@@ -190,8 +249,46 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
190
249
|
}
|
|
191
250
|
}
|
|
192
251
|
}
|
|
252
|
+
/**
|
|
253
|
+
* Normalize the configured text2command/assistant instance ids to the short form (`text2command.0`).
|
|
254
|
+
*
|
|
255
|
+
* The config UI before v1.12.6 stored the instance in the long form (`system.adapter.text2command.0`).
|
|
256
|
+
* `sendTo` accepts both forms, so such a value kept working unnoticed for years - but the jsonConfig
|
|
257
|
+
* instance selector expects the short form and shows an empty field for it. Persist the short form once,
|
|
258
|
+
* so the config dialog displays the selected instance again. The controller restarts the instance after
|
|
259
|
+
* the config update; until then the normalized value is used in memory.
|
|
260
|
+
* See https://github.com/iobroker-community-adapters/ioBroker.telegram/issues/1365
|
|
261
|
+
*/
|
|
262
|
+
async migrateInstanceIds() {
|
|
263
|
+
const migrated = {};
|
|
264
|
+
for (const key of ['text2command', 'assistantInstance']) {
|
|
265
|
+
const value = this.config[key];
|
|
266
|
+
if (typeof value === 'string' && value.startsWith('system.adapter.')) {
|
|
267
|
+
const shortId = value.substring('system.adapter.'.length);
|
|
268
|
+
migrated[key] = shortId;
|
|
269
|
+
this.config[key] = shortId;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (Object.keys(migrated).length) {
|
|
273
|
+
this.log.info(`Migrating instance id(s) to the short form: ${JSON.stringify(migrated)}`);
|
|
274
|
+
try {
|
|
275
|
+
await this.updateConfig(migrated);
|
|
276
|
+
}
|
|
277
|
+
catch (err) {
|
|
278
|
+
this.log.warn(`Cannot store migrated instance id(s): ${err instanceof Error ? err.message : err}`);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
193
282
|
async onReady() {
|
|
194
283
|
this.isServer = this.config.server === 'true';
|
|
284
|
+
await this.migrateInstanceIds();
|
|
285
|
+
// An empty "API URL" field must fall back to the default: node-telegram-bot-api >= 1.x takes the
|
|
286
|
+
// configured value as-is (`??` instead of the former `||`), so "" would produce relative request URLs
|
|
287
|
+
// and every API call fails with "EFATAL: Failed to parse URL". A trailing slash is stripped as well,
|
|
288
|
+
// because the library builds `${baseApiUrl}/bot<token>/...`.
|
|
289
|
+
// See https://github.com/iobroker-community-adapters/ioBroker.telegram/issues/1371
|
|
290
|
+
this.config.baseApiUrl =
|
|
291
|
+
(this.config.baseApiUrl || '').trim().replace(/\/+$/, '') || 'https://api.telegram.org';
|
|
195
292
|
// i18n JSON files live in `<packageRoot>/i18n`; main.js runs from `<packageRoot>/build`
|
|
196
293
|
await adapter_core_1.I18n.init((0, node_path_1.join)(__dirname, '..'), this);
|
|
197
294
|
this.questions = [];
|
|
@@ -260,15 +357,13 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
260
357
|
this.log.error(`Cannot start server on ${this.config.bind || '0.0.0.0'}:${serverPort}: ${e}`);
|
|
261
358
|
}
|
|
262
359
|
if (!serverListening) {
|
|
263
|
-
this.terminate
|
|
264
|
-
? this.terminate(adapter_core_1.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION)
|
|
265
|
-
: process.exit(adapter_core_1.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
|
|
360
|
+
this.terminate(adapter_core_1.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
|
|
266
361
|
}
|
|
267
362
|
});
|
|
268
363
|
this.getPort(this.config.port, !this.config.bind || this.config.bind === '0.0.0.0' ? undefined : this.config.bind || undefined, port => {
|
|
269
364
|
if (parseInt(String(port), 10) !== this.config.port && !this.config.findNextPort) {
|
|
270
365
|
this.log.error(`port ${this.config.port} already in use`);
|
|
271
|
-
this.terminate
|
|
366
|
+
this.terminate(adapter_core_1.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
|
|
272
367
|
}
|
|
273
368
|
serverPort = port;
|
|
274
369
|
this.server.server?.listen(port, !this.config.bind || this.config.bind === '0.0.0.0'
|
|
@@ -305,6 +400,12 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
305
400
|
this.clearInterval(this.garbageCollectorInterval);
|
|
306
401
|
this.garbageCollectorInterval = undefined;
|
|
307
402
|
}
|
|
403
|
+
if (this.pollingRestartTimer) {
|
|
404
|
+
this.clearTimeout(this.pollingRestartTimer);
|
|
405
|
+
this.pollingRestartTimer = undefined;
|
|
406
|
+
}
|
|
407
|
+
// stop the long-poll loop (no-op in webhook mode)
|
|
408
|
+
this.bot?.stop();
|
|
308
409
|
// cancel any pending question answer-timeouts so they cannot fire after unload
|
|
309
410
|
this.questions?.forEach(q => q.timeout && this.clearTimeout(q.timeout));
|
|
310
411
|
this.questions = [];
|
|
@@ -540,8 +641,8 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
540
641
|
let errorCounter = 0;
|
|
541
642
|
const checkConnection = () => {
|
|
542
643
|
this.pollConnectionStatus = undefined;
|
|
543
|
-
this.bot
|
|
544
|
-
|
|
644
|
+
this.bot?.api
|
|
645
|
+
.getMe()
|
|
545
646
|
.then(data => {
|
|
546
647
|
this.log.debug(`getMe (reconnect): ${JSON.stringify(data)}`);
|
|
547
648
|
this.connectionState(true, errorCounter > 0);
|
|
@@ -585,27 +686,10 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
585
686
|
* @returns true if the send should be queued and retried later
|
|
586
687
|
*/
|
|
587
688
|
isRetryableSendError(error) {
|
|
588
|
-
|
|
589
|
-
//
|
|
590
|
-
//
|
|
591
|
-
|
|
592
|
-
return true;
|
|
593
|
-
}
|
|
594
|
-
if (code === 'ETELEGRAM') {
|
|
595
|
-
// the Bot API replied with ok:false - retry only on rate limit (429) or server errors (5xx)
|
|
596
|
-
const status = error?.response?.body?.error_code ?? error?.response?.statusCode;
|
|
597
|
-
if (status === 429 || (typeof status === 'number' && status >= 500 && status < 600)) {
|
|
598
|
-
return true;
|
|
599
|
-
}
|
|
600
|
-
const m = /ETELEGRAM:\s*(\d{3})/.exec(String(error?.message ?? error));
|
|
601
|
-
if (m) {
|
|
602
|
-
const s = parseInt(m[1], 10);
|
|
603
|
-
return s === 429 || (s >= 500 && s < 600);
|
|
604
|
-
}
|
|
605
|
-
return false;
|
|
606
|
-
}
|
|
607
|
-
// unknown error shape - be conservative and do not retry
|
|
608
|
-
return false;
|
|
689
|
+
// NetworkError/TimeoutError: telegram is unreachable; TelegramApiError with 429 or 5xx: rate limit or
|
|
690
|
+
// server-side problem; ParseError: telegram answered with a non-JSON body, typically a transient
|
|
691
|
+
// gateway error. Everything else (400 "chat not found", 403 "bot was blocked", ...) is permanent.
|
|
692
|
+
return (0, node_telegram_bot_api_1.isTransientError)(error) || error instanceof node_telegram_bot_api_1.ParseError;
|
|
609
693
|
}
|
|
610
694
|
/**
|
|
611
695
|
* Queue a send that failed because telegram was unreachable, so it can be resent on reconnect. The
|
|
@@ -737,7 +821,7 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
737
821
|
return;
|
|
738
822
|
}
|
|
739
823
|
res.end('OK');
|
|
740
|
-
this.bot.
|
|
824
|
+
void this.bot.handleUpdate(msg);
|
|
741
825
|
});
|
|
742
826
|
}
|
|
743
827
|
else {
|
|
@@ -747,8 +831,10 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
747
831
|
res.end('<!doctype html><html><head><title>404</title></head><body>404: Resource Not Found</body></html>');
|
|
748
832
|
}
|
|
749
833
|
}
|
|
750
|
-
saveSendRequest(
|
|
751
|
-
this.log.debug(`Request [saveSendRequest]: ${JSON.stringify(
|
|
834
|
+
saveSendRequest(result) {
|
|
835
|
+
this.log.debug(`Request [saveSendRequest]: ${JSON.stringify(result)}`);
|
|
836
|
+
// sendMediaGroup answers with the list of sent messages - remember the first one
|
|
837
|
+
const msg = Array.isArray(result) ? result[0] : result;
|
|
752
838
|
if (typeof msg === 'object') {
|
|
753
839
|
if (this.config.storeRawRequest) {
|
|
754
840
|
this.setState('communicate.botSendRaw', JSON.stringify(msg, null, 2), true).catch(err => this.log.error(err.message));
|
|
@@ -853,6 +939,32 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
853
939
|
}
|
|
854
940
|
return null;
|
|
855
941
|
}
|
|
942
|
+
/**
|
|
943
|
+
* Convert a send payload into what the Bot API client expects for a file parameter: raw bytes and local
|
|
944
|
+
* files become an upload (`InputFile`, streamed as multipart part), everything else - an `http(s)` URL or a
|
|
945
|
+
* telegram `file_id` - is passed through as string.
|
|
946
|
+
*
|
|
947
|
+
* @param content the payload: a Buffer, a local file path, a URL or a file_id
|
|
948
|
+
* @param fileName the file name telegram should see for an upload
|
|
949
|
+
* @param defaultName file name used for raw bytes when the caller did not provide one
|
|
950
|
+
* @returns the value for the file parameter of the send method
|
|
951
|
+
*/
|
|
952
|
+
async toInputFile(content, fileName, defaultName) {
|
|
953
|
+
// a Buffer that travelled through the ioBroker message bus arrives JSON-serialized
|
|
954
|
+
if (content &&
|
|
955
|
+
typeof content === 'object' &&
|
|
956
|
+
content.type === 'Buffer' &&
|
|
957
|
+
Array.isArray(content.data)) {
|
|
958
|
+
content = Buffer.from(content.data);
|
|
959
|
+
}
|
|
960
|
+
if (Buffer.isBuffer(content)) {
|
|
961
|
+
return new node_telegram_bot_api_1.InputFile(content, { filename: fileName || defaultName });
|
|
962
|
+
}
|
|
963
|
+
if (typeof content === 'string' && (0, node_fs_1.existsSync)(content)) {
|
|
964
|
+
return (0, node_1.fromPath)(content, fileName ? { filename: fileName } : undefined);
|
|
965
|
+
}
|
|
966
|
+
return String(content);
|
|
967
|
+
}
|
|
856
968
|
async sendMessageHelper(dest, name, text, options) {
|
|
857
969
|
const bot = this.bot;
|
|
858
970
|
// Resolve ioBroker URIs (iobfile://, iobobject://, iobstate://) to their content before dispatching.
|
|
@@ -894,13 +1006,16 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
894
1006
|
if (options?.editMessageReplyMarkup !== undefined) {
|
|
895
1007
|
this.log.debug(`Send editMessageReplyMarkup to "${name}"`);
|
|
896
1008
|
if (bot) {
|
|
897
|
-
this.executeSending(() => bot.editMessageReplyMarkup(
|
|
1009
|
+
this.executeSending(() => bot.api.editMessageReplyMarkup({
|
|
1010
|
+
...options.editMessageReplyMarkup.options,
|
|
1011
|
+
reply_markup: options.editMessageReplyMarkup.reply_markup,
|
|
1012
|
+
}), options, resolve);
|
|
898
1013
|
}
|
|
899
1014
|
}
|
|
900
1015
|
else if (options?.editMessageText !== undefined) {
|
|
901
1016
|
this.log.debug(`Send editMessageText to "${name}"`);
|
|
902
1017
|
if (bot) {
|
|
903
|
-
this.executeSending(() => bot.editMessageText({ ...options.editMessageText.options, text }), options, resolve);
|
|
1018
|
+
this.executeSending(() => bot.api.editMessageText({ ...options.editMessageText.options, text }), options, resolve);
|
|
904
1019
|
}
|
|
905
1020
|
}
|
|
906
1021
|
else if (options?.editMessageMedia !== undefined) {
|
|
@@ -947,31 +1062,34 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
947
1062
|
};
|
|
948
1063
|
}
|
|
949
1064
|
if (mediaInput) {
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
// We only pass the InputMedia object and the extra form fields.
|
|
953
|
-
const inputMedia = {
|
|
954
|
-
type: mediaInput.type,
|
|
955
|
-
media: mediaInput.media,
|
|
956
|
-
};
|
|
957
|
-
if (options.editMessageMedia.options?.caption) {
|
|
958
|
-
inputMedia.caption = options.editMessageMedia.options.caption;
|
|
959
|
-
}
|
|
960
|
-
if (options.editMessageMedia.options?.parse_mode) {
|
|
961
|
-
inputMedia.parse_mode = options.editMessageMedia.options.parse_mode;
|
|
962
|
-
}
|
|
1065
|
+
const { type: mediaType, media } = mediaInput;
|
|
1066
|
+
const editOptions = options.editMessageMedia.options;
|
|
963
1067
|
const form = {};
|
|
964
|
-
if (
|
|
965
|
-
form.chat_id =
|
|
1068
|
+
if (editOptions?.chat_id !== undefined) {
|
|
1069
|
+
form.chat_id = editOptions.chat_id;
|
|
966
1070
|
}
|
|
967
|
-
if (
|
|
968
|
-
form.message_id =
|
|
1071
|
+
if (editOptions?.message_id !== undefined) {
|
|
1072
|
+
form.message_id = editOptions.message_id;
|
|
969
1073
|
}
|
|
970
|
-
if (
|
|
971
|
-
form.reply_markup =
|
|
1074
|
+
if (editOptions?.reply_markup) {
|
|
1075
|
+
form.reply_markup = editOptions.reply_markup;
|
|
972
1076
|
}
|
|
973
1077
|
if (bot) {
|
|
974
|
-
this.executeSending(() =>
|
|
1078
|
+
this.executeSending(async () => {
|
|
1079
|
+
// a local file is uploaded as multipart part (the library adds the
|
|
1080
|
+
// `attach://` reference), a URL or file_id is passed through as string
|
|
1081
|
+
const inputMedia = {
|
|
1082
|
+
type: mediaType,
|
|
1083
|
+
media: await this.toInputFile(media, options.fileName, DEFAULT_FILE_NAMES[mediaType] || 'media.bin'),
|
|
1084
|
+
};
|
|
1085
|
+
if (editOptions?.caption) {
|
|
1086
|
+
inputMedia.caption = editOptions.caption;
|
|
1087
|
+
}
|
|
1088
|
+
if (editOptions?.parse_mode) {
|
|
1089
|
+
inputMedia.parse_mode = editOptions.parse_mode;
|
|
1090
|
+
}
|
|
1091
|
+
return bot.api.editMessageMedia({ ...form, media: inputMedia });
|
|
1092
|
+
}, options, resolve);
|
|
975
1093
|
}
|
|
976
1094
|
}
|
|
977
1095
|
else {
|
|
@@ -987,13 +1105,16 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
987
1105
|
else if (options?.editMessageCaption !== undefined) {
|
|
988
1106
|
this.log.debug(`Send editMessageCaption to "${name}"`);
|
|
989
1107
|
if (bot) {
|
|
990
|
-
this.executeSending(() => bot.editMessageCaption(
|
|
1108
|
+
this.executeSending(() => bot.api.editMessageCaption({ ...options.editMessageCaption.options, caption: text }), options, resolve);
|
|
991
1109
|
}
|
|
992
1110
|
}
|
|
993
1111
|
else if (options?.deleteMessage !== undefined) {
|
|
994
1112
|
this.log.debug(`Send deleteMessage to "${name}"`);
|
|
995
1113
|
if (bot) {
|
|
996
|
-
this.executeSending(() => bot.deleteMessage(
|
|
1114
|
+
this.executeSending(() => bot.api.deleteMessage({
|
|
1115
|
+
chat_id: options.deleteMessage.options.chat_id,
|
|
1116
|
+
message_id: options.deleteMessage.options.message_id,
|
|
1117
|
+
}), options, resolve);
|
|
997
1118
|
}
|
|
998
1119
|
}
|
|
999
1120
|
else if (options &&
|
|
@@ -1003,13 +1124,25 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1003
1124
|
options.address !== undefined) {
|
|
1004
1125
|
this.log.debug(`Send venue to "${name}": ${options.latitude},${options.longitude}`);
|
|
1005
1126
|
if (bot) {
|
|
1006
|
-
this.executeSending(() => bot.sendVenue(
|
|
1127
|
+
this.executeSending(() => bot.api.sendVenue({
|
|
1128
|
+
...toApiParams(options),
|
|
1129
|
+
chat_id: dest,
|
|
1130
|
+
latitude: parseFloat(String(options.latitude)),
|
|
1131
|
+
longitude: parseFloat(String(options.longitude)),
|
|
1132
|
+
title: options.title,
|
|
1133
|
+
address: options.address,
|
|
1134
|
+
}), options, resolve);
|
|
1007
1135
|
}
|
|
1008
1136
|
}
|
|
1009
1137
|
else if (options?.latitude !== undefined && options.longitude !== undefined) {
|
|
1010
1138
|
this.log.debug(`Send location to "${name}": ${options.latitude},${options.longitude}`);
|
|
1011
1139
|
if (bot) {
|
|
1012
|
-
this.executeSending(() => bot.sendLocation(
|
|
1140
|
+
this.executeSending(() => bot.api.sendLocation({
|
|
1141
|
+
...toApiParams(options),
|
|
1142
|
+
chat_id: dest,
|
|
1143
|
+
latitude: parseFloat(String(options.latitude)),
|
|
1144
|
+
longitude: parseFloat(String(options.longitude)),
|
|
1145
|
+
}), options, resolve);
|
|
1013
1146
|
}
|
|
1014
1147
|
}
|
|
1015
1148
|
else if (options?.type === 'mediagroup') {
|
|
@@ -1017,27 +1150,23 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1017
1150
|
if (bot) {
|
|
1018
1151
|
const { media: fileNames } = options;
|
|
1019
1152
|
if (fileNames instanceof Array) {
|
|
1020
|
-
bot.
|
|
1153
|
+
bot.api
|
|
1154
|
+
.sendChatAction({ chat_id: dest, action: 'upload_photo' })
|
|
1021
1155
|
.then(() => {
|
|
1022
1156
|
if (fileNames.every((name) => (0, node_fs_1.existsSync)(name))) {
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1157
|
+
this.log.info(`Send media group to "${name}": ${fileNames.length} file(s)`);
|
|
1158
|
+
this.executeSending(async () => {
|
|
1159
|
+
// the files are streamed from disk as multipart parts
|
|
1160
|
+
const media = [];
|
|
1161
|
+
for (const element of fileNames) {
|
|
1162
|
+
media.push({ type: 'photo', media: await (0, node_1.fromPath)(element) });
|
|
1027
1163
|
}
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
const size = filesAsArray
|
|
1035
|
-
.map(element => element.media.length)
|
|
1036
|
-
.reduce((acc, val) => acc + val);
|
|
1037
|
-
this.log.info(`Send media group to "${name}": ${size} bytes`);
|
|
1038
|
-
if (filesAsArray.length > 0) {
|
|
1039
|
-
this.executeSending(() => bot.sendMediaGroup(dest, filesAsArray), options, resolve);
|
|
1040
|
-
}
|
|
1164
|
+
return bot.api.sendMediaGroup({
|
|
1165
|
+
...toApiParams(options),
|
|
1166
|
+
chat_id: dest,
|
|
1167
|
+
media,
|
|
1168
|
+
});
|
|
1169
|
+
}, options, resolve);
|
|
1041
1170
|
}
|
|
1042
1171
|
else {
|
|
1043
1172
|
this.log.debug('files must exists');
|
|
@@ -1061,7 +1190,7 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1061
1190
|
else if (text && typeof text === 'string' && actions.includes(text)) {
|
|
1062
1191
|
this.log.debug(`Send action to "${name}": ${text}`);
|
|
1063
1192
|
if (bot) {
|
|
1064
|
-
this.executeSending(() => bot.sendChatAction(dest, text), options, resolve);
|
|
1193
|
+
this.executeSending(() => bot.api.sendChatAction({ chat_id: dest, action: text }), options, resolve);
|
|
1065
1194
|
}
|
|
1066
1195
|
}
|
|
1067
1196
|
else if (text &&
|
|
@@ -1074,7 +1203,11 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1074
1203
|
this.log.debug(`Send sticker to "${name}": ${text.length} bytes`);
|
|
1075
1204
|
}
|
|
1076
1205
|
if (bot) {
|
|
1077
|
-
this.executeSending(() => bot.sendSticker(
|
|
1206
|
+
this.executeSending(async () => bot.api.sendSticker({
|
|
1207
|
+
...toApiParams(options),
|
|
1208
|
+
chat_id: dest,
|
|
1209
|
+
sticker: await this.toInputFile(text, options.fileName, DEFAULT_FILE_NAMES.sticker),
|
|
1210
|
+
}), options, resolve);
|
|
1078
1211
|
}
|
|
1079
1212
|
}
|
|
1080
1213
|
else if (text &&
|
|
@@ -1087,7 +1220,11 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1087
1220
|
this.log.debug(`Send animation to "${name}": ${text.length} bytes`);
|
|
1088
1221
|
}
|
|
1089
1222
|
if (bot) {
|
|
1090
|
-
this.executeSending(() => bot.sendAnimation(
|
|
1223
|
+
this.executeSending(async () => bot.api.sendAnimation({
|
|
1224
|
+
...toApiParams(options),
|
|
1225
|
+
chat_id: dest,
|
|
1226
|
+
animation: await this.toInputFile(text, options.fileName, DEFAULT_FILE_NAMES.animation),
|
|
1227
|
+
}), options, resolve);
|
|
1091
1228
|
}
|
|
1092
1229
|
}
|
|
1093
1230
|
else if (text &&
|
|
@@ -1099,7 +1236,11 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1099
1236
|
this.log.debug(`Send video to "${name}": ${text.length} bytes`);
|
|
1100
1237
|
}
|
|
1101
1238
|
if (bot) {
|
|
1102
|
-
this.executeSending(() => bot.sendVideo(
|
|
1239
|
+
this.executeSending(async () => bot.api.sendVideo({
|
|
1240
|
+
...toApiParams(options),
|
|
1241
|
+
chat_id: dest,
|
|
1242
|
+
video: await this.toInputFile(text, options.fileName, DEFAULT_FILE_NAMES.video),
|
|
1243
|
+
}), options, resolve);
|
|
1103
1244
|
}
|
|
1104
1245
|
}
|
|
1105
1246
|
else if (text &&
|
|
@@ -1107,7 +1248,11 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1107
1248
|
options?.type === 'document')) {
|
|
1108
1249
|
this.log.debug(`Send document to "${name}": ${typeof text === 'string' ? text : text.length}`);
|
|
1109
1250
|
if (bot) {
|
|
1110
|
-
this.executeSending(() => bot.sendDocument(
|
|
1251
|
+
this.executeSending(async () => bot.api.sendDocument({
|
|
1252
|
+
...toApiParams(options),
|
|
1253
|
+
chat_id: dest,
|
|
1254
|
+
document: await this.toInputFile(text, options.fileName, DEFAULT_FILE_NAMES.document),
|
|
1255
|
+
}), options, resolve);
|
|
1111
1256
|
}
|
|
1112
1257
|
}
|
|
1113
1258
|
else if (text &&
|
|
@@ -1115,7 +1260,11 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1115
1260
|
(options && options?.type === 'audio'))) {
|
|
1116
1261
|
this.log.debug(`Send audio to "${name}": ${typeof text === 'string' ? text : text.length}`);
|
|
1117
1262
|
if (bot) {
|
|
1118
|
-
this.executeSending(() => bot.sendAudio(
|
|
1263
|
+
this.executeSending(async () => bot.api.sendAudio({
|
|
1264
|
+
...toApiParams(options),
|
|
1265
|
+
chat_id: dest,
|
|
1266
|
+
audio: await this.toInputFile(text, options.fileName, DEFAULT_FILE_NAMES.audio),
|
|
1267
|
+
}), options, resolve);
|
|
1119
1268
|
}
|
|
1120
1269
|
}
|
|
1121
1270
|
else if (text &&
|
|
@@ -1126,7 +1275,11 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1126
1275
|
) {
|
|
1127
1276
|
this.log.debug(`Send photo to "${name}": ${typeof text === 'string' ? text : text.length}`);
|
|
1128
1277
|
if (bot) {
|
|
1129
|
-
this.executeSending(() => bot.sendPhoto(
|
|
1278
|
+
this.executeSending(async () => bot.api.sendPhoto({
|
|
1279
|
+
...toApiParams(options),
|
|
1280
|
+
chat_id: dest,
|
|
1281
|
+
photo: await this.toInputFile(text, options.fileName, DEFAULT_FILE_NAMES.photo),
|
|
1282
|
+
}), options, resolve);
|
|
1130
1283
|
}
|
|
1131
1284
|
}
|
|
1132
1285
|
else if (options?.answerCallbackQuery !== undefined) {
|
|
@@ -1137,7 +1290,8 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1137
1290
|
if (bot && this.callbackQueryId[String(options.chatId)]) {
|
|
1138
1291
|
const originalChatId = this.callbackQueryId[String(options.chatId)].id;
|
|
1139
1292
|
delete this.callbackQueryId[String(options.chatId)];
|
|
1140
|
-
this.executeSending(() => bot.answerCallbackQuery(
|
|
1293
|
+
this.executeSending(() => bot.api.answerCallbackQuery({
|
|
1294
|
+
callback_query_id: originalChatId,
|
|
1141
1295
|
text: options.answerCallbackQuery.text,
|
|
1142
1296
|
show_alert: options.answerCallbackQuery.showAlert,
|
|
1143
1297
|
}), options, resolve);
|
|
@@ -1161,7 +1315,11 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1161
1315
|
}
|
|
1162
1316
|
}
|
|
1163
1317
|
if (bot) {
|
|
1164
|
-
this.executeSending(() => bot.sendMessage(
|
|
1318
|
+
this.executeSending(() => bot.api.sendMessage({
|
|
1319
|
+
...toApiParams(options),
|
|
1320
|
+
chat_id: dest,
|
|
1321
|
+
text: text || '',
|
|
1322
|
+
}), options, resolve);
|
|
1165
1323
|
}
|
|
1166
1324
|
}
|
|
1167
1325
|
});
|
|
@@ -1349,54 +1507,39 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1349
1507
|
}
|
|
1350
1508
|
saveFile(fileID, fileName, callback) {
|
|
1351
1509
|
this.log.debug(`Saving media file ${fileID} to ${fileName} (location = ${this.config.saveFilesTo})`);
|
|
1352
|
-
this.bot.
|
|
1353
|
-
.then(
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
});
|
|
1384
|
-
})
|
|
1385
|
-
.catch(err => this.log.error(err));
|
|
1386
|
-
}
|
|
1387
|
-
catch (err) {
|
|
1388
|
-
return callback({ error: `Error: ${err}` });
|
|
1389
|
-
}
|
|
1390
|
-
}
|
|
1391
|
-
});
|
|
1392
|
-
res.on('error', err => callback({ error: `Error: ${err}` }));
|
|
1393
|
-
}
|
|
1394
|
-
else {
|
|
1395
|
-
callback({ error: 'Error: statusCode !== 200' });
|
|
1396
|
-
}
|
|
1397
|
-
});
|
|
1510
|
+
this.bot.api.getFile({ file_id: fileID })
|
|
1511
|
+
.then(async (file) => {
|
|
1512
|
+
if (!file.file_path) {
|
|
1513
|
+
throw new Error('telegram did not return a file path');
|
|
1514
|
+
}
|
|
1515
|
+
// the library offers no download helper, so build the file URL ourselves
|
|
1516
|
+
const url = `${this.config.baseApiUrl}/file/bot${this.config.token}/${file.file_path}`;
|
|
1517
|
+
this.log.debug(`Download media file: ${url.replace(this.config.token, '<token>')}`);
|
|
1518
|
+
const response = await this.fetchImpl(url);
|
|
1519
|
+
if (!response.ok) {
|
|
1520
|
+
throw new Error(`statusCode ${response.status}`);
|
|
1521
|
+
}
|
|
1522
|
+
const content = Buffer.from(await response.arrayBuffer());
|
|
1523
|
+
if (this.config.saveFilesTo == 'filesystem') {
|
|
1524
|
+
const fileLocation = (0, node_path_1.join)(this.tmpDirName, fileName);
|
|
1525
|
+
(0, node_fs_1.writeFileSync)(fileLocation, content);
|
|
1526
|
+
callback({
|
|
1527
|
+
info: `media file has been saved to "${this.config.saveFilesTo}": ${fileLocation}`,
|
|
1528
|
+
location: this.config.saveFilesTo,
|
|
1529
|
+
path: fileLocation,
|
|
1530
|
+
});
|
|
1531
|
+
}
|
|
1532
|
+
else if (this.config.saveFilesTo == 'iobroker') {
|
|
1533
|
+
const fileLocation = (0, node_path_1.join)(this.tmpDirName, fileName); // TODO: check new urn format https://github.com/ioBroker/ioBroker.js-controller/issues/2710
|
|
1534
|
+
await this.writeFileAsync(this.namespace, fileName, content);
|
|
1535
|
+
callback({
|
|
1536
|
+
info: `media file has been saved to "${this.config.saveFilesTo}": ${fileLocation}`,
|
|
1537
|
+
location: this.config.saveFilesTo,
|
|
1538
|
+
path: fileLocation,
|
|
1539
|
+
});
|
|
1540
|
+
}
|
|
1398
1541
|
})
|
|
1399
|
-
.catch(err => callback({ error: `Error
|
|
1542
|
+
.catch(err => callback({ error: `Error: ${err}` }));
|
|
1400
1543
|
}
|
|
1401
1544
|
getMessage(msg) {
|
|
1402
1545
|
const date = new Date().toISOString().replace(/T/, '_').replace(/\..+/, '').replace(/:/g, '-');
|
|
@@ -1404,7 +1547,7 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1404
1547
|
// Remember the chat/group so other adapters can pick it by id (issue #312).
|
|
1405
1548
|
this.storeChat(msg.chat);
|
|
1406
1549
|
// Media messages (photo, document, voice, ...) do not contain `msg.text`, so they are not handled
|
|
1407
|
-
// by `processTelegramText` (which
|
|
1550
|
+
// by `processTelegramText` (which only runs for text messages). As a result the request metadata
|
|
1408
1551
|
// (chat id, message id, user id) would stay empty for received files. Populate it here so the
|
|
1409
1552
|
// sender can be identified. See https://github.com/iobroker-community-adapters/ioBroker.telegram/issues/1043
|
|
1410
1553
|
if (msg.voice ||
|
|
@@ -1434,6 +1577,15 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1434
1577
|
val: `${location.latitude};${location.longitude}`,
|
|
1435
1578
|
ack: true,
|
|
1436
1579
|
});
|
|
1580
|
+
// `live_period` and `heading` are only present while a live location is active. When the sharing
|
|
1581
|
+
// is stopped (or expires) Telegram sends a final `edited_message` without them, so
|
|
1582
|
+
// `requestLocationLive` drops back to false and the heading is cleared at that point.
|
|
1583
|
+
this.setStateSafe('communicate.requestLocationLive', { val: !!location.live_period, ack: true });
|
|
1584
|
+
this.setStateSafe('communicate.requestLocationHeading', { val: location.heading ?? null, ack: true });
|
|
1585
|
+
this.setStateSafe('communicate.requestLocationAccuracy', {
|
|
1586
|
+
val: location.horizontal_accuracy ?? null,
|
|
1587
|
+
ack: true,
|
|
1588
|
+
});
|
|
1437
1589
|
}
|
|
1438
1590
|
if (msg.voice) {
|
|
1439
1591
|
try {
|
|
@@ -1640,10 +1792,11 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1640
1792
|
// old, telegram answers "message to edit not found". Without a catch this
|
|
1641
1793
|
// rejection is unhandled and terminates the whole adapter. See
|
|
1642
1794
|
// https://github.com/iobroker-community-adapters/ioBroker.telegram/issues/879
|
|
1643
|
-
this.bot
|
|
1644
|
-
.editMessageReplyMarkup({
|
|
1795
|
+
this.bot.api
|
|
1796
|
+
.editMessageReplyMarkup({
|
|
1645
1797
|
chat_id: q.chatId,
|
|
1646
1798
|
message_id: q.msgId,
|
|
1799
|
+
reply_markup: { inline_keyboard: [] },
|
|
1647
1800
|
})
|
|
1648
1801
|
.then(() => this.log.debug(`removed inline_keyboard for msg ${q.msgId}: ${JSON.stringify(q)}`))
|
|
1649
1802
|
.catch(error => this.log.warn(`Cannot remove inline_keyboard for msg ${q.msgId}: ${error}`));
|
|
@@ -1885,7 +2038,9 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1885
2038
|
keyboard.push([`${cmd.alias} ?`]);
|
|
1886
2039
|
}
|
|
1887
2040
|
});
|
|
1888
|
-
this.bot.sendMessage(
|
|
2041
|
+
this.bot.api.sendMessage({
|
|
2042
|
+
chat_id: chatId,
|
|
2043
|
+
text: adapter_core_1.I18n.translate('Select option'),
|
|
1889
2044
|
reply_markup: {
|
|
1890
2045
|
keyboard: keyboard.map(row => row.map(text => ({ text }))),
|
|
1891
2046
|
resize_keyboard: true,
|
|
@@ -1927,10 +2082,11 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
1927
2082
|
// telegram answers "message to edit not found". Without a catch this rejection is
|
|
1928
2083
|
// unhandled and terminates the whole adapter. See
|
|
1929
2084
|
// https://github.com/iobroker-community-adapters/ioBroker.telegram/issues/879
|
|
1930
|
-
this.bot
|
|
1931
|
-
.editMessageReplyMarkup({
|
|
2085
|
+
this.bot.api
|
|
2086
|
+
.editMessageReplyMarkup({
|
|
1932
2087
|
chat_id: answeredChatId,
|
|
1933
2088
|
message_id: answeredMsgId,
|
|
2089
|
+
reply_markup: { inline_keyboard: [] },
|
|
1934
2090
|
})
|
|
1935
2091
|
.then(() => this.log.debug(`removed inline_keyboard for msg ${answeredMsgId}`))
|
|
1936
2092
|
.catch(error => this.log.warn(`Cannot remove inline_keyboard for msg ${answeredMsgId}: ${error}`));
|
|
@@ -2009,8 +2165,8 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2009
2165
|
// ignore all messages older than 30 seconds + polling interval
|
|
2010
2166
|
if (now - msg.date * 1000 > pollingInterval + 30000) {
|
|
2011
2167
|
this.log.warn(`Message from ${from.first_name} ignored, because too old: (${pollingInterval + 30000}) ${msgText}`);
|
|
2012
|
-
return bot
|
|
2013
|
-
.sendMessage(from.id, adapter_core_1.I18n.translate('Message ignored: ') + msgText)
|
|
2168
|
+
return bot.api
|
|
2169
|
+
.sendMessage({ chat_id: from.id, text: adapter_core_1.I18n.translate('Message ignored: ') + msgText })
|
|
2014
2170
|
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2015
2171
|
}
|
|
2016
2172
|
msgText = (msgText || '').trim();
|
|
@@ -2020,8 +2176,11 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2020
2176
|
msgText = msgText.substring(0, pos);
|
|
2021
2177
|
}
|
|
2022
2178
|
if (msgText === '/password' && !this.config.doNotAcceptNewUser) {
|
|
2023
|
-
return bot
|
|
2024
|
-
.sendMessage(
|
|
2179
|
+
return bot.api
|
|
2180
|
+
.sendMessage({
|
|
2181
|
+
chat_id: from.id,
|
|
2182
|
+
text: adapter_core_1.I18n.translate('Please enter password in form "/password phrase"'),
|
|
2183
|
+
})
|
|
2025
2184
|
.catch(error => this.log.error(`send Message Error:${error}`));
|
|
2026
2185
|
}
|
|
2027
2186
|
if (this.config.password && !this.config.doNotAcceptNewUsers) {
|
|
@@ -2031,8 +2190,11 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2031
2190
|
if (m) {
|
|
2032
2191
|
this.garbageCollector();
|
|
2033
2192
|
if (this.protection[user] && this.protection[user].length >= 5) {
|
|
2034
|
-
return bot
|
|
2035
|
-
.sendMessage(
|
|
2193
|
+
return bot.api
|
|
2194
|
+
.sendMessage({
|
|
2195
|
+
chat_id: from.id,
|
|
2196
|
+
text: `${adapter_core_1.I18n.translate('Too many attempts. Blocked for')} ${Math.round((now - this.protection[user][this.protection[user].length - 1]) / 1000)} ${adapter_core_1.I18n.translate('seconds')}`,
|
|
2197
|
+
})
|
|
2036
2198
|
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2037
2199
|
}
|
|
2038
2200
|
if (this.config.password === m[1]) {
|
|
@@ -2044,18 +2206,20 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2044
2206
|
this.log.warn(`User ${from.first_name} hast not set an username in the Telegram App!!`);
|
|
2045
2207
|
}
|
|
2046
2208
|
// delete the message that contains the password, so the passphrase is not left in the chat
|
|
2047
|
-
await bot
|
|
2048
|
-
.deleteMessage(msg.chat.id, msg.message_id)
|
|
2209
|
+
await bot.api
|
|
2210
|
+
.deleteMessage({ chat_id: msg.chat.id, message_id: msg.message_id })
|
|
2049
2211
|
.catch(error => this.log.warn(`Cannot delete password message: ${error}`));
|
|
2050
|
-
return bot
|
|
2051
|
-
.sendMessage(from.id, adapter_core_1.I18n.translate('Welcome ') + user)
|
|
2212
|
+
return bot.api
|
|
2213
|
+
.sendMessage({ chat_id: from.id, text: adapter_core_1.I18n.translate('Welcome ') + user })
|
|
2052
2214
|
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2053
2215
|
}
|
|
2054
2216
|
this.protection[user] ||= [];
|
|
2055
2217
|
this.protection[user].push(Date.now());
|
|
2056
2218
|
this.gcInterval ||= this.setInterval(() => this.garbageCollector(), 60000);
|
|
2057
2219
|
this.log.warn(`Got invalid password from ${user}: ${m[1]}`);
|
|
2058
|
-
bot.
|
|
2220
|
+
bot.api
|
|
2221
|
+
.sendMessage({ chat_id: from.id, text: adapter_core_1.I18n.translate('Invalid password') })
|
|
2222
|
+
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2059
2223
|
if (this.storedUsers[from.id]) {
|
|
2060
2224
|
delete this.storedUsers[from.id];
|
|
2061
2225
|
}
|
|
@@ -2064,15 +2228,18 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2064
2228
|
// todo support commands: instances, running, restart
|
|
2065
2229
|
// If a user is not in the trusted list
|
|
2066
2230
|
if ((this.config.password || this.config.doNotAcceptNewUsers) && !this.storedUsers[from.id]) {
|
|
2067
|
-
return bot
|
|
2068
|
-
.sendMessage(
|
|
2069
|
-
|
|
2070
|
-
:
|
|
2231
|
+
return bot.api
|
|
2232
|
+
.sendMessage({
|
|
2233
|
+
chat_id: from.id,
|
|
2234
|
+
text: adapter_core_1.I18n.translate(this.config.doNotAcceptNewUsers
|
|
2235
|
+
? 'User is not in the list'
|
|
2236
|
+
: 'Please enter password in form "/password phrase"'),
|
|
2237
|
+
})
|
|
2071
2238
|
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2072
2239
|
}
|
|
2073
2240
|
if (msgText === '/help') {
|
|
2074
|
-
return bot
|
|
2075
|
-
.sendMessage(from.id, this.getListOfCommands())
|
|
2241
|
+
return bot.api
|
|
2242
|
+
.sendMessage({ chat_id: from.id, text: this.getListOfCommands() })
|
|
2076
2243
|
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2077
2244
|
}
|
|
2078
2245
|
this.isAnswerForQuestion(msg);
|
|
@@ -2099,7 +2266,9 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2099
2266
|
found = true;
|
|
2100
2267
|
if (sValue === '?') {
|
|
2101
2268
|
const state = await this.getForeignStateAsync(id);
|
|
2102
|
-
bot.
|
|
2269
|
+
bot.api
|
|
2270
|
+
.sendMessage({ chat_id: msg.chat.id, text: this.getStatus(id, state) })
|
|
2271
|
+
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2103
2272
|
}
|
|
2104
2273
|
else {
|
|
2105
2274
|
let value;
|
|
@@ -2121,15 +2290,20 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2121
2290
|
sValue = sValue.replace('%', '').trim();
|
|
2122
2291
|
value = parseFloat(sValue);
|
|
2123
2292
|
if (sValue !== value.toString()) {
|
|
2124
|
-
bot.
|
|
2293
|
+
bot.api
|
|
2294
|
+
.sendMessage({
|
|
2295
|
+
chat_id: msg.chat.id,
|
|
2296
|
+
text: adapter_core_1.I18n.translate('Invalid number %s', sValue),
|
|
2297
|
+
})
|
|
2298
|
+
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2125
2299
|
continue;
|
|
2126
2300
|
}
|
|
2127
2301
|
}
|
|
2128
2302
|
else {
|
|
2129
2303
|
value = sValue;
|
|
2130
2304
|
}
|
|
2131
|
-
this.setForeignStateAsync(id, value, false, () => bot
|
|
2132
|
-
.sendMessage(msg.chat.id, adapter_core_1.I18n.translate('Done'))
|
|
2305
|
+
this.setForeignStateAsync(id, value, false, () => bot.api
|
|
2306
|
+
.sendMessage({ chat_id: msg.chat.id, text: adapter_core_1.I18n.translate('Done') })
|
|
2133
2307
|
.catch(error => this.log.error(`send Message Error: ${error}`)))?.catch(error => this.log.error(`setForeignState Error: ${error}`));
|
|
2134
2308
|
}
|
|
2135
2309
|
}
|
|
@@ -2161,7 +2335,9 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2161
2335
|
state = await this.getForeignStateAsync(id1);
|
|
2162
2336
|
}
|
|
2163
2337
|
catch (err) {
|
|
2164
|
-
bot.
|
|
2338
|
+
bot.api
|
|
2339
|
+
.sendMessage({ chat_id: from.id, text: err.message })
|
|
2340
|
+
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2165
2341
|
}
|
|
2166
2342
|
if (memoryLeak1) {
|
|
2167
2343
|
this.clearTimeout(memoryLeak1);
|
|
@@ -2173,18 +2349,25 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2173
2349
|
try {
|
|
2174
2350
|
await this.setForeignStateAsync(id1, val1, false);
|
|
2175
2351
|
if (currentMsg) {
|
|
2176
|
-
bot.
|
|
2352
|
+
bot.api
|
|
2353
|
+
.sendMessage({ chat_id: from.id, text: adapter_core_1.I18n.translate('Done') })
|
|
2354
|
+
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2177
2355
|
}
|
|
2178
2356
|
}
|
|
2179
2357
|
catch (err) {
|
|
2180
2358
|
if (currentMsg) {
|
|
2181
|
-
bot.
|
|
2359
|
+
bot.api
|
|
2360
|
+
.sendMessage({ chat_id: from.id, text: err.message })
|
|
2361
|
+
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2182
2362
|
}
|
|
2183
2363
|
}
|
|
2184
2364
|
}
|
|
2185
2365
|
else {
|
|
2186
2366
|
try {
|
|
2187
|
-
await bot.sendMessage(
|
|
2367
|
+
await bot.api.sendMessage({
|
|
2368
|
+
chat_id: from.id,
|
|
2369
|
+
text: adapter_core_1.I18n.translate('ID "%s" not found.', id1),
|
|
2370
|
+
});
|
|
2188
2371
|
}
|
|
2189
2372
|
catch (err) {
|
|
2190
2373
|
this.log.error(`send Message Error: ${err}`);
|
|
@@ -2210,7 +2393,9 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2210
2393
|
}
|
|
2211
2394
|
catch (err) {
|
|
2212
2395
|
if (currentMsg) {
|
|
2213
|
-
bot.
|
|
2396
|
+
bot.api
|
|
2397
|
+
.sendMessage({ chat_id: from.id, text: err.message })
|
|
2398
|
+
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2214
2399
|
}
|
|
2215
2400
|
}
|
|
2216
2401
|
if (memoryLeak2) {
|
|
@@ -2221,7 +2406,7 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2221
2406
|
if (currentMsg) {
|
|
2222
2407
|
if (state) {
|
|
2223
2408
|
try {
|
|
2224
|
-
await bot.sendMessage(from.id, String(state.val));
|
|
2409
|
+
await bot.api.sendMessage({ chat_id: from.id, text: String(state.val) });
|
|
2225
2410
|
}
|
|
2226
2411
|
catch (error) {
|
|
2227
2412
|
this.log.error(`send Message Error: ${error}`);
|
|
@@ -2229,7 +2414,10 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2229
2414
|
}
|
|
2230
2415
|
else {
|
|
2231
2416
|
try {
|
|
2232
|
-
await bot.sendMessage(
|
|
2417
|
+
await bot.api.sendMessage({
|
|
2418
|
+
chat_id: from.id,
|
|
2419
|
+
text: adapter_core_1.I18n.translate('ID "%s" not found.', id2),
|
|
2420
|
+
});
|
|
2233
2421
|
}
|
|
2234
2422
|
catch (error) {
|
|
2235
2423
|
this.log.error(`send Message Error: ${error}`);
|
|
@@ -2267,7 +2455,9 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2267
2455
|
}
|
|
2268
2456
|
}
|
|
2269
2457
|
this.log.debug(`Send response: ${text}`);
|
|
2270
|
-
bot.
|
|
2458
|
+
bot.api
|
|
2459
|
+
.sendMessage({ ...options, chat_id: response.id, text })
|
|
2460
|
+
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2271
2461
|
}
|
|
2272
2462
|
})
|
|
2273
2463
|
.catch(err => this.log.error(`Cannot send message to ${this.config.text2command}: ${err}`));
|
|
@@ -2290,7 +2480,9 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2290
2480
|
if (text) {
|
|
2291
2481
|
this.log.debug(`Assistant response: ${text}`);
|
|
2292
2482
|
const options = msg.is_topic_message ? { message_thread_id: msg.message_thread_id } : undefined;
|
|
2293
|
-
bot.
|
|
2483
|
+
bot.api
|
|
2484
|
+
.sendMessage({ ...options, chat_id: msg.chat.id, text })
|
|
2485
|
+
.catch(error => this.log.error(`send Message Error: ${error}`));
|
|
2294
2486
|
}
|
|
2295
2487
|
})
|
|
2296
2488
|
.catch(err => this.log.error(`Cannot send message to ${this.config.assistantInstance}: ${err}`));
|
|
@@ -2311,26 +2503,17 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2311
2503
|
if (this.bot) {
|
|
2312
2504
|
const bot = this.bot;
|
|
2313
2505
|
if (!this.isServer) {
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
this.log.debug('bot polling OK');
|
|
2317
|
-
}
|
|
2318
|
-
else {
|
|
2319
|
-
this.log.debug('bot restarting...');
|
|
2320
|
-
bot.stopPolling().then(() => {
|
|
2321
|
-
this.log.debug('Start Polling');
|
|
2322
|
-
bot.startPolling().catch(error => this.log.error(`Error start polling: ${error}`));
|
|
2323
|
-
}, error => {
|
|
2324
|
-
this.log.error(`Error stop polling: ${error}`);
|
|
2325
|
-
});
|
|
2326
|
-
}
|
|
2506
|
+
if (bot.isRunning()) {
|
|
2507
|
+
this.log.debug('bot polling OK');
|
|
2327
2508
|
}
|
|
2328
|
-
|
|
2329
|
-
|
|
2509
|
+
else {
|
|
2510
|
+
this.log.debug('bot restarting...');
|
|
2511
|
+
this.startPolling();
|
|
2330
2512
|
}
|
|
2331
2513
|
}
|
|
2332
2514
|
// Check connection
|
|
2333
|
-
bot.
|
|
2515
|
+
bot.api
|
|
2516
|
+
.getMe()
|
|
2334
2517
|
.then(data => {
|
|
2335
2518
|
this.log.debug(`getMe (reconnect): ${JSON.stringify(data)}`);
|
|
2336
2519
|
this.connectionState(true);
|
|
@@ -2338,39 +2521,43 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2338
2521
|
.catch(error => this.log.error(`getMe (reconnect) Error:${error}`));
|
|
2339
2522
|
}
|
|
2340
2523
|
else {
|
|
2524
|
+
// Route every telegram request (API calls and file downloads) through the configured proxy
|
|
2525
|
+
try {
|
|
2526
|
+
const proxy = (0, proxy_1.createProxyDispatcher)(this.config);
|
|
2527
|
+
if (proxy) {
|
|
2528
|
+
this.fetchImpl = (0, proxy_1.createProxiedFetch)(proxy.dispatcher);
|
|
2529
|
+
this.log.info(`Connecting to telegram via ${proxy.description}`);
|
|
2530
|
+
}
|
|
2531
|
+
}
|
|
2532
|
+
catch (err) {
|
|
2533
|
+
this.log.error(`Proxy is enabled but cannot be used: ${err instanceof Error ? err.message : String(err)} - connecting directly`);
|
|
2534
|
+
}
|
|
2535
|
+
const bot = new node_telegram_bot_api_1.Bot(this.config.token, { apiRoot: this.config.baseApiUrl, fetch: this.fetchImpl });
|
|
2536
|
+
this.bot = bot;
|
|
2537
|
+
// Route errors thrown by the update handlers to the ioBroker log (the library's default boundary
|
|
2538
|
+
// prints them to the console). The update is consumed either way, so polling keeps running.
|
|
2539
|
+
bot.catch((err, ctx) => this.log.error(`Cannot process update ${ctx.update.update_id}: ${err instanceof Error ? err.stack || err.message : String(err)}`));
|
|
2540
|
+
this.registerUpdateHandlers(bot);
|
|
2341
2541
|
if (this.isServer) {
|
|
2342
|
-
// Setup server way
|
|
2343
|
-
const serverOptions = {
|
|
2344
|
-
polling: false,
|
|
2345
|
-
filepath: true,
|
|
2346
|
-
baseApiUrl: this.config.baseApiUrl,
|
|
2347
|
-
};
|
|
2348
|
-
this.bot = new node_telegram_bot_api_1.default(this.config.token, serverOptions);
|
|
2542
|
+
// Setup server way: telegram pushes the updates to our own https server (see handleWebHook)
|
|
2349
2543
|
if (this.config.url[this.config.url.length - 1] === '/') {
|
|
2350
2544
|
this.config.url = this.config.url.substring(0, this.config.url.length - 1);
|
|
2351
2545
|
}
|
|
2352
|
-
|
|
2353
|
-
.setWebhook(`${this.config.url}/${this.config.token}`)
|
|
2546
|
+
bot.api
|
|
2547
|
+
.setWebhook({ url: `${this.config.url}/${this.config.token}` })
|
|
2354
2548
|
.catch(error => this.log.error(`setWebhook Error: ${error}`));
|
|
2355
2549
|
}
|
|
2356
2550
|
else {
|
|
2357
|
-
// Setup polling way
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
}
|
|
2362
|
-
|
|
2363
|
-
baseApiUrl: this.config.baseApiUrl,
|
|
2364
|
-
};
|
|
2365
|
-
this.log.debug(`Start polling with: ${pollingOptions.polling.interval}(${typeof pollingOptions.polling.interval}) ms interval`);
|
|
2366
|
-
this.bot = new node_telegram_bot_api_1.default(this.config.token, pollingOptions);
|
|
2367
|
-
this.bot.setWebhook('').catch(error => {
|
|
2368
|
-
this.log.error(`setWebhook Error:${error}`);
|
|
2369
|
-
});
|
|
2551
|
+
// Setup polling way. A webhook left over from a previous "server" configuration must be removed
|
|
2552
|
+
// first: getUpdates is rejected with 409 while a webhook is active, which would end the loop.
|
|
2553
|
+
bot.api
|
|
2554
|
+
.deleteWebhook()
|
|
2555
|
+
.catch(error => this.log.error(`deleteWebhook Error: ${error}`))
|
|
2556
|
+
.finally(() => this.startPolling());
|
|
2370
2557
|
}
|
|
2371
|
-
const bot = this.bot;
|
|
2372
2558
|
// Check connection
|
|
2373
|
-
bot.
|
|
2559
|
+
bot.api
|
|
2560
|
+
.getMe()
|
|
2374
2561
|
.then(data => {
|
|
2375
2562
|
this.log.debug(`getMe: ${JSON.stringify(data)}`);
|
|
2376
2563
|
this.connectionState(true);
|
|
@@ -2390,102 +2577,138 @@ class Telegram extends adapter_core_1.Adapter {
|
|
|
2390
2577
|
this.log.error(`getMe Error:${error}`);
|
|
2391
2578
|
this.connectionState(false);
|
|
2392
2579
|
});
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
bot.on('edited_message', msg => {
|
|
2413
|
-
// Only location updates are relevant here. Any other edit (typo fix in a text, changed caption
|
|
2414
|
-
// of a photo/document) would otherwise re-run getMessage() and e.g. download the media file a
|
|
2415
|
-
// second time and overwrite the request* states with the data of an old message.
|
|
2416
|
-
if (!msg.location) {
|
|
2417
|
-
return;
|
|
2418
|
-
}
|
|
2419
|
-
this.connectionState(true);
|
|
2420
|
-
if (this.config.storeRawRequest) {
|
|
2421
|
-
this.setStateSafe('communicate.requestRaw', { val: JSON.stringify(msg, null, 2), ack: true });
|
|
2422
|
-
}
|
|
2423
|
-
this.getMessage(msg);
|
|
2424
|
-
});
|
|
2425
|
-
// Channel posts (in a channel where the bot is an admin) are delivered as a separate event, not
|
|
2426
|
-
// as `message`, so they were ignored before. They are anonymous (no `msg.from`), therefore the
|
|
2427
|
-
// auth/command pipeline cannot run; instead expose the post text and metadata so scripts can
|
|
2428
|
-
// react. See https://github.com/iobroker-community-adapters/ioBroker.telegram/issues/289
|
|
2429
|
-
bot.on('channel_post', msg => {
|
|
2430
|
-
this.connectionState(true);
|
|
2431
|
-
if (this.config.storeRawRequest) {
|
|
2432
|
-
this.setStateSafe('communicate.requestRaw', { val: JSON.stringify(msg, null, 2), ack: true });
|
|
2433
|
-
}
|
|
2434
|
-
// stores the channel in communicate.chats and handles/saves any attached media
|
|
2435
|
-
this.getMessage(msg);
|
|
2436
|
-
const text = msg.text ?? msg.caption;
|
|
2437
|
-
if (text !== undefined) {
|
|
2438
|
-
const name = msg.chat.title || String(msg.chat.id);
|
|
2439
|
-
this.setStateSafe('communicate.requestChatId', { val: msg.chat.id, ack: true });
|
|
2440
|
-
this.setStateSafe('communicate.requestMessageId', { val: msg.message_id, ack: true });
|
|
2441
|
-
this.setStateSafe('communicate.requestMessageThreadId', {
|
|
2442
|
-
val: msg.is_topic_message ? msg.message_thread_id : 0,
|
|
2443
|
-
ack: true,
|
|
2444
|
-
});
|
|
2445
|
-
this.setStateSafe('communicate.request', { val: `[${name}]${text}`, ack: true });
|
|
2446
|
-
}
|
|
2447
|
-
});
|
|
2448
|
-
// callback InlineKeyboardButton
|
|
2449
|
-
bot.on('callback_query', (callbackQuery) => {
|
|
2450
|
-
this.connectionState(true);
|
|
2451
|
-
// write received answer into variable
|
|
2452
|
-
this.log.debug(`callback_query: ${JSON.stringify(callbackQuery)}`);
|
|
2453
|
-
this.callbackQueryId[callbackQuery.from.id] = { id: callbackQuery.id, ts: Date.now() };
|
|
2454
|
-
if (this.config.storeRawRequest) {
|
|
2455
|
-
this.setStateSafe('communicate.requestRaw', { val: JSON.stringify(callbackQuery), ack: true });
|
|
2456
|
-
}
|
|
2457
|
-
this.setStateSafe('communicate.requestMessageId', {
|
|
2458
|
-
val: callbackQuery.message.message_id,
|
|
2459
|
-
ack: true,
|
|
2460
|
-
});
|
|
2461
|
-
this.setStateSafe('communicate.requestChatId', { val: callbackQuery.message.chat.id, ack: true });
|
|
2462
|
-
this.setStateSafe('communicate.request', {
|
|
2463
|
-
val: `[${!this.config.useUsername
|
|
2464
|
-
? callbackQuery.from.first_name
|
|
2465
|
-
: !callbackQuery.from.username
|
|
2466
|
-
? callbackQuery.from.first_name
|
|
2467
|
-
: callbackQuery.from.username}]${callbackQuery.data}`,
|
|
2468
|
-
ack: true,
|
|
2469
|
-
});
|
|
2470
|
-
this.isAnswerForQuestion(callbackQuery);
|
|
2471
|
-
});
|
|
2472
|
-
bot.on('polling_error', (error) => {
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2582
|
+
/**
|
|
2583
|
+
* Start the long-poll loop (polling mode only). Transient errors (network, timeout, 429, 5xx) are retried by
|
|
2584
|
+
* the library itself and only mirrored into `info.connection`. A fatal error (e.g. 401 invalid token, or 409
|
|
2585
|
+
* because another bot instance polls with the same token) ends the loop; it is restarted after a delay.
|
|
2586
|
+
*/
|
|
2587
|
+
startPolling() {
|
|
2588
|
+
const bot = this.bot;
|
|
2589
|
+
if (!bot || this.isServer || bot.isRunning()) {
|
|
2590
|
+
return;
|
|
2591
|
+
}
|
|
2592
|
+
if (this.pollingRestartTimer) {
|
|
2593
|
+
this.clearTimeout(this.pollingRestartTimer);
|
|
2594
|
+
this.pollingRestartTimer = undefined;
|
|
2595
|
+
}
|
|
2596
|
+
this.log.debug('Start polling');
|
|
2597
|
+
bot.startPolling(undefined, {
|
|
2598
|
+
onError: error => {
|
|
2473
2599
|
if (this.isConnected) {
|
|
2474
|
-
this.log.warn(`polling_error: ${error
|
|
2600
|
+
this.log.warn(`polling_error: ${error instanceof Error ? error.message.replace(/<[^>]+>/g, '') : String(error)}`);
|
|
2475
2601
|
this.connectionState(false);
|
|
2476
2602
|
}
|
|
2477
|
-
}
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2603
|
+
},
|
|
2604
|
+
})
|
|
2605
|
+
.then(() => this.log.debug('Polling stopped'))
|
|
2606
|
+
.catch(error => {
|
|
2607
|
+
this.log.error(`Polling stopped: ${error}. Restart in ${Telegram.POLLING_RESTART_MS / 1000} seconds`);
|
|
2608
|
+
this.pollingRestartTimer = this.setTimeout(() => {
|
|
2609
|
+
this.pollingRestartTimer = undefined;
|
|
2610
|
+
this.startPolling();
|
|
2611
|
+
}, Telegram.POLLING_RESTART_MS);
|
|
2612
|
+
});
|
|
2613
|
+
}
|
|
2614
|
+
/**
|
|
2615
|
+
* Register the handlers for the incoming update types.
|
|
2616
|
+
*
|
|
2617
|
+
* @param bot the bot instance
|
|
2618
|
+
*/
|
|
2619
|
+
registerUpdateHandlers(bot) {
|
|
2620
|
+
bot.on('message', ctx => {
|
|
2621
|
+
const msg = ctx.message;
|
|
2622
|
+
if (!msg) {
|
|
2623
|
+
return;
|
|
2624
|
+
}
|
|
2625
|
+
this.connectionState(true);
|
|
2626
|
+
if (this.config.storeRawRequest) {
|
|
2627
|
+
this.setStateSafe('communicate.requestRaw', { val: JSON.stringify(msg, null, 2), ack: true });
|
|
2628
|
+
}
|
|
2629
|
+
this.getMessage(msg);
|
|
2630
|
+
// Text messages run through the auth/command pipeline (communicate.request, text2command, ...).
|
|
2631
|
+
// Media messages (photo, video, document, ...) carry their text in `msg.caption`, not in
|
|
2632
|
+
// `msg.text` - route the caption through the same pipeline by treating it as the message text.
|
|
2633
|
+
if (msg.text) {
|
|
2634
|
+
this.processTelegramText(msg).catch(error => this.log.error(`Cannot process message: ${error}`));
|
|
2635
|
+
}
|
|
2636
|
+
else if (msg.caption) {
|
|
2637
|
+
this.processTelegramText({ ...msg, text: msg.caption }).catch(error => this.log.error(`Cannot process message: ${error}`));
|
|
2638
|
+
}
|
|
2639
|
+
});
|
|
2640
|
+
// Telegram live location updates are delivered as `edited_message` events (only the first position
|
|
2641
|
+
// arrives as a normal `message`). Route them through getMessage() so communicate.requestLocation
|
|
2642
|
+
// (and requestRaw) follow the moving position.
|
|
2643
|
+
bot.on('edited_message', ctx => {
|
|
2644
|
+
const msg = ctx.editedMessage;
|
|
2645
|
+
// Only location updates are relevant here. Any other edit (typo fix in a text, changed caption
|
|
2646
|
+
// of a photo/document) would otherwise re-run getMessage() and e.g. download the media file a
|
|
2647
|
+
// second time and overwrite the request* states with the data of an old message.
|
|
2648
|
+
if (!msg?.location) {
|
|
2649
|
+
return;
|
|
2650
|
+
}
|
|
2651
|
+
this.connectionState(true);
|
|
2652
|
+
if (this.config.storeRawRequest) {
|
|
2653
|
+
this.setStateSafe('communicate.requestRaw', { val: JSON.stringify(msg, null, 2), ack: true });
|
|
2654
|
+
}
|
|
2655
|
+
this.getMessage(msg);
|
|
2656
|
+
});
|
|
2657
|
+
// Channel posts (in a channel where the bot is an admin) are delivered as a separate event, not
|
|
2658
|
+
// as `message`, so they were ignored before. They are anonymous (no `msg.from`), therefore the
|
|
2659
|
+
// auth/command pipeline cannot run; instead expose the post text and metadata so scripts can
|
|
2660
|
+
// react. See https://github.com/iobroker-community-adapters/ioBroker.telegram/issues/289
|
|
2661
|
+
bot.on('channel_post', ctx => {
|
|
2662
|
+
const msg = ctx.channelPost;
|
|
2663
|
+
if (!msg) {
|
|
2664
|
+
return;
|
|
2665
|
+
}
|
|
2666
|
+
this.connectionState(true);
|
|
2667
|
+
if (this.config.storeRawRequest) {
|
|
2668
|
+
this.setStateSafe('communicate.requestRaw', { val: JSON.stringify(msg, null, 2), ack: true });
|
|
2669
|
+
}
|
|
2670
|
+
// stores the channel in communicate.chats and handles/saves any attached media
|
|
2671
|
+
this.getMessage(msg);
|
|
2672
|
+
const text = msg.text ?? msg.caption;
|
|
2673
|
+
if (text !== undefined) {
|
|
2674
|
+
const name = msg.chat.title || String(msg.chat.id);
|
|
2675
|
+
this.setStateSafe('communicate.requestChatId', { val: msg.chat.id, ack: true });
|
|
2676
|
+
this.setStateSafe('communicate.requestMessageId', { val: msg.message_id, ack: true });
|
|
2677
|
+
this.setStateSafe('communicate.requestMessageThreadId', {
|
|
2678
|
+
val: msg.is_topic_message ? msg.message_thread_id : 0,
|
|
2679
|
+
ack: true,
|
|
2486
2680
|
});
|
|
2681
|
+
this.setStateSafe('communicate.request', { val: `[${name}]${text}`, ack: true });
|
|
2682
|
+
}
|
|
2683
|
+
});
|
|
2684
|
+
// callback InlineKeyboardButton
|
|
2685
|
+
bot.on('callback_query', ctx => {
|
|
2686
|
+
const callbackQuery = ctx.callbackQuery;
|
|
2687
|
+
if (!callbackQuery) {
|
|
2688
|
+
return;
|
|
2689
|
+
}
|
|
2690
|
+
this.connectionState(true);
|
|
2691
|
+
// write received answer into variable
|
|
2692
|
+
this.log.debug(`callback_query: ${JSON.stringify(callbackQuery)}`);
|
|
2693
|
+
this.callbackQueryId[callbackQuery.from.id] = { id: callbackQuery.id, ts: Date.now() };
|
|
2694
|
+
if (this.config.storeRawRequest) {
|
|
2695
|
+
this.setStateSafe('communicate.requestRaw', { val: JSON.stringify(callbackQuery), ack: true });
|
|
2696
|
+
}
|
|
2697
|
+
this.setStateSafe('communicate.requestMessageId', {
|
|
2698
|
+
val: callbackQuery.message.message_id,
|
|
2699
|
+
ack: true,
|
|
2487
2700
|
});
|
|
2488
|
-
|
|
2701
|
+
this.setStateSafe('communicate.requestChatId', { val: callbackQuery.message.chat.id, ack: true });
|
|
2702
|
+
this.setStateSafe('communicate.request', {
|
|
2703
|
+
val: `[${!this.config.useUsername
|
|
2704
|
+
? callbackQuery.from.first_name
|
|
2705
|
+
: !callbackQuery.from.username
|
|
2706
|
+
? callbackQuery.from.first_name
|
|
2707
|
+
: callbackQuery.from.username}]${callbackQuery.data}`,
|
|
2708
|
+
ack: true,
|
|
2709
|
+
});
|
|
2710
|
+
this.isAnswerForQuestion(callbackQuery);
|
|
2711
|
+
});
|
|
2489
2712
|
}
|
|
2490
2713
|
async updateUsers() {
|
|
2491
2714
|
if (this.config.rememberUsers) {
|