forked from guidone/node-red-contrib-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatbot-telegram-receive.js
590 lines (549 loc) · 19.8 KB
/
chatbot-telegram-receive.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
var _ = require('underscore');
var TelegramBot = require('node-telegram-bot-api');
var moment = require('moment');
var ChatLog = require('./lib/chat-log');
var ChatContextStore = require('./lib/chat-context-store');
var helpers = require('./lib/telegram/telegram');
var utils = require('./lib/helpers/utils');
var DEBUG = false;
module.exports = function(RED) {
function TelegramBotNode(n) {
RED.nodes.createNode(this, n);
var self = this;
this.botname = n.botname;
this.polling = n.polling;
this.log = n.log;
this.usernames = [];
if (n.usernames) {
this.usernames = _(n.usernames.split(',')).chain()
.map(function(userId) {
return userId.match(/^[a-zA-Z0-9_]+?$/) ? userId : null
})
.compact()
.value();
}
this.isAuthorized = function (username, userId) {
if (self.usernames.length > 0) {
return self.usernames.indexOf(username) != -1 || self.usernames.indexOf(String(userId)) != -1;
}
return true;
};
// creates the message details object from the original message
this.getMessageDetails = function getMessageDetails(botMsg) {
var telegramBot = self.telegramBot;
return new Promise(function(resolve, reject) {
if (botMsg.text) {
resolve({
chatId: botMsg.chat.id,
messageId: botMsg.message_id,
type: 'message',
content: botMsg.text,
date: moment.unix(botMsg.date),
inbound: true
});
} else if (botMsg.photo) {
telegramBot.getFileLink(botMsg.photo[botMsg.photo.length - 1].file_id)
.then(function(path) {
return helpers.downloadFile(path);
})
.then(function(buffer) {
resolve({
chatId: botMsg.chat.id,
messageId: botMsg.message_id,
type: 'photo',
content: buffer,
caption: botMsg.caption,
date: moment.unix(botMsg.date),
inbound: true
});
})
.catch(function(error) {
reject(error);
});
} else if (botMsg.voice) {
telegramBot.getFileLink(botMsg.voice.file_id)
.then(function(path) {
return helpers.downloadFile(path);
})
.then(function(buffer) {
resolve({
chatId: botMsg.chat.id,
messageId: botMsg.message_id,
type: 'audio',
content: buffer,
caption: botMsg.caption,
date: moment.unix(botMsg.date),
inbound: true
});
});
} else if (botMsg.document) {
telegramBot.getFileLink(botMsg.document.file_id)
.then(function(path) {
return helpers.downloadFile(path);
})
.then(function(buffer) {
resolve({
chatId: botMsg.chat.id,
messageId: botMsg.message_id,
type: 'document',
content: buffer,
caption: botMsg.caption,
date: moment.unix(botMsg.date),
inbound: true
});
});
} else if (botMsg.sticker) {
resolve({
chatId: botMsg.chat.id,
messageId: botMsg.message_id,
type: 'sticker',
content: botMsg.sticker.file_id,
date: moment.unix(botMsg.date),
inbound: true
});
} else if (botMsg.video) {
telegramBot.getFileLink(botMsg.video.file_id)
.then(function(path) {
return helpers.downloadFile(path);
})
.then(function(buffer) {
resolve({
chatId: botMsg.chat.id,
messageId: botMsg.message_id,
type: 'video',
content: buffer,
caption: botMsg.caption,
date: moment.unix(botMsg.date),
inbound: true
});
});
} else if (botMsg.location) {
resolve({
chatId: botMsg.chat.id,
messageId: botMsg.message_id,
type: 'location',
content: botMsg.location,
date: moment.unix(botMsg.date),
inbound: true
});
} else if (botMsg.contact) {
resolve({
chatId: botMsg.chat.id,
messageId: botMsg.message_id,
type: 'contact',
content: botMsg.contact,
date: moment.unix(botMsg.date),
inbound: true
});
} else {
reject('Unable to detect incoming Telegram message');
}
});
};
this.handleCallback = function(botMsg) {
var chatId = botMsg.message.chat.id;
var alert = false;
var answer = null;
if (self.telegramBot.lastInlineButtons[chatId] != null) {
// find the button with the right value, takes the answer and alert if any
var button = _(self.telegramBot.lastInlineButtons[chatId]).findWhere({value: botMsg.data});
if (button != null) {
answer = button.answer;
alert = button.alert;
}
// do not remove from hash, the user could click again
}
// copy the "from" of the message containing user information, not chatbot detail
botMsg.message.from = botMsg.from;
// send answer back to client
self.telegramBot.answerCallbackQuery(botMsg.id, answer, alert)
.then(function() {
// send through the message as usual
botMsg.message.text = botMsg.data;
self.handleMessage(botMsg.message);
});
};
this.handleMessage = function(botMsg) {
var telegramBot = self.telegramBot;
// mark the original message with the platform
botMsg.transport = 'telegram';
if (DEBUG) {
// eslint-disable-next-line no-console
console.log('START:-------');
// eslint-disable-next-line no-console
console.log(botMsg);
// eslint-disable-next-line no-console
console.log('END:-------');
}
var username = !_.isEmpty(botMsg.from.username) ? botMsg.from.username : null;
var chatId = botMsg.chat.id;
var userId = botMsg.from.id;
var isAuthorized = self.isAuthorized(username, userId);
var chatContext = ChatContextStore.getOrCreateChatContext(self, chatId);
// store some information
chatContext.set('chatId', chatId);
chatContext.set('messageId', botMsg.message_id);
chatContext.set('userId', userId);
chatContext.set('firstName', botMsg.from.first_name);
chatContext.set('lastName', botMsg.from.last_name);
chatContext.set('authorized', isAuthorized);
chatContext.set('transport', 'telegram');
chatContext.set('message', botMsg.text);
// decode the message
self.getMessageDetails(botMsg)
.then(function(payload) {
var chatLog = new ChatLog(chatContext);
return chatLog.log({
payload: payload,
originalMessage: botMsg,
chat: function() {
return ChatContextStore.getChatContext(self, chatId);
}
}, self.log)
})
/*.then(function(msg) {
return analytics.dashbot.inbound(msg);
})*/
.then(function(msg) {
var currentConversationNode = chatContext.get('currentConversationNode');
// if a conversation is going on, go straight to the conversation node, otherwise if authorized
// then first pin, if not second pin
if (currentConversationNode != null) {
// void node id
chatContext.set('currentConversationNode', null);
// emit message directly the node where the conversation stopped
RED.events.emit('node:' + currentConversationNode, msg);
} else {
telegramBot.emit('relay', msg);
}
})
.catch(function(error) {
telegramBot.emit('relay', null, error);
});
}; // end handleMessage
var telegramBot = null;
if (this.credentials) {
this.token = this.credentials.token;
if (this.token) {
this.token = this.token.trim();
if (!this.telegramBot) {
telegramBot = new TelegramBot(this.token, {
polling: {
params: {
timeout: 10
},
interval: !isNaN(parseInt(self.polling, 10)) ? parseInt(self.polling, 10) : 1000
}
});
this.telegramBot = telegramBot;
this.telegramBot.setMaxListeners(0);
this.telegramBot.on('message', this.handleMessage);
this.telegramBot.on('callback_query', this.handleCallback);
}
}
}
this.on('close', function (done) {
// stop polling only once
if (this.telegramBot != null && this.telegramBot._polling) {
self.telegramBot.off('message', self.handleMessage);
self.telegramBot.off('callback_query', self.handleCallback);
self.telegramBot.stopPolling()
.then(function() {
self.telegramBot = null;
done();
});
} else {
done();
}
});
} // end TelegramBotNode
RED.nodes.registerType('chatbot-telegram-node', TelegramBotNode, {
credentials: {
token: {
type: 'text'
}
}
});
function TelegramInNode(config) {
RED.nodes.createNode(this, config);
var node = this;
this.bot = config.bot;
this.config = RED.nodes.getNode(this.bot);
if (this.config) {
this.status({fill: 'red', shape: 'ring', text: 'disconnected'});
node.telegramBot = this.config.telegramBot;
if (node.telegramBot) {
this.status({fill: 'green', shape: 'ring', text: 'connected'});
/*
todo implement inline
node.telegramBot.on('inline_query', function(botMsg) {
console.log('inline request', botMsg);
});*/
node.telegramBot.on('relay', function(message, error) {
if (error != null) {
node.error(error);
} else {
node.send(message);
}
});
} else {
node.warn("no bot in config.");
}
} else {
node.warn("no config.");
}
}
RED.nodes.registerType('chatbot-telegram-receive', TelegramInNode);
function TelegramOutNode(config) {
RED.nodes.createNode(this, config);
var node = this;
this.bot = config.bot;
this.track = config.track;
this.config = RED.nodes.getNode(this.bot);
if (this.config) {
this.status({
fill: 'red',
shape: 'ring',
text: 'disconnected'
});
node.telegramBot = this.config.telegramBot;
if (node.telegramBot) {
this.status({
fill: 'green',
shape: 'ring',
text: 'connected'
});
} else {
node.warn("no bot in config.");
}
} else {
node.warn("no config.");
}
// relay message
var handler = function(msg) {
node.send(msg);
};
RED.events.on('node:' + config.id, handler);
// cleanup on close
this.on('close',function() {
RED.events.removeListener('node:' + config.id, handler);
});
this.handleError = function(error, msg) {
// convert to string
var plainError = error != null ? String(error) : '';
// remove anything before any eventual '{', telegram lib returns a plain text error
// in order to parse it
var jsonError = plainError.replace(/^.*\{/,'{');
var errorCode = null;
var errorDescription = plainError;
// now try to parse
try {
var parsedError = JSON.parse(jsonError);
errorCode = parsedError.error_code;
errorDescription = parsedError.description;
} catch(e) {
// do nothing
}
// send out, second parameter goes through the catch all node
node.error(plainError, {
chatId: msg.payload.chatId,
code: errorCode,
description: errorDescription
});
};
this.on('input', function (msg) {
// check if the message is from telegram
if (msg.originalMessage != null && msg.originalMessage.transport !== 'telegram') {
// exit, it's not from telegram
return;
}
if (msg.payload == null) {
node.warn('msg.payload is empty');
return;
}
if (msg.payload.chatId == null) {
node.warn('msg.payload.chatId is empty');
return;
}
if (msg.payload.type == null) {
node.warn('msg.payload.type is empty');
return;
}
//var context = node.context();
var buttons = null;
var track = node.track;
var chatId = utils.getChatId(msg);
var chatContext = utils.getChatContext(msg);
var type = msg.payload.type;
// check if this node has some wirings in the follow up pin, in that case
// the next message should be redirected here
if (chatContext != null && track && !_.isEmpty(node.wires[0])) {
chatContext.set('currentConversationNode', node.id);
chatContext.set('currentConversationNode_at', moment());
}
var messageOk = function (response) {
chatContext.set('messageId', response.message_id)
};
var messageError = function (error) {
node.handleError(error, msg);
};
var chatLog = new ChatLog(chatContext);
chatLog.log(msg, this.config.log)
.then(function() {
switch (type) {
case 'message':
if (msg.originalMessage.modify_message_id != null) {
node.telegramBot.editMessageText(msg.payload.content, {
chat_id: chatId,
message_id: msg.originalMessage.modify_message_id
}).then(messageOk, messageError);
} else {
node.telegramBot.sendMessage(chatId, msg.payload.content, msg.payload.options)
.then(messageOk, messageError);
}
break;
case 'photo':
node.telegramBot.sendPhoto(chatId, msg.payload.content, {
caption: msg.payload.caption
}).then(messageOk, messageError);
break;
case 'document':
node.telegramBot.sendDocument(chatId, msg.payload.content, {
caption: msg.payload.caption
}, {
filename: msg.payload.filename
}).then(messageOk, messageError);
break;
case 'sticker':
node.telegramBot.sendSticker(chatId, msg.payload.content, msg.payload.options)
.then(messageOk, messageError);
break;
case 'video':
node.telegramBot.sendVideo(chatId, msg.payload.content, {
caption: msg.payload.caption
}).then(messageOk, messageError);
break;
case 'audio':
node.telegramBot.sendVoice(chatId, msg.payload.content, msg.payload.options)
.then(messageOk, messageError);
break;
case 'location':
node.telegramBot.sendLocation(chatId, msg.payload.content.latitude, msg.payload.content.longitude, msg.payload.options)
.then(messageOk, messageError);
break;
case 'action':
node.telegramBot.sendChatAction(chatId, msg.payload.waitingType != null ? msg.payload.waitingType : 'typing')
.then(messageOk, messageError);
break;
case 'request':
var keyboard = null;
if (msg.payload.requestType === 'location') {
keyboard = [
[{
text: !_.isEmpty(msg.payload.buttonLabel) ? msg.payload.buttonLabel : 'Send your position',
request_location: true
}]
];
} else if (msg.payload.requestType === 'phone-number') {
keyboard = [
[{
text: !_.isEmpty(msg.payload.buttonLabel) ? msg.payload.buttonLabel : 'Send your phone number',
request_contact: true
}]
];
}
if (keyboard != null) {
node.telegramBot
.sendMessage(chatId, msg.payload.content, {
reply_markup: JSON.stringify({
keyboard: keyboard,
'resize_keyboard': true,
'one_time_keyboard': true
})
})
.then(messageOk, messageError);
} else {
node.error('Request type not supported');
}
break;
case 'inline-buttons':
// create inline buttons, docs for this is https://core.telegram.org/bots/api#inlinekeyboardmarkup
// create the first array of array
var inlineKeyboard = [[]];
// cycle through buttons, add new line at the end if flag
_(msg.payload.buttons).each(function(button) {
var json = null;
if (!_.isEmpty(button.url)) {
json = {
text: button.label,
url: button.url
};
} else if (!_.isEmpty(button.value)) {
json = {
text: button.label,
callback_data: button.value
};
} else {
json = {
text: button.label,
callback_data: button.label
};
}
// add the button to the last row
inlineKeyboard[inlineKeyboard.length -1].push(json);
// if new line, then add a blank array
if (button.newLine) {
inlineKeyboard.push([]);
}
});
// store the last buttons, this will be handled by the receiver
if (node.telegramBot.lastInlineButtons == null) {
node.telegramBot.lastInlineButtons = {};
}
node.telegramBot.lastInlineButtons[chatId] = msg.payload.buttons;
// send buttons or edit
if (msg.originalMessage.modify_message_id != null) {
node.telegramBot.editMessageReplyMarkup(JSON.stringify({
inline_keyboard: inlineKeyboard
}), {
chat_id: chatId,
message_id: msg.originalMessage.modify_message_id
}).then(messageOk, messageError);
} else {
// finally send
node.telegramBot.sendMessage(chatId, msg.payload.content, {
reply_markup: JSON.stringify({
inline_keyboard: inlineKeyboard
})
}).then(messageOk, messageError);
}
break;
case 'buttons':
if (_.isEmpty(msg.payload.content)) {
node.error('Buttons node needs a non-empty message');
return;
}
buttons = {
reply_markup: JSON.stringify({
keyboard: _(msg.payload.buttons).map(function(button) {
return [button.value];
}),
resize_keyboard: true,
one_time_keyboard: true
})
};
// finally send
node.telegramBot.sendMessage(
chatId,
msg.payload.content,
buttons
).then(messageOk, messageError);
break;
default:
// unknown type, do nothing
}
});
});
}
RED.nodes.registerType('chatbot-telegram-send', TelegramOutNode);
};