From 6ebf7b9bd38c69e9b8a9a25cedbc62f9228da9f8 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Wed, 30 Aug 2023 21:47:50 +0200 Subject: [PATCH 1/8] WIP --- src/interactions/autocomplete/lyrics.ts | 4 +- src/interactions/autocomplete/play.ts | 4 +- src/interactions/commands/info/help.ts | 4 +- src/interactions/commands/info/status.ts | 4 +- src/interactions/commands/player/filters.ts | 4 +- src/interactions/commands/player/leave.ts | 4 +- src/interactions/commands/player/loop.ts | 4 +- src/interactions/commands/player/lyrics.ts | 4 +- .../commands/player/nowplaying.ts | 4 +- src/interactions/commands/player/pause.ts | 4 +- src/interactions/commands/player/play.ts | 4 +- src/interactions/commands/player/queue.ts | 4 +- src/interactions/commands/player/remove.ts | 4 +- src/interactions/commands/player/seek.ts | 4 +- src/interactions/commands/player/shuffle.ts | 4 +- src/interactions/commands/player/skip.ts | 4 +- src/interactions/commands/player/stop.ts | 4 +- src/interactions/commands/player/test.ts | 23 +++++ src/interactions/commands/player/volume.ts | 4 +- src/interactions/commands/system/guilds.ts | 4 +- src/interactions/commands/system/reload.ts | 4 +- src/interactions/commands/system/shards.ts | 4 +- .../commands/system/systemstatus.ts | 4 +- .../components/filters-disable-button.ts | 4 +- .../components/filters-select-menu.ts | 4 +- .../components/nowplaying-skip-button.ts | 4 +- src/types/clientTypes.ts | 7 +- src/types/interactionTypes.ts | 85 +++++++++++++++---- src/utils/deploySlashCommands.ts | 18 +++- src/utils/registerClientCommands.ts | 12 ++- 30 files changed, 174 insertions(+), 71 deletions(-) create mode 100644 src/interactions/commands/player/test.ts diff --git a/src/interactions/autocomplete/lyrics.ts b/src/interactions/autocomplete/lyrics.ts index 208090a..8094edf 100644 --- a/src/interactions/autocomplete/lyrics.ts +++ b/src/interactions/autocomplete/lyrics.ts @@ -3,7 +3,7 @@ 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'; +import { BaseAutocompleteInteraction } from '../../types/interactionTypes'; const loggerTemplate: Logger = loggerModule.child({ source: 'lyrics.js', @@ -14,7 +14,7 @@ const loggerTemplate: Logger = loggerModule.child({ // TODO: create interface for recent query object const recentQueries = new Map(); -const autocomplete: CustomAutocompleteInteraction = { +const autocomplete: BaseAutocompleteInteraction = { execute: async ({ interaction, executionId }) => { const logger: Logger = loggerTemplate.child({ executionId: executionId, diff --git a/src/interactions/autocomplete/play.ts b/src/interactions/autocomplete/play.ts index c0f7a4b..57f78c5 100644 --- a/src/interactions/autocomplete/play.ts +++ b/src/interactions/autocomplete/play.ts @@ -2,7 +2,7 @@ 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'; +import { BaseAutocompleteInteraction } from '../../types/interactionTypes'; const loggerTemplate: Logger = loggerModule.child({ source: 'play.js', @@ -13,7 +13,7 @@ const loggerTemplate: Logger = loggerModule.child({ // TODO: create interface for recent query object const recentQueries = new Map(); -const autocomplete: CustomAutocompleteInteraction = { +const autocomplete: BaseAutocompleteInteraction = { execute: async ({ interaction, executionId }) => { const logger: Logger = loggerTemplate.child({ executionId: executionId, diff --git a/src/interactions/commands/info/help.ts b/src/interactions/commands/info/help.ts index 7751a0f..2bddf4b 100644 --- a/src/interactions/commands/info/help.ts +++ b/src/interactions/commands/info/help.ts @@ -3,12 +3,12 @@ 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 { BaseSlashCommandInteraction } from '../../../types/interactionTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/info/status.ts b/src/interactions/commands/info/status.ts index a0362ac..74b2c5c 100644 --- a/src/interactions/commands/info/status.ts +++ b/src/interactions/commands/info/status.ts @@ -6,12 +6,12 @@ import { Logger } from 'pino'; import { version } from '../../../../package.json'; import loggerModule from '../../../services/logger'; import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { BaseSlashCommandInteraction } from '../../../types/interactionTypes'; import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/filters.ts b/src/interactions/commands/player/filters.ts index a44af2e..b1d2473 100644 --- a/src/interactions/commands/player/filters.ts +++ b/src/interactions/commands/player/filters.ts @@ -16,14 +16,14 @@ import { import { Logger } from 'pino'; import loggerModule from '../../../services/logger'; import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { BaseSlashCommandInteraction } 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 = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/leave.ts b/src/interactions/commands/player/leave.ts index a6f6203..fa7b545 100644 --- a/src/interactions/commands/player/leave.ts +++ b/src/interactions/commands/player/leave.ts @@ -4,13 +4,13 @@ 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 } from '../../../types/interactionTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/loop.ts b/src/interactions/commands/player/loop.ts index 22c3265..e7c7868 100644 --- a/src/interactions/commands/player/loop.ts +++ b/src/interactions/commands/player/loop.ts @@ -4,14 +4,14 @@ import { EmbedBuilder, GuildMember, SlashCommandBuilder, SlashCommandStringOptio import { Logger } from 'pino'; import loggerModule from '../../../services/logger'; import { BotOptions, EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { BaseSlashCommandInteraction } 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'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/lyrics.ts b/src/interactions/commands/player/lyrics.ts index 9ddb013..2dd18c6 100644 --- a/src/interactions/commands/player/lyrics.ts +++ b/src/interactions/commands/player/lyrics.ts @@ -5,7 +5,7 @@ import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { LyricsData, lyricsExtractor } from '@discord-player/extractor'; import loggerModule from '../../../services/logger'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { BaseSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; @@ -19,7 +19,7 @@ const loggerTemplate: Logger = loggerModule.child({ name: '/lyrics' }); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/nowplaying.ts b/src/interactions/commands/player/nowplaying.ts index 1527d71..78e2c91 100644 --- a/src/interactions/commands/player/nowplaying.ts +++ b/src/interactions/commands/player/nowplaying.ts @@ -12,7 +12,7 @@ import { } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CustomSlashCommandInteraction, TrackMetadata } from '../../../types/interactionTypes'; +import { BaseSlashCommandInteraction, TrackMetadata } from '../../../types/interactionTypes'; import { EmbedOptions, PlayerOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; @@ -21,7 +21,7 @@ import { Logger } from 'pino'; const embedOptions: EmbedOptions = config.get('embedOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/pause.ts b/src/interactions/commands/player/pause.ts index cb440f6..72d01c1 100644 --- a/src/interactions/commands/player/pause.ts +++ b/src/interactions/commands/player/pause.ts @@ -4,13 +4,13 @@ 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 } from '../../../types/interactionTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/play.ts b/src/interactions/commands/player/play.ts index 59637a1..7bfbd9f 100644 --- a/src/interactions/commands/player/play.ts +++ b/src/interactions/commands/player/play.ts @@ -3,7 +3,7 @@ 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 { CustomError, BaseSlashCommandInteraction } from '../../../types/interactionTypes'; import { BotOptions, EmbedOptions, PlayerOptions } from '../../../types/configTypes'; import { cannotJoinVoiceOrTalk } from '../../../utils/validation/permissionValidator'; import { transformQuery } from '../../../utils/validation/searchQueryValidator'; @@ -20,7 +20,7 @@ const loggerTemplate: Logger = loggerModule.child({ name: '/play' }); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/queue.ts b/src/interactions/commands/player/queue.ts index 846c154..2fb542a 100644 --- a/src/interactions/commands/player/queue.ts +++ b/src/interactions/commands/player/queue.ts @@ -4,14 +4,14 @@ 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 } 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 = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/remove.ts b/src/interactions/commands/player/remove.ts index e219376..2cb40d4 100644 --- a/src/interactions/commands/player/remove.ts +++ b/src/interactions/commands/player/remove.ts @@ -4,13 +4,13 @@ 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 } from '../../../types/interactionTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/seek.ts b/src/interactions/commands/player/seek.ts index 690d404..8e10096 100644 --- a/src/interactions/commands/player/seek.ts +++ b/src/interactions/commands/player/seek.ts @@ -4,13 +4,13 @@ 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 } from '../../../types/interactionTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/shuffle.ts b/src/interactions/commands/player/shuffle.ts index 722ede2..28b6821 100644 --- a/src/interactions/commands/player/shuffle.ts +++ b/src/interactions/commands/player/shuffle.ts @@ -4,13 +4,13 @@ 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 } from '../../../types/interactionTypes'; import { queueDoesNotExist, queueIsEmpty } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/skip.ts b/src/interactions/commands/player/skip.ts index 9e9386d..da803da 100644 --- a/src/interactions/commands/player/skip.ts +++ b/src/interactions/commands/player/skip.ts @@ -4,13 +4,13 @@ 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 } from '../../../types/interactionTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/stop.ts b/src/interactions/commands/player/stop.ts index 5097f44..078a027 100644 --- a/src/interactions/commands/player/stop.ts +++ b/src/interactions/commands/player/stop.ts @@ -4,13 +4,13 @@ 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 } from '../../../types/interactionTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/player/test.ts b/src/interactions/commands/player/test.ts new file mode 100644 index 0000000..2c13c88 --- /dev/null +++ b/src/interactions/commands/player/test.ts @@ -0,0 +1,23 @@ +import { SlashCommandBuilder } from 'discord.js'; +import { BaseCommandInteraction, BaseSlashCommandParams } from '../../../types/interactionTypes'; + +export class TestCommandInteraction extends BaseCommandInteraction { + constructor() { + const data = new SlashCommandBuilder().setName('test').setDescription('Test command'); + super(data); + } + + async execute(params: BaseSlashCommandParams): Promise { + const { executionId, interaction } = params; + const logger = this.getLogger('test.ts', 'test', executionId, interaction); + + logger.info('test command executed'); + logger.info(`${interaction.user.tag} executed test command`); + logger.info(`Execution ID: ${executionId}`); + + logger.info(this.embedOptions.icons.success + ' Icon success from config.'); + return; + } +} + +export default new TestCommandInteraction(); diff --git a/src/interactions/commands/player/volume.ts b/src/interactions/commands/player/volume.ts index fe853a2..2f0f9a8 100644 --- a/src/interactions/commands/player/volume.ts +++ b/src/interactions/commands/player/volume.ts @@ -4,13 +4,13 @@ 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 } from '../../../types/interactionTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() diff --git a/src/interactions/commands/system/guilds.ts b/src/interactions/commands/system/guilds.ts index 5e37f99..4641038 100644 --- a/src/interactions/commands/system/guilds.ts +++ b/src/interactions/commands/system/guilds.ts @@ -3,12 +3,12 @@ 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 } from '../../../types/interactionTypes'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isSystemCommand: true, isNew: false, isBeta: false, diff --git a/src/interactions/commands/system/reload.ts b/src/interactions/commands/system/reload.ts index e39ad07..860db44 100644 --- a/src/interactions/commands/system/reload.ts +++ b/src/interactions/commands/system/reload.ts @@ -4,12 +4,12 @@ import { Logger } from 'pino'; import loggerModule from '../../../services/logger'; import { ExtendedClient } from '../../../types/clientTypes'; import { EmbedOptions } from '../../../types/configTypes'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { BaseSlashCommandInteraction } from '../../../types/interactionTypes'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isSystemCommand: true, isNew: false, isBeta: false, diff --git a/src/interactions/commands/system/shards.ts b/src/interactions/commands/system/shards.ts index 5123dda..12c2062 100644 --- a/src/interactions/commands/system/shards.ts +++ b/src/interactions/commands/system/shards.ts @@ -4,12 +4,12 @@ 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, ShardInfo } from '../../../types/interactionTypes'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isSystemCommand: true, isNew: false, isBeta: false, diff --git a/src/interactions/commands/system/systemstatus.ts b/src/interactions/commands/system/systemstatus.ts index 2ccfc24..a9abe42 100644 --- a/src/interactions/commands/system/systemstatus.ts +++ b/src/interactions/commands/system/systemstatus.ts @@ -4,7 +4,7 @@ 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 { BaseSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; @@ -12,7 +12,7 @@ import { Logger } from 'pino'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const command: CustomSlashCommandInteraction = { +const command: BaseSlashCommandInteraction = { isSystemCommand: true, isNew: false, isBeta: false, diff --git a/src/interactions/components/filters-disable-button.ts b/src/interactions/components/filters-disable-button.ts index 06957c3..019b266 100644 --- a/src/interactions/components/filters-disable-button.ts +++ b/src/interactions/components/filters-disable-button.ts @@ -4,12 +4,12 @@ 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 } 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 = { +const component: BaseComponentInteraction = { execute: async ({ interaction, executionId }) => { const logger: Logger = loggerModule.child({ source: 'filters-disable-button.js', diff --git a/src/interactions/components/filters-select-menu.ts b/src/interactions/components/filters-select-menu.ts index b15650a..cdac0f6 100644 --- a/src/interactions/components/filters-select-menu.ts +++ b/src/interactions/components/filters-select-menu.ts @@ -4,13 +4,13 @@ import { EmbedBuilder, GuildMember, StringSelectMenuInteraction } from 'discord. import { Logger } from 'pino'; import loggerModule from '../../services/logger'; import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../types/configTypes'; -import { CustomComponentInteraction } from '../../types/interactionTypes'; +import { BaseComponentInteraction } 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 = { +const component: BaseComponentInteraction = { execute: async ({ interaction, executionId }) => { const logger: Logger = loggerModule.child({ source: 'filters-select-menu.js', diff --git a/src/interactions/components/nowplaying-skip-button.ts b/src/interactions/components/nowplaying-skip-button.ts index 41ea8cc..8015325 100644 --- a/src/interactions/components/nowplaying-skip-button.ts +++ b/src/interactions/components/nowplaying-skip-button.ts @@ -4,13 +4,13 @@ import { EmbedBuilder, GuildMember } from 'discord.js'; import loggerModule from '../../services/logger'; import { EmbedOptions } from '../../types/configTypes'; -import { CustomComponentInteraction } from '../../types/interactionTypes'; +import { BaseComponentInteraction } from '../../types/interactionTypes'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; import { Logger } from 'pino'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const component: CustomComponentInteraction = { +const component: BaseComponentInteraction = { execute: async ({ interaction, referenceId, executionId }) => { const logger: Logger = loggerModule.child({ source: 'nowplaying-skip.js', diff --git a/src/types/clientTypes.ts b/src/types/clientTypes.ts index 921106b..dd99cd7 100644 --- a/src/types/clientTypes.ts +++ b/src/types/clientTypes.ts @@ -1,7 +1,9 @@ -import { Client, Collection, SharedNameAndDescription } from 'discord.js'; +import { Client, Collection } from 'discord.js'; +import { BaseCommandInteraction } from './interactionTypes'; type RegisterClientCommandsFunction = (params: { client: Client; executionId: string }) => void; +/* export interface Command { isNew?: boolean; isBeta?: boolean; @@ -14,8 +16,9 @@ export interface Command { execute: (params: { interaction: object; client: ExtendedClient | undefined; executionId: string }) => void; autocomplete?: (params: { interaction: object; executionId: string }) => void; } +*/ export interface ExtendedClient extends Client { registerClientCommands?: RegisterClientCommandsFunction; - commands?: Collection; + commands?: Collection; } diff --git a/src/types/interactionTypes.ts b/src/types/interactionTypes.ts index c7113da..89f392f 100644 --- a/src/types/interactionTypes.ts +++ b/src/types/interactionTypes.ts @@ -1,49 +1,53 @@ +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 { EmbedOptions } from './configTypes'; -// Local types -interface CommandParams { - client?: ExtendedClient; +interface BaseInteractionParams { executionId: string; - interaction: ChatInputCommandInteraction; } -interface AutocompleteParams { - executionId: string; +export interface BaseSlashCommandParams extends BaseInteractionParams { + interaction: ChatInputCommandInteraction; + client?: ExtendedClient; +} + +interface BaseAutocompleteParams { interaction: AutocompleteInteraction; } -interface ComponentParams { +interface BaseComponentParams { interaction: MessageComponentInteraction; referenceId?: string; - executionId: string; } // Interaction types -export interface CustomSlashCommandInteraction { +export interface BaseSlashCommandInteraction { isNew: boolean; isBeta: boolean; isSystemCommand?: boolean; data: Omit; - execute(params: CommandParams): Promise | void>; + execute(params: BaseSlashCommandParams): Promise | void>; } -export interface CustomAutocompleteInteraction { - execute(params: AutocompleteParams): Promise; +export interface BaseAutocompleteInteraction { + execute(params: BaseAutocompleteParams): Promise; } -export interface CustomComponentInteraction { - execute(params: ComponentParams): Promise | void>; +export interface BaseComponentInteraction { + execute(params: BaseComponentParams): Promise | void>; } -// Command specific types export interface ShardInfo { shardId: number; memUsage: number; @@ -66,3 +70,54 @@ export class CustomError extends Error { type?: string; code?: string; } + +abstract class BaseInteraction { + protected getLoggerBase( + module: string, + source: string, + name: string, + executionId: string, + interaction: Interaction + ): Logger { + return loggerModule.child({ + source: source, + module: module, + name: name, + executionId: executionId, + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id + }); + } + + abstract execute( + params: BaseInteractionParams + ): Promise | ApplicationCommandOptionChoiceData | void>; +} + +export abstract class BaseCommandInteraction extends BaseInteraction { + data: Omit; + isSystemCommand: boolean; + isNew: boolean; + isBeta: boolean; + embedOptions: EmbedOptions; + + constructor( + data: Omit, + isSystemCommand?: boolean, + isNew?: boolean, + isBeta?: boolean + ) { + super(); + this.data = data; + this.isSystemCommand = isSystemCommand || false; + this.isNew = isNew || false; + this.isBeta = isBeta || false; + this.embedOptions = config.get('embedOptions'); + } + + protected getLogger(source: string, name: string, executionId: string, interaction: Interaction): Logger { + return super.getLoggerBase('slashCommand', source, name, executionId, interaction); + } + + abstract execute(params: BaseSlashCommandParams): Promise | void>; +} diff --git a/src/utils/deploySlashCommands.ts b/src/utils/deploySlashCommands.ts index cd142dd..1db4a73 100644 --- a/src/utils/deploySlashCommands.ts +++ b/src/utils/deploySlashCommands.ts @@ -1,7 +1,13 @@ import 'dotenv/config'; import config from 'config'; -import { REST, RouteLike, Routes, SlashCommandBuilder } from 'discord.js'; +import { + REST, + RESTPostAPIChatInputApplicationCommandsJSONBody, + RouteLike, + Routes, + SlashCommandBuilder +} from 'discord.js'; import fs from 'node:fs'; import path from 'node:path'; import { v4 as uuidv4 } from 'uuid'; @@ -23,8 +29,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) { @@ -45,6 +51,7 @@ const rest: REST = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_ process.exit(1); } + /* for (const folder of commandFolders) { const commandFiles: string[] = fs .readdirSync(path.resolve(`./dist/interactions/commands/${folder}`)) @@ -59,6 +66,11 @@ const rest: REST = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_ : slashCommands.push(command.data.toJSON()); } } + */ + + const commandModule = await import('../interactions/commands/player/test.js'); + const command = commandModule.default; + slashCommands.push(command.data.toJSON()); try { logger.debug(`Bot user slash commands found: ${slashCommands.map((command) => `/${command.name}`).join(', ')}`); diff --git a/src/utils/registerClientCommands.ts b/src/utils/registerClientCommands.ts index 7f4ca46..f251f1f 100644 --- a/src/utils/registerClientCommands.ts +++ b/src/utils/registerClientCommands.ts @@ -18,13 +18,15 @@ export const registerClientCommands = async ({ client, executionId }: RegisterCl 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 @@ -44,7 +46,15 @@ export const registerClientCommands = async ({ client, executionId }: RegisterCl } } } + } + */ + + const commandModule = await import('../interactions/commands/player/test.js'); + const command = commandModule.default; + + logger.info(command.data); + client.commands.set('test', command); logger.trace('Registering client commands complete.'); }; From 3be362f0968a8e3139aa04fc1a03ae9f5c346496 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Wed, 30 Aug 2023 22:16:26 +0200 Subject: [PATCH 2/8] WIP working example --- src/interactions/commands/player/test.ts | 10 ++++++---- src/types/interactionTypes.ts | 15 ++++----------- src/utils/deploySlashCommands.ts | 9 +-------- src/utils/registerClientCommands.ts | 23 ++++++----------------- 4 files changed, 17 insertions(+), 40 deletions(-) diff --git a/src/interactions/commands/player/test.ts b/src/interactions/commands/player/test.ts index 2c13c88..af93a28 100644 --- a/src/interactions/commands/player/test.ts +++ b/src/interactions/commands/player/test.ts @@ -1,4 +1,4 @@ -import { SlashCommandBuilder } from 'discord.js'; +import { EmbedBuilder, Message, SlashCommandBuilder } from 'discord.js'; import { BaseCommandInteraction, BaseSlashCommandParams } from '../../../types/interactionTypes'; export class TestCommandInteraction extends BaseCommandInteraction { @@ -7,16 +7,18 @@ export class TestCommandInteraction extends BaseCommandInteraction { super(data); } - async execute(params: BaseSlashCommandParams): Promise { + async execute(params: BaseSlashCommandParams): Promise | void> { const { executionId, interaction } = params; - const logger = this.getLogger('test.ts', 'test', executionId, interaction); + const logger = this.getLogger('test.js', executionId, interaction); logger.info('test command executed'); logger.info(`${interaction.user.tag} executed test command`); logger.info(`Execution ID: ${executionId}`); logger.info(this.embedOptions.icons.success + ' Icon success from config.'); - return; + return await interaction.editReply({ + embeds: [new EmbedBuilder().setDescription('It works!').setColor(this.embedOptions.colors.success)] + }); } } diff --git a/src/types/interactionTypes.ts b/src/types/interactionTypes.ts index 89f392f..a039df7 100644 --- a/src/types/interactionTypes.ts +++ b/src/types/interactionTypes.ts @@ -72,17 +72,10 @@ export class CustomError extends Error { } abstract class BaseInteraction { - protected getLoggerBase( - module: string, - source: string, - name: string, - executionId: string, - interaction: Interaction - ): Logger { + protected getLoggerBase(module: string, source: string, executionId: string, interaction: Interaction): Logger { return loggerModule.child({ source: source, module: module, - name: name, executionId: executionId, shardId: interaction.guild?.shardId, guildId: interaction.guild?.id @@ -108,15 +101,15 @@ export abstract class BaseCommandInteraction extends BaseInteraction { isBeta?: boolean ) { super(); - this.data = data; + this.data = data.setDMPermission(false).setNSFW(false); this.isSystemCommand = isSystemCommand || false; this.isNew = isNew || false; this.isBeta = isBeta || false; this.embedOptions = config.get('embedOptions'); } - protected getLogger(source: string, name: string, executionId: string, interaction: Interaction): Logger { - return super.getLoggerBase('slashCommand', source, name, executionId, interaction); + protected getLogger(source: string, executionId: string, interaction: Interaction): Logger { + return super.getLoggerBase('slashCommand', source, executionId, interaction); } abstract execute(params: BaseSlashCommandParams): Promise | void>; diff --git a/src/utils/deploySlashCommands.ts b/src/utils/deploySlashCommands.ts index 1db4a73..8c27480 100644 --- a/src/utils/deploySlashCommands.ts +++ b/src/utils/deploySlashCommands.ts @@ -51,7 +51,6 @@ const rest: REST = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_ process.exit(1); } - /* for (const folder of commandFolders) { const commandFiles: string[] = fs .readdirSync(path.resolve(`./dist/interactions/commands/${folder}`)) @@ -59,18 +58,12 @@ 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()); } } - */ - - const commandModule = await import('../interactions/commands/player/test.js'); - const command = commandModule.default; - slashCommands.push(command.data.toJSON()); try { logger.debug(`Bot user slash commands found: ${slashCommands.map((command) => `/${command.name}`).join(', ')}`); diff --git a/src/utils/registerClientCommands.ts b/src/utils/registerClientCommands.ts index f251f1f..cee2ed5 100644 --- a/src/utils/registerClientCommands.ts +++ b/src/utils/registerClientCommands.ts @@ -18,26 +18,23 @@ export const registerClientCommands = async ({ client, executionId }: RegisterCl 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); + // load command and register it to client.commands collection + const { default: command } = await import(`../interactions/commands/${folder}/${file}`); + client.commands.delete(command.data.name); + client.commands.set(command.data.name, command); } catch (error) { if (error instanceof Error) { logger.error(`Error registering command ${folder}/${file}: ${error.message}`); @@ -46,15 +43,7 @@ export const registerClientCommands = async ({ client, executionId }: RegisterCl } } } - } - */ - - const commandModule = await import('../interactions/commands/player/test.js'); - const command = commandModule.default; - - logger.info(command.data); - client.commands.set('test', command); logger.trace('Registering client commands complete.'); }; From 6d7a931f163065ed755747c44c6da5ca0a09f36b Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Wed, 30 Aug 2023 22:42:40 +0200 Subject: [PATCH 3/8] WIP --- src/handlers/interactionCommandHandler.ts | 7 +++++-- src/interactions/commands/info/help.ts | 20 +++++++++++++++----- src/interactions/commands/player/test.ts | 4 ++-- src/types/clientTypes.ts | 19 ++----------------- src/types/interactionTypes.ts | 13 +++---------- src/utils/deploySlashCommands.ts | 8 +------- 6 files changed, 28 insertions(+), 43 deletions(-) diff --git a/src/handlers/interactionCommandHandler.ts b/src/handlers/interactionCommandHandler.ts index 8efb713..d928317 100644 --- a/src/handlers/interactionCommandHandler.ts +++ b/src/handlers/interactionCommandHandler.ts @@ -1,8 +1,9 @@ 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 { cannotSendMessageInChannel } from '../utils/validation/permissionValidator'; +import { BaseSlashCommandInteraction } from '../types/interactionTypes'; export const handleCommand = async ( interaction: ChatInputCommandInteraction, @@ -20,7 +21,9 @@ export const handleCommand = async ( logger.debug('Interaction deferred.'); // TODO: Update TS Type for command - const command: Command = client.commands?.get(interaction.commandName) as Command; + const command: BaseSlashCommandInteraction = client.commands!.get( + interaction.commandName + ) as BaseSlashCommandInteraction; if (!command) { logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); return; diff --git a/src/interactions/commands/info/help.ts b/src/interactions/commands/info/help.ts index 2bddf4b..d1cc392 100644 --- a/src/interactions/commands/info/help.ts +++ b/src/interactions/commands/info/help.ts @@ -1,5 +1,11 @@ import config from 'config'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { + EmbedBuilder, + SharedSlashCommandOptions, + SlashCommandBuilder, + SlashCommandNumberOption, + SlashCommandStringOption +} from 'discord.js'; import { Logger } from 'pino'; import loggerModule from '../../../services/logger'; import { BotOptions, EmbedOptions } from '../../../types/configTypes'; @@ -27,16 +33,20 @@ const command: BaseSlashCommandInteraction = { }); // TODO: Create interface for command list - const commandList = client!.commands! - .filter((command) => { + const commandList = client! + .commands!.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}\`**` + ' ' : ''; + .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 ? `${embedOptions.icons.beta} ` : ''; const newCommand: string = command.isNew ? `${embedOptions.icons.new} ` : ''; return `- **\`/${command.data.name}\`** ${params}- ${beta}${newCommand}${command.data.description}`; diff --git a/src/interactions/commands/player/test.ts b/src/interactions/commands/player/test.ts index af93a28..7bda8b7 100644 --- a/src/interactions/commands/player/test.ts +++ b/src/interactions/commands/player/test.ts @@ -1,7 +1,7 @@ import { EmbedBuilder, Message, SlashCommandBuilder } from 'discord.js'; -import { BaseCommandInteraction, BaseSlashCommandParams } from '../../../types/interactionTypes'; +import { BaseSlashCommandInteraction, BaseSlashCommandParams } from '../../../types/interactionTypes'; -export class TestCommandInteraction extends BaseCommandInteraction { +export class TestCommandInteraction extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder().setName('test').setDescription('Test command'); super(data); diff --git a/src/types/clientTypes.ts b/src/types/clientTypes.ts index dd99cd7..606a614 100644 --- a/src/types/clientTypes.ts +++ b/src/types/clientTypes.ts @@ -1,24 +1,9 @@ import { Client, Collection } from 'discord.js'; -import { BaseCommandInteraction } from './interactionTypes'; +import { 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; -} -*/ - export interface ExtendedClient extends Client { registerClientCommands?: RegisterClientCommandsFunction; - commands?: Collection; + commands?: Collection; } diff --git a/src/types/interactionTypes.ts b/src/types/interactionTypes.ts index a039df7..8b0168f 100644 --- a/src/types/interactionTypes.ts +++ b/src/types/interactionTypes.ts @@ -22,23 +22,16 @@ export interface BaseSlashCommandParams extends BaseInteractionParams { client?: ExtendedClient; } -interface BaseAutocompleteParams { +interface BaseAutocompleteParams extends BaseInteractionParams { interaction: AutocompleteInteraction; } -interface BaseComponentParams { +interface BaseComponentParams extends BaseInteractionParams { interaction: MessageComponentInteraction; referenceId?: string; } // Interaction types -export interface BaseSlashCommandInteraction { - isNew: boolean; - isBeta: boolean; - isSystemCommand?: boolean; - data: Omit; - execute(params: BaseSlashCommandParams): Promise | void>; -} export interface BaseAutocompleteInteraction { execute(params: BaseAutocompleteParams): Promise; @@ -87,7 +80,7 @@ abstract class BaseInteraction { ): Promise | ApplicationCommandOptionChoiceData | void>; } -export abstract class BaseCommandInteraction extends BaseInteraction { +export abstract class BaseSlashCommandInteraction extends BaseInteraction { data: Omit; isSystemCommand: boolean; isNew: boolean; diff --git a/src/utils/deploySlashCommands.ts b/src/utils/deploySlashCommands.ts index 8c27480..ff5b1f9 100644 --- a/src/utils/deploySlashCommands.ts +++ b/src/utils/deploySlashCommands.ts @@ -1,13 +1,7 @@ import 'dotenv/config'; import config from 'config'; -import { - REST, - RESTPostAPIChatInputApplicationCommandsJSONBody, - 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'; From 335f4bb84e0f47431bb9bb7f8e1db4146c8f5523 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Thu, 31 Aug 2023 11:03:04 +0200 Subject: [PATCH 4/8] WIP few changes to class --- src/interactions/commands/info/help.ts | 70 ++++++++++-------------- src/interactions/commands/player/test.ts | 26 +++++---- src/types/interactionTypes.ts | 22 +++++--- 3 files changed, 57 insertions(+), 61 deletions(-) diff --git a/src/interactions/commands/info/help.ts b/src/interactions/commands/info/help.ts index d1cc392..2f98c3e 100644 --- a/src/interactions/commands/info/help.ts +++ b/src/interactions/commands/info/help.ts @@ -1,38 +1,22 @@ -import config from 'config'; +import { EmbedBuilder, SlashCommandBuilder, SlashCommandNumberOption, SlashCommandStringOption } from 'discord.js'; import { - EmbedBuilder, - SharedSlashCommandOptions, - SlashCommandBuilder, - SlashCommandNumberOption, - SlashCommandStringOption -} from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; -import { BotOptions, EmbedOptions } from '../../../types/configTypes'; -import { BaseSlashCommandInteraction } from '../../../types/interactionTypes'; + 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 a list of commands and their usage.'); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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('help.js', executionId, interaction); - // TODO: Create interface for command list const commandList = client! .commands!.filter((command: BaseSlashCommandInteraction) => { // don't include system commands @@ -47,18 +31,22 @@ const command: BaseSlashCommandInteraction = { if (option instanceof SlashCommandNumberOption || option instanceof SlashCommandStringOption) { params = `**\`${option.name}\`**` + ' '; } - const beta: string = command.isBeta ? `${embedOptions.icons.beta} ` : ''; - const newCommand: string = command.isNew ? `${embedOptions.icons.new} ` : ''; + 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.'); @@ -66,15 +54,15 @@ const command: BaseSlashCommandInteraction = { 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/player/test.ts b/src/interactions/commands/player/test.ts index 7bda8b7..4912529 100644 --- a/src/interactions/commands/player/test.ts +++ b/src/interactions/commands/player/test.ts @@ -1,25 +1,27 @@ -import { EmbedBuilder, Message, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction, BaseSlashCommandParams } from '../../../types/interactionTypes'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { + BaseSlashCommandInteraction, + BaseSlashCommandParams, + BaseSlashCommandReturnType +} from '../../../types/interactionTypes'; -export class TestCommandInteraction extends BaseSlashCommandInteraction { +class TestCommand extends BaseSlashCommandInteraction { constructor() { - const data = new SlashCommandBuilder().setName('test').setDescription('Test command'); + const data = new SlashCommandBuilder() + .setName('test') + .setDescription('This is a test command description lorem ipsum.'); super(data); } - async execute(params: BaseSlashCommandParams): Promise | void> { + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; const logger = this.getLogger('test.js', executionId, interaction); - logger.info('test command executed'); - logger.info(`${interaction.user.tag} executed test command`); - logger.info(`Execution ID: ${executionId}`); - - logger.info(this.embedOptions.icons.success + ' Icon success from config.'); + logger.debug('Responding with success embed.'); return await interaction.editReply({ - embeds: [new EmbedBuilder().setDescription('It works!').setColor(this.embedOptions.colors.success)] + embeds: [new EmbedBuilder().setDescription(`Success reply from command '${this.commandName}'.`).setColor(this.embedOptions.colors.success)] }); } } -export default new TestCommandInteraction(); +export default new TestCommand(); diff --git a/src/types/interactionTypes.ts b/src/types/interactionTypes.ts index 8b0168f..7c19c31 100644 --- a/src/types/interactionTypes.ts +++ b/src/types/interactionTypes.ts @@ -11,7 +11,7 @@ import { import { Logger } from 'pino'; import loggerModule from '../services/logger'; import { ExtendedClient } from './clientTypes'; -import { EmbedOptions } from './configTypes'; +import { BotOptions, EmbedOptions } from './configTypes'; interface BaseInteractionParams { executionId: string; @@ -22,6 +22,8 @@ export interface BaseSlashCommandParams extends BaseInteractionParams { client?: ExtendedClient; } +export type BaseSlashCommandReturnType = Promise | void>; + interface BaseAutocompleteParams extends BaseInteractionParams { interaction: AutocompleteInteraction; } @@ -86,24 +88,28 @@ export abstract class BaseSlashCommandInteraction extends BaseInteraction { isNew: boolean; isBeta: boolean; embedOptions: EmbedOptions; + botOptions: BotOptions; + commandName: string; constructor( data: Omit, - isSystemCommand?: boolean, - isNew?: boolean, - isBeta?: boolean + isSystemCommand: boolean = false, + isNew: boolean = false, + isBeta: boolean = false ) { super(); this.data = data.setDMPermission(false).setNSFW(false); - this.isSystemCommand = isSystemCommand || false; - this.isNew = isNew || false; - this.isBeta = isBeta || false; + this.isSystemCommand = isSystemCommand; + this.isNew = isNew; + this.isBeta = isBeta; this.embedOptions = config.get('embedOptions'); + this.botOptions = config.get('botOptions'); + this.commandName = data.name; } protected getLogger(source: string, executionId: string, interaction: Interaction): Logger { return super.getLoggerBase('slashCommand', source, executionId, interaction); } - abstract execute(params: BaseSlashCommandParams): Promise | void>; + abstract execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType; } From d81fc1d2e75e50436ebd3b786d345e258c1f9c20 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Thu, 31 Aug 2023 13:22:28 +0200 Subject: [PATCH 5/8] converted commands to classes --- src/events/client/disconnect.ts | 4 +- src/events/client/ready.ts | 4 +- src/events/client/reconnecting.ts | 4 +- src/events/player/generalError.ts | 8 +- src/events/player/playerError.ts | 8 +- src/events/player/playerSkip.ts | 8 +- src/handlers/interactionErrorHandler.ts | 4 +- 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/test.ts | 7 +- src/interactions/commands/player/volume.ts | 78 ++++++------ src/interactions/commands/system/guilds.ts | 51 ++++---- src/interactions/commands/system/reload.ts | 50 +++----- src/interactions/commands/system/shards.ts | 94 +++++++------- .../commands/system/systemstatus.ts | 55 ++++----- .../components/filters-disable-button.ts | 6 +- .../components/filters-select-menu.ts | 2 +- .../components/nowplaying-skip-button.ts | 16 +-- src/types/interactionTypes.ts | 8 +- src/utils/validation/permissionValidator.ts | 8 +- src/utils/validation/queueValidator.ts | 12 +- .../validation/systemCommandValidator.ts | 4 +- src/utils/validation/voiceChannelValidator.ts | 8 +- 35 files changed, 618 insertions(+), 768 deletions(-) diff --git a/src/events/client/disconnect.ts b/src/events/client/disconnect.ts index b7217dd..8dfc757 100644 --- a/src/events/client/disconnect.ts +++ b/src/events/client/disconnect.ts @@ -35,10 +35,10 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `${embedOptions.icons.warning} **${client.user?.tag}** is **\`disconnected\`**!` + + `${this.embedOptions.icons.warning} **${client.user?.tag}** is **\`disconnected\`**!` + `\n\n<@${systemOptions.systemUserId}>` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index 7e89f70..1bb7282 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -50,9 +50,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.success} All shards ready**\n**${client.user?.tag}** is now **\`online\`**!` + `**${this.embedOptions.icons.success} All shards ready**\n**${client.user?.tag}** is now **\`online\`**!` ) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ] }); } diff --git a/src/events/client/reconnecting.ts b/src/events/client/reconnecting.ts index 640191e..68be092 100644 --- a/src/events/client/reconnecting.ts +++ b/src/events/client/reconnecting.ts @@ -36,10 +36,10 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `${embedOptions.icons.warning} **${client.user?.tag}** is **\`reconnecting\`**!` + + `${this.embedOptions.icons.warning} **${client.user?.tag}** is **\`reconnecting\`**!` + `\n\n<@${systemOptions.systemUserId}>` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } diff --git a/src/events/player/generalError.ts b/src/events/player/generalError.ts index 2dc5313..3baf3ff 100644 --- a/src/events/player/generalError.ts +++ b/src/events/player/generalError.ts @@ -31,9 +31,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue related to the queue or current track.\n\nIf you performed a command, you can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + `**${this.embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue related to the queue or current track.\n\nIf you performed a command, you can try 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}` }) ] }); @@ -47,10 +47,10 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `${embedOptions.icons.error} **player.events.on('error')**\nExecution id: ${executionId}\n${error.message}` + + `${this.embedOptions.icons.error} **player.events.on('error')**\nExecution id: ${executionId}\n${error.message}` + `\n\n<@${systemOptions.systemUserId}>` ) - .setColor(embedOptions.colors.error) + .setColor(this.embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); diff --git a/src/events/player/playerError.ts b/src/events/player/playerError.ts index e8a1b10..44a13fc 100644 --- a/src/events/player/playerError.ts +++ b/src/events/player/playerError.ts @@ -31,9 +31,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue while streaming the track.\n\nIf you performed a command, you can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + `**${this.embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue while streaming the track.\n\nIf you performed a command, you can try 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}` }) ] }); @@ -47,10 +47,10 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `${embedOptions.icons.error} **player.events.on('playerError')**\nExecution id: ${executionId}\n${error.message}` + + `${this.embedOptions.icons.error} **player.events.on('playerError')**\nExecution id: ${executionId}\n${error.message}` + `\n\n<@${systemOptions.systemUserId}>` ) - .setColor(embedOptions.colors.error) + .setColor(this.embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); diff --git a/src/events/player/playerSkip.ts b/src/events/player/playerSkip.ts index 0755285..c630f38 100644 --- a/src/events/player/playerSkip.ts +++ b/src/events/player/playerSkip.ts @@ -32,9 +32,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue while loading stream for the track.\n\nIf you performed a command, you can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + `**${this.embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue while loading stream for the track.\n\nIf you performed a command, you can try 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}` }) ] }); @@ -48,10 +48,10 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `${embedOptions.icons.error} **player.events.on('playerSkip')**\nExecution id: ${executionId}\n${track.url}` + + `${this.embedOptions.icons.error} **player.events.on('playerSkip')**\nExecution id: ${executionId}\n${track.url}` + `\n\n<@${systemOptions.systemUserId}>` ) - .setColor(embedOptions.colors.error) + .setColor(this.embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); diff --git a/src/handlers/interactionErrorHandler.ts b/src/handlers/interactionErrorHandler.ts index 3f02b5c..5ed5262 100644 --- a/src/handlers/interactionErrorHandler.ts +++ b/src/handlers/interactionErrorHandler.ts @@ -27,9 +27,9 @@ export const handleError = async ( embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to perform this action. You can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + `**${this.embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to perform this action. You can try 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}` }) ] }; diff --git a/src/interactions/commands/info/status.ts b/src/interactions/commands/info/status.ts index 74b2c5c..47582ce 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 { BaseSlashCommandInteraction } 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 the bot and system status.'); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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('status.js', 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: BaseSlashCommandInteraction = { 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 b1d2473..58327f2 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 { BaseSlashCommandInteraction } 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: BaseSlashCommandInteraction = { - 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 during playback.'); + super(data); + } + + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.commandName, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -92,7 +87,7 @@ const command: BaseSlashCommandInteraction = { .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: BaseSlashCommandInteraction = { 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 fa7b545..b7ce843 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 { BaseSlashCommandInteraction } 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 track queue and remove the bot from voice channel.'); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -61,15 +53,15 @@ const command: BaseSlashCommandInteraction = { 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 e7c7868..1f4868c 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 { BaseSlashCommandInteraction } 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('Mode to set for looping.') + .setRequired(false) + .addChoices( + { name: 'Track', value: '1' }, + { name: 'Queue', value: '2' }, + { name: 'Autoplay', value: '3' }, + { name: 'Disabled', value: '0' } + ) + ); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -77,10 +68,10 @@ const command: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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 2dd18c6..63ea313 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 { BaseSlashCommandInteraction } 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('Get lyrics from Genius for current or specified track.') + .addStringOption((option) => + option + .setName('query') + .setDescription('Search query 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: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); const query: string = interaction.options.getString('query')!; const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -84,9 +71,9 @@ const command: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { embeds: [ new EmbedBuilder() .setDescription(`\`\`\`fix\n${message}\`\`\``) - .setColor(embedOptions.colors.info) + .setColor(this.embedOptions.colors.info) ] }); } @@ -195,15 +182,15 @@ const command: BaseSlashCommandInteraction = { 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 78e2c91..5328eb0 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 { BaseSlashCommandInteraction, 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: BaseSlashCommandInteraction = { - 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 track currently playing.'); + super(data); + } + + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.commandName, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -64,11 +59,11 @@ const command: BaseSlashCommandInteraction = { ]); 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: BaseSlashCommandInteraction = { } 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: BaseSlashCommandInteraction = { .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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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 72d01c1..0e46501 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 { BaseSlashCommandInteraction } 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('Pause or resume the current track.'); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -51,7 +42,7 @@ const command: BaseSlashCommandInteraction = { : `\`${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: BaseSlashCommandInteraction = { 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 7bfbd9f..716ae2c 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, BaseSlashCommandInteraction } 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 searching or url.') + .addStringOption((option) => + option + .setName('query') + .setDescription('Search query or URL.') + .setRequired(true) + .setMinLength(2) + .setMaxLength(500) + .setAutocomplete(true) + ); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); let queue: GuildQueue = useQueue(interaction.guild!.id)!; if (queue && (await notInSameVoiceChannel({ interaction, queue, executionId }))) { @@ -83,9 +74,9 @@ const command: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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 2fb542a..df46158 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 { BaseSlashCommandInteraction } 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: BaseSlashCommandInteraction = { - 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 the list of tracks added to the queue.') + .addNumberOption((option) => + option.setName('page').setDescription('Page number of the queue').setMinValue(1) + ); + super(data); + } + + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.commandName, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -58,11 +56,11 @@ const command: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { } 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: BaseSlashCommandInteraction = { 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 2cb40d4..860d34a 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 { BaseSlashCommandInteraction } 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 a specific track from the queue') + .addNumberOption((option) => + option + .setName('tracknumber') + .setDescription('Track number to remove from queue.') + .setMinValue(1) + .setRequired(true) + ); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -59,9 +51,9 @@ const command: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { : `\`${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: BaseSlashCommandInteraction = { 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 8e10096..e7f9c09 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 { BaseSlashCommandInteraction } 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 specified duration in the current track.') + .addStringOption((option) => + option + .setName('duration') + .setDescription('Duration in format 00:00:00 (HH:mm:ss) to seek to.') + .setRequired(true) + ); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -78,12 +70,12 @@ const command: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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 28b6821..59f584b 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 { BaseSlashCommandInteraction } 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('Shuffle tracks in the queue randomly.'); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -60,15 +52,15 @@ const command: BaseSlashCommandInteraction = { 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 da803da..66dc648 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 { BaseSlashCommandInteraction } 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('test') + .setDescription('Skip current or specified track.') + .addNumberOption((option) => + option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1) + ); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -57,9 +49,9 @@ const command: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { : `\`${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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { : `\`${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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { ? '' : `\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 078a027..68554a1 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 { BaseSlashCommandInteraction } 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('Stop playing audio and clear the track queue.'); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -63,15 +55,15 @@ const command: BaseSlashCommandInteraction = { 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/test.ts b/src/interactions/commands/player/test.ts index 4912529..eeff5d2 100644 --- a/src/interactions/commands/player/test.ts +++ b/src/interactions/commands/player/test.ts @@ -15,12 +15,9 @@ class TestCommand extends BaseSlashCommandInteraction { async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger('test.js', executionId, interaction); + const logger = this.getLogger(this.commandName, executionId, interaction); - logger.debug('Responding with success embed.'); - return await interaction.editReply({ - embeds: [new EmbedBuilder().setDescription(`Success reply from command '${this.commandName}'.`).setColor(this.embedOptions.colors.success)] - }); + // logic } } diff --git a/src/interactions/commands/player/volume.ts b/src/interactions/commands/player/volume.ts index 2f0f9a8..e3e255b 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 { BaseSlashCommandInteraction } 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 set the playback volume for tracks.') + .addNumberOption((option) => + option + .setName('percentage') + .setDescription('Set volume percentage from 1% to 100%.') + .setMinValue(0) + .setMaxValue(100) + ); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; @@ -62,10 +54,12 @@ const command: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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: BaseSlashCommandInteraction = { 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 4641038..d2ed62a 100644 --- a/src/interactions/commands/system/guilds.ts +++ b/src/interactions/commands/system/guilds.ts @@ -1,31 +1,22 @@ -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 { BaseSlashCommandInteraction } 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 list of guilds where bot is added.'); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); if (await notValidGuildId({ interaction, executionId })) { return; @@ -35,8 +26,8 @@ const command: BaseSlashCommandInteraction = { 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 +55,7 @@ const command: BaseSlashCommandInteraction = { 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 +69,9 @@ const command: BaseSlashCommandInteraction = { 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 860db44..14570f6 100644 --- a/src/interactions/commands/system/reload.ts +++ b/src/interactions/commands/system/reload.ts @@ -1,32 +1,21 @@ -import config from 'config'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { Logger } from 'pino'; -import loggerModule from '../../../services/logger'; import { ExtendedClient } from '../../../types/clientTypes'; -import { EmbedOptions } from '../../../types/configTypes'; -import { BaseSlashCommandInteraction } 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 the bot commands.'); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); if (await notValidGuildId({ interaction, executionId })) { return; @@ -53,9 +42,9 @@ const command: BaseSlashCommandInteraction = { 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}` }) ] }); @@ -66,13 +55,14 @@ const command: BaseSlashCommandInteraction = { 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 12c2062..c683789 100644 --- a/src/interactions/commands/system/shards.ts +++ b/src/interactions/commands/system/shards.ts @@ -1,49 +1,40 @@ -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 { BaseSlashCommandInteraction, 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 the running shards.') + .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)); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); if (await notValidGuildId({ interaction, executionId })) { return; @@ -122,17 +113,17 @@ const command: BaseSlashCommandInteraction = { 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 +142,8 @@ const command: BaseSlashCommandInteraction = { 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 +175,15 @@ const command: BaseSlashCommandInteraction = { 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 a9abe42..d2ef93f 100644 --- a/src/interactions/commands/system/systemstatus.ts +++ b/src/interactions/commands/system/systemstatus.ts @@ -1,35 +1,26 @@ -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 { BaseSlashCommandInteraction } 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 the bot and system status.'); + super(data); + } -const command: BaseSlashCommandInteraction = { - 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.commandName, executionId, interaction); if (await notValidGuildId({ interaction, executionId })) { return; @@ -132,33 +123,33 @@ const command: BaseSlashCommandInteraction = { 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 019b266..7c1d909 100644 --- a/src/interactions/components/filters-disable-button.ts +++ b/src/interactions/components/filters-disable-button.ts @@ -56,12 +56,12 @@ const component: BaseComponentInteraction = { 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: [] }); diff --git a/src/interactions/components/filters-select-menu.ts b/src/interactions/components/filters-select-menu.ts index cdac0f6..211c847 100644 --- a/src/interactions/components/filters-select-menu.ts +++ b/src/interactions/components/filters-select-menu.ts @@ -103,7 +103,7 @@ const component: BaseComponentInteraction = { }) .join('\n')}` ) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ], components: [] }); diff --git a/src/interactions/components/nowplaying-skip-button.ts b/src/interactions/components/nowplaying-skip-button.ts index 8015325..dd0d62c 100644 --- a/src/interactions/components/nowplaying-skip-button.ts +++ b/src/interactions/components/nowplaying-skip-button.ts @@ -46,9 +46,9 @@ const component: BaseComponentInteraction = { 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 +62,9 @@ const component: BaseComponentInteraction = { 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 +77,7 @@ const component: BaseComponentInteraction = { : `\`${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,10 +105,10 @@ const component: BaseComponentInteraction = { 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}](${ + `**${this.embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${ skippedTrack.raw.url ?? skippedTrack.url })**` + `${ @@ -122,7 +122,7 @@ const component: BaseComponentInteraction = { }` ) .setThumbnail(skippedTrack.thumbnail) - .setColor(embedOptions.colors.success) + .setColor(this.embedOptions.colors.success) ], components: [] }); diff --git a/src/types/interactionTypes.ts b/src/types/interactionTypes.ts index 7c19c31..8c8723f 100644 --- a/src/types/interactionTypes.ts +++ b/src/types/interactionTypes.ts @@ -67,10 +67,10 @@ export class CustomError extends Error { } abstract class BaseInteraction { - protected getLoggerBase(module: string, source: string, executionId: string, interaction: Interaction): Logger { + protected getLoggerBase(module: string, name: string, executionId: string, interaction: Interaction): Logger { return loggerModule.child({ - source: source, module: module, + name: name, executionId: executionId, shardId: interaction.guild?.shardId, guildId: interaction.guild?.id @@ -107,8 +107,8 @@ export abstract class BaseSlashCommandInteraction extends BaseInteraction { this.commandName = data.name; } - protected getLogger(source: string, executionId: string, interaction: Interaction): Logger { - return super.getLoggerBase('slashCommand', source, executionId, interaction); + protected getLogger(name: string, executionId: string, interaction: Interaction): Logger { + return super.getLoggerBase('slashCommand', name, executionId, interaction); } abstract execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType; diff --git a/src/utils/validation/permissionValidator.ts b/src/utils/validation/permissionValidator.ts index 8cd39a1..27f81e6 100644 --- a/src/utils/validation/permissionValidator.ts +++ b/src/utils/validation/permissionValidator.ts @@ -35,9 +35,9 @@ export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: Cannot embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nI do not have permission to play audio in the voice channel you are in.\n\nPlease make sure I have the **\`Connect\`** and **\`Speak\`** permissions in this voice channel.` + `**${this.embedOptions.icons.warning} Oops!**\nI do not have permission to play audio in the voice channel you are in.\n\nPlease make sure I have the **\`Connect\`** and **\`Speak\`** permissions in this voice channel.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); @@ -84,9 +84,9 @@ export const cannotSendMessageInChannel = async ({ interaction, executionId }: C embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nI do not have permission to send message replies in the channel you are in.\n\nPlease make sure I have the **\`View Channel\`** permission in this text channel.` + `**${this.embedOptions.icons.warning} Oops!**\nI do not have permission to send message replies in the channel you are in.\n\nPlease make sure I have the **\`View Channel\`** permission in this text channel.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); } diff --git a/src/utils/validation/queueValidator.ts b/src/utils/validation/queueValidator.ts index dbd037c..7384eff 100644 --- a/src/utils/validation/queueValidator.ts +++ b/src/utils/validation/queueValidator.ts @@ -25,9 +25,9 @@ export const queueDoesNotExist = async ({ interaction, queue, executionId }: Que embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` + `**${this.embedOptions.icons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); @@ -56,9 +56,9 @@ export const queueNoCurrentTrack = async ({ interaction, queue, executionId }: Q 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) ] }); @@ -87,9 +87,9 @@ export const queueIsEmpty = async ({ interaction, queue, executionId }: QueueIsE embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nThere are no tracks added to the queue. First add some tracks with **\`/play\`**!` + `**${this.embedOptions.icons.warning} Oops!**\nThere are no tracks added to the queue. First add some tracks with **\`/play\`**!` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); diff --git a/src/utils/validation/systemCommandValidator.ts b/src/utils/validation/systemCommandValidator.ts index 9e7ac31..0513ab3 100644 --- a/src/utils/validation/systemCommandValidator.ts +++ b/src/utils/validation/systemCommandValidator.ts @@ -26,9 +26,9 @@ export const notValidGuildId = async ({ interaction, executionId }: NotValidGuil embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command **\`/${interactionIdentifier}\`** cannot be executed in this server.` + `**${this.embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command **\`/${interactionIdentifier}\`** cannot be executed in this server.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); diff --git a/src/utils/validation/voiceChannelValidator.ts b/src/utils/validation/voiceChannelValidator.ts index af1211e..1102a99 100644 --- a/src/utils/validation/voiceChannelValidator.ts +++ b/src/utils/validation/voiceChannelValidator.ts @@ -25,9 +25,9 @@ export const notInVoiceChannel = async ({ interaction, executionId }: NotInVoice embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Not in a voice channel**\nYou need to be in a voice channel to use this command.` + `**${this.embedOptions.icons.warning} Not in a voice channel**\nYou need to be in a voice channel to use this command.` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); @@ -64,9 +64,9 @@ export const notInSameVoiceChannel = async ({ interaction, queue, executionId }: embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Not in same voice channel**\nYou need to be in the same voice channel as me to use this command.\n\n**Voice channel:** ${queue.dispatcher.channel.name}` + `**${this.embedOptions.icons.warning} Not in same voice channel**\nYou need to be in the same voice channel as me to use this command.\n\n**Voice channel:** ${queue.dispatcher.channel.name}` ) - .setColor(embedOptions.colors.warning) + .setColor(this.embedOptions.colors.warning) ] }); From 775d942e2d472668184d9ed93ab9a30b4a1a52d1 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Thu, 31 Aug 2023 13:46:25 +0200 Subject: [PATCH 6/8] solve build errors --- src/events/client/disconnect.ts | 4 ++-- src/events/client/ready.ts | 4 ++-- src/events/client/reconnecting.ts | 4 ++-- src/events/player/generalError.ts | 8 +++---- src/events/player/playerError.ts | 8 +++---- src/events/player/playerSkip.ts | 8 +++---- src/handlers/interactionErrorHandler.ts | 4 ++-- src/interactions/commands/player/test.ts | 24 ------------------- src/interactions/commands/system/reload.ts | 15 +++++++++--- .../components/filters-disable-button.ts | 6 ++--- .../components/filters-select-menu.ts | 2 +- .../components/nowplaying-skip-button.ts | 16 ++++++------- src/utils/validation/permissionValidator.ts | 8 +++---- src/utils/validation/queueValidator.ts | 12 +++++----- .../validation/systemCommandValidator.ts | 4 ++-- src/utils/validation/voiceChannelValidator.ts | 8 +++---- 16 files changed, 60 insertions(+), 75 deletions(-) delete mode 100644 src/interactions/commands/player/test.ts diff --git a/src/events/client/disconnect.ts b/src/events/client/disconnect.ts index 8dfc757..b7217dd 100644 --- a/src/events/client/disconnect.ts +++ b/src/events/client/disconnect.ts @@ -35,10 +35,10 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `${this.embedOptions.icons.warning} **${client.user?.tag}** is **\`disconnected\`**!` + + `${embedOptions.icons.warning} **${client.user?.tag}** is **\`disconnected\`**!` + `\n\n<@${systemOptions.systemUserId}>` ) - .setColor(this.embedOptions.colors.warning) + .setColor(embedOptions.colors.warning) ] }); } diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index 1bb7282..7e89f70 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -50,9 +50,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.success} All shards ready**\n**${client.user?.tag}** is now **\`online\`**!` + `**${embedOptions.icons.success} All shards ready**\n**${client.user?.tag}** is now **\`online\`**!` ) - .setColor(this.embedOptions.colors.success) + .setColor(embedOptions.colors.success) ] }); } diff --git a/src/events/client/reconnecting.ts b/src/events/client/reconnecting.ts index 68be092..640191e 100644 --- a/src/events/client/reconnecting.ts +++ b/src/events/client/reconnecting.ts @@ -36,10 +36,10 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `${this.embedOptions.icons.warning} **${client.user?.tag}** is **\`reconnecting\`**!` + + `${embedOptions.icons.warning} **${client.user?.tag}** is **\`reconnecting\`**!` + `\n\n<@${systemOptions.systemUserId}>` ) - .setColor(this.embedOptions.colors.warning) + .setColor(embedOptions.colors.warning) ] }); } diff --git a/src/events/player/generalError.ts b/src/events/player/generalError.ts index 3baf3ff..2dc5313 100644 --- a/src/events/player/generalError.ts +++ b/src/events/player/generalError.ts @@ -31,9 +31,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue related to the queue or current track.\n\nIf you performed a command, you can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._` + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue related to the queue or current track.\n\nIf you performed a command, you can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` ) - .setColor(this.embedOptions.colors.error) + .setColor(embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); @@ -47,10 +47,10 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `${this.embedOptions.icons.error} **player.events.on('error')**\nExecution id: ${executionId}\n${error.message}` + + `${embedOptions.icons.error} **player.events.on('error')**\nExecution id: ${executionId}\n${error.message}` + `\n\n<@${systemOptions.systemUserId}>` ) - .setColor(this.embedOptions.colors.error) + .setColor(embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); diff --git a/src/events/player/playerError.ts b/src/events/player/playerError.ts index 44a13fc..e8a1b10 100644 --- a/src/events/player/playerError.ts +++ b/src/events/player/playerError.ts @@ -31,9 +31,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue while streaming the track.\n\nIf you performed a command, you can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._` + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue while streaming the track.\n\nIf you performed a command, you can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` ) - .setColor(this.embedOptions.colors.error) + .setColor(embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); @@ -47,10 +47,10 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `${this.embedOptions.icons.error} **player.events.on('playerError')**\nExecution id: ${executionId}\n${error.message}` + + `${embedOptions.icons.error} **player.events.on('playerError')**\nExecution id: ${executionId}\n${error.message}` + `\n\n<@${systemOptions.systemUserId}>` ) - .setColor(this.embedOptions.colors.error) + .setColor(embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); diff --git a/src/events/player/playerSkip.ts b/src/events/player/playerSkip.ts index c630f38..0755285 100644 --- a/src/events/player/playerSkip.ts +++ b/src/events/player/playerSkip.ts @@ -32,9 +32,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue while loading stream for the track.\n\nIf you performed a command, you can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._` + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue while loading stream for the track.\n\nIf you performed a command, you can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` ) - .setColor(this.embedOptions.colors.error) + .setColor(embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); @@ -48,10 +48,10 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `${this.embedOptions.icons.error} **player.events.on('playerSkip')**\nExecution id: ${executionId}\n${track.url}` + + `${embedOptions.icons.error} **player.events.on('playerSkip')**\nExecution id: ${executionId}\n${track.url}` + `\n\n<@${systemOptions.systemUserId}>` ) - .setColor(this.embedOptions.colors.error) + .setColor(embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }); diff --git a/src/handlers/interactionErrorHandler.ts b/src/handlers/interactionErrorHandler.ts index 5ed5262..3f02b5c 100644 --- a/src/handlers/interactionErrorHandler.ts +++ b/src/handlers/interactionErrorHandler.ts @@ -27,9 +27,9 @@ export const handleError = async ( embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to perform this action. You can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._` + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to perform this action. You can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` ) - .setColor(this.embedOptions.colors.error) + .setColor(embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) ] }; diff --git a/src/interactions/commands/player/test.ts b/src/interactions/commands/player/test.ts deleted file mode 100644 index eeff5d2..0000000 --- a/src/interactions/commands/player/test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { - BaseSlashCommandInteraction, - BaseSlashCommandParams, - BaseSlashCommandReturnType -} from '../../../types/interactionTypes'; - -class TestCommand extends BaseSlashCommandInteraction { - constructor() { - const data = new SlashCommandBuilder() - .setName('test') - .setDescription('This is a test command description lorem ipsum.'); - super(data); - } - - async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { - const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); - - // logic - } -} - -export default new TestCommand(); diff --git a/src/interactions/commands/system/reload.ts b/src/interactions/commands/system/reload.ts index 14570f6..a134b79 100644 --- a/src/interactions/commands/system/reload.ts +++ b/src/interactions/commands/system/reload.ts @@ -1,4 +1,4 @@ -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { ApplicationCommandOption, ApplicationCommandOptionData, EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { ExtendedClient } from '../../../types/clientTypes'; import { BaseSlashCommandInteraction, @@ -50,8 +50,17 @@ class ReloadCommand extends BaseSlashCommandInteraction { }); } - 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!.commands?.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}`; }); diff --git a/src/interactions/components/filters-disable-button.ts b/src/interactions/components/filters-disable-button.ts index 7c1d909..019b266 100644 --- a/src/interactions/components/filters-disable-button.ts +++ b/src/interactions/components/filters-disable-button.ts @@ -56,12 +56,12 @@ const component: BaseComponentInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl }) .setDescription( - `**${this.embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.` + `**${embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.` ) - .setColor(this.embedOptions.colors.success) + .setColor(embedOptions.colors.success) ], components: [] }); diff --git a/src/interactions/components/filters-select-menu.ts b/src/interactions/components/filters-select-menu.ts index 211c847..cdac0f6 100644 --- a/src/interactions/components/filters-select-menu.ts +++ b/src/interactions/components/filters-select-menu.ts @@ -103,7 +103,7 @@ const component: BaseComponentInteraction = { }) .join('\n')}` ) - .setColor(this.embedOptions.colors.success) + .setColor(embedOptions.colors.success) ], components: [] }); diff --git a/src/interactions/components/nowplaying-skip-button.ts b/src/interactions/components/nowplaying-skip-button.ts index dd0d62c..8015325 100644 --- a/src/interactions/components/nowplaying-skip-button.ts +++ b/src/interactions/components/nowplaying-skip-button.ts @@ -46,9 +46,9 @@ const component: BaseComponentInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(this.embedOptions.colors.warning) + .setColor(embedOptions.colors.warning) ], components: [] }); @@ -62,9 +62,9 @@ const component: BaseComponentInteraction = { embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.` + `**${embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.` ) - .setColor(this.embedOptions.colors.warning) + .setColor(embedOptions.colors.warning) ], components: [] }); @@ -77,7 +77,7 @@ const component: BaseComponentInteraction = { : `\`${skippedTrack.duration}\``; if (skippedTrack.raw.live) { - durationFormat = `${this.embedOptions.icons.liveTrack} \`LIVE\``; + durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; } queue.node.skip(); logger.debug('Skipped the track.'); @@ -105,10 +105,10 @@ const component: BaseComponentInteraction = { new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl + iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl }) .setDescription( - `**${this.embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${ + `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${ skippedTrack.raw.url ?? skippedTrack.url })**` + `${ @@ -122,7 +122,7 @@ const component: BaseComponentInteraction = { }` ) .setThumbnail(skippedTrack.thumbnail) - .setColor(this.embedOptions.colors.success) + .setColor(embedOptions.colors.success) ], components: [] }); diff --git a/src/utils/validation/permissionValidator.ts b/src/utils/validation/permissionValidator.ts index 27f81e6..8cd39a1 100644 --- a/src/utils/validation/permissionValidator.ts +++ b/src/utils/validation/permissionValidator.ts @@ -35,9 +35,9 @@ export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: Cannot embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.warning} Oops!**\nI do not have permission to play audio in the voice channel you are in.\n\nPlease make sure I have the **\`Connect\`** and **\`Speak\`** permissions in this voice channel.` + `**${embedOptions.icons.warning} Oops!**\nI do not have permission to play audio in the voice channel you are in.\n\nPlease make sure I have the **\`Connect\`** and **\`Speak\`** permissions in this voice channel.` ) - .setColor(this.embedOptions.colors.warning) + .setColor(embedOptions.colors.warning) ] }); @@ -84,9 +84,9 @@ export const cannotSendMessageInChannel = async ({ interaction, executionId }: C embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.warning} Oops!**\nI do not have permission to send message replies in the channel you are in.\n\nPlease make sure I have the **\`View Channel\`** permission in this text channel.` + `**${embedOptions.icons.warning} Oops!**\nI do not have permission to send message replies in the channel you are in.\n\nPlease make sure I have the **\`View Channel\`** permission in this text channel.` ) - .setColor(this.embedOptions.colors.warning) + .setColor(embedOptions.colors.warning) ] }); } diff --git a/src/utils/validation/queueValidator.ts b/src/utils/validation/queueValidator.ts index 7384eff..dbd037c 100644 --- a/src/utils/validation/queueValidator.ts +++ b/src/utils/validation/queueValidator.ts @@ -25,9 +25,9 @@ export const queueDoesNotExist = async ({ interaction, queue, executionId }: Que embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(this.embedOptions.colors.warning) + .setColor(embedOptions.colors.warning) ] }); @@ -56,9 +56,9 @@ export const queueNoCurrentTrack = async ({ interaction, queue, executionId }: Q embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(this.embedOptions.colors.warning) + .setColor(embedOptions.colors.warning) ] }); @@ -87,9 +87,9 @@ export const queueIsEmpty = async ({ interaction, queue, executionId }: QueueIsE embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.warning} Oops!**\nThere are no tracks added to the queue. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere are no tracks added to the queue. First add some tracks with **\`/play\`**!` ) - .setColor(this.embedOptions.colors.warning) + .setColor(embedOptions.colors.warning) ] }); diff --git a/src/utils/validation/systemCommandValidator.ts b/src/utils/validation/systemCommandValidator.ts index 0513ab3..9e7ac31 100644 --- a/src/utils/validation/systemCommandValidator.ts +++ b/src/utils/validation/systemCommandValidator.ts @@ -26,9 +26,9 @@ export const notValidGuildId = async ({ interaction, executionId }: NotValidGuil embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command **\`/${interactionIdentifier}\`** cannot be executed in this server.` + `**${embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command **\`/${interactionIdentifier}\`** cannot be executed in this server.` ) - .setColor(this.embedOptions.colors.warning) + .setColor(embedOptions.colors.warning) ] }); diff --git a/src/utils/validation/voiceChannelValidator.ts b/src/utils/validation/voiceChannelValidator.ts index 1102a99..af1211e 100644 --- a/src/utils/validation/voiceChannelValidator.ts +++ b/src/utils/validation/voiceChannelValidator.ts @@ -25,9 +25,9 @@ export const notInVoiceChannel = async ({ interaction, executionId }: NotInVoice embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.warning} Not in a voice channel**\nYou need to be in a voice channel to use this command.` + `**${embedOptions.icons.warning} Not in a voice channel**\nYou need to be in a voice channel to use this command.` ) - .setColor(this.embedOptions.colors.warning) + .setColor(embedOptions.colors.warning) ] }); @@ -64,9 +64,9 @@ export const notInSameVoiceChannel = async ({ interaction, queue, executionId }: embeds: [ new EmbedBuilder() .setDescription( - `**${this.embedOptions.icons.warning} Not in same voice channel**\nYou need to be in the same voice channel as me to use this command.\n\n**Voice channel:** ${queue.dispatcher.channel.name}` + `**${embedOptions.icons.warning} Not in same voice channel**\nYou need to be in the same voice channel as me to use this command.\n\n**Voice channel:** ${queue.dispatcher.channel.name}` ) - .setColor(this.embedOptions.colors.warning) + .setColor(embedOptions.colors.warning) ] }); From ddeaf82c113972fb3b89733578818a6a4864cb97 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Thu, 31 Aug 2023 15:39:23 +0200 Subject: [PATCH 7/8] update command descriptions and set logger name --- src/interactions/autocomplete/lyrics.ts | 34 +++--- src/interactions/autocomplete/play.ts | 33 +++--- src/interactions/commands/info/help.ts | 4 +- src/interactions/commands/info/status.ts | 4 +- src/interactions/commands/player/filters.ts | 4 +- src/interactions/commands/player/leave.ts | 4 +- src/interactions/commands/player/loop.ts | 4 +- src/interactions/commands/player/lyrics.ts | 6 +- .../commands/player/nowplaying.ts | 4 +- src/interactions/commands/player/pause.ts | 4 +- src/interactions/commands/player/play.ts | 6 +- src/interactions/commands/player/queue.ts | 6 +- src/interactions/commands/player/remove.ts | 6 +- src/interactions/commands/player/seek.ts | 6 +- src/interactions/commands/player/shuffle.ts | 4 +- src/interactions/commands/player/skip.ts | 6 +- src/interactions/commands/player/stop.ts | 4 +- src/interactions/commands/player/volume.ts | 6 +- src/interactions/commands/system/guilds.ts | 7 +- src/interactions/commands/system/reload.ts | 9 +- src/interactions/commands/system/shards.ts | 13 ++- .../commands/system/systemstatus.ts | 7 +- .../components/filters-disable-button.ts | 35 +++--- .../components/filters-select-menu.ts | 33 +++--- .../components/nowplaying-skip-button.ts | 56 ++++------ src/types/interactionTypes.ts | 103 ++++++++++++------ 26 files changed, 209 insertions(+), 199 deletions(-) diff --git a/src/interactions/autocomplete/lyrics.ts b/src/interactions/autocomplete/lyrics.ts index 8094edf..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 { BaseAutocompleteInteraction } 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: BaseAutocompleteInteraction = { - 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: BaseAutocompleteInteraction = { 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 57f78c5..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 { BaseAutocompleteInteraction } 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: BaseAutocompleteInteraction = { - 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: BaseAutocompleteInteraction = { 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 2f98c3e..d8801f3 100644 --- a/src/interactions/commands/info/help.ts +++ b/src/interactions/commands/info/help.ts @@ -9,13 +9,13 @@ class HelpCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('help') - .setDescription('Show a list of commands and their usage.'); + .setDescription('Show the list of bot commands.'); super(data); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, client, interaction } = params; - const logger = this.getLogger('help.js', executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const commandList = client! .commands!.filter((command: BaseSlashCommandInteraction) => { diff --git a/src/interactions/commands/info/status.ts b/src/interactions/commands/info/status.ts index 47582ce..d4830a2 100644 --- a/src/interactions/commands/info/status.ts +++ b/src/interactions/commands/info/status.ts @@ -11,13 +11,13 @@ import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted'; class StatusCommand extends BaseSlashCommandInteraction { constructor() { - const data = new SlashCommandBuilder().setName('status').setDescription('Show the bot and system status.'); + const data = new SlashCommandBuilder().setName('status').setDescription('Show operational status of the bot.'); super(data); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction, client } = params; - const logger = this.getLogger('status.js', executionId, interaction); + 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'); diff --git a/src/interactions/commands/player/filters.ts b/src/interactions/commands/player/filters.ts index 58327f2..5380e53 100644 --- a/src/interactions/commands/player/filters.ts +++ b/src/interactions/commands/player/filters.ts @@ -28,13 +28,13 @@ class FiltersCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('filters') - .setDescription('Toggle various audio filters during playback.'); + .setDescription('Toggle various audio filters.'); super(data); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/commands/player/leave.ts b/src/interactions/commands/player/leave.ts index b7ce843..62303cb 100644 --- a/src/interactions/commands/player/leave.ts +++ b/src/interactions/commands/player/leave.ts @@ -12,13 +12,13 @@ class LeaveCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('leave') - .setDescription('Clear the track queue and remove the bot from voice channel.'); + .setDescription('Clear the queue and remove bot from voice channel.'); super(data); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/commands/player/loop.ts b/src/interactions/commands/player/loop.ts index 1f4868c..92f32f7 100644 --- a/src/interactions/commands/player/loop.ts +++ b/src/interactions/commands/player/loop.ts @@ -16,7 +16,7 @@ class LoopCommand extends BaseSlashCommandInteraction { .addStringOption(() => new SlashCommandStringOption() .setName('mode') - .setDescription('Mode to set for looping.') + .setDescription('Loop mode: Track, queue, autoplay or disabled.') .setRequired(false) .addChoices( { name: 'Track', value: '1' }, @@ -30,7 +30,7 @@ class LoopCommand extends BaseSlashCommandInteraction { async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/commands/player/lyrics.ts b/src/interactions/commands/player/lyrics.ts index 63ea313..0350e03 100644 --- a/src/interactions/commands/player/lyrics.ts +++ b/src/interactions/commands/player/lyrics.ts @@ -13,11 +13,11 @@ class LyricsCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('lyrics') - .setDescription('Get lyrics from Genius for current or specified track.') + .setDescription('Search Genius lyrics for current or specified track.') .addStringOption((option) => option .setName('query') - .setDescription('Search query or URL.') + .setDescription('Search query by text or URL.') .setRequired(false) .setMinLength(2) .setMaxLength(500) @@ -28,7 +28,7 @@ class LyricsCommand extends BaseSlashCommandInteraction { async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const query: string = interaction.options.getString('query')!; const queue: GuildQueue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/commands/player/nowplaying.ts b/src/interactions/commands/player/nowplaying.ts index 5328eb0..cb46422 100644 --- a/src/interactions/commands/player/nowplaying.ts +++ b/src/interactions/commands/player/nowplaying.ts @@ -26,13 +26,13 @@ class NowPlayingCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('nowplaying') - .setDescription('Show information about the track currently playing.'); + .setDescription('Show information about the current track.'); super(data); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/commands/player/pause.ts b/src/interactions/commands/player/pause.ts index 0e46501..0ff6c73 100644 --- a/src/interactions/commands/player/pause.ts +++ b/src/interactions/commands/player/pause.ts @@ -11,13 +11,13 @@ import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validat class PauseCommand extends BaseSlashCommandInteraction { constructor() { - const data = new SlashCommandBuilder().setName('pause').setDescription('Pause or resume the current track.'); + const data = new SlashCommandBuilder().setName('pause').setDescription('Toggle pause for the current track.'); super(data); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/commands/player/play.ts b/src/interactions/commands/player/play.ts index 716ae2c..26f69df 100644 --- a/src/interactions/commands/player/play.ts +++ b/src/interactions/commands/player/play.ts @@ -18,11 +18,11 @@ class PlayCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('play') - .setDescription('Add a track or playlist to the queue by searching or url.') + .setDescription('Add a track or playlist to the queue by search query or URL.') .addStringOption((option) => option .setName('query') - .setDescription('Search query or URL.') + .setDescription('Search query by text or URL') .setRequired(true) .setMinLength(2) .setMaxLength(500) @@ -33,7 +33,7 @@ class PlayCommand extends BaseSlashCommandInteraction { async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); let queue: GuildQueue = useQueue(interaction.guild!.id)!; if (queue && (await notInSameVoiceChannel({ interaction, queue, executionId }))) { diff --git a/src/interactions/commands/player/queue.ts b/src/interactions/commands/player/queue.ts index df46158..95b83d7 100644 --- a/src/interactions/commands/player/queue.ts +++ b/src/interactions/commands/player/queue.ts @@ -17,16 +17,16 @@ class QueueCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('queue') - .setDescription('Show the list of tracks added to the queue.') + .setDescription('Show tracks that have been added to the queue.') .addNumberOption((option) => - option.setName('page').setDescription('Page number of the queue').setMinValue(1) + 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.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/commands/player/remove.ts b/src/interactions/commands/player/remove.ts index 860d34a..b21a31c 100644 --- a/src/interactions/commands/player/remove.ts +++ b/src/interactions/commands/player/remove.ts @@ -12,11 +12,11 @@ class RemoveCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('remove') - .setDescription('Remove a specific track from the queue') + .setDescription('Remove specified track from the queue') .addNumberOption((option) => option .setName('tracknumber') - .setDescription('Track number to remove from queue.') + .setDescription('The position in queue for track to remove.') .setMinValue(1) .setRequired(true) ); @@ -25,7 +25,7 @@ class RemoveCommand extends BaseSlashCommandInteraction { async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/commands/player/seek.ts b/src/interactions/commands/player/seek.ts index e7f9c09..c39651b 100644 --- a/src/interactions/commands/player/seek.ts +++ b/src/interactions/commands/player/seek.ts @@ -12,11 +12,11 @@ class SeekCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('seek') - .setDescription('Seek to a specified duration in the current track.') + .setDescription('Seek to a duration in the current track.') .addStringOption((option) => option .setName('duration') - .setDescription('Duration in format 00:00:00 (HH:mm:ss) to seek to.') + .setDescription('Duration in format 00:00:00 (HH:mm:ss).') .setRequired(true) ); super(data); @@ -24,7 +24,7 @@ class SeekCommand extends BaseSlashCommandInteraction { async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/commands/player/shuffle.ts b/src/interactions/commands/player/shuffle.ts index 59f584b..d870195 100644 --- a/src/interactions/commands/player/shuffle.ts +++ b/src/interactions/commands/player/shuffle.ts @@ -12,13 +12,13 @@ class ShuffleCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('shuffle') - .setDescription('Shuffle tracks in the queue randomly.'); + .setDescription('Randomly shuffle all tracks in the queue.'); super(data); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/commands/player/skip.ts b/src/interactions/commands/player/skip.ts index 66dc648..34f1c97 100644 --- a/src/interactions/commands/player/skip.ts +++ b/src/interactions/commands/player/skip.ts @@ -12,16 +12,16 @@ class SkipCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('test') - .setDescription('Skip current or specified track.') + .setDescription('Skip track to next or specified position in queue.') .addNumberOption((option) => - option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1) + option.setName('tracknumber').setDescription('The position in queue to skip to.').setMinValue(1) ); super(data); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/commands/player/stop.ts b/src/interactions/commands/player/stop.ts index 68554a1..620d3fd 100644 --- a/src/interactions/commands/player/stop.ts +++ b/src/interactions/commands/player/stop.ts @@ -12,13 +12,13 @@ class StopCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('stop') - .setDescription('Stop playing audio and clear the track queue.'); + .setDescription('Clear the queue and stop playing audio.'); super(data); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/commands/player/volume.ts b/src/interactions/commands/player/volume.ts index e3e255b..18779e6 100644 --- a/src/interactions/commands/player/volume.ts +++ b/src/interactions/commands/player/volume.ts @@ -12,11 +12,11 @@ class VolumeCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('volume') - .setDescription('Show or set the playback volume for tracks.') + .setDescription('Show or change the playback volume for tracks.') .addNumberOption((option) => option .setName('percentage') - .setDescription('Set volume percentage from 1% to 100%.') + .setDescription('Volume percentage: From 1% to 100%.') .setMinValue(0) .setMaxValue(100) ); @@ -25,7 +25,7 @@ class VolumeCommand extends BaseSlashCommandInteraction { async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); const queue: GuildQueue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/commands/system/guilds.ts b/src/interactions/commands/system/guilds.ts index d2ed62a..0213822 100644 --- a/src/interactions/commands/system/guilds.ts +++ b/src/interactions/commands/system/guilds.ts @@ -10,13 +10,14 @@ class GuildsCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('guilds') - .setDescription('Show list of guilds where bot is added.'); - super(data); + .setDescription('Show the top 25 guilds by member count.'); + const isSystemCommand: boolean = true; + super(data, isSystemCommand); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction, client } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); if (await notValidGuildId({ interaction, executionId })) { return; diff --git a/src/interactions/commands/system/reload.ts b/src/interactions/commands/system/reload.ts index a134b79..eb4ed5f 100644 --- a/src/interactions/commands/system/reload.ts +++ b/src/interactions/commands/system/reload.ts @@ -9,13 +9,16 @@ import { notValidGuildId } from '../../../utils/validation/systemCommandValidato class ReloadCommand extends BaseSlashCommandInteraction { constructor() { - const data = new SlashCommandBuilder().setName('reload').setDescription('Reload the bot commands.'); - super(data); + const data = new SlashCommandBuilder() + .setName('reload') + .setDescription('Reload all slash commands across shards.'); + const isSystemCommand: boolean = true; + super(data, isSystemCommand); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction, client } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); if (await notValidGuildId({ interaction, executionId })) { return; diff --git a/src/interactions/commands/system/shards.ts b/src/interactions/commands/system/shards.ts index c683789..d7ccdaf 100644 --- a/src/interactions/commands/system/shards.ts +++ b/src/interactions/commands/system/shards.ts @@ -12,11 +12,11 @@ class ShardsCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('shards') - .setDescription('Show information about the running shards.') + .setDescription('Show information about all connected shards.') .addStringOption((option) => option .setName('sort') - .setDescription('If specified, what to sort the shards by.') + .setDescription('What to sort the shards by.') .setRequired(false) .addChoices( { name: 'None (Shard ID)', value: 'none' }, @@ -28,13 +28,16 @@ class ShardsCommand extends BaseSlashCommandInteraction { { name: 'Members', value: 'members' } ) ) - .addNumberOption((option) => option.setName('page').setDescription('Page number to show').setMinValue(1)); - super(data); + .addNumberOption((option) => + option.setName('page').setDescription('Page number to display for the shards').setMinValue(1) + ); + const isSystemCommand: boolean = true; + super(data, isSystemCommand); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction, client } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); if (await notValidGuildId({ interaction, executionId })) { return; diff --git a/src/interactions/commands/system/systemstatus.ts b/src/interactions/commands/system/systemstatus.ts index d2ef93f..93d238c 100644 --- a/src/interactions/commands/system/systemstatus.ts +++ b/src/interactions/commands/system/systemstatus.ts @@ -14,13 +14,14 @@ class SystemStatusCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() .setName('systemstatus') - .setDescription('Show the bot and system status.'); - super(data); + .setDescription('Show operational status of the bot with additional technical information.'); + const isSystemCommand: boolean = true; + super(data, isSystemCommand); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction, client } = params; - const logger = this.getLogger(this.commandName, executionId, interaction); + const logger = this.getLogger(this.name, executionId, interaction); if (await notValidGuildId({ interaction, executionId })) { return; diff --git a/src/interactions/components/filters-disable-button.ts b/src/interactions/components/filters-disable-button.ts index 019b266..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 { BaseComponentInteraction } 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: BaseComponentInteraction = { - 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: BaseComponentInteraction = { 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 cdac0f6..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 { BaseComponentInteraction } 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: BaseComponentInteraction = { - 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: BaseComponentInteraction = { }) .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: BaseComponentInteraction = { }) .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 8015325..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 { BaseComponentInteraction } 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: BaseComponentInteraction = { - 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: BaseComponentInteraction = { 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: BaseComponentInteraction = { 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: BaseComponentInteraction = { : `\`${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: BaseComponentInteraction = { 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/interactionTypes.ts b/src/types/interactionTypes.ts index 8c8723f..9bc3f4f 100644 --- a/src/types/interactionTypes.ts +++ b/src/types/interactionTypes.ts @@ -13,36 +13,6 @@ import loggerModule from '../services/logger'; import { ExtendedClient } from './clientTypes'; import { BotOptions, EmbedOptions } from './configTypes'; -interface BaseInteractionParams { - executionId: string; -} - -export interface BaseSlashCommandParams extends BaseInteractionParams { - interaction: ChatInputCommandInteraction; - client?: ExtendedClient; -} - -export type BaseSlashCommandReturnType = Promise | void>; - -interface BaseAutocompleteParams extends BaseInteractionParams { - interaction: AutocompleteInteraction; -} - -interface BaseComponentParams extends BaseInteractionParams { - interaction: MessageComponentInteraction; - referenceId?: string; -} - -// Interaction types - -export interface BaseAutocompleteInteraction { - execute(params: BaseAutocompleteParams): Promise; -} - -export interface BaseComponentInteraction { - execute(params: BaseComponentParams): Promise | void>; -} - export interface ShardInfo { shardId: number; memUsage: number; @@ -66,8 +36,37 @@ export class CustomError extends Error { 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): Logger { + protected getLoggerBase( + module: string, + name: string, + executionId: string, + interaction: Interaction | MessageComponentInteraction + ): Logger { return loggerModule.child({ module: module, name: name, @@ -89,7 +88,7 @@ export abstract class BaseSlashCommandInteraction extends BaseInteraction { isBeta: boolean; embedOptions: EmbedOptions; botOptions: BotOptions; - commandName: string; + name: string; constructor( data: Omit, @@ -104,12 +103,46 @@ export abstract class BaseSlashCommandInteraction extends BaseInteraction { this.isBeta = isBeta; this.embedOptions = config.get('embedOptions'); this.botOptions = config.get('botOptions'); - this.commandName = data.name; + this.name = data.name; } - protected getLogger(name: string, executionId: string, interaction: Interaction): Logger { - return super.getLoggerBase('slashCommand', name, executionId, interaction); + 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; +} From 475c5c58d6a36d1fae8e89b9b5a36798c8dba91b Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Thu, 31 Aug 2023 17:27:08 +0200 Subject: [PATCH 8/8] Add registering of all interactions to client --- src/bot.ts | 10 +- src/events/interactions/interactionCreate.ts | 23 +++- .../interactionAutocompleteHandler.ts | 23 +++- src/handlers/interactionCommandHandler.ts | 26 ++-- src/handlers/interactionComponentHandler.ts | 27 ++-- src/handlers/interactionErrorHandler.ts | 12 +- src/interactions/commands/info/help.ts | 2 +- src/interactions/commands/player/skip.ts | 2 +- src/interactions/commands/system/reload.ts | 4 +- src/types/clientTypes.ts | 10 +- src/types/utilTypes.ts | 2 +- src/utils/registerClientCommands.ts | 49 ------- src/utils/registerClientInteractions.ts | 124 ++++++++++++++++++ 13 files changed, 217 insertions(+), 97 deletions(-) delete mode 100644 src/utils/registerClientCommands.ts create mode 100644 src/utils/registerClientInteractions.ts diff --git a/src/bot.ts b/src/bot.ts index 366b812..5cc22a5 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -7,7 +7,7 @@ import loggerModule from './services/logger'; import { ExtendedClient } from './types/clientTypes'; import { createClient } from './utils/factory/createClient'; import { createPlayer } from './utils/factory/createPlayer'; -import { registerClientCommands } from './utils/registerClientCommands'; +import { registerClientInteractions } from './utils/registerClientInteractions'; import { registerEventListeners } from './utils/registerEventListeners'; import { Player } from 'discord-player'; import { Logger } from 'pino'; @@ -25,14 +25,14 @@ const logger: Logger = loggerModule.child({ try { const client: ExtendedClient = await createClient({ executionId }); const player: Player = await createPlayer({ client, executionId }); - + client.on('allShardsReady', async () => { - client.registerClientCommands = registerClientCommands; + client.registerClientInteractions = registerClientInteractions; await registerEventListeners({ client, player, executionId }); - await registerClientCommands({ client, executionId }); + await registerClientInteractions({ client, executionId }); client.emit('ready', client as Client); }); - + client.login(process.env.DISCORD_BOT_TOKEN); } catch (error) { logger.error(error); diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index 751dcc2..d9e0d93 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -47,15 +47,30 @@ module.exports = { logger.debug('Started handling interaction.'); switch (interaction.type) { case InteractionType.ApplicationCommand: - await handleCommand(interaction as ChatInputCommandInteraction, client, executionId); + await handleCommand( + interaction as ChatInputCommandInteraction, + client, + executionId, + interactionIdentifier + ); break; case InteractionType.ApplicationCommandAutocomplete: - await handleAutocomplete(interaction as AutocompleteInteraction, executionId); + await handleAutocomplete( + interaction as AutocompleteInteraction, + client, + executionId, + interactionIdentifier + ); break; case InteractionType.MessageComponent: - await handleComponent(interaction as MessageComponentInteraction, executionId); + await handleComponent( + interaction as MessageComponentInteraction, + client, + executionId, + interactionIdentifier + ); break; default: @@ -67,7 +82,7 @@ module.exports = { } } catch (error) { logger.debug('Error while handling received interaction.'); - await handleError(interaction, error as CustomError, interactionIdentifier, executionId); + await handleError(interaction, error as CustomError, executionId, interactionIdentifier); } const outputTime: number = new Date().getTime(); diff --git a/src/handlers/interactionAutocompleteHandler.ts b/src/handlers/interactionAutocompleteHandler.ts index fe65513..7310231 100644 --- a/src/handlers/interactionAutocompleteHandler.ts +++ b/src/handlers/interactionAutocompleteHandler.ts @@ -1,20 +1,31 @@ import { AutocompleteInteraction } from 'discord.js'; import { Logger } from 'pino'; import loggerModule from '../services/logger'; +import { ExtendedClient } from '../types/clientTypes'; +import { BaseAutocompleteInteraction } from '../types/interactionTypes'; -export const handleAutocomplete = async (interaction: AutocompleteInteraction, executionId: string) => { +export const handleAutocomplete = async ( + interaction: AutocompleteInteraction, + client: ExtendedClient, + executionId: string, + interactionIdentifier: string +) => { // TODO: Define TS Type for handlers, and require logger constant? const logger: Logger = loggerModule.child({ - source: 'interactionCutocompleteHandler.ts', + source: 'interactionAutocompleteHandler.ts', module: 'handler', name: 'interactionAutocompleteHandler', executionId: executionId }); - // TODO: Create TS Type for autocompleteModule - const autocompleteModule = await import(`../interactions/autocomplete/${interaction.commandName}.js`); - const { default: autocomplete } = autocompleteModule; + const autocomplete: BaseAutocompleteInteraction = client.autocompleteInteractions!.get( + interactionIdentifier + ) as BaseAutocompleteInteraction; + if (!autocomplete) { + logger.warn(`Interaction created but autocomplete '${interactionIdentifier}' was not found.`); + return; + } - logger.debug('Executing autocomplete interaction.'); + logger.debug(`Executing autocomplete interaction '${interactionIdentifier}'.`); await autocomplete.execute({ interaction, executionId }); }; diff --git a/src/handlers/interactionCommandHandler.ts b/src/handlers/interactionCommandHandler.ts index d928317..e7ddb4a 100644 --- a/src/handlers/interactionCommandHandler.ts +++ b/src/handlers/interactionCommandHandler.ts @@ -2,13 +2,14 @@ import { ChatInputCommandInteraction } from 'discord.js'; import { Logger } from 'pino'; import loggerModule from '../services/logger'; import { ExtendedClient } from '../types/clientTypes'; -import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator'; import { BaseSlashCommandInteraction } from '../types/interactionTypes'; +import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator'; export const handleCommand = async ( interaction: ChatInputCommandInteraction, client: ExtendedClient, - executionId: string + executionId: string, + interactionIdentifier: string ) => { const logger: Logger = loggerModule.child({ source: 'interactionCommandHandler.ts', @@ -20,19 +21,18 @@ export const handleCommand = async ( await interaction.deferReply(); logger.debug('Interaction deferred.'); - // TODO: Update TS Type for command - const command: BaseSlashCommandInteraction = client.commands!.get( - interaction.commandName - ) as BaseSlashCommandInteraction; - if (!command) { - logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); - return; - } - if (await cannotSendMessageInChannel({ interaction, executionId })) { return; } - logger.debug('Executing command interaction.'); - await command.execute({ interaction, client, executionId }); + const slashCommand: BaseSlashCommandInteraction = client.slashCommandInteractions!.get( + interactionIdentifier + ) as BaseSlashCommandInteraction; + if (!slashCommand) { + logger.warn(`Interaction created but slash command '${interactionIdentifier}' was not found.`); + return; + } + + logger.debug(`Executing slash command interaction '${interactionIdentifier}'.`); + await slashCommand.execute({ interaction, client, executionId }); }; diff --git a/src/handlers/interactionComponentHandler.ts b/src/handlers/interactionComponentHandler.ts index 55fb172..34ff9e5 100644 --- a/src/handlers/interactionComponentHandler.ts +++ b/src/handlers/interactionComponentHandler.ts @@ -1,9 +1,16 @@ import { MessageComponentInteraction } from 'discord.js'; import { Logger } from 'pino'; import loggerModule from '../services/logger'; +import { ExtendedClient } from '../types/clientTypes'; +import { BaseComponentInteraction } from '../types/interactionTypes'; import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator'; -export const handleComponent = async (interaction: MessageComponentInteraction, executionId: string) => { +export const handleComponent = async ( + interaction: MessageComponentInteraction, + client: ExtendedClient, + executionId: string, + interactionIdentifier: string +) => { const logger: Logger = loggerModule.child({ source: 'interactionComponentHandler.js', module: 'handler', @@ -14,19 +21,23 @@ export const handleComponent = async (interaction: MessageComponentInteraction, await interaction.deferReply(); logger.debug('Interaction deferred.'); - const componentId: string = interaction.customId.split('_')[0]; - const referenceId: string = interaction.customId.split('_')[1]; + const componentId: string = interactionIdentifier.split('_')[0]; + const referenceId: string = interactionIdentifier.split('_')[1]; - logger.debug(`Parsed componentId: ${componentId}`); + logger.debug(`Parsed componentId '${componentId}' from identifier '${interactionIdentifier}'.`); if (await cannotSendMessageInChannel({ interaction, executionId })) { return; } - // TODO: Create TS Type for component - const componentModule = await import(`../interactions/components/${componentId}.js`); - const { default: component } = componentModule; + const component: BaseComponentInteraction = client.componentInteractions!.get( + componentId + ) as BaseComponentInteraction; + if (!component) { + logger.warn(`Interaction created but component '${componentId}' was not found.`); + return; + } - logger.debug('Executing component interaction.'); + logger.debug(`Executing component interaction '${componentId}'.`); await component.execute({ interaction, referenceId, executionId }); }; diff --git a/src/handlers/interactionErrorHandler.ts b/src/handlers/interactionErrorHandler.ts index 3f02b5c..b3def55 100644 --- a/src/handlers/interactionErrorHandler.ts +++ b/src/handlers/interactionErrorHandler.ts @@ -1,5 +1,11 @@ import config from 'config'; -import { ChatInputCommandInteraction, EmbedBuilder, Interaction, InteractionReplyOptions, MessageComponentInteraction } from 'discord.js'; +import { + ChatInputCommandInteraction, + EmbedBuilder, + Interaction, + InteractionReplyOptions, + MessageComponentInteraction +} from 'discord.js'; import { Logger } from 'pino'; import loggerModule from '../services/logger'; import { BotOptions, EmbedOptions } from '../types/configTypes'; @@ -12,8 +18,8 @@ const botOptions: BotOptions = config.get('botOptions'); export const handleError = async ( interaction: Interaction, error: CustomError, - interactionIdentifier: string, - executionId: string + executionId: string, + interactionIdentifier: string ) => { const logger: Logger = loggerModule.child({ source: 'interactionErrorHandler.ts', diff --git a/src/interactions/commands/info/help.ts b/src/interactions/commands/info/help.ts index d8801f3..2a6d22a 100644 --- a/src/interactions/commands/info/help.ts +++ b/src/interactions/commands/info/help.ts @@ -18,7 +18,7 @@ class HelpCommand extends BaseSlashCommandInteraction { const logger = this.getLogger(this.name, executionId, interaction); const commandList = client! - .commands!.filter((command: BaseSlashCommandInteraction) => { + .slashCommandInteractions!.filter((command: BaseSlashCommandInteraction) => { // don't include system commands if (command.isSystemCommand) { return false; diff --git a/src/interactions/commands/player/skip.ts b/src/interactions/commands/player/skip.ts index 34f1c97..1bf00c3 100644 --- a/src/interactions/commands/player/skip.ts +++ b/src/interactions/commands/player/skip.ts @@ -11,7 +11,7 @@ import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validat class SkipCommand extends BaseSlashCommandInteraction { constructor() { const data = new SlashCommandBuilder() - .setName('test') + .setName('skip') .setDescription('Skip track to next or specified position in queue.') .addNumberOption((option) => option.setName('tracknumber').setDescription('The position in queue to skip to.').setMinValue(1) diff --git a/src/interactions/commands/system/reload.ts b/src/interactions/commands/system/reload.ts index eb4ed5f..7170792 100644 --- a/src/interactions/commands/system/reload.ts +++ b/src/interactions/commands/system/reload.ts @@ -29,7 +29,7 @@ class ReloadCommand extends BaseSlashCommandInteraction { await client! .shard!.broadcastEval( async (shardClient: ExtendedClient, { executionId }) => { - shardClient.registerClientCommands!({ client: shardClient, executionId }); + shardClient.registerClientInteractions!({ client: shardClient, executionId }); }, { context: { executionId: executionId } } ) @@ -53,7 +53,7 @@ class ReloadCommand extends BaseSlashCommandInteraction { }); } - const commands: string[] | undefined = client!.commands?.map((command: BaseSlashCommandInteraction) => { + const commands: string[] | undefined = client!.slashCommandInteractions?.map((command: BaseSlashCommandInteraction) => { let params: string = ''; if (command.data.options && command.data.options.length > 1) { diff --git a/src/types/clientTypes.ts b/src/types/clientTypes.ts index 606a614..cd2a1b0 100644 --- a/src/types/clientTypes.ts +++ b/src/types/clientTypes.ts @@ -1,9 +1,11 @@ import { Client, Collection } from 'discord.js'; -import { BaseSlashCommandInteraction } from './interactionTypes'; +import { BaseAutocompleteInteraction, BaseComponentInteraction, BaseSlashCommandInteraction } from './interactionTypes'; -type RegisterClientCommandsFunction = (params: { client: Client; executionId: string }) => void; +type RegisterClientInteractionsFunction = (params: { client: Client; executionId: string }) => void; export interface ExtendedClient extends Client { - registerClientCommands?: RegisterClientCommandsFunction; - commands?: Collection; + registerClientInteractions?: RegisterClientInteractionsFunction; + slashCommandInteractions?: Collection; + autocompleteInteractions?: Collection; + componentInteractions?: Collection; } diff --git a/src/types/utilTypes.ts b/src/types/utilTypes.ts index 86e5eb0..3ea3e2f 100644 --- a/src/types/utilTypes.ts +++ b/src/types/utilTypes.ts @@ -9,7 +9,7 @@ export interface RegisterEventListenersParams { executionId: string; } -export interface RegisterClientCommandsParams { +export interface RegisterClientInteractionsParams { client: ExtendedClient; executionId: string; } diff --git a/src/utils/registerClientCommands.ts b/src/utils/registerClientCommands.ts deleted file mode 100644 index cee2ed5..0000000 --- a/src/utils/registerClientCommands.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Collection } from 'discord.js'; -import fs from 'node:fs'; -import path from 'node:path'; - -import loggerModule from '../services/logger'; -import { RegisterClientCommandsParams } from '../types/utilTypes'; -import { Logger } from 'pino'; - -export const registerClientCommands = async ({ client, executionId }: RegisterClientCommandsParams) => { - const logger: Logger = loggerModule.child({ - source: 'registerClientCommands.js', - module: 'register', - name: 'registerClientCommands', - executionId: executionId, - shardId: client.shard?.ids[0] - }); - - logger.debug('Registering client commands...'); - client.commands = new Collection(); - - const commandFolders: string[] = fs.readdirSync(path.resolve('./dist/interactions/commands')); - for (const folder of commandFolders) { - logger.trace(`Registering client commands for folder '${folder}'...`); - - const commandFiles: string[] = fs - .readdirSync(path.resolve(`./dist/interactions/commands/${folder}`)) - .filter((file) => file.endsWith('.js')); - - for (const file of commandFiles) { - try { - // delete command from require cache - delete require.cache[require.resolve(`../interactions/commands/${folder}/${file}`)]; - - // load command and register it to client.commands collection - const { default: command } = await import(`../interactions/commands/${folder}/${file}`); - client.commands.delete(command.data.name); - client.commands.set(command.data.name, command); - } catch (error) { - if (error instanceof Error) { - logger.error(`Error registering command ${folder}/${file}: ${error.message}`); - } else { - throw error; - } - } - } - } - - logger.trace('Registering client commands complete.'); -}; diff --git a/src/utils/registerClientInteractions.ts b/src/utils/registerClientInteractions.ts new file mode 100644 index 0000000..2a95b54 --- /dev/null +++ b/src/utils/registerClientInteractions.ts @@ -0,0 +1,124 @@ +import { Collection } from 'discord.js'; +import fs from 'node:fs'; +import path from 'node:path'; + +import loggerModule from '../services/logger'; +import { RegisterClientInteractionsParams } from '../types/utilTypes'; +import { Logger } from 'pino'; +import { ExtendedClient } from '../types/clientTypes'; + +export const registerClientInteractions = async ({ client, executionId }: RegisterClientInteractionsParams) => { + const logger: Logger = loggerModule.child({ + source: 'registerClientInteractions.js', + module: 'register', + name: 'registerClientInteractions', + executionId: executionId, + shardId: client.shard?.ids[0] + }); + + await registerSlashCommandInteractions(logger, client); + await registerAutocompleteInteractions(logger, client); + await registerComponentInteractions(logger, client); + + logger.debug('Registering all client interactions complete.'); +}; + +async function registerSlashCommandInteractions(logger: Logger, client: ExtendedClient) { + logger.debug('Registering client slash command interactions...'); + client.slashCommandInteractions = new Collection(); + + const baseFolderPath = './dist/interactions/commands'; + const slashCommandInteractionFolders: string[] = fs.readdirSync(path.resolve(baseFolderPath)); + + for (const categoryFolder of slashCommandInteractionFolders) { + logger.trace(`Registering client commands for folder '${categoryFolder}'...`); + + const files: string[] = fs + .readdirSync(path.resolve(`${baseFolderPath}/${categoryFolder}`)) + .filter((file) => file.endsWith('.js')); + + for (const file of files) { + try { + const filePath = path.resolve(`${baseFolderPath}/${categoryFolder}/${file}`); + + // delete require cache for file + delete require.cache[filePath]; + + // import and register to client collection + const { default: slashCommandInteraction } = await import(filePath); + client.slashCommandInteractions.delete(slashCommandInteraction.name); + client.slashCommandInteractions.set(slashCommandInteraction.name, slashCommandInteraction); + } catch (error) { + if (error instanceof Error) { + logger.error( + `Error registering slash command interaction '${categoryFolder}/${file}': ${error.message}` + ); + } else { + throw error; + } + } + } + } + + logger.trace('Registering client slash command interactions complete.'); +} + +async function registerAutocompleteInteractions(logger: Logger, client: ExtendedClient) { + logger.debug('Registering client autocomplete interactions...'); + client.autocompleteInteractions = new Collection(); + + const baseFolderPath = './dist/interactions/autocomplete'; + const files: string[] = fs.readdirSync(path.resolve(`${baseFolderPath}`)).filter((file) => file.endsWith('.js')); + + for (const file of files) { + try { + const filePath = path.resolve(`${baseFolderPath}/${file}`); + + // delete require cache for file + delete require.cache[filePath]; + + // import and register to client collection + const { default: autocompleteInteraction } = await import(filePath); + client.autocompleteInteractions.delete(autocompleteInteraction.name); + client.autocompleteInteractions.set(autocompleteInteraction.name, autocompleteInteraction); + } catch (error) { + if (error instanceof Error) { + logger.error(`Error registering autocomplete interaction '${file}': ${error.message}`); + } else { + throw error; + } + } + } + + logger.trace('Registering client autocomplete interactions complete.'); +} + +async function registerComponentInteractions(logger: Logger, client: ExtendedClient) { + logger.debug('Registering client component interactions...'); + client.componentInteractions = new Collection(); + + const baseFolderPath = './dist/interactions/components'; + const files: string[] = fs.readdirSync(path.resolve(`${baseFolderPath}`)).filter((file) => file.endsWith('.js')); + + for (const file of files) { + try { + const filePath = path.resolve(`${baseFolderPath}/${file}`); + + // delete require cache for file + delete require.cache[filePath]; + + // import and register to client collection + const { default: componentInteraction } = await import(filePath); + client.componentInteractions.delete(componentInteraction.name); + client.componentInteractions.set(componentInteraction.name, componentInteraction); + } catch (error) { + if (error instanceof Error) { + logger.error(`Error registering component interaction '${file}': ${error.message}`); + } else { + throw error; + } + } + } + + logger.trace('Registering client component interactions complete.'); +}