Skip to content

Commit 2de4b17

Browse files
committed
refactor: create register all commands fn
1 parent 9baf3aa commit 2de4b17

File tree

2 files changed

+30
-27
lines changed

2 files changed

+30
-27
lines changed

src/commands/commands.module.ts

+7-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,13 @@ export class CommandsModule implements OnModuleInit, OnApplicationBootstrap {
2828
return;
2929
}
3030

31-
return this.client.once('ready', async () => this.commandsService.register());
31+
return this.client.once('ready', async () => {
32+
if (this.client.application.partial) {
33+
await this.client.application.fetch();
34+
}
35+
36+
return this.commandsService.registerAllCommands();
37+
});
3238
}
3339

3440
public onApplicationBootstrap() {

src/commands/commands.service.ts

+23-26
Original file line numberDiff line numberDiff line change
@@ -14,39 +14,36 @@ export class CommandsService {
1414
private readonly slashCommandsService: SlashCommandsService
1515
) {}
1616

17-
public async register() {
18-
if (this.client.application.partial) {
19-
await this.client.application.fetch();
20-
}
17+
public async registerAllCommands() {
18+
const guilds = new Set(this.getCommandsByGuilds().keys());
2119

2220
this.logger.log(`Started refreshing application commands.`);
23-
for (const [guild, commands] of this.getCommandsByGuilds().entries()) {
24-
if (commands.length === 0) {
25-
this.logger.log(
26-
`Skipping ${guild ? `guild ${guild}` : 'global'} as it has no commands.`
27-
);
28-
continue;
29-
}
30-
31-
const rawCommands = commands.flatMap(command => command.toJSON());
32-
33-
await this.client.application.commands.set(rawCommands, guild).catch(error => {
34-
this.logger.error(
35-
`Failed to register application commands (${
36-
guild ? `in guild ${guild}` : 'global'
37-
}): ${error}`,
38-
error.stack
39-
);
40-
});
21+
for (const guild of guilds) {
22+
await this.registerInGuild(guild);
4123
}
4224
this.logger.log(`Successfully reloaded application commands.`);
4325
}
4426

4527
public async registerInGuild(guildId: string) {
46-
return this.client.application.commands.set(
47-
this.getGuildCommands(guildId).flatMap(command => command.toJSON()),
48-
guildId
49-
);
28+
const commands = this.getGuildCommands(guildId);
29+
30+
if (commands.length === 0) {
31+
this.logger.log(
32+
`Skipping ${guildId ? `guild ${guildId}` : 'global'} as it has no commands.`
33+
);
34+
return;
35+
}
36+
37+
const rawCommands = commands.flatMap(command => command.toJSON());
38+
39+
return this.client.application.commands.set(rawCommands, guildId).catch(error => {
40+
this.logger.error(
41+
`Failed to register application commands (${
42+
guildId ? `in guild ${guildId}` : 'global'
43+
}): ${error}`,
44+
error.stack
45+
);
46+
});
5047
}
5148

5249
public getCommands(): CommandDiscovery[] {

0 commit comments

Comments
 (0)