-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommands.js
67 lines (59 loc) · 1.53 KB
/
commands.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
/**
* @typedef {Object} Message
* @property {string} body - The body of the message.
* @property {string} type - The type of the message: {'text','html','image'}
* @property {string} nick - The nickname of the sender.
*/
/**
* This built-in command counts the vowels in the message and responds
* with a count.
*
* @param {Message} Input message from user
* @returns {Message} Response message from bot
*/
function countvowels(message) {
const vowels = ['a', 'e', 'i', 'o', 'u']
let count = 0;
for (const c of message.body) {
if (vowels.includes(c)) count++
}
return {
body: `countvowels: ${count}`,
type: 'text',
nick: 'bot',
}
}
// These are all our built in commands
const BUILTIN_COMMANDS = {
countvowels
}
/**
* Returns a list of command names for the auto-complete
*/
export async function getCommands() {
return Object.keys(BUILTIN_COMMANDS)
}
/**
* Handles a message
*/
export async function commandHandler(message) {
// split into command and commandBody
const re = new RegExp('^/([^\\s]+)\\s*(.*)$');
const [_full, commandName, commandBody] = message.body.match(re)
// replace the body with just the arguments to the command for simplicity
if (commandBody) message.body = commandBody
let botMessage = {
body: `Error: unknown command ${commandName}`,
type: 'text',
nick: 'bot',
}
const command = BUILTIN_COMMANDS[commandName]
if (command) {
botMessage = command(message)
}
botMessage.nick = 'bot'
return {
type: "message",
payload: botMessage
}
}