From 1ec1281e985d2e34a0822f01d4d6f841f86a00e3 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 13:44:30 +0200 Subject: [PATCH] feat!: Extract logic for autocomplete and component interactions --- .gitattributes | 1 + src/bot.ts | 30 +- src/events/interactions/interactionCreate.ts | 368 ++++++++++++------ src/interactions/autocomplete/lyrics.ts | 78 ++++ src/interactions/autocomplete/play.ts | 68 ++++ src/interactions/commands/info/help.ts | 9 +- src/interactions/commands/info/status.ts | 9 +- src/interactions/commands/player/filters.ts | 9 +- src/interactions/commands/player/leave.ts | 9 +- src/interactions/commands/player/loop.ts | 15 +- src/interactions/commands/player/lyrics.ts | 69 +--- .../commands/player/nowplaying.ts | 12 +- src/interactions/commands/player/pause.ts | 9 +- src/interactions/commands/player/play.ts | 61 +-- src/interactions/commands/player/queue.ts | 9 +- src/interactions/commands/player/remove.ts | 9 +- src/interactions/commands/player/seek.ts | 9 +- src/interactions/commands/player/shuffle.ts | 9 +- src/interactions/commands/player/skip.ts | 9 +- src/interactions/commands/player/stop.ts | 9 +- src/interactions/commands/player/volume.ts | 9 +- src/interactions/commands/system/guilds.ts | 9 +- src/interactions/commands/system/reload.ts | 9 +- src/interactions/commands/system/shards.ts | 9 +- .../commands/system/systemstatus.ts | 8 +- .../components/nowplaying-skip-button.ts | 184 ++++----- src/types/commandTypes.ts | 38 -- src/types/interactionTypes.ts | 58 ++- src/utils/registerClientCommands.ts | 11 +- 29 files changed, 694 insertions(+), 442 deletions(-) create mode 100644 src/interactions/autocomplete/lyrics.ts create mode 100644 src/interactions/autocomplete/play.ts delete mode 100644 src/types/commandTypes.ts diff --git a/.gitattributes b/.gitattributes index 0c42f3c..4530571 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ * text=auto eol=crlf +*.js linguist-language=TypeScript diff --git a/src/bot.ts b/src/bot.ts index 6d6acd9..948d967 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -20,17 +20,19 @@ const logger = loggerModule.child({ }); (async () => { - const client: ExtendedClient = await createClient({ executionId }); - const player = await createPlayer({ client, executionId }); - - client.on('allShardsReady', async () => { - client.registerClientCommands = registerClientCommands; - await registerEventListeners({ client, player, executionId }); - await registerClientCommands({ client, executionId }); - client.emit('ready', client as Client); - }); - - client.login(process.env.DISCORD_BOT_TOKEN); -})().catch((error) => { - logger.error(error); -}); + try { + const client: ExtendedClient = await createClient({ executionId }); + const player = await createPlayer({ client, executionId }); + + client.on('allShardsReady', async () => { + client.registerClientCommands = registerClientCommands; + await registerEventListeners({ client, player, executionId }); + await registerClientCommands({ 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 a3a846b..5dd5f50 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -1,5 +1,7 @@ import config from 'config'; import { + AutocompleteInteraction, + ChatInputCommandInteraction, EmbedBuilder, Events, Interaction, @@ -37,136 +39,276 @@ module.exports = { const componentId = interaction.customId.split('_')[0]; const trackId = interaction.customId.split('_')[1]; const componentModule = await import(`../../interactions/components/${componentId}.js`); - componentModule.execute({ interaction, trackId, executionId }); + await componentModule.execute({ interaction, trackId, executionId }); }; - switch (interactionType) { - case InteractionType.ApplicationCommand: - interactionString = 'ApplicationCommand'; - break; - case InteractionType.MessageComponent: - interactionString = 'MessageComponent'; - handleComponent(interaction as MessageComponentInteraction); + const handleAutocomplete = async (interaction: AutocompleteInteraction) => { + //const command = client.commands?.get(interaction.commandName) as Command; + const autocompleteModule = await import(`../../interactions/autocomplete/${interaction.commandName}.js`); + const { default: autocomplete } = autocompleteModule; + await autocomplete.execute({ interaction, executionId }); + }; - break; - case InteractionType.ApplicationCommandAutocomplete: - interactionString = 'ApplicationCommandAutocomplete'; - break; - default: - interactionString = 'Unknown'; - break; - } - - logger.debug(`Interaction of type '${interactionString}' created.`); - - // TODO: separate slash commands and autocomplete into separate files - // /src/interactions/commands and /src/interactions/autocomplete - if (interaction.isChatInputCommand() || interaction.isAutocomplete()) { + const handleCommand = async (interaction: ChatInputCommandInteraction) => { const command = client.commands?.get(interaction.commandName) as Command; + if (!command) { + logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); + return; + } - if (interaction.isChatInputCommand()) { - if (!command) { - logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); - return; - } - logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`); - try { - await interaction.deferReply(); + logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`); + //try { + await interaction.deferReply(); - if (await cannotSendMessageInChannel({ interaction, executionId })) { - return; - } + if (await cannotSendMessageInChannel({ interaction, executionId })) { + return; + } - const inputTime: number = new Date().getTime(); + const inputTime: number = new Date().getTime(); - await command.execute({ interaction, client, executionId }); + await command.execute({ interaction, client, executionId }); - const outputTime: number = new Date().getTime(); - const executionTime: number = outputTime - inputTime; + /* doesnt work because need to find subfolder + /* Update registerClientCommands to registerClientInteractions + /* Add client.interactions with { commandInteractions, componentInteractions, autocompleteInteractions + const commandModule = await import(`../../interactions/commands/SUBFOLDER/${interaction.commandName}.js`); + const { default: command } = commandModule; + await command.execute({ interaction, client, executionId }); + */ - logger.info(`Command '${interaction}' executed in ${executionTime} ms.`); - } catch (error) { - if (error instanceof Error) { - logger.warn( - error, - `Command '${interaction}' throwed an unhandled error and might have failed to execute properly.` - ); + const outputTime: number = new Date().getTime(); + const executionTime: number = outputTime - inputTime; - if ( - error.message === 'Unknown interaction' || - error.message === 'Interaction has already been acknowledged.' - ) { - logger.debug( - 'Command failed to be responded to, unknown interaction or already acknowledged.' - ); - return; - } else { - if (!interaction.deferred || !interaction.replied) { - logger.warn('Interaction was not deferred or replied to, and an error was thrown.'); - return; - } + logger.info(`Command '${interaction}' executed in ${executionTime} ms.`); + /* + } catch (error) { + if (error instanceof Error) { + logger.warn( + error, + `Command '${interaction}' throwed an unhandled error and might have failed to execute properly.` + ); - if (interaction.replied) { - // If the interaction has already been replied to, most likely command executed successfully or error is already handled. - return; - } else if (interaction.deferred) { - logger.info('Interaction was deferred, editing reply and sending Uh-oh message.'); - await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); - } else { - logger.info( - 'Interaction was not deferred or replied, sending new reply with Uh-oh message.' - ); - await interaction.reply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); - } - } - } else { - throw error; - } - } - } else if (interaction.isAutocomplete()) { - logger.debug('Autocomplete interaction created.'); - try { - command?.autocomplete && (await command?.autocomplete({ interaction, executionId })); - } catch (error) { - if (error instanceof Error) { - if ( - error.message === 'Unknown interaction' || - error.message === 'Interaction has already been acknowledged.' - ) { - logger.debug( - 'Autocomplete failed to be responded to, unknown interaction or already acknowledged.' - ); - return; - } else { - logger.warn(error, 'Autocomplete failed to execute.'); - } + if ( + error.message === 'Unknown interaction' || + error.message === 'Interaction has already been acknowledged.' + ) { + logger.debug('Command failed to be responded to, unknown interaction or already acknowledged.'); return; } else { - throw error; + if (!interaction.deferred || !interaction.replied) { + logger.warn('Interaction was not deferred or replied to, and an error was thrown.'); + return; + } + + if (interaction.replied) { + // If the interaction has already been replied to, most likely command executed successfully or error is already handled. + return; + } else if (interaction.deferred) { + logger.info('Interaction was deferred, editing reply and sending Uh-oh message.'); + await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }); + } else { + logger.info( + 'Interaction was not deferred or replied, sending new reply with Uh-oh message.' + ); + await interaction.reply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }); + } } + } else { + throw error; } } - } else { - logger.warn('Interaction created but was not a chat input or autocomplete interaction.'); - logger.trace(interaction); + */ + }; + + try { + switch (interactionType) { + case InteractionType.ApplicationCommand: + interactionString = 'ApplicationCommand'; + handleCommand(interaction as ChatInputCommandInteraction); + break; + + case InteractionType.ApplicationCommandAutocomplete: + interactionString = 'ApplicationCommandAutocomplete'; + handleAutocomplete(interaction as AutocompleteInteraction); + break; + + case InteractionType.MessageComponent: + interactionString = 'MessageComponent'; + handleComponent(interaction as MessageComponentInteraction); + break; + + default: + interactionString = 'Unknown'; + break; + } + + logger.debug(`Interaction of type '${interactionString}' created.`); + } catch (error) { + logger.error(error, `Error handling interaction of type '${interactionString}'`); + + const errorReply = { + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }; + + const handleErrorWithReplyToUser = async (interaction: Interaction, error: Error) => { + logger.error(error, `Error handling interaction of type '${interactionString}'`); + if (interaction.channel) { + // Send message to user in channel where interaction was made + logger.debug(`Sending error reply to channel '${interaction.channel.id}'.`); + await interaction.channel.send(errorReply); + } else { + // Send message to user in DMs + logger.debug(`Sending error reply to user '${interaction.user.id}'.`); + await interaction.user.send(errorReply); + } + }; + + switch (true) { + case interaction instanceof ChatInputCommandInteraction: + await handleErrorWithReplyToUser(interaction, error as Error); + break; + case interaction instanceof AutocompleteInteraction: + await handleErrorWithReplyToUser(interaction, error as Error); + break; + case interaction instanceof MessageComponentInteraction: + await handleErrorWithReplyToUser(interaction, error as Error); + break; + default: + // Something else went wrong + logger.error(error, 'Unhandled error while handling unkown interaction.'); + break; + } } + + /* + if (interaction.isAutocomplete()) { + + try { + command?.autocomplete && (await command?.autocomplete({ interaction, executionId })); + } catch (error) { + if (error instanceof Error) { + if ( + error.message === 'Unknown interaction' || + error.message === 'Interaction has already been acknowledged.' + ) { + logger.debug( + 'Autocomplete failed to be responded to, unknown interaction or already acknowledged.' + ); + return; + } else { + logger.warn(error, 'Autocomplete failed to execute.'); + } + return; + } else { + throw error; + } + } + } + */ + + /* + if (interaction.isChatInputCommand()) { + const command = client.commands?.get(interaction.commandName) as Command; + if (!command) { + logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); + return; + } + logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`); + try { + await interaction.deferReply(); + + if (await cannotSendMessageInChannel({ interaction, executionId })) { + return; + } + + const inputTime: number = new Date().getTime(); + + await command.execute({ interaction, client, executionId }); + + const outputTime: number = new Date().getTime(); + const executionTime: number = outputTime - inputTime; + + logger.info(`Command '${interaction}' executed in ${executionTime} ms.`); + } catch (error) { + if (error instanceof Error) { + logger.warn( + error, + `Command '${interaction}' throwed an unhandled error and might have failed to execute properly.` + ); + + if ( + error.message === 'Unknown interaction' || + error.message === 'Interaction has already been acknowledged.' + ) { + logger.debug('Command failed to be responded to, unknown interaction or already acknowledged.'); + return; + } else { + if (!interaction.deferred || !interaction.replied) { + logger.warn('Interaction was not deferred or replied to, and an error was thrown.'); + return; + } + + if (interaction.replied) { + // If the interaction has already been replied to, most likely command executed successfully or error is already handled. + return; + } else if (interaction.deferred) { + logger.info('Interaction was deferred, editing reply and sending Uh-oh message.'); + await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }); + } else { + logger.info( + 'Interaction was not deferred or replied, sending new reply with Uh-oh message.' + ); + await interaction.reply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }); + } + } + } else { + throw error; + } + } + } + */ } }; diff --git a/src/interactions/autocomplete/lyrics.ts b/src/interactions/autocomplete/lyrics.ts new file mode 100644 index 0000000..6ce99e9 --- /dev/null +++ b/src/interactions/autocomplete/lyrics.ts @@ -0,0 +1,78 @@ +import { useMainPlayer } from 'discord-player'; +import loggerModule from '../../services/logger'; +import { CustomAutocompleteInteraction } from '../../types/interactionTypes'; +import { lyricsExtractor } from '@discord-player/extractor'; + +const loggerTemplate = loggerModule.child({ + source: 'lyrics.js', + module: 'slashCommand', + name: '/lyrics' +}); + +const recentQueries = new Map(); + +const autocomplete: CustomAutocompleteInteraction = { + execute: async ({ interaction, executionId }) => { + // TODO: Extract autocomplete logic + const logger = loggerTemplate.child({ + executionId: executionId, + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id + }); + + const query = interaction.options.getString('query', true); + + const { lastQuery, result, timestamp } = recentQueries.get(interaction.user.id) || {}; + + if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) { + logger.debug(`Responding with results from lastQuery for query '${query}'`); + return interaction.respond(result); + } + + if (query.length < 3) { + logger.debug(`Responding with empty results due to < 3 length for query '${query}'`); + return interaction.respond([]); + } + + const genius = lyricsExtractor(); + const lyricsResult = await genius.search(query).catch(() => null); + let response = []; + + if (!lyricsResult) { + logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`); + const player = useMainPlayer()!; + const searchResults = await player.search(query); + response = searchResults.tracks.slice(0, 1).map((track) => ({ + name: + `${track.title} [Artist: ${track.author}]`.length > 100 + ? `${track.title}`.slice(0, 100) + : `${track.title} [Artist: ${track.author}]`, + value: track.title.slice(0, 100) + })); + } else { + logger.debug(`Found Genius lyrics for query '${query}'.`); + response = [ + { + name: `${lyricsResult.title} [Artist: ${lyricsResult.artist.name}]`.slice(0, 100), + value: lyricsResult.title.slice(0, 100) + } + ]; + } + + if (!response || response.length === 0) { + logger.debug(`Responding with empty results for query '${query}'`); + return interaction.respond([]); + } + + recentQueries.set(interaction.user.id, { + lastQuery: query, + result: response, + timestamp: Date.now() + }); + + logger.debug(`Responding to autocomplete with results for query: '${query}'.`); + return interaction.respond(response); + } +}; + +export default autocomplete; diff --git a/src/interactions/autocomplete/play.ts b/src/interactions/autocomplete/play.ts new file mode 100644 index 0000000..4f501d8 --- /dev/null +++ b/src/interactions/autocomplete/play.ts @@ -0,0 +1,68 @@ +import { useMainPlayer } from 'discord-player'; +import loggerModule from '../../services/logger'; +import { CustomAutocompleteInteraction } from '../../types/interactionTypes'; + +const loggerTemplate = loggerModule.child({ + source: 'play.js', + module: 'slashCommand', + name: '/play' +}); + +const recentQueries = new Map(); + +const autocomplete: CustomAutocompleteInteraction = { + execute: async ({ interaction, executionId }) => { + const logger = loggerTemplate.child({ + executionId: executionId, + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id + }); + + const player = useMainPlayer()!; + const query = interaction.options.getString('query', true); + + const { lastQuery, results, timestamp } = recentQueries.get(interaction.user.id) || {}; + + if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) { + logger.debug(`Responding with results from lastQuery for query '${query}'`); + return interaction.respond(results); + } + + if (query.length < 3) { + logger.debug(`Responding with empty results due to < 3 length for query '${query}'`); + return interaction.respond([]); + } + const searchResults = await player.search(query); + + let response = []; + + response = searchResults.tracks.slice(0, 5).map((track) => { + if (track.url.length > 100) { + track.url = track.title.slice(0, 100); + } + return { + name: + `${track.title} [Author: ${track.author}]`.length > 100 + ? `${track.title}`.slice(0, 100) + : `${track.title} [Author: ${track.author}]`, + value: track.url + }; + }); + + recentQueries.set(interaction.user.id, { + lastQuery: query, + results: response, + timestamp: Date.now() + }); + + if (!response || response.length === 0) { + logger.debug(`Responding with empty results for query '${query}'`); + return interaction.respond([]); + } + + logger.debug(`Responding to autocomplete with results for query: '${query}'.`); + return interaction.respond(response); + } +}; + +export default autocomplete; diff --git a/src/interactions/commands/info/help.ts b/src/interactions/commands/info/help.ts index 693c21b..5caedc7 100644 --- a/src/interactions/commands/info/help.ts +++ b/src/interactions/commands/info/help.ts @@ -2,12 +2,13 @@ import config from 'config'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { BotOptions, EmbedOptions } from '../../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -15,7 +16,7 @@ module.exports = { .setDescription('Show a list of commands and their usage.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }: CommandParams) => { + execute: async ({ interaction, client, executionId }) => { const logger = loggerModule.child({ source: 'help.js', module: 'slashCommand', @@ -69,3 +70,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/info/status.ts b/src/interactions/commands/info/status.ts index 619cff7..68022a7 100644 --- a/src/interactions/commands/info/status.ts +++ b/src/interactions/commands/info/status.ts @@ -5,12 +5,13 @@ import osu from 'node-os-utils'; // @ts-ignore import { version } from '../../../../package.json'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -18,7 +19,7 @@ module.exports = { .setDescription('Show the bot and system status.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }: CommandParams) => { + execute: async ({ interaction, client, executionId }) => { const logger = loggerModule.child({ source: 'status.js', module: 'slashCommand', @@ -133,3 +134,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/filters.ts b/src/interactions/commands/player/filters.ts index 454dbb4..1d632d8 100644 --- a/src/interactions/commands/player/filters.ts +++ b/src/interactions/commands/player/filters.ts @@ -15,14 +15,15 @@ import { } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams, CustomError } from '../../../types/commandTypes'; +import { CustomError, CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -30,7 +31,7 @@ module.exports = { .setDescription('Toggle various audio filters during playback.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'filters.js', module: 'slashCommand', @@ -237,3 +238,5 @@ module.exports = { } } }; + +export default command; diff --git a/src/interactions/commands/player/leave.ts b/src/interactions/commands/player/leave.ts index 894a0df..a4bab4e 100644 --- a/src/interactions/commands/player/leave.ts +++ b/src/interactions/commands/player/leave.ts @@ -3,12 +3,13 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -16,7 +17,7 @@ module.exports = { .setDescription('Clear the track queue and remove the bot from voice channel.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'leave.js', module: 'slashCommand', @@ -80,3 +81,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/loop.ts b/src/interactions/commands/player/loop.ts index 3f6a42d..46528b7 100644 --- a/src/interactions/commands/player/loop.ts +++ b/src/interactions/commands/player/loop.ts @@ -1,16 +1,17 @@ import config from 'config'; import { NodeResolvable, useQueue } from 'discord-player'; -import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; +import { EmbedBuilder, GuildMember, SlashCommandBuilder, SlashCommandStringOption } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { BotOptions, EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -18,8 +19,8 @@ module.exports = { .setDescription('Toggle looping a track, the whole queue or autoplay.') .setDMPermission(false) .setNSFW(false) - .addStringOption((option) => - option + .addStringOption(() => + new SlashCommandStringOption() .setName('mode') .setDescription('Mode to set for looping.') .setRequired(false) @@ -30,7 +31,7 @@ module.exports = { { name: 'Disabled', value: '0' } ) ), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'loop.js', module: 'slashCommand', @@ -184,3 +185,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/lyrics.ts b/src/interactions/commands/player/lyrics.ts index 4f90ec1..f8b99f3 100644 --- a/src/interactions/commands/player/lyrics.ts +++ b/src/interactions/commands/player/lyrics.ts @@ -5,13 +5,12 @@ import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { lyricsExtractor } from '@discord-player/extractor'; import loggerModule from '../../../services/logger'; -import { CommandAutocompleteParams, CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const recentQueries = new Map(); const loggerTemplate = loggerModule.child({ source: 'lyrics.js', @@ -19,7 +18,7 @@ const loggerTemplate = loggerModule.child({ name: '/lyrics' }); -module.exports = { +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -36,67 +35,7 @@ module.exports = { .setMaxLength(500) .setAutocomplete(true) ), - autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => { - const logger = loggerTemplate.child({ - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); - - const query = interaction.options.getString('query', true); - - const { lastQuery, result, timestamp } = recentQueries.get(interaction.user.id) || {}; - - if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) { - logger.debug(`Responding with results from lastQuery for query '${query}'`); - return interaction.respond(result); - } - - if (query.length < 3) { - logger.debug(`Responding with empty results due to < 3 length for query '${query}'`); - return interaction.respond([]); - } - - const genius = lyricsExtractor(); - const lyricsResult = await genius.search(query).catch(() => null); - let response = []; - - if (!lyricsResult) { - logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`); - const player = useMainPlayer()!; - const searchResults = await player.search(query); - response = searchResults.tracks.slice(0, 1).map((track) => ({ - name: - `${track.title} [Artist: ${track.author}]`.length > 100 - ? `${track.title}`.slice(0, 100) - : `${track.title} [Artist: ${track.author}]`, - value: track.title.slice(0, 100) - })); - } else { - logger.debug(`Found Genius lyrics for query '${query}'.`); - response = [ - { - name: `${lyricsResult.title} [Artist: ${lyricsResult.artist.name}]`.slice(0, 100), - value: lyricsResult.title.slice(0, 100) - } - ]; - } - - if (!response || response.length === 0) { - logger.debug(`Responding with empty results for query '${query}'`); - return interaction.respond([]); - } - - recentQueries.set(interaction.user.id, { - lastQuery: query, - result: response, - timestamp: Date.now() - }); - - logger.debug(`Responding to autocomplete with results for query: '${query}'.`); - return interaction.respond(response); - }, - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerTemplate.child({ executionId: executionId, shardId: interaction.guild?.shardId, @@ -267,3 +206,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/nowplaying.ts b/src/interactions/commands/player/nowplaying.ts index 9154b1d..e456db7 100644 --- a/src/interactions/commands/player/nowplaying.ts +++ b/src/interactions/commands/player/nowplaying.ts @@ -11,7 +11,7 @@ import { } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams, TrackMetadata } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction, TrackMetadata } from '../../../types/interactionTypes'; import { EmbedOptions, PlayerOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; @@ -19,7 +19,7 @@ import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validat const embedOptions: EmbedOptions = config.get('embedOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); -module.exports = { +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -27,7 +27,7 @@ module.exports = { .setDescription('Show information about the track currently playing.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'nowplaying.js', module: 'slashCommand', @@ -136,7 +136,7 @@ module.exports = { logger.debug('Successfully retrieved information about the current track.'); logger.debug('Sending info embed with action row components.'); - await interaction.editReply({ + return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ @@ -185,7 +185,7 @@ module.exports = { ], components: [nowPlayingActionRow as APIActionRowComponent] }); - - logger.debug('Finished sending response.'); } }; + +export default command; diff --git a/src/interactions/commands/player/pause.ts b/src/interactions/commands/player/pause.ts index 0b8c484..3c014cf 100644 --- a/src/interactions/commands/player/pause.ts +++ b/src/interactions/commands/player/pause.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -17,7 +18,7 @@ module.exports = { .setDescription('Pause or resume the current track.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'pause.js', module: 'slashCommand', @@ -87,3 +88,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/play.ts b/src/interactions/commands/player/play.ts index 53ac4d5..5c4bb75 100644 --- a/src/interactions/commands/player/play.ts +++ b/src/interactions/commands/player/play.ts @@ -3,7 +3,7 @@ import { useMainPlayer, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandAutocompleteParams, CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { BotOptions, EmbedOptions, PlayerOptions } from '../../../types/configTypes'; import { cannotJoinVoiceOrTalk } from '../../../utils/validation/permissionValidator'; import { transformQuery } from '../../../utils/validation/searchQueryValidator'; @@ -12,7 +12,6 @@ import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validat const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); -const recentQueries = new Map(); const loggerTemplate = loggerModule.child({ source: 'play.js', @@ -20,7 +19,7 @@ const loggerTemplate = loggerModule.child({ name: '/play' }); -module.exports = { +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -37,59 +36,7 @@ module.exports = { .setMaxLength(500) .setAutocomplete(true) ), - autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => { - const logger = loggerTemplate.child({ - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); - - const player = useMainPlayer()!; - const query = interaction.options.getString('query', true); - - const { lastQuery, results, timestamp } = recentQueries.get(interaction.user.id) || {}; - - if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) { - logger.debug(`Responding with results from lastQuery for query '${query}'`); - return interaction.respond(results); - } - - if (query.length < 3) { - logger.debug(`Responding with empty results due to < 3 length for query '${query}'`); - return interaction.respond([]); - } - const searchResults = await player.search(query); - - let response = []; - - response = searchResults.tracks.slice(0, 5).map((track) => { - if (track.url.length > 100) { - track.url = track.title.slice(0, 100); - } - return { - name: - `${track.title} [Author: ${track.author}]`.length > 100 - ? `${track.title}`.slice(0, 100) - : `${track.title} [Author: ${track.author}]`, - value: track.url - }; - }); - - recentQueries.set(interaction.user.id, { - lastQuery: query, - results: response, - timestamp: Date.now() - }); - - if (!response || response.length === 0) { - logger.debug(`Responding with empty results for query '${query}'`); - return interaction.respond([]); - } - - logger.debug(`Responding to autocomplete with results for query: '${query}'.`); - return interaction.respond(response); - }, - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerTemplate.child({ executionId: executionId, shardId: interaction.guild?.shardId, @@ -411,3 +358,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/queue.ts b/src/interactions/commands/player/queue.ts index 62a3896..8b27b7d 100644 --- a/src/interactions/commands/player/queue.ts +++ b/src/interactions/commands/player/queue.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions, PlayerOptions } from '../../../types/configTypes'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -18,7 +19,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false) .addNumberOption((option) => option.setName('page').setDescription('Page number of the queue').setMinValue(1)), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'queue.js', module: 'slashCommand', @@ -207,3 +208,5 @@ module.exports = { } } }; + +export default command; diff --git a/src/interactions/commands/player/remove.ts b/src/interactions/commands/player/remove.ts index 511e448..1e3275c 100644 --- a/src/interactions/commands/player/remove.ts +++ b/src/interactions/commands/player/remove.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -24,7 +25,7 @@ module.exports = { .setMinValue(1) .setRequired(true) ), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'remove.js', module: 'slashCommand', @@ -104,3 +105,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/seek.ts b/src/interactions/commands/player/seek.ts index b88198e..cf3e6ec 100644 --- a/src/interactions/commands/player/seek.ts +++ b/src/interactions/commands/player/seek.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -23,7 +24,7 @@ module.exports = { .setDescription('Duration in format 00:00:00 (HH:mm:ss) to seek to.') .setRequired(true) ), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'seek.js', module: 'slashCommand', @@ -186,3 +187,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/shuffle.ts b/src/interactions/commands/player/shuffle.ts index 82a9dd8..81e4027 100644 --- a/src/interactions/commands/player/shuffle.ts +++ b/src/interactions/commands/player/shuffle.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueIsEmpty } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -17,7 +18,7 @@ module.exports = { .setDescription('Shuffle tracks in the queue randomly.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'shuffle.js', module: 'slashCommand', @@ -72,3 +73,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/skip.ts b/src/interactions/commands/player/skip.ts index a284b26..ffd4664 100644 --- a/src/interactions/commands/player/skip.ts +++ b/src/interactions/commands/player/skip.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -20,7 +21,7 @@ module.exports = { .addNumberOption((option) => option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1) ), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'skip.js', module: 'slashCommand', @@ -181,3 +182,5 @@ module.exports = { } } }; + +export default command; diff --git a/src/interactions/commands/player/stop.ts b/src/interactions/commands/player/stop.ts index f5e3564..dcc2cb8 100644 --- a/src/interactions/commands/player/stop.ts +++ b/src/interactions/commands/player/stop.ts @@ -3,12 +3,13 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -16,7 +17,7 @@ module.exports = { .setDescription('Stop playing audio and clear the track queue.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'stop.js', module: 'slashCommand', @@ -82,3 +83,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/volume.ts b/src/interactions/commands/player/volume.ts index 6cb9cc3..88e2b98 100644 --- a/src/interactions/commands/player/volume.ts +++ b/src/interactions/commands/player/volume.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -24,7 +25,7 @@ module.exports = { .setMinValue(0) .setMaxValue(100) ), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'volume.js', module: 'slashCommand', @@ -126,3 +127,5 @@ module.exports = { } } }; + +export default command; diff --git a/src/interactions/commands/system/guilds.ts b/src/interactions/commands/system/guilds.ts index 292bfda..1f5609f 100644 --- a/src/interactions/commands/system/guilds.ts +++ b/src/interactions/commands/system/guilds.ts @@ -2,12 +2,13 @@ import config from 'config'; import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isSystemCommand: true, isNew: false, isBeta: false, @@ -16,7 +17,7 @@ module.exports = { .setDescription('Show list of guilds where bot is added.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }: CommandParams) => { + execute: async ({ interaction, client, executionId }) => { const logger = loggerModule.child({ source: 'guilds.js', module: 'slashCommand', @@ -86,3 +87,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/system/reload.ts b/src/interactions/commands/system/reload.ts index d3ac0c4..551eb63 100644 --- a/src/interactions/commands/system/reload.ts +++ b/src/interactions/commands/system/reload.ts @@ -3,12 +3,13 @@ import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; import { ExtendedClient } from '../../../types/clientTypes'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isSystemCommand: true, isNew: false, isBeta: false, @@ -17,7 +18,7 @@ module.exports = { .setDescription('Reload the bot commands.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }: CommandParams) => { + execute: async ({ interaction, client, executionId }) => { const logger = loggerModule.child({ source: 'reload.js', module: 'slashCommand', @@ -82,3 +83,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/system/shards.ts b/src/interactions/commands/system/shards.ts index efc9204..56a894c 100644 --- a/src/interactions/commands/system/shards.ts +++ b/src/interactions/commands/system/shards.ts @@ -3,12 +3,13 @@ import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; import { ExtendedClient } from '../../../types/clientTypes'; -import { CommandParams, ShardInfo } from '../../../types/commandTypes'; +import { ShardInfo, CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isSystemCommand: true, isNew: false, isBeta: false, @@ -34,7 +35,7 @@ module.exports = { ) .addNumberOption((option) => option.setName('page').setDescription('Page number to show').setMinValue(1)), - execute: async ({ interaction, client, executionId }: CommandParams) => { + execute: async ({ interaction, client, executionId }) => { const logger = loggerModule.child({ source: 'shards.js', module: 'slashCommand', @@ -198,3 +199,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/system/systemstatus.ts b/src/interactions/commands/system/systemstatus.ts index c1d957c..fe32b4e 100644 --- a/src/interactions/commands/system/systemstatus.ts +++ b/src/interactions/commands/system/systemstatus.ts @@ -5,14 +5,14 @@ import osu from 'node-os-utils'; // @ts-ignore import { dependencies, version } from '../../../../package.json'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { +const command: CustomSlashCommandInteraction = { isSystemCommand: true, isNew: false, isBeta: false, @@ -21,7 +21,7 @@ module.exports = { .setDescription('Show the bot and system status.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }: CommandParams) => { + execute: async ({ interaction, client, executionId }) => { const logger = loggerModule.child({ source: 'systemstatus.js', module: 'slashCommand', @@ -171,3 +171,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/components/nowplaying-skip-button.ts b/src/interactions/components/nowplaying-skip-button.ts index 7b2c489..9b5ecc0 100644 --- a/src/interactions/components/nowplaying-skip-button.ts +++ b/src/interactions/components/nowplaying-skip-button.ts @@ -4,108 +4,112 @@ import { EmbedBuilder, GuildMember } from 'discord.js'; import loggerModule from '../../services/logger'; import { EmbedOptions } from '../../types/configTypes'; -import { ComponentInteractionParams } from '../../types/interactionTypes'; +import { CustomComponentInteraction } from '../../types/interactionTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -export const execute = async ({ interaction, trackId, executionId }: ComponentInteractionParams) => { - const logger = loggerModule.child({ - source: 'nowplaying-skip.js', - module: 'componentInteraction', - name: 'nowplaying-skip', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); +const component: CustomComponentInteraction = { + execute: async ({ interaction, trackId, executionId }) => { + const logger = loggerModule.child({ + source: 'nowplaying-skip.js', + module: 'componentInteraction', + name: 'nowplaying-skip', + executionId: executionId, + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id + }); - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; - logger.debug(`Received skip confirmation for track id ${trackId}.`); - if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { - logger.debug('Tried skipping track but there was no queue.'); + logger.debug(`Received skip confirmation for track id ${trackId}.`); + if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { + logger.debug('Tried skipping track but there was no queue.'); - logger.debug('Responding with warning embed.'); + logger.debug('Responding with warning embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + ) + .setColor(embedOptions.colors.warning) + ], + components: [] + }); + } + + if (queue.currentTrack!.id !== trackId) { + logger.debug('Tried skipping track but it is not the current track and therefore already skipped/removed.'); + + logger.debug('Responding with warning embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.` + ) + .setColor(embedOptions.colors.warning) + ], + components: [] + }); + } + + const skippedTrack = queue.currentTrack!; + let durationFormat = + Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00' + ? '' + : `\`${skippedTrack.duration}\``; + + if (skippedTrack.raw.live) { + durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; + } + queue.node.skip(); + logger.debug('Skipped the track.'); + + const loopModesFormatted = new Map([ + [0, 'disabled'], + [1, 'track'], + [2, 'queue'], + [3, 'autoplay'] + ]); + + const repeatModeUserString = loopModesFormatted.get(queue.repeatMode); + + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() + .setAuthor({ + name: authorName, + iconURL: interaction.user.avatarURL() || '' + }) .setDescription( - `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${ + skippedTrack.raw.url ?? skippedTrack.url + })**` + + `${ + queue.repeatMode === 0 + ? '' + : `\n\n**${ + queue.repeatMode === 3 + ? embedOptions.icons.autoplaying + : embedOptions.icons.looping + } Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.` + }` ) - .setColor(embedOptions.colors.warning) + .setThumbnail(skippedTrack.thumbnail) + .setColor(embedOptions.colors.success) ], components: [] }); } - - if (queue.currentTrack!.id !== trackId) { - logger.debug('Tried skipping track but it is not the current track and therefore already skipped/removed.'); - - logger.debug('Responding with warning embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.` - ) - .setColor(embedOptions.colors.warning) - ], - components: [] - }); - } - - const skippedTrack = queue.currentTrack!; - let durationFormat = - Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00' - ? '' - : `\`${skippedTrack.duration}\``; - - if (skippedTrack.raw.live) { - durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; - } - queue.node.skip(); - logger.debug('Skipped the track.'); - - const loopModesFormatted = new Map([ - [0, 'disabled'], - [1, 'track'], - [2, 'queue'], - [3, 'autoplay'] - ]); - - const repeatModeUserString = loopModesFormatted.get(queue.repeatMode); - - let authorName: string; - - if (interaction.member instanceof GuildMember) { - authorName = interaction.member.nickname || interaction.user.username; - } else { - authorName = interaction.user.username; - } - - logger.debug('Responding with success embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setAuthor({ - name: authorName, - iconURL: interaction.user.avatarURL() || '' - }) - .setDescription( - `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${ - skippedTrack.raw.url ?? skippedTrack.url - })**` + - `${ - queue.repeatMode === 0 - ? '' - : `\n\n**${ - queue.repeatMode === 3 - ? embedOptions.icons.autoplaying - : embedOptions.icons.looping - } Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.` - }` - ) - .setThumbnail(skippedTrack.thumbnail) - .setColor(embedOptions.colors.success) - ], - components: [] - }); }; + +export default component; diff --git a/src/types/commandTypes.ts b/src/types/commandTypes.ts deleted file mode 100644 index d5a1316..0000000 --- a/src/types/commandTypes.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { AutocompleteInteraction, ChatInputCommandInteraction } from 'discord.js'; - -import { ExtendedClient } from './clientTypes'; - -export interface CommandParams { - interaction: ChatInputCommandInteraction; - client: ExtendedClient | undefined; - executionId: string; -} - -export interface CommandAutocompleteParams { - interaction: AutocompleteInteraction; - client: ExtendedClient | undefined; - executionId: string; -} - -export interface ShardInfo { - shardId: number; - memUsage: number; - guildCount: number; - guildMemberCount: number; - playerStatistics: { - activeVoiceConnections: number; - totalTracks: number; - totalListeners: number; - }; -} - -export interface TrackMetadata { - bridge: { - views: number; - }; -} - -export class CustomError extends Error { - type?: string; - code?: string; -} diff --git a/src/types/interactionTypes.ts b/src/types/interactionTypes.ts index 7aa72a7..2f1c59e 100644 --- a/src/types/interactionTypes.ts +++ b/src/types/interactionTypes.ts @@ -1,7 +1,61 @@ -import { MessageComponentInteraction } from 'discord.js'; +import { AutocompleteInteraction, ChatInputCommandInteraction, Message, MessageComponentInteraction, SlashCommandBuilder } from 'discord.js'; +import { ExtendedClient } from './clientTypes'; -export interface ComponentInteractionParams { +// Local types +interface CommandParams { + client?: ExtendedClient; + executionId: string; + interaction: ChatInputCommandInteraction; +} + +interface AutocompleteParams { + executionId: string; + interaction: AutocompleteInteraction; +} + +interface ComponentParams { interaction: MessageComponentInteraction; trackId?: string; executionId: string; } + +// Interaction types +export interface CustomSlashCommandInteraction { + isNew: boolean; + isBeta: boolean; + isSystemCommand?: boolean; + data: Omit; + execute(params: CommandParams): Promise | undefined>; +} + +export interface CustomAutocompleteInteraction { + execute(params: AutocompleteParams): Promise; +} + +export interface CustomComponentInteraction { + execute(params: ComponentParams): Promise | undefined>; +} + +// Command specific types +export interface ShardInfo { + shardId: number; + memUsage: number; + guildCount: number; + guildMemberCount: number; + playerStatistics: { + activeVoiceConnections: number; + totalTracks: number; + totalListeners: number; + }; +} + +export interface TrackMetadata { + bridge: { + views: number; + }; +} + +export class CustomError extends Error { + type?: string; + code?: string; +} diff --git a/src/utils/registerClientCommands.ts b/src/utils/registerClientCommands.ts index ef16c69..fcaa279 100644 --- a/src/utils/registerClientCommands.ts +++ b/src/utils/registerClientCommands.ts @@ -5,7 +5,7 @@ import path from 'node:path'; import loggerModule from '../services/logger'; import { RegisterClientCommandsParams } from '../types/utilTypes'; -export const registerClientCommands = ({ client, executionId }: RegisterClientCommandsParams) => { +export const registerClientCommands = async ({ client, executionId }: RegisterClientCommandsParams) => { const logger = loggerModule.child({ source: 'registerClientCommands.js', module: 'register', @@ -30,10 +30,11 @@ export const registerClientCommands = ({ client, executionId }: RegisterClientCo delete require.cache[require.resolve(`../interactions/commands/${folder}/${file}`)]; // register command - /* eslint-disable @typescript-eslint/no-var-requires */ - const command = require(`../interactions/commands/${folder}/${file}`); - client.commands.delete(command.data.name); - client.commands.set(command.data.name, command); + //const command = require(`../interactions/commands/${folder}/${file}`); + const commandModule = await import(`../interactions/commands/${folder}/${file}`); + + client.commands.delete(commandModule.default.data.name); + client.commands.set(commandModule.default.data.name, commandModule.default); } catch (error) { if (error instanceof Error) { logger.error(`Error registering command ${folder}/${file}: ${error.message}`);