-
Notifications
You must be signed in to change notification settings - Fork 0
/
keyword-spotter.js
50 lines (44 loc) · 1.45 KB
/
keyword-spotter.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
import { loadDataset } from "./pulse-engine.js";
export async function keywordSpotter(message) {
// Load the dataset
return await loadDataset("./datasets/responses.json").then((dataset) => {
const responses = dataset.responses; // Responses to keywords
// Split the message into words, and remove punctuation
const words = message.toLowerCase().replace(/[.,\/#!$%?\^&\*;:{}=\-_`~()]/g, "").split(" ");
// Perform keyword search on the message
let response = null;
let do_next = null;
let responseIndex = 0;
const responseMap = {};
responses.forEach((response_object) => {
response_object.keyword.forEach((keyword) => {
words.forEach((word) => {
if (word.toLowerCase() == keyword.toLowerCase()) {
response = response_object.responses[Math.floor(Math.random() * response_object.responses.length)];
do_next = response_object.do_next;
responseIndex = responses.indexOf(response_object);
}
});
});
});
for (const word of words) {
const wordLower = word.toLowerCase();
if (responseMap[wordLower]) {
const responseObj = responseMap[wordLower];
const response = responseObj.responses[Math.floor(Math.random() * responseObj.responses.length)];
do_next = responseObj.do_next;
responseIndex = responses.indexOf(responseObj);
break;
}
}
if (response == null) {
return null;
} else {
return {
response: response,
do_next: do_next,
responseIndex: responseIndex
};
}
});
}