5
5
import fs from 'fs' ;
6
6
import path from 'path' ;
7
7
8
- import { Client , GatewayIntentBits } from 'discord.js' ;
8
+ import { Client , GatewayIntentBits , REST , RESTPostAPIChatInputApplicationCommandsJSONBody , Routes } from 'discord.js' ;
9
+ import fastify from 'fastify' ;
9
10
10
- import { DiscordEvent } from './interfaces' ;
11
+ import { DiscordEvent , SlashCommand } from './interfaces' ;
11
12
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 ( ) {
13
54
const client = new Client ( { intents : [ GatewayIntentBits . Guilds ] } ) ;
14
55
15
56
const eventsPath = path . resolve ( __dirname , './events' ) ;
@@ -31,6 +72,12 @@ async function main() {
31
72
await client . login ( process . env . DISCORD_TOKEN ) ;
32
73
}
33
74
75
+ async function main ( ) {
76
+ await loadSlashCommands ( ) ;
77
+ await startDiscordClient ( ) ;
78
+ await startServer ( ) ;
79
+ }
80
+
34
81
main ( ) . catch ( ( err ) => {
35
82
console . error ( '----- FATAL ERROR -----' ) ;
36
83
console . error ( err ) ;
0 commit comments