forked from guidone/node-red-contrib-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatbot-language.js
66 lines (57 loc) · 1.72 KB
/
chatbot-language.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
var speak = require("speakeasy-nlp");
var levenshtein = require('fast-levenshtein');
var _ = require('underscore');
var lngDetector = new (require('languagedetect'));
module.exports = function(RED) {
function ChatBotLanguage(config) {
RED.nodes.createNode(this, config);
var node = this;
this.language = config.language;
this.mode = config.mode;
this.on('input', function(msg) {
var language = node.language;
var mode = node.mode;
// exit if not string
if (_.isString(msg.payload.content)) {
// if it's a command, then don't care about the language
if (msg.payload.content.match(/^\/[A-Za-z0-9]*$/)) {
node.send([msg, null]);
return;
}
// if it's shorter than 5 chars, make it through, it's hard to tell the language
if (msg.payload.content.length <= 5) {
node.send([msg, null]);
return;
}
// match the language
var matchLanguage = lngDetector.detect(msg.payload.content, 10);
// find position
var position = -1;
_(matchLanguage).each(function(duet, idx) {
if (duet[0] === language) {
position = idx;
}
});
// set the trigger level
var trigger = 0;
switch(mode) {
case 'strict':
trigger = 0;
break;
case 'medium':
trigger = 2;
break;
case 'loose':
trigger = 5;
break;
}
if (position !== -1 && position <= trigger) {
node.send([msg, null]);
return;
}
}
node.send([null, msg]);
});
}
RED.nodes.registerType('chatbot-language', ChatBotLanguage);
};