forked from guidone/node-red-contrib-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatbot-listen.js
88 lines (72 loc) · 2.39 KB
/
chatbot-listen.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
var _ = require('underscore');
var NplMatcher = require('./lib/npl-matcher');
var clc = require('cli-color');
var prettyjson = require('prettyjson');
var helpers = require('./lib/helpers/regexps');
var green = clc.greenBright;
var white = clc.white;
var grey = clc.blackBright;
module.exports = function(RED) {
function ChatBotListen(config) {
RED.nodes.createNode(this, config);
var node = this;
this.rules = config.rules;
this.showdebug = config.showdebug;
this.on('input', function(msg) {
var originalMessage = msg.originalMessage;
var chatContext = msg.chat();
var rules = node.rules;
var debug = node.showdebug;
// do nothing if it's not a chat message
if (originalMessage == null || _.isEmpty(rules)) {
return;
}
var output = [];
var matched = false;
// parse incoming message
var message = msg.payload.content;
var terms = NplMatcher.parseSentence(message);
// do not try to parse if it's a command like
if (helpers.isCommand(message)) {
return;
}
// debug the terms
if (debug) {
// eslint-disable-next-line no-console
console.log('');
// eslint-disable-next-line no-console
console.log(grey('------ Sentence Analysis ----------------'));
// eslint-disable-next-line no-console
console.log(green('Message:'), white(message));
try {
// eslint-disable-next-line no-console
console.log(prettyjson.render(terms._terms));
} catch(e) {
// pretty json may breaks
}
}
rules.forEach(function(rule) {
var matchedRule = null;
if (!matched && rule === '*') {
// mark as matched, only the first wins
matched = true;
output.push(msg);
} else if (!matched && (matchedRule = NplMatcher.matchRule(terms, new NplMatcher.MatchRules(rule.split(',')))) != null) {
// mark as matched, only the first wins
matched = true;
// store variables
matchedRule.forEach(function(rule) {
if (!_.isEmpty(rule.variable)) {
chatContext.set(rule.variable, rule.value);
}
});
output.push(msg);
} else {
output.push(null);
}
});
node.send(output);
});
}
RED.nodes.registerType('chatbot-listen', ChatBotListen);
};