forked from guidone/node-red-contrib-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatbot-conversation.js
74 lines (64 loc) · 2.14 KB
/
chatbot-conversation.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
var _ = require('underscore');
var ChatContextStore = require('./lib/chat-context-store');
module.exports = function(RED) {
function ChatBotConversation(config) {
RED.nodes.createNode(this, config);
var node = this;
this.chatId = config.chatId;
this.transport = config.transport;
this.contextMessageId = config.contextMessageId;
this.messageId = config.messageId;
this.on('input', function(msg) {
// evaluate chat id
var chatId = null;
if (!_.isEmpty(node.chatId)) {
chatId = node.chatId;
} else if (msg.payload != null && msg.payload.chatId != null) {
chatId = msg.payload.chatId;
}
// evaluate platform transport
var transport = null;
if (!_.isEmpty(node.transport)) {
transport = node.transport;
} else if (msg.payload != null && msg.payload.transport != null) {
transport = msg.payload.transport;
}
// get the chat context
var chatContext = ChatContextStore.getOrCreateChatContext(node, chatId, {
chatId: chatId,
transport: transport
});
// evaluate message if
var messageId = null;
if (!_.isEmpty(node.messageId)) {
messageId = node.messageId;
} else if (msg.payload != null && msg.payload.messageId != null) {
messageId = msg.payload.messageId;
} else if (this.contextMessageId && chatContext.get('messageId') != null) {
messageId = chatContext.get('messageId');
}
// ensure the original message is injected
msg.originalMessage = {
chat: {
id: chatId
},
message_id: null,
modify_message_id: messageId,
transport: transport
};
msg.chat = function() {
return ChatContextStore.getOrCreateChatContext(node, chatId, {
chatId: chatId,
transport: transport,
authorized: true
});
};
// fix chat id in payload if any
if (_.isObject(msg.payload) && msg.payload.chatId != null) {
msg.payload.chatId = chatId;
}
node.send(msg);
});
}
RED.nodes.registerType('chatbot-conversation', ChatBotConversation);
};