From 475c5c58d6a36d1fae8e89b9b5a36798c8dba91b Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Thu, 31 Aug 2023 17:27:08 +0200 Subject: [PATCH] Add registering of all interactions to client --- src/bot.ts | 10 +- src/events/interactions/interactionCreate.ts | 23 +++- .../interactionAutocompleteHandler.ts | 23 +++- src/handlers/interactionCommandHandler.ts | 26 ++-- src/handlers/interactionComponentHandler.ts | 27 ++-- src/handlers/interactionErrorHandler.ts | 12 +- src/interactions/commands/info/help.ts | 2 +- src/interactions/commands/player/skip.ts | 2 +- src/interactions/commands/system/reload.ts | 4 +- src/types/clientTypes.ts | 10 +- src/types/utilTypes.ts | 2 +- src/utils/registerClientCommands.ts | 49 ------- src/utils/registerClientInteractions.ts | 124 ++++++++++++++++++ 13 files changed, 217 insertions(+), 97 deletions(-) delete mode 100644 src/utils/registerClientCommands.ts create mode 100644 src/utils/registerClientInteractions.ts diff --git a/src/bot.ts b/src/bot.ts index 366b812..5cc22a5 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -7,7 +7,7 @@ import loggerModule from './services/logger'; import { ExtendedClient } from './types/clientTypes'; import { createClient } from './utils/factory/createClient'; import { createPlayer } from './utils/factory/createPlayer'; -import { registerClientCommands } from './utils/registerClientCommands'; +import { registerClientInteractions } from './utils/registerClientInteractions'; import { registerEventListeners } from './utils/registerEventListeners'; import { Player } from 'discord-player'; import { Logger } from 'pino'; @@ -25,14 +25,14 @@ const logger: Logger = loggerModule.child({ try { const client: ExtendedClient = await createClient({ executionId }); const player: Player = await createPlayer({ client, executionId }); - + client.on('allShardsReady', async () => { - client.registerClientCommands = registerClientCommands; + client.registerClientInteractions = registerClientInteractions; await registerEventListeners({ client, player, executionId }); - await registerClientCommands({ client, executionId }); + await registerClientInteractions({ client, executionId }); client.emit('ready', client as Client); }); - + client.login(process.env.DISCORD_BOT_TOKEN); } catch (error) { logger.error(error); diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index 751dcc2..d9e0d93 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -47,15 +47,30 @@ module.exports = { logger.debug('Started handling interaction.'); switch (interaction.type) { case InteractionType.ApplicationCommand: - await handleCommand(interaction as ChatInputCommandInteraction, client, executionId); + await handleCommand( + interaction as ChatInputCommandInteraction, + client, + executionId, + interactionIdentifier + ); break; case InteractionType.ApplicationCommandAutocomplete: - await handleAutocomplete(interaction as AutocompleteInteraction, executionId); + await handleAutocomplete( + interaction as AutocompleteInteraction, + client, + executionId, + interactionIdentifier + ); break; case InteractionType.MessageComponent: - await handleComponent(interaction as MessageComponentInteraction, executionId); + await handleComponent( + interaction as MessageComponentInteraction, + client, + executionId, + interactionIdentifier + ); break; default: @@ -67,7 +82,7 @@ module.exports = { } } catch (error) { logger.debug('Error while handling received interaction.'); - await handleError(interaction, error as CustomError, interactionIdentifier, executionId); + await handleError(interaction, error as CustomError, executionId, interactionIdentifier); } const outputTime: number = new Date().getTime(); diff --git a/src/handlers/interactionAutocompleteHandler.ts b/src/handlers/interactionAutocompleteHandler.ts index fe65513..7310231 100644 --- a/src/handlers/interactionAutocompleteHandler.ts +++ b/src/handlers/interactionAutocompleteHandler.ts @@ -1,20 +1,31 @@ import { AutocompleteInteraction } from 'discord.js'; import { Logger } from 'pino'; import loggerModule from '../services/logger'; +import { ExtendedClient } from '../types/clientTypes'; +import { BaseAutocompleteInteraction } from '../types/interactionTypes'; -export const handleAutocomplete = async (interaction: AutocompleteInteraction, executionId: string) => { +export const handleAutocomplete = async ( + interaction: AutocompleteInteraction, + client: ExtendedClient, + executionId: string, + interactionIdentifier: string +) => { // TODO: Define TS Type for handlers, and require logger constant? const logger: Logger = loggerModule.child({ - source: 'interactionCutocompleteHandler.ts', + source: 'interactionAutocompleteHandler.ts', module: 'handler', name: 'interactionAutocompleteHandler', executionId: executionId }); - // TODO: Create TS Type for autocompleteModule - const autocompleteModule = await import(`../interactions/autocomplete/${interaction.commandName}.js`); - const { default: autocomplete } = autocompleteModule; + const autocomplete: BaseAutocompleteInteraction = client.autocompleteInteractions!.get( + interactionIdentifier + ) as BaseAutocompleteInteraction; + if (!autocomplete) { + logger.warn(`Interaction created but autocomplete '${interactionIdentifier}' was not found.`); + return; + } - logger.debug('Executing autocomplete interaction.'); + logger.debug(`Executing autocomplete interaction '${interactionIdentifier}'.`); await autocomplete.execute({ interaction, executionId }); }; diff --git a/src/handlers/interactionCommandHandler.ts b/src/handlers/interactionCommandHandler.ts index d928317..e7ddb4a 100644 --- a/src/handlers/interactionCommandHandler.ts +++ b/src/handlers/interactionCommandHandler.ts @@ -2,13 +2,14 @@ import { ChatInputCommandInteraction } from 'discord.js'; import { Logger } from 'pino'; import loggerModule from '../services/logger'; import { ExtendedClient } from '../types/clientTypes'; -import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator'; import { BaseSlashCommandInteraction } from '../types/interactionTypes'; +import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator'; export const handleCommand = async ( interaction: ChatInputCommandInteraction, client: ExtendedClient, - executionId: string + executionId: string, + interactionIdentifier: string ) => { const logger: Logger = loggerModule.child({ source: 'interactionCommandHandler.ts', @@ -20,19 +21,18 @@ export const handleCommand = async ( await interaction.deferReply(); logger.debug('Interaction deferred.'); - // TODO: Update TS Type for command - const command: BaseSlashCommandInteraction = client.commands!.get( - interaction.commandName - ) as BaseSlashCommandInteraction; - if (!command) { - logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); - return; - } - if (await cannotSendMessageInChannel({ interaction, executionId })) { return; } - logger.debug('Executing command interaction.'); - await command.execute({ interaction, client, executionId }); + const slashCommand: BaseSlashCommandInteraction = client.slashCommandInteractions!.get( + interactionIdentifier + ) as BaseSlashCommandInteraction; + if (!slashCommand) { + logger.warn(`Interaction created but slash command '${interactionIdentifier}' was not found.`); + return; + } + + logger.debug(`Executing slash command interaction '${interactionIdentifier}'.`); + await slashCommand.execute({ interaction, client, executionId }); }; diff --git a/src/handlers/interactionComponentHandler.ts b/src/handlers/interactionComponentHandler.ts index 55fb172..34ff9e5 100644 --- a/src/handlers/interactionComponentHandler.ts +++ b/src/handlers/interactionComponentHandler.ts @@ -1,9 +1,16 @@ import { MessageComponentInteraction } from 'discord.js'; import { Logger } from 'pino'; import loggerModule from '../services/logger'; +import { ExtendedClient } from '../types/clientTypes'; +import { BaseComponentInteraction } from '../types/interactionTypes'; import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator'; -export const handleComponent = async (interaction: MessageComponentInteraction, executionId: string) => { +export const handleComponent = async ( + interaction: MessageComponentInteraction, + client: ExtendedClient, + executionId: string, + interactionIdentifier: string +) => { const logger: Logger = loggerModule.child({ source: 'interactionComponentHandler.js', module: 'handler', @@ -14,19 +21,23 @@ export const handleComponent = async (interaction: MessageComponentInteraction, await interaction.deferReply(); logger.debug('Interaction deferred.'); - const componentId: string = interaction.customId.split('_')[0]; - const referenceId: string = interaction.customId.split('_')[1]; + const componentId: string = interactionIdentifier.split('_')[0]; + const referenceId: string = interactionIdentifier.split('_')[1]; - logger.debug(`Parsed componentId: ${componentId}`); + logger.debug(`Parsed componentId '${componentId}' from identifier '${interactionIdentifier}'.`); if (await cannotSendMessageInChannel({ interaction, executionId })) { return; } - // TODO: Create TS Type for component - const componentModule = await import(`../interactions/components/${componentId}.js`); - const { default: component } = componentModule; + const component: BaseComponentInteraction = client.componentInteractions!.get( + componentId + ) as BaseComponentInteraction; + if (!component) { + logger.warn(`Interaction created but component '${componentId}' was not found.`); + return; + } - logger.debug('Executing component interaction.'); + logger.debug(`Executing component interaction '${componentId}'.`); await component.execute({ interaction, referenceId, executionId }); }; diff --git a/src/handlers/interactionErrorHandler.ts b/src/handlers/interactionErrorHandler.ts index 3f02b5c..b3def55 100644 --- a/src/handlers/interactionErrorHandler.ts +++ b/src/handlers/interactionErrorHandler.ts @@ -1,5 +1,11 @@ import config from 'config'; -import { ChatInputCommandInteraction, EmbedBuilder, Interaction, InteractionReplyOptions, MessageComponentInteraction } from 'discord.js'; +import { + ChatInputCommandInteraction, + EmbedBuilder, + Interaction, + InteractionReplyOptions, + MessageComponentInteraction +} from 'discord.js'; import { Logger } from 'pino'; import loggerModule from '../services/logger'; import { BotOptions, EmbedOptions } from '../types/configTypes'; @@ -12,8 +18,8 @@ const botOptions: BotOptions = config.get('botOptions'); export const handleError = async ( interaction: Interaction, error: CustomError, - interactionIdentifier: string, - executionId: string + executionId: string, + interactionIdentifier: string ) => { const logger: Logger = loggerModule.child({ source: 'interactionErrorHandler.ts', diff --git a/src/interactions/commands/info/help.ts b/src/interactions/commands/info/help.ts index d8801f3..2a6d22a 100644 --- a/src/interactions/commands/info/help.ts +++ b/src/interactions/commands/info/help.ts @@ -18,7 +18,7 @@ class HelpCommand extends BaseSlashCommandInteraction { const logger = this.getLogger(this.name, executionId, interaction); const commandList = client! - .commands!.filter((command: BaseSlashCommandInteraction) => { + .slashCommandInteractions!.filter((command: BaseSlashCommandInteraction) => { // don't include system commands if (command.isSystemCommand) { return false; diff --git a/src/interactions/commands/player/skip.ts b/src/interactions/commands/player/skip.ts index 34f1c97..1bf00c3 100644 --- a/src/interactions/commands/player/skip.ts +++ b/src/interactions/commands/player/skip.ts @@ -11,7 +11,7 @@ import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validat class SkipCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() - .setName('test') + .setName('skip') .setDescription('Skip track to next or specified position in queue.') .addNumberOption((option) => option.setName('tracknumber').setDescription('The position in queue to skip to.').setMinValue(1) diff --git a/src/interactions/commands/system/reload.ts b/src/interactions/commands/system/reload.ts index eb4ed5f..7170792 100644 --- a/src/interactions/commands/system/reload.ts +++ b/src/interactions/commands/system/reload.ts @@ -29,7 +29,7 @@ class ReloadCommand extends BaseSlashCommandInteraction { await client! .shard!.broadcastEval( async (shardClient: ExtendedClient, { executionId }) => { - shardClient.registerClientCommands!({ client: shardClient, executionId }); + shardClient.registerClientInteractions!({ client: shardClient, executionId }); }, { context: { executionId: executionId } } ) @@ -53,7 +53,7 @@ class ReloadCommand extends BaseSlashCommandInteraction { }); } - const commands: string[] | undefined = client!.commands?.map((command: BaseSlashCommandInteraction) => { + const commands: string[] | undefined = client!.slashCommandInteractions?.map((command: BaseSlashCommandInteraction) => { let params: string = ''; if (command.data.options && command.data.options.length > 1) { diff --git a/src/types/clientTypes.ts b/src/types/clientTypes.ts index 606a614..cd2a1b0 100644 --- a/src/types/clientTypes.ts +++ b/src/types/clientTypes.ts @@ -1,9 +1,11 @@ import { Client, Collection } from 'discord.js'; -import { BaseSlashCommandInteraction } from './interactionTypes'; +import { BaseAutocompleteInteraction, BaseComponentInteraction, BaseSlashCommandInteraction } from './interactionTypes'; -type RegisterClientCommandsFunction = (params: { client: Client; executionId: string }) => void; +type RegisterClientInteractionsFunction = (params: { client: Client; executionId: string }) => void; export interface ExtendedClient extends Client { - registerClientCommands?: RegisterClientCommandsFunction; - commands?: Collection; + registerClientInteractions?: RegisterClientInteractionsFunction; + slashCommandInteractions?: Collection; + autocompleteInteractions?: Collection; + componentInteractions?: Collection; } diff --git a/src/types/utilTypes.ts b/src/types/utilTypes.ts index 86e5eb0..3ea3e2f 100644 --- a/src/types/utilTypes.ts +++ b/src/types/utilTypes.ts @@ -9,7 +9,7 @@ export interface RegisterEventListenersParams { executionId: string; } -export interface RegisterClientCommandsParams { +export interface RegisterClientInteractionsParams { client: ExtendedClient; executionId: string; } diff --git a/src/utils/registerClientCommands.ts b/src/utils/registerClientCommands.ts deleted file mode 100644 index cee2ed5..0000000 --- a/src/utils/registerClientCommands.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Collection } from 'discord.js'; -import fs from 'node:fs'; -import path from 'node:path'; - -import loggerModule from '../services/logger'; -import { RegisterClientCommandsParams } from '../types/utilTypes'; -import { Logger } from 'pino'; - -export const registerClientCommands = async ({ client, executionId }: RegisterClientCommandsParams) => { - const logger: Logger = loggerModule.child({ - source: 'registerClientCommands.js', - module: 'register', - name: 'registerClientCommands', - executionId: executionId, - shardId: client.shard?.ids[0] - }); - - logger.debug('Registering client commands...'); - client.commands = new Collection(); - - const commandFolders: string[] = fs.readdirSync(path.resolve('./dist/interactions/commands')); - for (const folder of commandFolders) { - logger.trace(`Registering client commands for folder '${folder}'...`); - - const commandFiles: string[] = fs - .readdirSync(path.resolve(`./dist/interactions/commands/${folder}`)) - .filter((file) => file.endsWith('.js')); - - for (const file of commandFiles) { - try { - // delete command from require cache - delete require.cache[require.resolve(`../interactions/commands/${folder}/${file}`)]; - - // load command and register it to client.commands collection - const { default: command } = await import(`../interactions/commands/${folder}/${file}`); - client.commands.delete(command.data.name); - client.commands.set(command.data.name, command); - } catch (error) { - if (error instanceof Error) { - logger.error(`Error registering command ${folder}/${file}: ${error.message}`); - } else { - throw error; - } - } - } - } - - logger.trace('Registering client commands complete.'); -}; diff --git a/src/utils/registerClientInteractions.ts b/src/utils/registerClientInteractions.ts new file mode 100644 index 0000000..2a95b54 --- /dev/null +++ b/src/utils/registerClientInteractions.ts @@ -0,0 +1,124 @@ +import { Collection } from 'discord.js'; +import fs from 'node:fs'; +import path from 'node:path'; + +import loggerModule from '../services/logger'; +import { RegisterClientInteractionsParams } from '../types/utilTypes'; +import { Logger } from 'pino'; +import { ExtendedClient } from '../types/clientTypes'; + +export const registerClientInteractions = async ({ client, executionId }: RegisterClientInteractionsParams) => { + const logger: Logger = loggerModule.child({ + source: 'registerClientInteractions.js', + module: 'register', + name: 'registerClientInteractions', + executionId: executionId, + shardId: client.shard?.ids[0] + }); + + await registerSlashCommandInteractions(logger, client); + await registerAutocompleteInteractions(logger, client); + await registerComponentInteractions(logger, client); + + logger.debug('Registering all client interactions complete.'); +}; + +async function registerSlashCommandInteractions(logger: Logger, client: ExtendedClient) { + logger.debug('Registering client slash command interactions...'); + client.slashCommandInteractions = new Collection(); + + const baseFolderPath = './dist/interactions/commands'; + const slashCommandInteractionFolders: string[] = fs.readdirSync(path.resolve(baseFolderPath)); + + for (const categoryFolder of slashCommandInteractionFolders) { + logger.trace(`Registering client commands for folder '${categoryFolder}'...`); + + const files: string[] = fs + .readdirSync(path.resolve(`${baseFolderPath}/${categoryFolder}`)) + .filter((file) => file.endsWith('.js')); + + for (const file of files) { + try { + const filePath = path.resolve(`${baseFolderPath}/${categoryFolder}/${file}`); + + // delete require cache for file + delete require.cache[filePath]; + + // import and register to client collection + const { default: slashCommandInteraction } = await import(filePath); + client.slashCommandInteractions.delete(slashCommandInteraction.name); + client.slashCommandInteractions.set(slashCommandInteraction.name, slashCommandInteraction); + } catch (error) { + if (error instanceof Error) { + logger.error( + `Error registering slash command interaction '${categoryFolder}/${file}': ${error.message}` + ); + } else { + throw error; + } + } + } + } + + logger.trace('Registering client slash command interactions complete.'); +} + +async function registerAutocompleteInteractions(logger: Logger, client: ExtendedClient) { + logger.debug('Registering client autocomplete interactions...'); + client.autocompleteInteractions = new Collection(); + + const baseFolderPath = './dist/interactions/autocomplete'; + const files: string[] = fs.readdirSync(path.resolve(`${baseFolderPath}`)).filter((file) => file.endsWith('.js')); + + for (const file of files) { + try { + const filePath = path.resolve(`${baseFolderPath}/${file}`); + + // delete require cache for file + delete require.cache[filePath]; + + // import and register to client collection + const { default: autocompleteInteraction } = await import(filePath); + client.autocompleteInteractions.delete(autocompleteInteraction.name); + client.autocompleteInteractions.set(autocompleteInteraction.name, autocompleteInteraction); + } catch (error) { + if (error instanceof Error) { + logger.error(`Error registering autocomplete interaction '${file}': ${error.message}`); + } else { + throw error; + } + } + } + + logger.trace('Registering client autocomplete interactions complete.'); +} + +async function registerComponentInteractions(logger: Logger, client: ExtendedClient) { + logger.debug('Registering client component interactions...'); + client.componentInteractions = new Collection(); + + const baseFolderPath = './dist/interactions/components'; + const files: string[] = fs.readdirSync(path.resolve(`${baseFolderPath}`)).filter((file) => file.endsWith('.js')); + + for (const file of files) { + try { + const filePath = path.resolve(`${baseFolderPath}/${file}`); + + // delete require cache for file + delete require.cache[filePath]; + + // import and register to client collection + const { default: componentInteraction } = await import(filePath); + client.componentInteractions.delete(componentInteraction.name); + client.componentInteractions.set(componentInteraction.name, componentInteraction); + } catch (error) { + if (error instanceof Error) { + logger.error(`Error registering component interaction '${file}': ${error.message}`); + } else { + throw error; + } + } + } + + logger.trace('Registering client component interactions complete.'); +}