From b96a73df6f2e143d00310ba0532353baf60acc01 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Wed, 30 Aug 2023 21:47:50 +0200 Subject: [PATCH] Add class for interactions --- src/bot.ts | 10 +- src/events/interactions/interactionCreate.ts | 23 ++- .../interactionAutocompleteHandler.ts | 23 ++- src/handlers/interactionCommandHandler.ts | 25 +-- src/handlers/interactionComponentHandler.ts | 27 +++- src/handlers/interactionErrorHandler.ts | 12 +- src/interactions/autocomplete/lyrics.ts | 34 ++-- src/interactions/autocomplete/play.ts | 33 ++-- src/interactions/commands/info/help.ts | 78 +++++---- src/interactions/commands/info/status.ts | 50 +++--- src/interactions/commands/player/filters.ts | 47 +++--- src/interactions/commands/player/leave.ts | 48 +++--- src/interactions/commands/player/loop.ts | 97 +++++------ src/interactions/commands/player/lyrics.ts | 85 +++++----- .../commands/player/nowplaying.ts | 69 ++++---- src/interactions/commands/player/pause.ts | 49 +++--- src/interactions/commands/player/play.ts | 115 ++++++------- src/interactions/commands/player/queue.ts | 67 ++++---- src/interactions/commands/player/remove.ts | 72 ++++----- src/interactions/commands/player/seek.ts | 76 ++++----- src/interactions/commands/player/shuffle.ts | 48 +++--- src/interactions/commands/player/skip.ts | 76 ++++----- src/interactions/commands/player/stop.ts | 48 +++--- src/interactions/commands/player/volume.ts | 78 +++++---- src/interactions/commands/system/guilds.ts | 52 +++--- src/interactions/commands/system/reload.ts | 70 ++++---- src/interactions/commands/system/shards.ts | 97 ++++++----- .../commands/system/systemstatus.ts | 56 +++---- .../components/filters-disable-button.ts | 35 ++-- .../components/filters-select-menu.ts | 33 ++-- .../components/nowplaying-skip-button.ts | 56 +++---- src/types/clientTypes.ts | 24 +-- src/types/interactionTypes.ts | 152 +++++++++++++----- src/types/utilTypes.ts | 2 +- src/utils/deploySlashCommands.ts | 9 +- src/utils/registerClientCommands.ts | 50 ------ src/utils/registerClientInteractions.ts | 124 ++++++++++++++ 37 files changed, 1038 insertions(+), 1012 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 8efb713..e7ddb4a 100644 --- a/src/handlers/interactionCommandHandler.ts +++ b/src/handlers/interactionCommandHandler.ts @@ -1,13 +1,15 @@ import { ChatInputCommandInteraction } from 'discord.js'; import { Logger } from 'pino'; import loggerModule from '../services/logger'; -import { Command, ExtendedClient } from '../types/clientTypes'; +import { ExtendedClient } from '../types/clientTypes'; +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', @@ -19,17 +21,18 @@ export const handleCommand = async ( await interaction.deferReply(); logger.debug('Interaction deferred.'); - // TODO: Update TS Type for command - const command: Command = client.commands?.get(interaction.commandName) as Command; - 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/autocomplete/lyrics.ts b/src/interactions/autocomplete/lyrics.ts index 208090a..ae2c12b 100644 --- a/src/interactions/autocomplete/lyrics.ts +++ b/src/interactions/autocomplete/lyrics.ts @@ -1,29 +1,25 @@ import { LyricsData, lyricsExtractor } from '@discord-player/extractor'; import { Player, SearchResult, useMainPlayer } from 'discord-player'; import { ApplicationCommandOptionChoiceData } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; -import { CustomAutocompleteInteraction } from '../../types/interactionTypes'; - -const loggerTemplate: Logger = loggerModule.child({ - source: 'lyrics.js', - module: 'autocompleteInteraction', - name: '/lyrics' -}); +import { + BaseAutocompleteInteraction, + BaseAutocompleteParams, + BaseAutocompleteReturnType +} from '../../types/interactionTypes'; // TODO: create interface for recent query object const recentQueries = new Map(); -const autocomplete: CustomAutocompleteInteraction = { - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerTemplate.child({ - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); +class LyricsAutocomplete extends BaseAutocompleteInteraction { + constructor() { + super('lyrics'); + } + + async execute(params: BaseAutocompleteParams): BaseAutocompleteReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const query: string = 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) { @@ -76,6 +72,6 @@ const autocomplete: CustomAutocompleteInteraction = { logger.debug(`Responding to autocomplete with results for query: '${query}'.`); return interaction.respond(response); } -}; +} -export default autocomplete; +export default new LyricsAutocomplete(); diff --git a/src/interactions/autocomplete/play.ts b/src/interactions/autocomplete/play.ts index c0f7a4b..0b34fee 100644 --- a/src/interactions/autocomplete/play.ts +++ b/src/interactions/autocomplete/play.ts @@ -1,25 +1,22 @@ import { Player, SearchResult, useMainPlayer } from 'discord-player'; import { ApplicationCommandOptionChoiceData } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; -import { CustomAutocompleteInteraction } from '../../types/interactionTypes'; - -const loggerTemplate: Logger = loggerModule.child({ - source: 'play.js', - module: 'autocompleteInteraction', - name: '/play' -}); +import { + BaseAutocompleteInteraction, + BaseAutocompleteParams, + BaseAutocompleteReturnType +} from '../../types/interactionTypes'; // TODO: create interface for recent query object const recentQueries = new Map(); -const autocomplete: CustomAutocompleteInteraction = { - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerTemplate.child({ - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); +class PlayAutocomplete extends BaseAutocompleteInteraction { + constructor() { + super('play'); + } + + async execute(params: BaseAutocompleteParams): BaseAutocompleteReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const player: Player = useMainPlayer()!; const query: string = interaction.options.getString('query', true); @@ -66,6 +63,6 @@ const autocomplete: CustomAutocompleteInteraction = { logger.debug(`Responding to autocomplete with results for query: '${query}'.`); return interaction.respond(response); } -}; +} -export default autocomplete; +export default new PlayAutocomplete(); diff --git a/src/interactions/commands/info/help.ts b/src/interactions/commands/info/help.ts index 7751a0f..2a6d22a 100644 --- a/src/interactions/commands/info/help.ts +++ b/src/interactions/commands/info/help.ts @@ -1,54 +1,52 @@ -import config from 'config'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; -import { BotOptions, EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { EmbedBuilder, SlashCommandBuilder, SlashCommandNumberOption, SlashCommandStringOption } from 'discord.js'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -const botOptions: BotOptions = config.get('botOptions'); +class HelpCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('help') + .setDescription('Show the list of bot commands.'); + super(data); + } -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('help') - .setDescription('Show a list of commands and their usage.') - .setDMPermission(false) - .setNSFW(false), - execute: async ({ interaction, client, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'help.js', - module: 'slashCommand', - name: '/help', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, client, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); - // TODO: Create interface for command list - const commandList = client!.commands! - .filter((command) => { + const commandList = client! + .slashCommandInteractions!.filter((command: BaseSlashCommandInteraction) => { // don't include system commands if (command.isSystemCommand) { return false; } return true; }) - .map((command) => { - const params: string = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : ''; - const beta: string = command.isBeta ? `${embedOptions.icons.beta} ` : ''; - const newCommand: string = command.isNew ? `${embedOptions.icons.new} ` : ''; + .map((command: BaseSlashCommandInteraction) => { + let params: string = ''; + const option = command.data.options[0]; + if (option instanceof SlashCommandNumberOption || option instanceof SlashCommandStringOption) { + params = `**\`${option.name}\`**` + ' '; + } + const beta: string = command.isBeta ? `${this.embedOptions.icons.beta} ` : ''; + const newCommand: string = command.isNew ? `${this.embedOptions.icons.new} ` : ''; return `- **\`/${command.data.name}\`** ${params}- ${beta}${newCommand}${command.data.description}`; }); const commandListString: string = commandList.join('\n'); - const supportServerString: string = botOptions.serverInviteUrl - ? `${embedOptions.icons.support} **Support server**\nJoin the support server for help or to suggest improvements: \n**${botOptions.serverInviteUrl}**\n\n` + const supportServerString: string = this.botOptions.serverInviteUrl + ? `${this.embedOptions.icons.support} **Support server**\n` + + 'Join the support server for help or to suggest improvements: \n' + + `**${this.botOptions.serverInviteUrl}**\n\n` : ''; - const addBotString: string = botOptions.botInviteUrl - ? `${embedOptions.icons.bot} **Enjoying ${botOptions.name}?**\nAdd me to another server: \n**[Click me!](${botOptions.botInviteUrl})**` + const addBotString: string = this.botOptions.botInviteUrl + ? `${this.embedOptions.icons.bot} **Enjoying ${this.botOptions.name}?**\n` + + 'Add me to another server: \n' + + `**[Click me!](${this.botOptions.botInviteUrl})**` : ''; logger.debug('Responding with info embed.'); @@ -56,15 +54,15 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `${embedOptions.icons.rule} **List of commands**\n` + + `${this.embedOptions.icons.rule} **List of commands**\n` + `${commandListString}\n\n` + supportServerString + addBotString ) - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) ] }); } -}; +} -export default command; +export default new HelpCommand(); diff --git a/src/interactions/commands/info/status.ts b/src/interactions/commands/info/status.ts index a0362ac..d4830a2 100644 --- a/src/interactions/commands/info/status.ts +++ b/src/interactions/commands/info/status.ts @@ -1,33 +1,23 @@ -import config from 'config'; import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; import osu from 'node-os-utils'; -import { Logger } from 'pino'; // @ts-ignore import { version } from '../../../../package.json'; -import loggerModule from '../../../services/logger'; -import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class StatusCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder().setName('status').setDescription('Show operational status of the bot.'); + super(data); + } -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('status') - .setDescription('Show the bot and system status.') - .setDMPermission(false) - .setNSFW(false), - execute: async ({ interaction, client, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'status.js', - module: 'slashCommand', - name: '/status', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction, client } = params; + const logger = this.getLogger(this.name, executionId, interaction); const uptimeString: string = await getUptimeFormatted({ executionId }); const usedMemoryInMB: string = Math.ceil((await osu.mem.info()).usedMemMb).toLocaleString('en-US'); @@ -97,28 +87,28 @@ const command: CustomSlashCommandInteraction = { return await interaction.editReply({ embeds: [ new EmbedBuilder() - .setDescription(`**${embedOptions.icons.bot} Bot status**\n` + botStatusString) + .setDescription(`**${this.embedOptions.icons.bot} Bot status**\n` + botStatusString) .addFields( { - name: `**${embedOptions.icons.queue} Queue status**`, + name: `**${this.embedOptions.icons.queue} Queue status**`, value: queueStatusString, inline: false }, { - name: `**${embedOptions.icons.server} System status**`, + name: `**${this.embedOptions.icons.server} System status**`, value: systemStatusString, inline: false }, { - name: `**${embedOptions.icons.discord} Discord status**`, + name: `**${this.embedOptions.icons.discord} Discord status**`, value: discordStatusString, inline: false } ) - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) ] }); } -}; +} -export default command; +export default new StatusCommand(); diff --git a/src/interactions/commands/player/filters.ts b/src/interactions/commands/player/filters.ts index a44af2e..5380e53 100644 --- a/src/interactions/commands/player/filters.ts +++ b/src/interactions/commands/player/filters.ts @@ -13,33 +13,28 @@ import { StringSelectMenuBuilder, StringSelectMenuOptionBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; -import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { FFmpegFilterOption, FFmpegFilterOptions } from '../../../types/configTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; 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'); -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('filters') - .setDescription('Toggle various audio filters during playback.') - .setDMPermission(false) - .setNSFW(false), - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'filters.js', - module: 'slashCommand', - name: '/filters', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); +class FiltersCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('filters') + .setDescription('Toggle various audio filters.'); + super(data); + } + + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -92,7 +87,7 @@ const command: CustomSlashCommandInteraction = { .setCustomId('filters-disable-button') .setLabel('Disable all filters') .setStyle(ButtonStyle.Secondary) - .setEmoji(embedOptions.icons.disable) + .setEmoji(this.embedOptions.icons.disable) .toJSON(); const disableFiltersActionRow: APIActionRowComponent = { @@ -105,11 +100,11 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription('**Toggle filters**\nEnable or disable audio filters for playback from the menu.') - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) ], components: [filterActionRow, disableFiltersActionRow] }); } -}; +} -export default command; +export default new FiltersCommand(); diff --git a/src/interactions/commands/player/leave.ts b/src/interactions/commands/player/leave.ts index a6f6203..62303cb 100644 --- a/src/interactions/commands/player/leave.ts +++ b/src/interactions/commands/player/leave.ts @@ -1,32 +1,24 @@ -import config from 'config'; import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; -import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class LeaveCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('leave') + .setDescription('Clear the queue and remove bot from voice channel.'); + super(data); + } -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('leave') - .setDescription('Clear the track queue and remove the bot from voice channel.') - .setDMPermission(false) - .setNSFW(false), - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'leave.js', - module: 'slashCommand', - name: '/leave', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -61,15 +53,15 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.success} Leaving channel**\nCleared the track queue and left voice channel.\n\nTo play more music, use the **\`/play\`** command!` + `**${this.embedOptions.icons.success} Leaving channel**\nCleared the track queue and left voice channel.\n\nTo play more music, use the **\`/play\`** command!` ) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } -}; +} -export default command; +export default new LeaveCommand(); diff --git a/src/interactions/commands/player/loop.ts b/src/interactions/commands/player/loop.ts index 22c3265..92f32f7 100644 --- a/src/interactions/commands/player/loop.ts +++ b/src/interactions/commands/player/loop.ts @@ -1,45 +1,36 @@ -import config from 'config'; import { GuildQueue, QueueRepeatMode, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder, SlashCommandStringOption } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; -import { BotOptions, EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; 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'); +class LoopCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('loop') + .setDescription('Toggle looping a track, the whole queue or autoplay.') + .addStringOption(() => + new SlashCommandStringOption() + .setName('mode') + .setDescription('Loop mode: Track, queue, autoplay or disabled.') + .setRequired(false) + .addChoices( + { name: 'Track', value: '1' }, + { name: 'Queue', value: '2' }, + { name: 'Autoplay', value: '3' }, + { name: 'Disabled', value: '0' } + ) + ); + super(data); + } -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('loop') - .setDescription('Toggle looping a track, the whole queue or autoplay.') - .setDMPermission(false) - .setNSFW(false) - .addStringOption(() => - new SlashCommandStringOption() - .setName('mode') - .setDescription('Mode to set for looping.') - .setRequired(false) - .addChoices( - { name: 'Track', value: '1' }, - { name: 'Queue', value: '2' }, - { name: 'Autoplay', value: '3' }, - { name: 'Disabled', value: '0' } - ) - ), - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'loop.js', - module: 'slashCommand', - name: '/loop', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -77,10 +68,10 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setDescription( `**${ - currentMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop + currentMode === 3 ? this.embedOptions.icons.autoplay : this.embedOptions.icons.loop } Current loop mode**\nThe looping mode is currently set to **\`${currentModeUserString}\`**.` ) - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) ] }); } @@ -93,9 +84,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nLoop mode is already **\`${modeUserString}\`**.` + `**${this.embedOptions.icons.warning} Oops!**\nLoop mode is already **\`${modeUserString}\`**.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -114,9 +105,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.error} Uh-oh... Failed to change loop mode!**\nI tried to change the loop mode to **\`${modeUserString}\`**, but something went wrong.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect or the issue persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + `**${this.embedOptions.icons.error} Uh-oh... Failed to change loop mode!**\nI tried to change the loop mode to **\`${modeUserString}\`**, but something went wrong.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect or the issue persists, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._` ) - .setColor(embedOptions.colors.error) + .setColor(this.embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); @@ -140,12 +131,12 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.success} Loop mode disabled**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${currentModeUserString} will no longer play on repeat!` + `**${this.embedOptions.icons.success} Loop mode disabled**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${currentModeUserString} will no longer play on repeat!` ) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } @@ -159,12 +150,12 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.autoplaying} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nWhen the queue is empty, similar tracks will start playing!` + `**${this.embedOptions.icons.autoplaying} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nWhen the queue is empty, similar tracks will start playing!` ) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } @@ -177,15 +168,15 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.looping} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${modeUserString} will now play on repeat!` + `**${this.embedOptions.icons.looping} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${modeUserString} will now play on repeat!` ) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } -}; +} -export default command; +export default new LoopCommand(); diff --git a/src/interactions/commands/player/lyrics.ts b/src/interactions/commands/player/lyrics.ts index 9ddb013..0350e03 100644 --- a/src/interactions/commands/player/lyrics.ts +++ b/src/interactions/commands/player/lyrics.ts @@ -1,47 +1,34 @@ -import config from 'config'; +import { LyricsData, lyricsExtractor } from '@discord-player/extractor'; import { GuildQueue, Player, QueryType, useMainPlayer, useQueue } from 'discord-player'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; - -import { LyricsData, lyricsExtractor } from '@discord-player/extractor'; - -import loggerModule from '../../../services/logger'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; -import { EmbedOptions } from '../../../types/configTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; -import { Logger } from 'pino'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class LyricsCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('lyrics') + .setDescription('Search Genius lyrics for current or specified track.') + .addStringOption((option) => + option + .setName('query') + .setDescription('Search query by text or URL.') + .setRequired(false) + .setMinLength(2) + .setMaxLength(500) + .setAutocomplete(true) + ); + super(data); + } -const loggerTemplate: Logger = loggerModule.child({ - source: 'lyrics.js', - module: 'slashCommand', - name: '/lyrics' -}); - -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('lyrics') - .setDescription('Get lyrics from Genius for current or specified track.') - .setDMPermission(false) - .setNSFW(false) - .addStringOption((option) => - option - .setName('query') - .setDescription('Search query or URL.') - .setRequired(false) - .setMinLength(2) - .setMaxLength(500) - .setAutocomplete(true) - ), - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerTemplate.child({ - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const query: string = interaction.options.getString('query')!; const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -84,9 +71,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} No search results found**\nThere was no search results found for query **${query}**.` + `**${this.embedOptions.icons.warning} No search results found**\nThere was no search results found for query **${query}**.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -144,9 +131,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} No lyrics found**\nThere was no Genius lyrics found for track **${geniusSearchQuery}**.` + `**${this.embedOptions.icons.warning} No lyrics found**\nThere was no Genius lyrics found for track **${geniusSearchQuery}**.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -166,12 +153,12 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.queue} Showing lyrics**\n` + + `**${this.embedOptions.icons.queue} Showing lyrics**\n` + `**Track: [${lyricsResult.title}](${lyricsResult.url})**\n` + `**Artist: [${lyricsResult.artist.name}](${lyricsResult.artist.url})**` + `\n\n\`\`\`fix\n${message}\`\`\`` ) - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) ] }); continue; @@ -181,7 +168,7 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription(`\`\`\`fix\n${message}\`\`\``) - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) ] }); } @@ -195,15 +182,15 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.queue} Showing lyrics**\n` + + `**${this.embedOptions.icons.queue} Showing lyrics**\n` + `**Track: [${lyricsResult.title}](${lyricsResult.url})**\n` + `**Artist: [${lyricsResult.artist.name}](${lyricsResult.artist.url})**` + `\n\n\`\`\`fix\n${lyricsResult.lyrics}\`\`\`` ) - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) ] }); } -}; +} -export default command; +export default new LyricsCommand(); diff --git a/src/interactions/commands/player/nowplaying.ts b/src/interactions/commands/player/nowplaying.ts index 1527d71..cb46422 100644 --- a/src/interactions/commands/player/nowplaying.ts +++ b/src/interactions/commands/player/nowplaying.ts @@ -10,34 +10,29 @@ import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; - -import loggerModule from '../../../services/logger'; -import { CustomSlashCommandInteraction, TrackMetadata } from '../../../types/interactionTypes'; -import { EmbedOptions, PlayerOptions } from '../../../types/configTypes'; +import { PlayerOptions } from '../../../types/configTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType, + TrackMetadata +} from '../../../types/interactionTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; -import { Logger } from 'pino'; -const embedOptions: EmbedOptions = config.get('embedOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('nowplaying') - .setDescription('Show information about the track currently playing.') - .setDMPermission(false) - .setNSFW(false), - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'nowplaying.js', - module: 'slashCommand', - name: '/nowplaying', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); +class NowPlayingCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('nowplaying') + .setDescription('Show information about the current track.'); + super(data); + } + + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -64,11 +59,11 @@ const command: CustomSlashCommandInteraction = { ]); const sourceIcons: Map = new Map([ - ['youtube', embedOptions.icons.sourceYouTube], - ['soundcloud', embedOptions.icons.sourceSoundCloud], - ['spotify', embedOptions.icons.sourceSpotify], - ['apple_music', embedOptions.icons.sourceAppleMusic], - ['arbitrary', embedOptions.icons.sourceArbitrary] + ['youtube', this.embedOptions.icons.sourceYouTube], + ['soundcloud', this.embedOptions.icons.sourceSoundCloud], + ['spotify', this.embedOptions.icons.sourceSpotify], + ['apple_music', this.embedOptions.icons.sourceAppleMusic], + ['arbitrary', this.embedOptions.icons.sourceArbitrary] ]); const currentTrack: Track = queue.currentTrack!; @@ -106,7 +101,7 @@ const command: CustomSlashCommandInteraction = { } if (currentTrack.raw.live) { - bar = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`; + bar = `${this.embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`; } const customId: string = `nowplaying-skip-button_${currentTrack.id}`; @@ -116,7 +111,7 @@ const command: CustomSlashCommandInteraction = { .setCustomId(customId) .setLabel('Skip track') .setStyle(ButtonStyle.Secondary) - .setEmoji(embedOptions.icons.nextTrack) + .setEmoji(this.embedOptions.icons.nextTrack) .toJSON(); const nowPlayingActionRow: APIActionRowComponent = { @@ -141,12 +136,12 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`, - iconURL: interaction.guild!.iconURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.guild!.iconURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( (queue.node.isPaused() ? '**Currently Paused**\n' - : `**${embedOptions.icons.audioPlaying} Now Playing**\n`) + + : `**${this.embedOptions.icons.audioPlaying} Now Playing**\n`) + `**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**` + `\nRequested by: <@${currentTrack.requestedBy?.id}>` + `\n ${bar}\n\n` + @@ -154,7 +149,9 @@ const command: CustomSlashCommandInteraction = { queue.repeatMode === 0 ? '' : `**${ - queue.repeatMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop + queue.repeatMode === 3 + ? this.embedOptions.icons.autoplay + : this.embedOptions.icons.loop } Looping**\nLoop mode is set to **\`${loopModeUserString}\`**. You can change it with **\`/loop\`**.` }` ) @@ -181,11 +178,11 @@ const command: CustomSlashCommandInteraction = { text: queueLength ? `${queueLength} other tracks in the queue...` : ' ' }) .setThumbnail(queue.currentTrack!.thumbnail) - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) ], components: [nowPlayingActionRow as APIActionRowComponent] }); } -}; +} -export default command; +export default new NowPlayingCommand(); diff --git a/src/interactions/commands/player/pause.ts b/src/interactions/commands/player/pause.ts index cb440f6..0ff6c73 100644 --- a/src/interactions/commands/player/pause.ts +++ b/src/interactions/commands/player/pause.ts @@ -1,32 +1,23 @@ -import config from 'config'; import { GuildQueue, Track, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; -import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; + +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class PauseCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder().setName('pause').setDescription('Toggle pause for the current track.'); + super(data); + } -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('pause') - .setDescription('Pause or resume the current track.') - .setDMPermission(false) - .setNSFW(false), - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'pause.js', - module: 'slashCommand', - name: '/pause', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -51,7 +42,7 @@ const command: CustomSlashCommandInteraction = { : `\`${currentTrack.duration}\``; if (currentTrack.raw.live) { - durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; + durationFormat = `${this.embedOptions.icons.liveTrack} \`LIVE\``; } // change paused state to opposite of current state @@ -72,18 +63,18 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.pauseResumed} ${ + `**${this.embedOptions.icons.pauseResumed} ${ queue.node.isPaused() ? 'Paused Track' : 'Resumed track' }**\n**${durationFormat} [${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**` ) .setThumbnail(currentTrack.thumbnail) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } -}; +} -export default command; +export default new PauseCommand(); diff --git a/src/interactions/commands/player/play.ts b/src/interactions/commands/player/play.ts index 59637a1..26f69df 100644 --- a/src/interactions/commands/player/play.ts +++ b/src/interactions/commands/player/play.ts @@ -1,48 +1,39 @@ import config from 'config'; import { GuildQueue, useMainPlayer, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; - -import loggerModule from '../../../services/logger'; -import { CustomError, CustomSlashCommandInteraction } from '../../../types/interactionTypes'; -import { BotOptions, EmbedOptions, PlayerOptions } from '../../../types/configTypes'; +import { PlayerOptions } from '../../../types/configTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType, + CustomError +} from '../../../types/interactionTypes'; import { cannotJoinVoiceOrTalk } from '../../../utils/validation/permissionValidator'; import { transformQuery } from '../../../utils/validation/searchQueryValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; -import { Logger } from 'pino'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -const botOptions: BotOptions = config.get('botOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); -const loggerTemplate: Logger = loggerModule.child({ - source: 'play.js', - module: 'slashCommand', - name: '/play' -}); +class PlayCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('play') + .setDescription('Add a track or playlist to the queue by search query or URL.') + .addStringOption((option) => + option + .setName('query') + .setDescription('Search query by text or URL') + .setRequired(true) + .setMinLength(2) + .setMaxLength(500) + .setAutocomplete(true) + ); + super(data); + } -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('play') - .setDescription('Add a track or playlist to the queue by searching or url.') - .setDMPermission(false) - .setNSFW(false) - .addStringOption((option) => - option - .setName('query') - .setDescription('Search query or URL.') - .setRequired(true) - .setMinLength(2) - .setMaxLength(500) - .setAutocomplete(true) - ), - execute: async ({ interaction, executionId }) => { - const logger = loggerTemplate.child({ - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); let queue: GuildQueue = useQueue(interaction.guild!.id)!; if (queue && (await notInSameVoiceChannel({ interaction, queue, executionId }))) { @@ -83,9 +74,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} No track found**\nNo results found for **\`${transformedQuery}\`**.\n\nIf you specified a URL, please make sure it is valid and public.` + `**${this.embedOptions.icons.warning} No track found**\nNo results found for **\`${transformedQuery}\`**.\n\nIf you specified a URL, please make sure it is valid and public.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -101,9 +92,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Playlist too large**\nThis playlist is too large to be added to the queue.\n\nThe maximum amount of tracks that can be added to the queue is **${playerOptions.maxQueueSize}**.` + `**${this.embedOptions.icons.warning} Playlist too large**\nThis playlist is too large to be added to the queue.\n\nThe maximum amount of tracks that can be added to the queue is **${playerOptions.maxQueueSize}**.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -145,9 +136,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Cannot retrieve audio for track**\nThis audio source is age restricted and requires login to access. Because of this I cannot retrieve the audio for the track.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + `**${this.embedOptions.icons.warning} Cannot retrieve audio for track**\nThis audio source is age restricted and requires login to access. Because of this I cannot retrieve the audio for the track.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -162,9 +153,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Cannot retrieve audio for track**\nThis audio source cannot be played as the video source has a warning for graphic or sensistive topics. It requires a manual confirmation to to play the video, and because of this I am unable to extract the audio for this source.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + `**${this.embedOptions.icons.warning} Cannot retrieve audio for track**\nThis audio source cannot be played as the video source has a warning for graphic or sensistive topics. It requires a manual confirmation to to play the video, and because of this I am unable to extract the audio for this source.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -183,9 +174,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nAfter finding a result, I was unable to retrieve audio for the track.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + `**${this.embedOptions.icons.error} Uh-oh... Failed to add track!**\nAfter finding a result, I was unable to retrieve audio for the track.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._` ) - .setColor(embedOptions.colors.error) + .setColor(this.embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); @@ -199,9 +190,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nSomething unexpected happened and the operation was cancelled.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + `**${this.embedOptions.icons.error} Uh-oh... Failed to add track!**\nSomething unexpected happened and the operation was cancelled.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._` ) - .setColor(embedOptions.colors.error) + .setColor(this.embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); @@ -225,9 +216,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nThere was an issue adding this track to the queue.\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})**._` + `**${this.embedOptions.icons.error} Uh-oh... Failed to add track!**\nThere was an issue adding this track to the queue.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._` ) - .setColor(embedOptions.colors.error) + .setColor(this.embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); @@ -243,14 +234,14 @@ const command: CustomSlashCommandInteraction = { logger.debug( `Track found but source is arbitrary or missing thumbnail. Using fallback thumbnail url. Query: '${query}'.` ); - track.thumbnail = embedOptions.info.fallbackThumbnailUrl; + track.thumbnail = this.embedOptions.info.fallbackThumbnailUrl; } let durationFormat = Number(track.raw.duration) === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``; if (track.raw.live) { - durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; + durationFormat = `${this.embedOptions.icons.liveTrack} \`LIVE\``; } if (searchResult.playlist && searchResult.tracks.length > 1) { @@ -270,17 +261,17 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.success} Added playlist to queue**\n**${durationFormat} [${ + `**${this.embedOptions.icons.success} Added playlist to queue**\n**${durationFormat} [${ track.title }](${track.raw.url ?? track.url})**\n\nAnd **${ searchResult.tracks.length - 1 }** more tracks... **\`/queue\`** to view all.` ) .setThumbnail(track.thumbnail) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } @@ -302,15 +293,15 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.audioStartedPlaying} Started playing**\n**${durationFormat} [${ + `**${this.embedOptions.icons.audioStartedPlaying} Started playing**\n**${durationFormat} [${ track.title }](${track.raw.url ?? track.url})**` ) .setThumbnail(track.thumbnail) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } @@ -331,18 +322,18 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `${embedOptions.icons.success} **Added to queue**\n**${durationFormat} [${track.title}](${ + `${this.embedOptions.icons.success} **Added to queue**\n**${durationFormat} [${track.title}](${ track.raw.url ?? track.url })**` ) .setThumbnail(track.thumbnail) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } -}; +} -export default command; +export default new PlayCommand(); diff --git a/src/interactions/commands/player/queue.ts b/src/interactions/commands/player/queue.ts index 846c154..95b83d7 100644 --- a/src/interactions/commands/player/queue.ts +++ b/src/interactions/commands/player/queue.ts @@ -1,34 +1,32 @@ import config from 'config'; import { GuildQueue, PlayerTimestamp, Track, useQueue } from 'discord-player'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; import { EmbedOptions, PlayerOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('queue') - .setDescription('Show the list of tracks added to the queue.') - .setDMPermission(false) - .setNSFW(false) - .addNumberOption((option) => option.setName('page').setDescription('Page number of the queue').setMinValue(1)), - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'queue.js', - module: 'slashCommand', - name: '/queue', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); +class QueueCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('queue') + .setDescription('Show tracks that have been added to the queue.') + .addNumberOption((option) => + option.setName('page').setDescription('Page number to display for the queue').setMinValue(1) + ); + super(data); + } + + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -58,11 +56,11 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nPage **\`${ + `**${this.embedOptions.icons.warning} Oops!**\nPage **\`${ pageIndex + 1 }\`** is not a valid page number.\n\nThere are only a total of **\`${totalPages}\`** pages in the queue.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -78,7 +76,7 @@ const command: CustomSlashCommandInteraction = { Number(track.raw.duration) === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``; if (track.raw.live) { - durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; + durationFormat = `${this.embedOptions.icons.liveTrack} \`LIVE\``; } return `**${pageIndex * 10 + index + 1}.** **${durationFormat} [${track.title}](${ @@ -116,15 +114,16 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`, - iconURL: interaction.guild!.iconURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.guild!.iconURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `${repeatModeString}` + `**${embedOptions.icons.queue} Tracks in queue**\n${queueString}` + `${repeatModeString}` + + `**${this.embedOptions.icons.queue} Tracks in queue**\n${queueString}` ) .setFooter({ text: `Page ${pageIndex + 1} of ${totalPages} (${queueLength} tracks)` }) - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) ] }); } else { @@ -144,7 +143,7 @@ const command: CustomSlashCommandInteraction = { } if (currentTrack.raw.live) { - bar = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`; + bar = `${this.embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`; } logger.debug('Responding with info embed.'); @@ -153,27 +152,27 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`, - iconURL: interaction.guild!.iconURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.guild!.iconURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.audioPlaying} Now playing**\n` + + `**${this.embedOptions.icons.audioPlaying} Now playing**\n` + (currentTrack ? `**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**` : 'None') + `\nRequested by: <@${currentTrack.requestedBy?.id}>` + `\n ${bar}\n\n` + `${repeatModeString}` + - `**${embedOptions.icons.queue} Tracks in queue**\n${queueString}` + `**${this.embedOptions.icons.queue} Tracks in queue**\n${queueString}` ) .setThumbnail(currentTrack.thumbnail) .setFooter({ text: `Page ${pageIndex + 1} of ${totalPages} (${queueLength} tracks)` }) - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) ] }); } } -}; +} -export default command; +export default new QueueCommand(); diff --git a/src/interactions/commands/player/remove.ts b/src/interactions/commands/player/remove.ts index e219376..b21a31c 100644 --- a/src/interactions/commands/player/remove.ts +++ b/src/interactions/commands/player/remove.ts @@ -1,39 +1,31 @@ -import config from 'config'; import { GuildQueue, Track, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; -import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class RemoveCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('remove') + .setDescription('Remove specified track from the queue') + .addNumberOption((option) => + option + .setName('tracknumber') + .setDescription('The position in queue for track to remove.') + .setMinValue(1) + .setRequired(true) + ); + super(data); + } -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('remove') - .setDescription('Remove a specific track from the queue.') - .setDMPermission(false) - .setNSFW(false) - .addNumberOption((option) => - option - .setName('tracknumber') - .setDescription('Track number to remove from queue.') - .setMinValue(1) - .setRequired(true) - ), - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'remove.js', - module: 'slashCommand', - name: '/remove', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -59,9 +51,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nTrack **\`${removeTrackNumber}\`** is not a valid track number. There are a total of **\`${queue.tracks.data.length}\`** tracks in the queue.\n\nView tracks added to the queue with **\`/queue\`**.` + `**${this.embedOptions.icons.warning} Oops!**\nTrack **\`${removeTrackNumber}\`** is not a valid track number. There are a total of **\`${queue.tracks.data.length}\`** tracks in the queue.\n\nView tracks added to the queue with **\`/queue\`**.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -75,7 +67,7 @@ const command: CustomSlashCommandInteraction = { : `\`${removedTrack.duration}\``; if (removedTrack.raw.live) { - durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; + durationFormat = `${this.embedOptions.icons.liveTrack} \`LIVE\``; } let authorName: string; @@ -92,18 +84,18 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${ - removedTrack.raw.url ?? removedTrack.url - })**` + `**${this.embedOptions.icons.success} Removed track**\n**${durationFormat} [${ + removedTrack.title + }](${removedTrack.raw.url ?? removedTrack.url})**` ) .setThumbnail(removedTrack.thumbnail) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } -}; +} -export default command; +export default new RemoveCommand(); diff --git a/src/interactions/commands/player/seek.ts b/src/interactions/commands/player/seek.ts index 690d404..c39651b 100644 --- a/src/interactions/commands/player/seek.ts +++ b/src/interactions/commands/player/seek.ts @@ -1,38 +1,30 @@ -import config from 'config'; import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; -import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class SeekCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('seek') + .setDescription('Seek to a duration in the current track.') + .addStringOption((option) => + option + .setName('duration') + .setDescription('Duration in format 00:00:00 (HH:mm:ss).') + .setRequired(true) + ); + super(data); + } -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('seek') - .setDescription('Seek to a specified duration in the current track.') - .setDMPermission(false) - .setNSFW(false) - .addStringOption((option) => - option - .setName('duration') - .setDescription('Duration in format 00:00:00 (HH:mm:ss) to seek to.') - .setRequired(true) - ), - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'seek.js', - module: 'slashCommand', - name: '/seek', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -78,12 +70,12 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` + + `**${this.embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` + '- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + '- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + '- **`/seek`** **`42`** - Seek to 42 seconds.' ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -100,12 +92,12 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` + + `**${this.embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` + '- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + '- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + '- **`/seek`** **`42`** - Seek to 42 seconds.' ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -123,12 +115,12 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` + + `**${this.embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` + '- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + '- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + '- **`/seek`** **`42`** - Seek to 42 seconds.' ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -146,12 +138,12 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setDescription( `**${ - embedOptions.icons.warning + this.embedOptions.icons.warning } Oops!**\nYou entered **\`${durationString}\`**, which is a duration that is longer than the duration for the current track.\n\nPlease try a duration that is less than the duration of the track (**\`${ queue.currentTrack!.duration }\`**).` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -173,16 +165,16 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.success} Seeking to duration**\nSeeking to **\`${durationString}\`** in current track.` + `**${this.embedOptions.icons.success} Seeking to duration**\nSeeking to **\`${durationString}\`** in current track.` ) .setThumbnail(queue.currentTrack!.thumbnail) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } -}; +} -export default command; +export default new SeekCommand(); diff --git a/src/interactions/commands/player/shuffle.ts b/src/interactions/commands/player/shuffle.ts index 722ede2..d870195 100644 --- a/src/interactions/commands/player/shuffle.ts +++ b/src/interactions/commands/player/shuffle.ts @@ -1,32 +1,24 @@ -import config from 'config'; import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; -import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { queueDoesNotExist, queueIsEmpty } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class ShuffleCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('shuffle') + .setDescription('Randomly shuffle all tracks in the queue.'); + super(data); + } -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('shuffle') - .setDescription('Shuffle tracks in the queue randomly.') - .setDMPermission(false) - .setNSFW(false), - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'shuffle.js', - module: 'slashCommand', - name: '/shuffle', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -60,15 +52,15 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.shuffled} Shuffled queue tracks**\nThe **${queue.tracks.data.length}** tracks in the queue has been shuffled.\n\nView the new queue order with **\`/queue\`**.` + `**${this.embedOptions.icons.shuffled} Shuffled queue tracks**\nThe **${queue.tracks.data.length}** tracks in the queue has been shuffled.\n\nView the new queue order with **\`/queue\`**.` ) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } -}; +} -export default command; +export default new ShuffleCommand(); diff --git a/src/interactions/commands/player/skip.ts b/src/interactions/commands/player/skip.ts index 9e9386d..1bf00c3 100644 --- a/src/interactions/commands/player/skip.ts +++ b/src/interactions/commands/player/skip.ts @@ -1,35 +1,27 @@ -import config from 'config'; import { GuildQueue, Track, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; -import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class SkipCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .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) + ); + super(data); + } -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('skip') - .setDescription('Skip current or specified track.') - .setDMPermission(false) - .setNSFW(false) - .addNumberOption((option) => - option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1) - ), - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'skip.js', - module: 'slashCommand', - name: '/skip', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -57,9 +49,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nThere are only **\`${queue.tracks.data.length}\`** tracks in the queue. You cannot skip to track **\`${skipToTrack}\`**.\n\nView tracks added to the queue with **\`/queue\`**.` + `**${this.embedOptions.icons.warning} Oops!**\nThere are only **\`${queue.tracks.data.length}\`** tracks in the queue. You cannot skip to track **\`${skipToTrack}\`**.\n\nView tracks added to the queue with **\`/queue\`**.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } else { @@ -72,7 +64,7 @@ const command: CustomSlashCommandInteraction = { : `\`${skippedTrack.duration}\``; if (skippedTrack.raw.live) { - durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; + durationFormat = `${this.embedOptions.icons.liveTrack} \`LIVE\``; } queue.node.skipTo(skipToTrack - 1); @@ -92,15 +84,15 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${ + `**${this.embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${ skippedTrack.title }](${skippedTrack.raw.url ?? skippedTrack.url})**` ) .setThumbnail(skippedTrack.thumbnail) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } @@ -113,9 +105,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + `**${this.embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } @@ -128,7 +120,7 @@ const command: CustomSlashCommandInteraction = { : `\`${skippedTrack.duration}\``; if (skippedTrack.raw.live) { - durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; + durationFormat = `${this.embedOptions.icons.liveTrack} \`LIVE\``; } queue.node.skip(); logger.debug('Skipped current track.'); @@ -156,10 +148,10 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${ + `**${this.embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${ skippedTrack.title }](${skippedTrack.raw.url ?? skippedTrack.url})**` + `${ @@ -167,17 +159,17 @@ const command: CustomSlashCommandInteraction = { ? '' : `\n\n**${ queue.repeatMode === 3 - ? embedOptions.icons.autoplaying - : embedOptions.icons.looping + ? this.embedOptions.icons.autoplaying + : this.embedOptions.icons.looping } Looping**\nLoop mode is set to **\`${loopModeUserString}\`**. You can change it with **\`/loop\`**.` }` ) .setThumbnail(skippedTrack.thumbnail) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } } -}; +} -export default command; +export default new SkipCommand(); diff --git a/src/interactions/commands/player/stop.ts b/src/interactions/commands/player/stop.ts index 5097f44..620d3fd 100644 --- a/src/interactions/commands/player/stop.ts +++ b/src/interactions/commands/player/stop.ts @@ -1,32 +1,24 @@ -import config from 'config'; import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; -import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class StopCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('stop') + .setDescription('Clear the queue and stop playing audio.'); + super(data); + } -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('stop') - .setDescription('Stop playing audio and clear the track queue.') - .setDMPermission(false) - .setNSFW(false), - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'stop.js', - module: 'slashCommand', - name: '/stop', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -63,15 +55,15 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.success} Stopped playing**\nStopped playing audio and cleared the track queue.\n\nTo play more music, use the **\`/play\`** command!` + `**${this.embedOptions.icons.success} Stopped playing**\nStopped playing audio and cleared the track queue.\n\nTo play more music, use the **\`/play\`** command!` ) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } -}; +} -export default command; +export default new StopCommand(); diff --git a/src/interactions/commands/player/volume.ts b/src/interactions/commands/player/volume.ts index fe853a2..18779e6 100644 --- a/src/interactions/commands/player/volume.ts +++ b/src/interactions/commands/player/volume.ts @@ -1,39 +1,31 @@ -import config from 'config'; import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; -import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class VolumeCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('volume') + .setDescription('Show or change the playback volume for tracks.') + .addNumberOption((option) => + option + .setName('percentage') + .setDescription('Volume percentage: From 1% to 100%.') + .setMinValue(0) + .setMaxValue(100) + ); + super(data); + } -const command: CustomSlashCommandInteraction = { - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('volume') - .setDescription('Show or set the playback volume for tracks.') - .setDMPermission(false) - .setNSFW(false) - .addNumberOption((option) => - option - .setName('percentage') - .setDescription('Set volume percentage from 1% to 100%.') - .setMinValue(0) - .setMaxValue(100) - ), - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'volume.js', - module: 'slashCommand', - name: '/volume', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -62,10 +54,12 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setDescription( `**${ - currentVolume === 0 ? embedOptions.icons.volumeIsMuted : embedOptions.icons.volume + currentVolume === 0 + ? this.embedOptions.icons.volumeIsMuted + : this.embedOptions.icons.volume } Playback volume**\nThe playback volume is currently set to **\`${currentVolume}%\`**.` ) - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) ] }); } else if (volume > 100 || volume < 0) { @@ -76,9 +70,9 @@ const command: CustomSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nYou cannot set the volume to **\`${volume}%\`**, please pick a value betwen **\`1%\`** and **\`100%\`**.` + `**${this.embedOptions.icons.warning} Oops!**\nYou cannot set the volume to **\`${volume}%\`**, please pick a value betwen **\`1%\`** and **\`100%\`**.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } else { @@ -100,12 +94,12 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.volumeMuted} Audio muted**\nPlayback audio has been muted, because volume was set to **\`${volume}%\`**.` + `**${this.embedOptions.icons.volumeMuted} Audio muted**\nPlayback audio has been muted, because volume was set to **\`${volume}%\`**.` ) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } @@ -116,16 +110,16 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.volumeChanged} Volume changed**\nPlayback volume has been changed to **\`${volume}%\`**.` + `**${this.embedOptions.icons.volumeChanged} Volume changed**\nPlayback volume has been changed to **\`${volume}%\`**.` ) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } } -}; +} -export default command; +export default new VolumeCommand(); diff --git a/src/interactions/commands/system/guilds.ts b/src/interactions/commands/system/guilds.ts index 5e37f99..0213822 100644 --- a/src/interactions/commands/system/guilds.ts +++ b/src/interactions/commands/system/guilds.ts @@ -1,31 +1,23 @@ -import config from 'config'; import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; -import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class GuildsCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('guilds') + .setDescription('Show the top 25 guilds by member count.'); + const isSystemCommand: boolean = true; + super(data, isSystemCommand); + } -const command: CustomSlashCommandInteraction = { - isSystemCommand: true, - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('guilds') - .setDescription('Show list of guilds where bot is added.') - .setDMPermission(false) - .setNSFW(false), - execute: async ({ interaction, client, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'guilds.js', - module: 'slashCommand', - name: '/guilds', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction, client } = params; + const logger = this.getLogger(this.name, executionId, interaction); if (await notValidGuildId({ interaction, executionId })) { return; @@ -35,8 +27,8 @@ const command: CustomSlashCommandInteraction = { let totalGuildCount: number = 0; logger.debug('Fetching guilds from all shards.'); - await client!.shard! - .broadcastEval((c) => { + await client! + .shard!.broadcastEval((c) => { return c.guilds.cache.map((guild) => { return guild; }); @@ -64,7 +56,7 @@ const command: CustomSlashCommandInteraction = { const totalMemberCount: number = shardGuilds.reduce((a, b) => a + b.memberCount, 0); let embedDescription = - `**${embedOptions.icons.bot} ${ + `**${this.embedOptions.icons.bot} ${ totalGuildCount < 25 ? `Top ${totalGuildCount} guilds` : 'Top 25 guilds' } by member count (${totalGuildCount} total)**\n${guildListFormatted}` + `\n\n**Total members:** **\`${totalMemberCount}\`**`; @@ -78,9 +70,9 @@ const command: CustomSlashCommandInteraction = { logger.debug('Responding with info embed.'); return await interaction.editReply({ - embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(embedOptions.colors.info)] + embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(this.embedOptions.colors.info)] }); } -}; +} -export default command; +export default new GuildsCommand(); diff --git a/src/interactions/commands/system/reload.ts b/src/interactions/commands/system/reload.ts index e39ad07..7170792 100644 --- a/src/interactions/commands/system/reload.ts +++ b/src/interactions/commands/system/reload.ts @@ -1,32 +1,24 @@ -import config from 'config'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; +import { ApplicationCommandOption, ApplicationCommandOptionData, EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { ExtendedClient } from '../../../types/clientTypes'; -import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class ReloadCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('reload') + .setDescription('Reload all slash commands across shards.'); + const isSystemCommand: boolean = true; + super(data, isSystemCommand); + } -const command: CustomSlashCommandInteraction = { - isSystemCommand: true, - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('reload') - .setDescription('Reload the bot commands.') - .setDMPermission(false) - .setNSFW(false), - execute: async ({ interaction, client, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'reload.js', - module: 'slashCommand', - name: '/reload', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction, client } = params; + const logger = this.getLogger(this.name, executionId, interaction); if (await notValidGuildId({ interaction, executionId })) { return; @@ -37,7 +29,7 @@ const command: CustomSlashCommandInteraction = { await client! .shard!.broadcastEval( async (shardClient: ExtendedClient, { executionId }) => { - shardClient.registerClientCommands!({ client: shardClient, executionId }); + shardClient.registerClientInteractions!({ client: shardClient, executionId }); }, { context: { executionId: executionId } } ) @@ -53,26 +45,36 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setDescription( - `**${embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to reload commands across shards.` + `**${this.embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to reload commands across shards.` ) - .setColor(embedOptions.colors.error) + .setColor(this.embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); } - const commands: string[] | undefined = client!.commands?.map((command) => { - const params: string = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : ''; + const commands: string[] | undefined = client!.slashCommandInteractions?.map((command: BaseSlashCommandInteraction) => { + let params: string = ''; + + if (command.data.options && command.data.options.length > 1) { + const options = command.data.options as unknown as ApplicationCommandOptionData[]; + + options.map((option: ApplicationCommandOption) => { + params += `**\`${option.name}\`**` + ' '; + }); + } + return `- **\`/${command.data.name}\`** ${params}- ${command.data.description}`; }); - const embedDescription: string = `**${embedOptions.icons.bot} Reloaded commands**\n` + commands?.join('\n'); + const embedDescription: string = + `**${this.embedOptions.icons.bot} Reloaded commands**\n` + commands?.join('\n'); logger.debug('Responding with success embed.'); return await interaction.editReply({ - embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(embedOptions.colors.success)] + embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(this.embedOptions.colors.success)] }); } -}; +} -export default command; +export default new ReloadCommand(); diff --git a/src/interactions/commands/system/shards.ts b/src/interactions/commands/system/shards.ts index 5123dda..d7ccdaf 100644 --- a/src/interactions/commands/system/shards.ts +++ b/src/interactions/commands/system/shards.ts @@ -1,49 +1,43 @@ -import config from 'config'; import { EmbedBuilder, EmbedField, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; import { ExtendedClient } from '../../../types/clientTypes'; -import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction, ShardInfo } from '../../../types/interactionTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType, + ShardInfo +} from '../../../types/interactionTypes'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class ShardsCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('shards') + .setDescription('Show information about all connected shards.') + .addStringOption((option) => + option + .setName('sort') + .setDescription('What to sort the shards by.') + .setRequired(false) + .addChoices( + { name: 'None (Shard ID)', value: 'none' }, + { name: 'Memory usage', value: 'memory' }, + { name: 'Voice Connections', value: 'connections' }, + { name: 'Tracks', value: 'tracks' }, + { name: 'Listeners', value: 'listeners' }, + { name: 'Guilds', value: 'guilds' }, + { name: 'Members', value: 'members' } + ) + ) + .addNumberOption((option) => + option.setName('page').setDescription('Page number to display for the shards').setMinValue(1) + ); + const isSystemCommand: boolean = true; + super(data, isSystemCommand); + } -const command: CustomSlashCommandInteraction = { - isSystemCommand: true, - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('shards') - .setDescription('Show information about the running shards.') - .setDMPermission(false) - .setNSFW(false) - .addStringOption((option) => - option - .setName('sort') - .setDescription('If specified, what to sort the shards by.') - .setRequired(false) - .addChoices( - { name: 'None (Shard ID)', value: 'none' }, - { name: 'Memory usage', value: 'memory' }, - { name: 'Voice Connections', value: 'connections' }, - { name: 'Tracks', value: 'tracks' }, - { name: 'Listeners', value: 'listeners' }, - { name: 'Guilds', value: 'guilds' }, - { name: 'Members', value: 'members' } - ) - ) - - .addNumberOption((option) => option.setName('page').setDescription('Page number to show').setMinValue(1)), - execute: async ({ interaction, client, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'shards.js', - module: 'slashCommand', - name: '/shards', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction, client } = params; + const logger = this.getLogger(this.name, executionId, interaction); if (await notValidGuildId({ interaction, executionId })) { return; @@ -122,17 +116,17 @@ const command: CustomSlashCommandInteraction = { new EmbedBuilder() .setDescription( - `**${embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to fetch player statistics and client values from shards.` + `**${this.embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to fetch player statistics and client values from shards.` ) - .setColor(embedOptions.colors.error) + .setColor(this.embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); } const shardCount: number = shardInfoList.length; - const totalPages:number = Math.ceil(shardCount / 10) || 1; - const pageIndex:number = (interaction.options.getNumber('page') || 1) - 1; + const totalPages: number = Math.ceil(shardCount / 10) || 1; + const pageIndex: number = (interaction.options.getNumber('page') || 1) - 1; const currentPageShards: ShardInfo[] = shardInfoList.slice(pageIndex * 10, pageIndex * 10 + 10); @@ -151,7 +145,8 @@ const command: CustomSlashCommandInteraction = { return string; } - const evenShardIndexesString: string = evenShardIndexes.map(shardInfoToString).join('\n') + 'ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ'; + const evenShardIndexesString: string = + evenShardIndexes.map(shardInfoToString).join('\n') + 'ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ'; const oddShardIndexesString: string = oddShardIndexes.map(shardInfoToString).join('\n'); const embedFields: EmbedField[] = []; @@ -183,13 +178,15 @@ const command: CustomSlashCommandInteraction = { return await interaction.editReply({ embeds: [ new EmbedBuilder() - .setDescription(`**${embedOptions.icons.server} Shard overview - ${shardCount} total shards**\n`) + .setDescription( + `**${this.embedOptions.icons.server} Shard overview - ${shardCount} total shards**\n` + ) .addFields(...embedFields) - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) .setFooter({ text: `Shard id: ${client!.shard!.ids[0]}, page ${pageIndex + 1} of ${totalPages}` }) ] }); } -}; +} -export default command; +export default new ShardsCommand(); diff --git a/src/interactions/commands/system/systemstatus.ts b/src/interactions/commands/system/systemstatus.ts index 2ccfc24..93d238c 100644 --- a/src/interactions/commands/system/systemstatus.ts +++ b/src/interactions/commands/system/systemstatus.ts @@ -1,35 +1,27 @@ -import config from 'config'; import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; import osu from 'node-os-utils'; // @ts-ignore import { dependencies, version } from '../../../../package.json'; -import loggerModule from '../../../services/logger'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; -import { EmbedOptions } from '../../../types/configTypes'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; -import { Logger } from 'pino'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +class SystemStatusCommand extends BaseSlashCommandInteraction { + constructor() { + const data = new SlashCommandBuilder() + .setName('systemstatus') + .setDescription('Show operational status of the bot with additional technical information.'); + const isSystemCommand: boolean = true; + super(data, isSystemCommand); + } -const command: CustomSlashCommandInteraction = { - isSystemCommand: true, - isNew: false, - isBeta: false, - data: new SlashCommandBuilder() - .setName('systemstatus') - .setDescription('Show the bot and system status.') - .setDMPermission(false) - .setNSFW(false), - execute: async ({ interaction, client, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'systemstatus.js', - module: 'slashCommand', - name: '/systemstatus', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction, client } = params; + const logger = this.getLogger(this.name, executionId, interaction); if (await notValidGuildId({ interaction, executionId })) { return; @@ -132,33 +124,33 @@ const command: CustomSlashCommandInteraction = { return await interaction.editReply({ embeds: [ new EmbedBuilder() - .setDescription(`**${embedOptions.icons.bot} Bot status**\n` + botStatusString) + .setDescription(`**${this.embedOptions.icons.bot} Bot status**\n` + botStatusString) .addFields( { - name: `**${embedOptions.icons.queue} Queue status**`, + name: `**${this.embedOptions.icons.queue} Queue status**`, value: queueStatusString, inline: false }, { - name: `**${embedOptions.icons.server} System status**`, + name: `**${this.embedOptions.icons.server} System status**`, value: systemStatusString, inline: false }, { - name: `**${embedOptions.icons.discord} Discord status**`, + name: `**${this.embedOptions.icons.discord} Discord status**`, value: discordStatusString, inline: false }, { - name: `**${embedOptions.icons.bot} Dependencies**`, + name: `**${this.embedOptions.icons.bot} Dependencies**`, value: dependenciesString, inline: false } ) - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) ] }); } -}; +} -export default command; +export default new SystemStatusCommand(); diff --git a/src/interactions/components/filters-disable-button.ts b/src/interactions/components/filters-disable-button.ts index 06957c3..ca814eb 100644 --- a/src/interactions/components/filters-disable-button.ts +++ b/src/interactions/components/filters-disable-button.ts @@ -1,26 +1,17 @@ -import config from 'config'; import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; -import { EmbedOptions } from '../../types/configTypes'; -import { CustomComponentInteraction } from '../../types/interactionTypes'; +import { BaseComponentInteraction, BaseComponentParams, BaseComponentReturnType } from '../../types/interactionTypes'; import { queueDoesNotExist } from '../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -const component: CustomComponentInteraction = { - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'filters-disable-button.js', - module: 'componentInteraction', - name: 'filters-disable-button', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); +class FiltersDisableButtonComponent extends BaseComponentInteraction { + constructor() { + super('filters-disable-button'); + } - logger.debug('Received disable confirmation.'); + async execute(params: BaseComponentParams): BaseComponentReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -56,16 +47,16 @@ const component: CustomComponentInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.` + `**${this.embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.` ) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ], components: [] }); } -}; +} -export default component; +export default new FiltersDisableButtonComponent(); diff --git a/src/interactions/components/filters-select-menu.ts b/src/interactions/components/filters-select-menu.ts index b15650a..e35cae7 100644 --- a/src/interactions/components/filters-select-menu.ts +++ b/src/interactions/components/filters-select-menu.ts @@ -1,25 +1,20 @@ import config from 'config'; import { GuildQueue, QueueFilters, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, StringSelectMenuInteraction } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; -import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../types/configTypes'; -import { CustomComponentInteraction } from '../../types/interactionTypes'; +import { FFmpegFilterOption, FFmpegFilterOptions } from '../../types/configTypes'; +import { BaseComponentInteraction, BaseComponentParams, BaseComponentReturnType } from '../../types/interactionTypes'; import { queueDoesNotExist } from '../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -const embedOptions: EmbedOptions = config.get('embedOptions'); const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions'); -const component: CustomComponentInteraction = { - execute: async ({ interaction, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'filters-select-menu.js', - module: 'componentInteraction', - name: 'filters-select-menu', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); +class FiltersSelectMenuComponent extends BaseComponentInteraction { + constructor() { + super('filters-select-menu'); + } + + async execute(params: BaseComponentParams): BaseComponentReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); logger.debug('Received select menu confirmation.'); @@ -87,7 +82,7 @@ const component: CustomComponentInteraction = { }) .setDescription( `**${ - embedOptions.icons.success + this.embedOptions.icons.success } Filters toggled**\nNow using these filters:\n${selectMenuInteraction.values .map((enabledFilter: string) => { const filter: FFmpegFilterOption | undefined = @@ -103,11 +98,11 @@ const component: CustomComponentInteraction = { }) .join('\n')}` ) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ], components: [] }); } -}; +} -export default component; +export default new FiltersSelectMenuComponent(); diff --git a/src/interactions/components/nowplaying-skip-button.ts b/src/interactions/components/nowplaying-skip-button.ts index 41ea8cc..e3cfec4 100644 --- a/src/interactions/components/nowplaying-skip-button.ts +++ b/src/interactions/components/nowplaying-skip-button.ts @@ -1,27 +1,17 @@ -import config from 'config'; import { GuildQueue, Track, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember } from 'discord.js'; - -import loggerModule from '../../services/logger'; -import { EmbedOptions } from '../../types/configTypes'; -import { CustomComponentInteraction } from '../../types/interactionTypes'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { BaseComponentInteraction, BaseComponentParams, BaseComponentReturnType } from '../../types/interactionTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; -import { Logger } from 'pino'; -const embedOptions: EmbedOptions = config.get('embedOptions'); +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -const component: CustomComponentInteraction = { - execute: async ({ interaction, referenceId, executionId }) => { - const logger: Logger = loggerModule.child({ - source: 'nowplaying-skip.js', - module: 'componentInteraction', - name: 'nowplaying-skip', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); +class NowplayingSkipButton extends BaseComponentInteraction { + constructor() { + super('nowplaying-skip-button'); + } - logger.debug(`Received skip confirmation for track id ${referenceId}.`); + async execute(params: BaseComponentParams): BaseComponentReturnType { + const { executionId, interaction, referenceId } = params; + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -46,9 +36,9 @@ const component: CustomComponentInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + `**${this.embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ], components: [] }); @@ -62,9 +52,9 @@ const component: CustomComponentInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.` + `**${this.embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ], components: [] }); @@ -77,7 +67,7 @@ const component: CustomComponentInteraction = { : `\`${skippedTrack.duration}\``; if (skippedTrack.raw.live) { - durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; + durationFormat = `${this.embedOptions.icons.liveTrack} \`LIVE\``; } queue.node.skip(); logger.debug('Skipped the track.'); @@ -105,28 +95,28 @@ const component: CustomComponentInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl }) .setDescription( - `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${ - skippedTrack.raw.url ?? skippedTrack.url - })**` + + `**${this.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 + ? this.embedOptions.icons.autoplaying + : this.embedOptions.icons.looping } Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.` }` ) .setThumbnail(skippedTrack.thumbnail) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ], components: [] }); } -}; +} -export default component; +export default new NowplayingSkipButton(); diff --git a/src/types/clientTypes.ts b/src/types/clientTypes.ts index 921106b..cd2a1b0 100644 --- a/src/types/clientTypes.ts +++ b/src/types/clientTypes.ts @@ -1,21 +1,11 @@ -import { Client, Collection, SharedNameAndDescription } from 'discord.js'; +import { Client, Collection } from 'discord.js'; +import { BaseAutocompleteInteraction, BaseComponentInteraction, BaseSlashCommandInteraction } from './interactionTypes'; -type RegisterClientCommandsFunction = (params: { client: Client; executionId: string }) => void; - -export interface Command { - isNew?: boolean; - isBeta?: boolean; - isSystemCommand?: boolean; - data: { - name: string; - description: string; - options: SharedNameAndDescription[] - }; - execute: (params: { interaction: object; client: ExtendedClient | undefined; executionId: string }) => void; - autocomplete?: (params: { interaction: object; 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/interactionTypes.ts b/src/types/interactionTypes.ts index c7113da..9bc3f4f 100644 --- a/src/types/interactionTypes.ts +++ b/src/types/interactionTypes.ts @@ -1,49 +1,18 @@ +import config from 'config'; import { ApplicationCommandOptionChoiceData, AutocompleteInteraction, ChatInputCommandInteraction, + Interaction, Message, MessageComponentInteraction, SlashCommandBuilder } from 'discord.js'; +import { Logger } from 'pino'; +import loggerModule from '../services/logger'; import { ExtendedClient } from './clientTypes'; +import { BotOptions, EmbedOptions } from './configTypes'; -// Local types -interface CommandParams { - client?: ExtendedClient; - executionId: string; - interaction: ChatInputCommandInteraction; -} - -interface AutocompleteParams { - executionId: string; - interaction: AutocompleteInteraction; -} - -interface ComponentParams { - interaction: MessageComponentInteraction; - referenceId?: string; - executionId: string; -} - -// Interaction types -export interface CustomSlashCommandInteraction { - isNew: boolean; - isBeta: boolean; - isSystemCommand?: boolean; - data: Omit; - execute(params: CommandParams): Promise | void>; -} - -export interface CustomAutocompleteInteraction { - execute(params: AutocompleteParams): Promise; -} - -export interface CustomComponentInteraction { - execute(params: ComponentParams): Promise | void>; -} - -// Command specific types export interface ShardInfo { shardId: number; memUsage: number; @@ -66,3 +35,114 @@ export class CustomError extends Error { type?: string; code?: string; } + +interface BaseInteractionParams { + executionId: string; +} + +export interface BaseSlashCommandParams extends BaseInteractionParams { + interaction: ChatInputCommandInteraction; + client?: ExtendedClient; +} + +export interface BaseAutocompleteParams extends BaseInteractionParams { + interaction: AutocompleteInteraction; +} + +export interface BaseComponentParams extends BaseInteractionParams { + interaction: MessageComponentInteraction; + referenceId?: string; +} + +export type BaseSlashCommandReturnType = Promise | void>; + +export type BaseAutocompleteReturnType = Promise; + +export type BaseComponentReturnType = Promise | void>; + +abstract class BaseInteraction { + protected getLoggerBase( + module: string, + name: string, + executionId: string, + interaction: Interaction | MessageComponentInteraction + ): Logger { + return loggerModule.child({ + module: module, + name: name, + executionId: executionId, + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id + }); + } + + abstract execute( + params: BaseInteractionParams + ): Promise | ApplicationCommandOptionChoiceData | void>; +} + +export abstract class BaseSlashCommandInteraction extends BaseInteraction { + data: Omit; + isSystemCommand: boolean; + isNew: boolean; + isBeta: boolean; + embedOptions: EmbedOptions; + botOptions: BotOptions; + name: string; + + constructor( + data: Omit, + isSystemCommand: boolean = false, + isNew: boolean = false, + isBeta: boolean = false + ) { + super(); + this.data = data.setDMPermission(false).setNSFW(false); + this.isSystemCommand = isSystemCommand; + this.isNew = isNew; + this.isBeta = isBeta; + this.embedOptions = config.get('embedOptions'); + this.botOptions = config.get('botOptions'); + this.name = data.name; + } + + protected getLogger(name: string, executionId: string, interaction: ChatInputCommandInteraction): Logger { + return super.getLoggerBase('slashCommandInteraction', name, executionId, interaction); + } + + abstract execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType; +} + +export abstract class BaseAutocompleteInteraction extends BaseInteraction { + name: string; + + constructor(name: string) { + super(); + this.name = name; + } + + protected getLogger(name: string, executionId: string, interaction: AutocompleteInteraction): Logger { + return super.getLoggerBase('autocompleteInteraction', name, executionId, interaction); + } + + abstract execute(params: BaseAutocompleteParams): BaseAutocompleteReturnType; +} + +export abstract class BaseComponentInteraction extends BaseInteraction { + embedOptions: EmbedOptions; + botOptions: BotOptions; + name: string; + + constructor(name: string) { + super(); + this.embedOptions = config.get('embedOptions'); + this.botOptions = config.get('botOptions'); + this.name = name; + } + + protected getLogger(name: string, executionId: string, interaction: MessageComponentInteraction): Logger { + return super.getLoggerBase('componentInteraction', name, executionId, interaction); + } + + abstract execute(params: BaseComponentParams): BaseComponentReturnType; +} 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/deploySlashCommands.ts b/src/utils/deploySlashCommands.ts index cd142dd..ff5b1f9 100644 --- a/src/utils/deploySlashCommands.ts +++ b/src/utils/deploySlashCommands.ts @@ -1,7 +1,7 @@ import 'dotenv/config'; import config from 'config'; -import { REST, RouteLike, Routes, SlashCommandBuilder } from 'discord.js'; +import { REST, RESTPostAPIChatInputApplicationCommandsJSONBody, RouteLike, Routes } from 'discord.js'; import fs from 'node:fs'; import path from 'node:path'; import { v4 as uuidv4 } from 'uuid'; @@ -23,8 +23,8 @@ const logger: Logger = loggerModule.child({ //TODO: Fix deploying not working with require() -const slashCommands: SlashCommandBuilder[] = []; -const systemCommands: SlashCommandBuilder[] = []; +const slashCommands: RESTPostAPIChatInputApplicationCommandsJSONBody[] = []; +const systemCommands: RESTPostAPIChatInputApplicationCommandsJSONBody[] = []; const commandFolders: string[] = fs.readdirSync(path.resolve('./dist/interactions/commands')); if (!process.env.DISCORD_BOT_TOKEN) { @@ -52,8 +52,7 @@ const rest: REST = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_ for (const file of commandFiles) { // TODO: create commandModule type - const commandModule = await import(`../interactions/commands/${folder}/${file}`); - const command = commandModule.default; + const { default: command } = await import(`../interactions/commands/${folder}/${file}`); command.isSystemCommand ? systemCommands.push(command.data.toJSON()) : slashCommands.push(command.data.toJSON()); diff --git a/src/utils/registerClientCommands.ts b/src/utils/registerClientCommands.ts deleted file mode 100644 index 7f4ca46..0000000 --- a/src/utils/registerClientCommands.ts +++ /dev/null @@ -1,50 +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}`)]; - - // register 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}`); - } 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.'); +}