-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
86 lines (79 loc) · 2.3 KB
/
Copy pathindex.js
File metadata and controls
86 lines (79 loc) · 2.3 KB
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
const request = require('request');
const Fuse = require('fuse.js');
const model = require('./model.js');
const config = require('./config.js');
let sendMessage = (data, error) => {
data.as_user = false;
data.username = config.BOT_USERNAME;
request.post(config.POST_MESSAGE_ENDPOINT, {
auth: {
bearer: process.env.BOT_USER_TOKEN
},
json: data
}, (err, res, body) => {
if (err) return error(err);
if (!body.ok) return error(body.error);
});
}
let randomItem = (items) => {
return items[Math.floor(Math.random()*items.length)];
}
let verify = (event, cb) => {
if (event.token === process.env.VERIFICATION_TOKEN) cb(null, event.challenge);
else cb('Token does not match.');
}
let findMatch = (text) => {
if (text.length < config.MIN_TEXT_LEN ||
text.length > config.MAX_TEST_LEN) return;
var options = {
threshold: config.FUZZY_MATCH_THRESHOLD,
location: 0,
distance: 100,
maxPatternLength: config.MAX_TEST_LEN,
minMatchCharLength: 1,
keys: [
"input"
]
};
var fuse = new Fuse(model, options);
var result = fuse.search(text);
for (let match of result) {
if (Math.abs(text.length - match.input.length) <= config.FUZZY_MATCH_MAX_LEN_DIFF) {
let response = randomItem(match.output);
console.log(`INPUT: "${text}", OUTPUT: "${response}"`);
return response;
}
}
return null;
}
let appMention = (event, error) => {
let response = findMatch(event.text);
if (response) {
let message = {
channel: event.channel,
text: response
}
sendMessage(message, error);
}
}
let eventCallback = (event, error) => {
if ('subtype' in event.event) return;
let response = findMatch(event.event.text);
if (response) {
let message = {
channel: event.event.channel,
text: response
}
sendMessage(message, error);
}
}
exports.handler = (event, context, cb) => {
switch(event.type) {
case 'app_mention':
return appMention(event, cb);
case 'url_verification':
return verify(event, cb);
case 'event_callback':
return eventCallback(event, cb);
}
};