forked from guidone/node-red-contrib-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatbot-message.js
71 lines (62 loc) · 2.2 KB
/
chatbot-message.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
var _ = require('underscore');
var utils = require('./lib/helpers/utils');
var MessageTemplate = require('./lib/message-template');
var emoji = require('node-emoji');
module.exports = function(RED) {
function ChatBotMessage(config) {
RED.nodes.createNode(this, config);
var node = this;
this.message = config.message;
this.answer = config.answer;
this.parse_mode = config.parse_mode;
this.transports = ['telegram', 'slack', 'facebook', 'smooch'];
this.pickOne = function(messages) {
var luck = Math.floor(Math.random() * messages.length);
return _.isString(messages[luck]) ? messages[luck] : messages[luck].message;
};
this.on('input', function(msg) {
var message = node.message;
var answer = node.answer;
var parse_mode = node.parse_mode;
var chatId = utils.getChatId(msg);
var messageId = utils.getMessageId(msg);
var template = MessageTemplate(msg, node);
// check transport compatibility
if (!_.contains(node.transports, msg.originalMessage.transport)) {
node.error('This node is not available for transport: ' + msg.originalMessage.transport);
return;
}
if (!_.isEmpty(node.message)) {
message = _.isArray(node.message) ? node.pickOne(node.message) : node.message;
} else if (_.isString(msg.payload) && !_.isEmpty(msg.payload)) {
message = msg.payload;
} else if (_.isArray(msg.payload) && !_.isEmpty(msg.payload)) {
message = node.pickOne(msg.payload);
} else if (_.isNumber(msg.payload)) {
message = String(msg.payload);
} else {
node.error('Empty message');
}
// payload
msg.payload = {
type: 'message',
content: emoji.emojify(template(message)),
chatId: chatId,
messageId: messageId,
inbound: false
};
msg.payload.options = {};
// parse mode
if (!_.isEmpty(parse_mode)) {
msg.payload.options.parse_mode = parse_mode;
}
// reply flag
if (answer) {
msg.payload.options.reply_to_message_id = messageId;
}
// send out reply
node.send(msg);
});
}
RED.nodes.registerType('chatbot-message', ChatBotMessage);
};