-
Notifications
You must be signed in to change notification settings - Fork 0
/
muse-bot.mjs
214 lines (205 loc) · 7.13 KB
/
muse-bot.mjs
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
import MuseDiscord from './discord/muse-discord.mjs';
import MuseGoogle from './google/muse-google.mjs';
import SlashCommander from './commands/slash-commander.mjs';
const START_TIME = 5;
const END_TIME = 21;
/**
* MuseBot class for initializing and running the Discord bot.
*/
export default class MuseBot {
static get ACTIONS() {
return [
'match',
'start',
'status',
'testGoogle',
'testDiscord',
'testEmoji',
'slashTest',
'slashStart',
'slashCreate',
];
}
constructor(logger, options) {
this.logger = logger.child({ class: 'MuseBot' });
this.options = options;
this.startTime = new Date();
this.endTime = null;
this.initialized = false;
this.discordClient = null;
this.googleClient = null;
this.slashCommander = null;
this.destroyClient = true;
}
/**
* Initializes the bot. This includes the following:
* - Initializes the Discord client
* - Initializes the Google OAuth client
* - Initializes SlashCommander for managing slash commands
*/
async init() {
this.logger.info('Initializing MuseBot');
this.discordClient = new MuseDiscord(this.logger);
this.googleClient = new MuseGoogle(this.logger);
this.slashCommander = new SlashCommander(this.logger, this.discordClient);
await Promise.all([
this.discordClient.init(),
// this.googleClient.init(),
this.slashCommander.init(),
]);
this.initialized = true;
}
/**
* Internal function to check that the bot has been initialized.
*
* If the bot is not initialized when this is invoked, it throws an error.
*/
requireInit() {
if (!this.initialized) {
throw new Error('Bot was not initialized');
}
}
/**
* Async function that says whether the bot should be enabled.
*
* If the `force` option is set, this will always return `true`. Otherwise,
* will only return `true` if the bot's state is set to `GO` in the
* spreadsheet and the current time is in the bot's allowed operating window.
*/
async isBotEnabled() {
const botState = await this.googleClient.getBotState();
const nowHour = new Date().getHours();
return botState === 'GO' && START_TIME < nowHour && nowHour < END_TIME;
}
/**
* Iterates through the command line arguments to perform the requested
* actions.
*
* Destroys the input array.
*
* Requires the bot to have been initialized first.
*
* Though async, this function waits for each action to fully complete before
* moving on to the next action.
*
* See handleAction method for information about allowed actions.
*
* @param {string[]} actions - Array of actions to perform. Destroyed during
* processing
*/
async process(actions) {
this.requireInit();
this.logger.debug({ actions }, 'Processing requested actions');
// this.logger.info(this.discordClient.client.application, 'application')
// this.logger.info(this.discordClient.client.application.commands, 'application.commands')
// this.logger.info(this.discordClient.guild, 'guild')
// this.logger.info(this.discordClient.guild.commands, 'guild.commands')
while (actions.length) {
if (!MuseBot.ACTIONS.includes(actions[0])) {
throw new Error(`Invalid action '${actions[0]}'`);
}
const i = actions.slice(1).findIndex((element) => MuseBot.ACTIONS.includes(element));
const toHandle = i === -1 ? actions.splice(0) : actions.splice(0, i + 1);
// eslint-disable-next-line no-await-in-loop
await this.handleAction(toHandle[0], toHandle.slice(1));
}
}
/**
* Dispatcher function to handle individual actions.
*
* Possible actions are:
* - `match` Posts a single match
* - `start` Starts the daemon to post matches, count reactions, etc.
* - `status` Prints the status of the current round
*
* This function is synchronous and waits for the action to fully complete
* before returning.
*
* @param {string} action - The name of the action to perform, as described
* above.
* @param {string[]} args - Optional list of string arguments to pass to the
* action handler.
*/
async handleAction(action, args = []) {
this.requireInit();
this.logger.debug(`Processing argument "${action}"`);
switch (action) {
case 'match':
// Post one match
this.logger.info('Posting one match');
// this.client.postMatch(options);
break;
case 'start':
// Do all the bot things, keep running:
// * Start round
// * Post matches
// * Collect reactions
// * End round when appropriate
this.logger.info('Starting daemon');
// this.client.start(options)
this.destroyClient = false;
break;
case 'status':
// Print out status of current bracket/round
this.logger.info('Status of current round');
break;
case 'testGoogle':
// We authorize the client on init, this is to verify that worked
this.logger.info('Test Google API authorization');
await this.googleClient.testAuthorization();
break;
case 'testDiscord':
// We authorize the client on init, this is to verify that worked
this.logger.info('Test Discord API authorization');
await this.discordClient.testAuthorization();
break;
case 'testEmoji':
this.logger.info('Test finding emoji');
await this.discordClient.findRecentEmoji();
break;
case 'slashTest':
if (!args.length) {
this.logger.error('`slashTest` action requires command name argument');
break;
}
this.logger.info(`Testing slash command ${args[0]}`);
this.logger.debug({ command: args[0], args: args.slice(1) }, 'Testing slash command with given arguments');
await this.slashCommander.dispatch(args[0], args.slice(1));
this.logger.debug({ command: args[0], args: args.slice(1) }, 'Slash command completed');
break;
case 'slashStart':
this.logger.info('Registering SlashCommander as slash command handler');
if (args.length) {
this.logger.info(`Only registering the following commands: '${args.join("', '")}'`);
}
await this.slashCommander.start(args);
this.destroyClient = false;
break;
case 'slashCreate':
this.logger.info({ args }, '(Re)creating slash commands');
this.slashCommander.createCommands(args);
this.logger.info({ args }, 'Slash command creation complete');
break;
default:
this.logger.error(`Unknown action: "${action}"`);
}
}
/**
* This function tears down the bot.
*
* This includes the following actions:
* - Logging the elapsed time
* - Destroying the Discord client (if applicable)
*/
teardown() {
this.requireInit();
this.endTime = new Date();
const elapsed = ((this.endTime - this.startTime) / 1000).toFixed(3);
this.logger.info(`Completed processing arguments. Elapsed time ${elapsed}s`);
if (this.destroyClient) {
this.logger.info('Destroying Discord client');
this.discordClient.destroy();
}
this.initialized = false;
}
}