forked from guidone/node-red-contrib-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatbot-context.js
74 lines (61 loc) · 1.92 KB
/
chatbot-context.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');
module.exports = function(RED) {
function ChatBotContext(config) {
RED.nodes.createNode(this, config);
var node = this;
this.command = config.command;
this.fieldValue = config.fieldValue;
this.fieldType = config.fieldType;
this.fieldName = config.fieldName;
this.on('input', function(msg) {
msg = RED.util.cloneMessage(msg);
var command = this.command;
var fieldValue = this.fieldValue;
var fieldType = this.fieldType;
var fieldName = this.fieldName;
var originalMessage = msg.originalMessage;
var chatId = msg.payload.chatId || (originalMessage && originalMessage.chat.id);
var chatContext = msg.chat();
if (chatContext == null) {
node.error('Unable to find a chat context for chatId: ' + chatId);
return;
}
if (_.isEmpty(fieldName)) {
node.error('Invalid variable name');
return;
}
switch(command) {
case 'get':
msg.payload = chatContext.get(fieldName);
node.send(msg);
break;
case 'delete':
chatContext.remove(fieldName);
node.send(msg);
break;
case 'set':
switch (fieldType) {
case 'str':
chatContext.set(fieldName, fieldValue);
break;
case 'num':
chatContext.set(fieldName, Number(fieldValue));
break;
case 'bol':
chatContext.set(fieldName, /^true$/i.test(fieldValue));
break;
case 'json':
try {
chatContext.set(fieldName, JSON.parse(fieldValue));
} catch(e) {
node.error('Unable to parse json in context node');
}
break;
}
node.send(msg);
break;
}
});
}
RED.nodes.registerType('chatbot-context', ChatBotContext);
};