-
Notifications
You must be signed in to change notification settings - Fork 2
/
BotRunner.js
73 lines (59 loc) · 2.11 KB
/
BotRunner.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
const { WIKIDATA_ERROR } = require('./constants');
const DeadOrAlive = require('./DeadOrAlive');
const parseTextFromCommand = (text, commandOffset) => {
const command = text.substring(commandOffset.offset, commandOffset.length);
const start = commandOffset.offset + commandOffset.length + 1;
return {
command,
text: text.substring(start, text.length)
};
};
const buildResponse = async (searchTerm) => {
try {
const result = await DeadOrAlive.search(searchTerm);
if (result.customMessage) {
return result.customMessage;
}
if (result.isDead) {
return `[${result.name}](${result.url}) died${result.hasDOB ? ` aged ${result.age}` : ''} on ${result.dateOfDeath}.`;
}
return `[${result.name}](${result.url}) is alive${result.hasDOB ? ` and kicking at ${result.age} years old` : ''}.`;
} catch (e) {
if (e.message === 'not-found') {
return `Couldn't find a person named ${searchTerm}.`;
}
if (e.message === WIKIDATA_ERROR) {
return "Oops! The bot seems to be having issues - please open an issue at https://github.com/weiran/dead-or-alive-bot/issues (include your search term) and I'll take a look 👀😁";
}
return e.message;
}
};
const textReceived = async (context) => {
const { message } = context;
let searchTerm = message.text;
// parse command and input text
if (message.entities !== undefined && message.entities.length > 0) {
const commandOffset = message.entities[0];
const { command, text } = parseTextFromCommand(searchTerm, commandOffset);
switch (command) {
case '/dead':
case '/alive': {
searchTerm = text;
break;
}
default:
return;
}
}
// eslint-disable-next-line no-console
console.log(`Querying '${searchTerm}'`);
const response = await buildResponse(searchTerm);
context.replyWithMarkdown(response);
};
module.exports = {
textReceived,
_private: {
buildResponse,
parseTextFromCommand
}
};