Skip to content

Commit 9321e32

Browse files
authored
Merge pull request #7 from withuno/smithki/discord-bot-health-check
Add health checks to discord bot service
2 parents 1e7779a + fc7c56f commit 9321e32

File tree

6 files changed

+938
-76
lines changed

6 files changed

+938
-76
lines changed

.github/workflows/bot-refresh.yml

-35
This file was deleted.
File renamed without changes.

bot/index.ts

+50-3
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,52 @@
55
import fs from 'fs';
66
import path from 'path';
77

8-
import { Client, GatewayIntentBits } from 'discord.js';
8+
import { Client, GatewayIntentBits, REST, RESTPostAPIChatInputApplicationCommandsJSONBody, Routes } from 'discord.js';
9+
import fastify from 'fastify';
910

10-
import { DiscordEvent } from './interfaces';
11+
import { DiscordEvent, SlashCommand } from './interfaces';
1112

12-
async function main() {
13+
/**
14+
* Start a `fastify` server to provide the app platform with health-checks.
15+
*/
16+
async function startServer() {
17+
const server = fastify();
18+
server.get('/', () => '[@withuno/locust] Locust Test Bot');
19+
await server.listen({
20+
port: Number(process.env.PORT ?? 8080),
21+
});
22+
}
23+
24+
/**
25+
* Update the Discord Bot with the latest slash commands spec.
26+
*/
27+
async function loadSlashCommands() {
28+
const commandsPath = path.resolve(__dirname, './commands');
29+
const commandFiles = await fs.promises.readdir(commandsPath);
30+
const commands: SlashCommand[] = commandFiles
31+
.map((filepath) => {
32+
return require(path.join(commandsPath, filepath))?.default;
33+
})
34+
.filter(Boolean);
35+
36+
const commandData: Array<RESTPostAPIChatInputApplicationCommandsJSONBody> = commands.map((cmd) => {
37+
return cmd.slash.toJSON();
38+
});
39+
40+
console.log(`◌ Refreshing ${commands.length} application command(s)...`);
41+
42+
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN!);
43+
const data: any = await rest.put(Routes.applicationCommands(process.env.DISCORD_CLIENT_ID!), {
44+
body: commandData,
45+
});
46+
47+
console.log(`◉ Refreshed ${data.length} application command(s)`);
48+
}
49+
50+
/**
51+
* Bootstrap a Discord client & start listening for events.
52+
*/
53+
async function startDiscordClient() {
1354
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
1455

1556
const eventsPath = path.resolve(__dirname, './events');
@@ -31,6 +72,12 @@ async function main() {
3172
await client.login(process.env.DISCORD_TOKEN);
3273
}
3374

75+
async function main() {
76+
await loadSlashCommands();
77+
await startDiscordClient();
78+
await startServer();
79+
}
80+
3481
main().catch((err) => {
3582
console.error('----- FATAL ERROR -----');
3683
console.error(err);

bot/scripts/refresh-commands.ts

-38
This file was deleted.

0 commit comments

Comments
 (0)