This repository has been archived by the owner on Jun 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 93
/
api.js
305 lines (244 loc) · 10 KB
/
api.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
var request = require('request');
var fs = require('fs');
const INTENT_CONFIDENCE_THRESHOLD = process.env.INTENT_CONFIDENCE_THRESHOLD || 0.7;
module.exports = function() {
var api = {}
var scripts = [];
var triggers = [];
var PATH_TO_SCRIPTS;
api.parseAdminUsers = function(string) {
if (!string) {
string = '';
}
var creds = string.split(/\s+/);
var users = {};
creds.forEach(function(u) {
var bits = u.split(/\:/);
users[bits[0]] = bits[1];
});
return users;
}
api.loadScriptsFromFile = function(src, alt_path) {
return new Promise(function(resolve, reject) {
if (fs.existsSync(src)) {
try {
scripts = require(src);
} catch(err) {
return reject('Cannot load scripts from file: ' + err.message);
}
} else {
console.warn('Loading sample scripts...');
try {
scripts = require(alt_path);
} catch(err) {
return reject(err);
}
}
PATH_TO_SCRIPTS = src;
api.mapTriggers();
resolve(scripts);
});
}
api.writeScriptsToFile = function(new_scripts, alt_path) {
return new Promise(function(resolve, reject) {
try {
require('fs').writeFileSync(alt_path || PATH_TO_SCRIPTS, JSON.stringify(new_scripts,null,2));
} catch(err) {
return reject('Cannot write scripts to file: ' + err.message);
}
scripts = new_scripts;
api.mapTriggers();
resolve(scripts);
});
}
api.mapTriggers = function() {
for (var s = 0; s < scripts.length; s++) {
// TODO: remove this when ID is part of datafile
if (!scripts[s].id) {
scripts[s].id = s;
}
for (var t = 0; t < scripts[s].triggers.length; t++) {
triggers.push({trigger: scripts[s].triggers[t], script: s});
}
}
// sort in the order of _descending pattern length_
triggers.sort(function(a,b) {
return b.trigger.pattern.length - a.trigger.pattern.length;
});
}
api.enrichMessage = function(message_text) {
return new Promise(function(resolve, reject) {
var query = {
text: message_text
};
// endpoint in the form of
// https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/<APPID>?subscription-key=<SUBID>&verbose=true&timezoneOffset=-360&q=
if (process.env.LUIS_ENDPOINT) {
var luis_uri = process.env.LUIS_ENDPOINT + query.text;
request(luis_uri, function(error, response, body) {
if (error) {
console.error('Error communicating with LUIS', error);
resolve(query);
} else {
var luis_results = {};
try {
luis_results = JSON.parse(body);
} catch(err) {
console.error('Error parsing LUIS response', err);
return resolve(query);
}
if (!luis_results.intents) {
console.warn('No intents returned from LUIS.ai. Key may be invalid');
resolve(query);
} else {
if (String(luis_results.Message) === 'The request is invalid.') {
console.warn('No intents returned from LUIS.ai. Key may be invalid');
resolve(query);
} else {
query.luis = luis_results;
query.intents = [];
query.entities = [];
luis_results.intents.forEach(function(i) {
query.intents.push(i);
});
luis_results.entities.forEach(function(e) {
query.entities.push(e);
});
resolve(query);
}
}
}
});
} else {
resolve(query);
}
})
}
api.evaluateTriggers = function(message_text) {
return new Promise(function(resolve, reject) {
var res = [];
api.enrichMessage(message_text).then(function(query) {
// if any intents were detected, check if they match a trigger...
if (query.intents && query.intents.length) {
// check intents first
for (var t = 0; t < triggers.length; t++) {
var trigger = triggers[t].trigger;
if (trigger.type == 'intent') {
for (var i = 0; i < query.intents.length; i++) {
var intent = query.intents[i];
if (Number(intent.score) >= INTENT_CONFIDENCE_THRESHOLD) {
if (intent.intent === trigger.pattern) {
res.push(triggers[t].script);
}
}
}
}
}
}
// check regular expressions
for (var t = 0; t < triggers.length; t++) {
var trigger = triggers[t].trigger;
if (trigger.type == 'regexp') {
var found = false;
try {
var test = new RegExp(trigger.pattern,'i');
found = query.text.match(test);
} catch(err) {
console.error('ERROR IN TRIGGER REGEX', err);
}
if (found !== false && found !== null) {
res.push(triggers[t].script);
}
}
}
// check keywords
for (var t = 0; t < triggers.length; t++) {
var trigger = triggers[t].trigger;
if (trigger.type == 'string') {
var found = false;
try {
var test = new RegExp('^' + trigger.pattern + '\\b','i');
found = query.text.match(test);
} catch(err) {
console.error('ERROR IN TRIGGER REGEX', err);
}
if (found !== false && found !== null) {
res.push(triggers[t].script);
}
}
}
// check for no results...
if (!res.length) {
// find a script set with is_fallback true
for (var s = 0; s < scripts.length; s++) {
if (scripts[s].is_fallback === true) {
res.push(s);
}
}
}
if (res.length) {
// this is the script that will be triggered.
var triggered = scripts[res[0]];
// copy entities from LUIS into the conversation script
if (query.entities && query.entities.length) {
query.entities.forEach(function(e) {
var ne = {
name: e.type,
value: e.entity,
type: 'entity'
};
var cv = triggered.variables.filter(function(v) {
return v.name === ne.name && v.value === ne.value && v.type === ne.type;
});
if (cv.length === 0) {
triggered.variables.push(ne);
}
});
}
// if LUIS results exist, pass them down to the bot.
if (query.luis) {
triggered.luis = query.luis;
}
resolve(triggered);
} else {
reject();
}
}).catch(reject);
});
}
api.getScript = function(name) {
return new Promise(function(resolve, reject) {
for (var s = 0; s < scripts.length; s++) {
if (name.toLowerCase() == scripts[s].command.toLowerCase()) {
return resolve(scripts[s]);
}
}
reject();
});
}
api.getScriptById = function(id) {
return new Promise(function(resolve, reject) {
for (var s = 0; s < scripts.length; s++) {
if (id == scripts[s]._id || id == scripts[s].id) {
return resolve(scripts[s]);
}
}
reject();
});
}
api.getScripts = function(tag) {
return new Promise(function(resolve, reject) {
if (tag) {
resolve(scripts.filter(function(s) {
return s.tags ? (s.tags.indexOf(tag) >= 0) : false;
}))
}
resolve(scripts);
});
}
api.useLocalStudio = function(botkit) {
var mutagen = require(__dirname + '/botkit_mutagen.js');
return mutagen(api, botkit);
}
return api;
}