From 9b02b21283e3b66a2aa0197b39b31a8a48ff4abf Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 23:20:32 +0200 Subject: [PATCH 01/14] feat!: Change interaction structure and handling of component responses --- src/events/interactions/interactionCreate.ts | 16 +- src/{ => interactions}/commands/info/help.ts | 6 +- .../commands/info/status.ts | 10 +- .../commands/player/filters.ts | 10 +- .../commands/player/leave.ts | 8 +- .../commands/player/loop.ts | 10 +- .../commands/player/lyrics.ts | 10 +- .../commands/player/nowplaying.ts | 147 ++---------------- .../commands/player/pause.ts | 10 +- .../commands/player/play.ts | 12 +- .../commands/player/queue.ts | 8 +- .../commands/player/remove.ts | 10 +- .../commands/player/seek.ts | 10 +- .../commands/player/shuffle.ts | 10 +- .../commands/player/skip.ts | 10 +- .../commands/player/stop.ts | 8 +- .../commands/player/volume.ts | 10 +- .../commands/system/guilds.ts | 8 +- .../commands/system/reload.ts | 10 +- .../commands/system/shards.ts | 10 +- .../commands/system/systemstatus.ts | 12 +- .../component/nowplaying-skip-button.ts | 111 +++++++++++++ src/types/interactionTypes.ts | 7 + src/utils/registerClientCommands.ts | 8 +- 24 files changed, 232 insertions(+), 239 deletions(-) rename src/{ => interactions}/commands/info/help.ts (93%) rename src/{ => interactions}/commands/info/status.ts (94%) rename src/{ => interactions}/commands/player/filters.ts (96%) rename src/{ => interactions}/commands/player/leave.ts (92%) rename src/{ => interactions}/commands/player/loop.ts (95%) rename src/{ => interactions}/commands/player/lyrics.ts (97%) rename src/{ => interactions}/commands/player/nowplaying.ts (53%) rename src/{ => interactions}/commands/player/pause.ts (90%) rename src/{ => interactions}/commands/player/play.ts (98%) rename src/{ => interactions}/commands/player/queue.ts (97%) rename src/{ => interactions}/commands/player/remove.ts (92%) rename src/{ => interactions}/commands/player/seek.ts (96%) rename src/{ => interactions}/commands/player/shuffle.ts (88%) rename src/{ => interactions}/commands/player/skip.ts (95%) rename src/{ => interactions}/commands/player/stop.ts (92%) rename src/{ => interactions}/commands/player/volume.ts (94%) rename src/{ => interactions}/commands/system/guilds.ts (91%) rename src/{ => interactions}/commands/system/reload.ts (90%) rename src/{ => interactions}/commands/system/shards.ts (96%) rename src/{ => interactions}/commands/system/systemstatus.ts (94%) create mode 100644 src/interactions/component/nowplaying-skip-button.ts create mode 100644 src/types/interactionTypes.ts diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index d313058..a704a74 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { EmbedBuilder, Events, Interaction, StringSelectMenuInteraction } from 'discord.js'; +import { EmbedBuilder, Events, Interaction } from 'discord.js'; import { v4 as uuidv4 } from 'uuid'; import loggerModule from '../../services/logger'; @@ -24,15 +24,11 @@ module.exports = { }); if (interaction.isMessageComponent()) { - if (interaction instanceof StringSelectMenuInteraction) { - logger.debug( - `Message component interaction created for id ${interaction.customId}${ - interaction.values ? ' and values ' + interaction.values : '' - }.` - ); - } - - return; + await interaction.deferReply(); + const componentId = interaction.customId.split('_')[0]; + const trackId = interaction.customId.split('_')[1]; + const componentModule = await import(`../../interactions/component/${componentId}.js`); + return componentModule.execute({ interaction, trackId, executionId }); } if (interaction.isChatInputCommand() || interaction.isAutocomplete()) { diff --git a/src/commands/info/help.ts b/src/interactions/commands/info/help.ts similarity index 93% rename from src/commands/info/help.ts rename to src/interactions/commands/info/help.ts index 7e98801..693c21b 100644 --- a/src/commands/info/help.ts +++ b/src/interactions/commands/info/help.ts @@ -1,9 +1,9 @@ import config from 'config'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { BotOptions, EmbedOptions } from '../../types/configTypes'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { BotOptions, EmbedOptions } from '../../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); diff --git a/src/commands/info/status.ts b/src/interactions/commands/info/status.ts similarity index 94% rename from src/commands/info/status.ts rename to src/interactions/commands/info/status.ts index 7105116..619cff7 100644 --- a/src/commands/info/status.ts +++ b/src/interactions/commands/info/status.ts @@ -3,11 +3,11 @@ import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; import osu from 'node-os-utils'; // @ts-ignore -import { version } from '../../../package.json'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted'; +import { version } from '../../../../package.json'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted'; const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { diff --git a/src/commands/player/filters.ts b/src/interactions/commands/player/filters.ts similarity index 96% rename from src/commands/player/filters.ts rename to src/interactions/commands/player/filters.ts index fb25c8e..454dbb4 100644 --- a/src/commands/player/filters.ts +++ b/src/interactions/commands/player/filters.ts @@ -14,11 +14,11 @@ import { StringSelectMenuOptionBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams, CustomError } from '../../types/commandTypes'; -import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../types/configTypes'; -import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandParams, CustomError } from '../../../types/commandTypes'; +import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../../types/configTypes'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions'); diff --git a/src/commands/player/leave.ts b/src/interactions/commands/player/leave.ts similarity index 92% rename from src/commands/player/leave.ts rename to src/interactions/commands/player/leave.ts index 9b5308e..894a0df 100644 --- a/src/commands/player/leave.ts +++ b/src/interactions/commands/player/leave.ts @@ -2,10 +2,10 @@ import config from 'config'; import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { diff --git a/src/commands/player/loop.ts b/src/interactions/commands/player/loop.ts similarity index 95% rename from src/commands/player/loop.ts rename to src/interactions/commands/player/loop.ts index 1424691..3f6a42d 100644 --- a/src/commands/player/loop.ts +++ b/src/interactions/commands/player/loop.ts @@ -2,11 +2,11 @@ import config from 'config'; import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { BotOptions, EmbedOptions } from '../../types/configTypes'; -import { queueDoesNotExist } from '../../utils/validation/queueValidator'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { BotOptions, EmbedOptions } from '../../../types/configTypes'; +import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); diff --git a/src/commands/player/lyrics.ts b/src/interactions/commands/player/lyrics.ts similarity index 97% rename from src/commands/player/lyrics.ts rename to src/interactions/commands/player/lyrics.ts index 332fa83..4f90ec1 100644 --- a/src/commands/player/lyrics.ts +++ b/src/interactions/commands/player/lyrics.ts @@ -4,11 +4,11 @@ import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { lyricsExtractor } from '@discord-player/extractor'; -import loggerModule from '../../services/logger'; -import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandAutocompleteParams, CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const recentQueries = new Map(); diff --git a/src/commands/player/nowplaying.ts b/src/interactions/commands/player/nowplaying.ts similarity index 53% rename from src/commands/player/nowplaying.ts rename to src/interactions/commands/player/nowplaying.ts index f56a8d9..9154b1d 100644 --- a/src/commands/player/nowplaying.ts +++ b/src/interactions/commands/player/nowplaying.ts @@ -7,19 +7,18 @@ import { ButtonStyle, ComponentType, EmbedBuilder, - GuildMember, - Interaction, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams, TrackMetadata, CustomError } from '../../types/commandTypes'; -import { EmbedOptions, PlayerOptions } from '../../types/configTypes'; -import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandParams, TrackMetadata } from '../../../types/commandTypes'; +import { EmbedOptions, PlayerOptions } from '../../../types/configTypes'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); + module.exports = { isNew: false, isBeta: false, @@ -110,15 +109,18 @@ module.exports = { bar = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`; } + const customId = `nowplaying-skip-button_${currentTrack.id}`; + logger.debug(`Generated custom id for skip button: ${customId}`); + const nowPlayingButton = new ButtonBuilder() - .setCustomId('nowplaying-skip') + .setCustomId(customId) .setLabel('Skip track') .setStyle(ButtonStyle.Secondary) .setEmoji(embedOptions.icons.nextTrack) - .toJSON(); // Convert the builder to a raw object + .toJSON(); const nowPlayingActionRow: APIActionRowComponent = { - type: ComponentType.ActionRow, // This might vary based on your discord.js version + type: ComponentType.ActionRow, components: [nowPlayingButton] }; @@ -134,7 +136,7 @@ module.exports = { logger.debug('Successfully retrieved information about the current track.'); logger.debug('Sending info embed with action row components.'); - const response = await interaction.editReply({ + await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ @@ -185,128 +187,5 @@ module.exports = { }); logger.debug('Finished sending response.'); - - const collectorFilter = (i: Interaction) => i.user.id === interaction.user.id; - try { - const confirmation = await response.awaitMessageComponent({ - filter: collectorFilter, - time: 300_000 - }); - - confirmation.deferUpdate(); - - logger.debug('Received component interaction response.'); - - if (confirmation.customId === 'nowplaying-skip') { - logger.debug('Received skip confirmation.'); - if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { - logger.debug('Tried skipping track but there was no queue.'); - - logger.debug('Responding with warning embed.'); - return await interaction.followUp({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` - ) - .setColor(embedOptions.colors.warning) - ], - components: [] - }); - } - - if (queue.currentTrack !== currentTrack) { - logger.debug( - 'Tried skipping track but it is not the current track and therefore already skipped/removed.' - ); - - logger.debug('Responding with warning embed.'); - return await interaction.followUp({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.` - ) - .setColor(embedOptions.colors.warning) - ], - components: [] - }); - } - - const skippedTrack = queue.currentTrack; - let durationFormat = - Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00' - ? '' - : `\`${skippedTrack.duration}\``; - - if (skippedTrack.raw.live) { - durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; - } - queue.node.skip(); - logger.debug('Skipped the track.'); - - const repeatModeUserString = loopModesFormatted.get(queue.repeatMode); - - let authorName: string; - - if (interaction.member instanceof GuildMember) { - authorName = interaction.member.nickname || interaction.user.username; - } else { - authorName = interaction.user.username; - } - - logger.debug('Responding with success embed.'); - return await interaction.followUp({ - embeds: [ - new EmbedBuilder() - .setAuthor({ - name: authorName, - iconURL: interaction.user.avatarURL() || '' - }) - .setDescription( - `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${ - skippedTrack.title - }](${skippedTrack.raw.url ?? skippedTrack.url})**` + - `${ - queue.repeatMode === 0 - ? '' - : `\n\n**${ - queue.repeatMode === 3 - ? embedOptions.icons.autoplaying - : embedOptions.icons.looping - } Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.` - }` - ) - .setThumbnail(skippedTrack.thumbnail) - .setColor(embedOptions.colors.success) - ], - components: [] - }); - } - } catch (error) { - if (error instanceof CustomError) { - if (error.code === 'InteractionCollectorError') { - logger.debug('Interaction response timed out.'); - return; - } - - if (error.message === 'Collector received no interactions before ending with reason: time') { - logger.debug('Interaction response timed out.'); - return; - } - - logger.error(error, 'Unhandled error while awaiting or handling component interaction.'); - return; - } else { - if ( - error instanceof Error && - error.message === 'Collector received no interactions before ending with reason: time' - ) { - logger.debug('Interaction response timed out.'); - return; - } - throw error; - } - } } }; diff --git a/src/commands/player/pause.ts b/src/interactions/commands/player/pause.ts similarity index 90% rename from src/commands/player/pause.ts rename to src/interactions/commands/player/pause.ts index 029cf31..0b8c484 100644 --- a/src/commands/player/pause.ts +++ b/src/interactions/commands/player/pause.ts @@ -2,11 +2,11 @@ import config from 'config'; import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { diff --git a/src/commands/player/play.ts b/src/interactions/commands/player/play.ts similarity index 98% rename from src/commands/player/play.ts rename to src/interactions/commands/player/play.ts index 371689c..53ac4d5 100644 --- a/src/commands/player/play.ts +++ b/src/interactions/commands/player/play.ts @@ -2,12 +2,12 @@ import config from 'config'; import { useMainPlayer, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes'; -import { BotOptions, EmbedOptions, PlayerOptions } from '../../types/configTypes'; -import { cannotJoinVoiceOrTalk } from '../../utils/validation/permissionValidator'; -import { transformQuery } from '../../utils/validation/searchQueryValidator'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandAutocompleteParams, CommandParams } from '../../../types/commandTypes'; +import { BotOptions, EmbedOptions, PlayerOptions } from '../../../types/configTypes'; +import { cannotJoinVoiceOrTalk } from '../../../utils/validation/permissionValidator'; +import { transformQuery } from '../../../utils/validation/searchQueryValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); diff --git a/src/commands/player/queue.ts b/src/interactions/commands/player/queue.ts similarity index 97% rename from src/commands/player/queue.ts rename to src/interactions/commands/player/queue.ts index 02208fd..62a3896 100644 --- a/src/commands/player/queue.ts +++ b/src/interactions/commands/player/queue.ts @@ -2,10 +2,10 @@ import config from 'config'; import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions, PlayerOptions } from '../../types/configTypes'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions, PlayerOptions } from '../../../types/configTypes'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); diff --git a/src/commands/player/remove.ts b/src/interactions/commands/player/remove.ts similarity index 92% rename from src/commands/player/remove.ts rename to src/interactions/commands/player/remove.ts index de23dc2..511e448 100644 --- a/src/commands/player/remove.ts +++ b/src/interactions/commands/player/remove.ts @@ -2,11 +2,11 @@ import config from 'config'; import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { queueDoesNotExist } from '../../utils/validation/queueValidator'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { diff --git a/src/commands/player/seek.ts b/src/interactions/commands/player/seek.ts similarity index 96% rename from src/commands/player/seek.ts rename to src/interactions/commands/player/seek.ts index 2d18851..b88198e 100644 --- a/src/commands/player/seek.ts +++ b/src/interactions/commands/player/seek.ts @@ -2,11 +2,11 @@ import config from 'config'; import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { diff --git a/src/commands/player/shuffle.ts b/src/interactions/commands/player/shuffle.ts similarity index 88% rename from src/commands/player/shuffle.ts rename to src/interactions/commands/player/shuffle.ts index e5692e8..82a9dd8 100644 --- a/src/commands/player/shuffle.ts +++ b/src/interactions/commands/player/shuffle.ts @@ -2,11 +2,11 @@ import config from 'config'; import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { queueDoesNotExist, queueIsEmpty } from '../../utils/validation/queueValidator'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { queueDoesNotExist, queueIsEmpty } from '../../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { diff --git a/src/commands/player/skip.ts b/src/interactions/commands/player/skip.ts similarity index 95% rename from src/commands/player/skip.ts rename to src/interactions/commands/player/skip.ts index 7724852..a284b26 100644 --- a/src/commands/player/skip.ts +++ b/src/interactions/commands/player/skip.ts @@ -2,11 +2,11 @@ import config from 'config'; import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { diff --git a/src/commands/player/stop.ts b/src/interactions/commands/player/stop.ts similarity index 92% rename from src/commands/player/stop.ts rename to src/interactions/commands/player/stop.ts index c3c15c7..f5e3564 100644 --- a/src/commands/player/stop.ts +++ b/src/interactions/commands/player/stop.ts @@ -2,10 +2,10 @@ import config from 'config'; import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { diff --git a/src/commands/player/volume.ts b/src/interactions/commands/player/volume.ts similarity index 94% rename from src/commands/player/volume.ts rename to src/interactions/commands/player/volume.ts index 989e652..6cb9cc3 100644 --- a/src/commands/player/volume.ts +++ b/src/interactions/commands/player/volume.ts @@ -2,11 +2,11 @@ import config from 'config'; import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { queueDoesNotExist } from '../../utils/validation/queueValidator'; -import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { diff --git a/src/commands/system/guilds.ts b/src/interactions/commands/system/guilds.ts similarity index 91% rename from src/commands/system/guilds.ts rename to src/interactions/commands/system/guilds.ts index 5f45a35..292bfda 100644 --- a/src/commands/system/guilds.ts +++ b/src/interactions/commands/system/guilds.ts @@ -1,10 +1,10 @@ import config from 'config'; import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { diff --git a/src/commands/system/reload.ts b/src/interactions/commands/system/reload.ts similarity index 90% rename from src/commands/system/reload.ts rename to src/interactions/commands/system/reload.ts index dc401ae..d3ac0c4 100644 --- a/src/commands/system/reload.ts +++ b/src/interactions/commands/system/reload.ts @@ -1,11 +1,11 @@ import config from 'config'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { ExtendedClient } from '../../types/clientTypes'; -import { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; +import loggerModule from '../../../services/logger'; +import { ExtendedClient } from '../../../types/clientTypes'; +import { CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { diff --git a/src/commands/system/shards.ts b/src/interactions/commands/system/shards.ts similarity index 96% rename from src/commands/system/shards.ts rename to src/interactions/commands/system/shards.ts index fa24251..efc9204 100644 --- a/src/commands/system/shards.ts +++ b/src/interactions/commands/system/shards.ts @@ -1,11 +1,11 @@ import config from 'config'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { ExtendedClient } from '../../types/clientTypes'; -import { CommandParams, ShardInfo } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; +import loggerModule from '../../../services/logger'; +import { ExtendedClient } from '../../../types/clientTypes'; +import { CommandParams, ShardInfo } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { diff --git a/src/commands/system/systemstatus.ts b/src/interactions/commands/system/systemstatus.ts similarity index 94% rename from src/commands/system/systemstatus.ts rename to src/interactions/commands/system/systemstatus.ts index 19c7a60..c1d957c 100644 --- a/src/commands/system/systemstatus.ts +++ b/src/interactions/commands/system/systemstatus.ts @@ -3,12 +3,12 @@ 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 { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions } from '../../types/configTypes'; -import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted'; -import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; +import { dependencies, version } from '../../../../package.json'; +import loggerModule from '../../../services/logger'; +import { CommandParams } from '../../../types/commandTypes'; +import { EmbedOptions } from '../../../types/configTypes'; +import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted'; +import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); diff --git a/src/interactions/component/nowplaying-skip-button.ts b/src/interactions/component/nowplaying-skip-button.ts new file mode 100644 index 0000000..7b2c489 --- /dev/null +++ b/src/interactions/component/nowplaying-skip-button.ts @@ -0,0 +1,111 @@ +import config from 'config'; +import { NodeResolvable, useQueue } from 'discord-player'; +import { EmbedBuilder, GuildMember } from 'discord.js'; + +import loggerModule from '../../services/logger'; +import { EmbedOptions } from '../../types/configTypes'; +import { ComponentInteractionParams } from '../../types/interactionTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); + +export const execute = async ({ interaction, trackId, executionId }: ComponentInteractionParams) => { + const logger = loggerModule.child({ + source: 'nowplaying-skip.js', + module: 'componentInteraction', + name: 'nowplaying-skip', + executionId: executionId, + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id + }); + + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + + logger.debug(`Received skip confirmation for track id ${trackId}.`); + if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { + logger.debug('Tried skipping track but there was no queue.'); + + logger.debug('Responding with warning embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + ) + .setColor(embedOptions.colors.warning) + ], + components: [] + }); + } + + if (queue.currentTrack!.id !== trackId) { + logger.debug('Tried skipping track but it is not the current track and therefore already skipped/removed.'); + + logger.debug('Responding with warning embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.` + ) + .setColor(embedOptions.colors.warning) + ], + components: [] + }); + } + + const skippedTrack = queue.currentTrack!; + let durationFormat = + Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00' + ? '' + : `\`${skippedTrack.duration}\``; + + if (skippedTrack.raw.live) { + durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; + } + queue.node.skip(); + logger.debug('Skipped the track.'); + + const loopModesFormatted = new Map([ + [0, 'disabled'], + [1, 'track'], + [2, 'queue'], + [3, 'autoplay'] + ]); + + const repeatModeUserString = loopModesFormatted.get(queue.repeatMode); + + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + + logger.debug('Responding with success embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setAuthor({ + name: authorName, + iconURL: interaction.user.avatarURL() || '' + }) + .setDescription( + `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${ + skippedTrack.raw.url ?? skippedTrack.url + })**` + + `${ + queue.repeatMode === 0 + ? '' + : `\n\n**${ + queue.repeatMode === 3 + ? embedOptions.icons.autoplaying + : embedOptions.icons.looping + } Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.` + }` + ) + .setThumbnail(skippedTrack.thumbnail) + .setColor(embedOptions.colors.success) + ], + components: [] + }); +}; diff --git a/src/types/interactionTypes.ts b/src/types/interactionTypes.ts new file mode 100644 index 0000000..7aa72a7 --- /dev/null +++ b/src/types/interactionTypes.ts @@ -0,0 +1,7 @@ +import { MessageComponentInteraction } from 'discord.js'; + +export interface ComponentInteractionParams { + interaction: MessageComponentInteraction; + trackId?: string; + executionId: string; +} diff --git a/src/utils/registerClientCommands.ts b/src/utils/registerClientCommands.ts index 6a4b664..ef16c69 100644 --- a/src/utils/registerClientCommands.ts +++ b/src/utils/registerClientCommands.ts @@ -17,21 +17,21 @@ export const registerClientCommands = ({ client, executionId }: RegisterClientCo logger.debug('Registering client commands...'); client.commands = new Collection(); - const commandFolders = fs.readdirSync(path.resolve('./dist/commands')); + const commandFolders = fs.readdirSync(path.resolve('./dist/interactions/commands')); for (const folder of commandFolders) { logger.trace(`Registering client commands for folder '${folder}'...`); const commandFiles = fs - .readdirSync(path.resolve(`./dist/commands/${folder}`)) + .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(`../commands/${folder}/${file}`)]; + delete require.cache[require.resolve(`../interactions/commands/${folder}/${file}`)]; // register command /* eslint-disable @typescript-eslint/no-var-requires */ - const command = require(`../commands/${folder}/${file}`); + const command = require(`../interactions/commands/${folder}/${file}`); client.commands.delete(command.data.name); client.commands.set(command.data.name, command); } catch (error) { From 975725276a6e1c804f0664746b4827e2dc6202f5 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 00:20:00 +0200 Subject: [PATCH 02/14] fix: refactored registering of event listeners --- src/bot.ts | 4 +- src/types/utilTypes.ts | 9 ++++ src/utils/registerEventListeners.ts | 67 +++++++++++++++++------------ 3 files changed, 51 insertions(+), 29 deletions(-) diff --git a/src/bot.ts b/src/bot.ts index b5379c3..6d6acd9 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -25,8 +25,8 @@ const logger = loggerModule.child({ client.on('allShardsReady', async () => { client.registerClientCommands = registerClientCommands; - registerEventListeners({ client, player, executionId }); - registerClientCommands({ client, executionId }); + await registerEventListeners({ client, player, executionId }); + await registerClientCommands({ client, executionId }); client.emit('ready', client as Client); }); diff --git a/src/types/utilTypes.ts b/src/types/utilTypes.ts index 812a1c0..64d3b6a 100644 --- a/src/types/utilTypes.ts +++ b/src/types/utilTypes.ts @@ -14,6 +14,15 @@ export interface RegisterClientCommandsParams { executionId: string; } +export interface CustomEvent { + name: string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + execute: (...args: any) => void; + once?: boolean; + isDebug?: boolean; + isPlayerEvent?: boolean; +} + export interface NotInVoiceChannelParams { interaction: ChatInputCommandInteraction; executionId: string; diff --git a/src/utils/registerEventListeners.ts b/src/utils/registerEventListeners.ts index f0b90c8..e1bec8e 100644 --- a/src/utils/registerEventListeners.ts +++ b/src/utils/registerEventListeners.ts @@ -2,16 +2,46 @@ import config from 'config'; import fs from 'node:fs'; import path from 'node:path'; +import { GuildQueueEvents, Player, PlayerEvents } from 'discord-player'; +import { Client } from 'discord.js'; import loggerModule from '../services/logger'; import { LoggerOptions } from '../types/configTypes'; -import { - ClientEventArguments, PlayerEventArguments, ProcessEventArguments -} from '../types/eventTypes'; -import { RegisterEventListenersParams } from '../types/utilTypes'; +import { ClientEventArguments, PlayerEventArguments, ProcessEventArguments } from '../types/eventTypes'; +import { CustomEvent, RegisterEventListenersParams } from '../types/utilTypes'; const loggerOptions: LoggerOptions = config.get('loggerOptions'); -export const registerEventListeners = ({ client, player, executionId }: RegisterEventListenersParams) => { +const registerClientEventListeners = (client: Client, event: CustomEvent) => { + if (event.once) { + client.once(event.name, (...args: ClientEventArguments) => event.execute(...args)); + } else { + if (!event.isDebug || process.env.MINIMUM_LOG_LEVEL === 'debug') { + client.on(event.name, (...args: ClientEventArguments) => event.execute(...args)); + } + } +}; + +const registerInteractionEventListeners = (client: Client, event: CustomEvent) => { + client.on(event.name, (...args: ClientEventArguments) => event.execute(...args, { client })); +}; + +const registerProcessEventListeners = (event: CustomEvent) => { + process.on(event.name, (...args: ProcessEventArguments) => event.execute(...args)); +}; + +const registerPlayerEventListeners = (player: Player, event: CustomEvent, loggerOptions: LoggerOptions) => { + if (!event.isDebug || (loggerOptions.minimumLogLevel === 'debug' && loggerOptions.discordPlayerDebug)) { + if (event.isPlayerEvent) { + player.events.on(event.name as keyof GuildQueueEvents, (...args: PlayerEventArguments) => + event.execute(...args) + ); + } else { + player.on(event.name as keyof PlayerEvents, (...args: PlayerEventArguments) => event.execute(...args)); + } + } +}; + +export const registerEventListeners = async ({ client, player, executionId }: RegisterEventListenersParams) => { const logger = loggerModule.child({ source: 'registerEventListeners.js', module: 'register', @@ -31,39 +61,22 @@ export const registerEventListeners = ({ client, player, executionId }: Register .filter((file) => file.endsWith('.js')); for (const file of eventFiles) { - /* eslint-disable @typescript-eslint/no-var-requires */ - const event = require(`../events/${folder}/${file}`); + const event = await import(`../events/${folder}/${file}`); switch (folder) { case 'client': - if (event.once) { - client.once(event.name, (...args: ClientEventArguments) => event.execute(...args)); - } else { - if (!event.isDebug || process.env.MINIMUM_LOG_LEVEL === 'debug') { - client.on(event.name, (...args: ClientEventArguments) => event.execute(...args)); - } - } + registerClientEventListeners(client, event); break; case 'interactions': - client.on(event.name, (...args: ClientEventArguments) => event.execute(...args, { client })); + registerInteractionEventListeners(client, event); break; case 'process': - process.on(event.name, (...args: ProcessEventArguments) => event.execute(...args)); + registerProcessEventListeners(event); break; case 'player': - if ( - !event.isDebug || - (loggerOptions.minimumLogLevel === 'debug' && loggerOptions.discordPlayerDebug) - ) { - if (event.isPlayerEvent) { - player.events.on(event.name, (...args: PlayerEventArguments) => event.execute(...args)); - break; - } else { - player.on(event.name, (...args: PlayerEventArguments) => event.execute(...args)); - } - } + registerPlayerEventListeners(player, event, loggerOptions); break; default: From f16a18deb544605704b419ca330dbd8fbb313530 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 00:21:33 +0200 Subject: [PATCH 03/14] WIP interaction handler --- src/events/interactions/interactionCreate.ts | 41 ++++++++++++++++--- .../nowplaying-skip-button.ts | 0 2 files changed, 36 insertions(+), 5 deletions(-) rename src/interactions/{component => components}/nowplaying-skip-button.ts (100%) diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index a704a74..a3a846b 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -1,5 +1,11 @@ import config from 'config'; -import { EmbedBuilder, Events, Interaction } from 'discord.js'; +import { + EmbedBuilder, + Events, + Interaction, + InteractionType, + MessageComponentInteraction +} from 'discord.js'; import { v4 as uuidv4 } from 'uuid'; import loggerModule from '../../services/logger'; @@ -23,14 +29,38 @@ module.exports = { guildId: interaction.guild?.id }); - if (interaction.isMessageComponent()) { + let interactionString: string = ''; + const interactionType: InteractionType = interaction.type; + + const handleComponent = async (interaction: MessageComponentInteraction) => { await interaction.deferReply(); const componentId = interaction.customId.split('_')[0]; const trackId = interaction.customId.split('_')[1]; - const componentModule = await import(`../../interactions/component/${componentId}.js`); - return componentModule.execute({ interaction, trackId, executionId }); + const componentModule = await import(`../../interactions/components/${componentId}.js`); + componentModule.execute({ interaction, trackId, executionId }); + }; + + switch (interactionType) { + case InteractionType.ApplicationCommand: + interactionString = 'ApplicationCommand'; + break; + case InteractionType.MessageComponent: + interactionString = 'MessageComponent'; + handleComponent(interaction as MessageComponentInteraction); + + break; + case InteractionType.ApplicationCommandAutocomplete: + interactionString = 'ApplicationCommandAutocomplete'; + break; + default: + interactionString = 'Unknown'; + break; } + logger.debug(`Interaction of type '${interactionString}' created.`); + + // TODO: separate slash commands and autocomplete into separate files + // /src/interactions/commands and /src/interactions/autocomplete if (interaction.isChatInputCommand() || interaction.isAutocomplete()) { const command = client.commands?.get(interaction.commandName) as Command; @@ -135,7 +165,8 @@ module.exports = { } } } else { - logger.warn(interaction, 'Interaction created but was not a chat input or autocomplete interaction.'); + logger.warn('Interaction created but was not a chat input or autocomplete interaction.'); + logger.trace(interaction); } } }; diff --git a/src/interactions/component/nowplaying-skip-button.ts b/src/interactions/components/nowplaying-skip-button.ts similarity index 100% rename from src/interactions/component/nowplaying-skip-button.ts rename to src/interactions/components/nowplaying-skip-button.ts From 1ec1281e985d2e34a0822f01d4d6f841f86a00e3 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 13:44:30 +0200 Subject: [PATCH 04/14] feat!: Extract logic for autocomplete and component interactions --- .gitattributes | 1 + src/bot.ts | 30 +- src/events/interactions/interactionCreate.ts | 368 ++++++++++++------ src/interactions/autocomplete/lyrics.ts | 78 ++++ src/interactions/autocomplete/play.ts | 68 ++++ src/interactions/commands/info/help.ts | 9 +- src/interactions/commands/info/status.ts | 9 +- src/interactions/commands/player/filters.ts | 9 +- src/interactions/commands/player/leave.ts | 9 +- src/interactions/commands/player/loop.ts | 15 +- src/interactions/commands/player/lyrics.ts | 69 +--- .../commands/player/nowplaying.ts | 12 +- src/interactions/commands/player/pause.ts | 9 +- src/interactions/commands/player/play.ts | 61 +-- src/interactions/commands/player/queue.ts | 9 +- src/interactions/commands/player/remove.ts | 9 +- src/interactions/commands/player/seek.ts | 9 +- src/interactions/commands/player/shuffle.ts | 9 +- src/interactions/commands/player/skip.ts | 9 +- src/interactions/commands/player/stop.ts | 9 +- src/interactions/commands/player/volume.ts | 9 +- src/interactions/commands/system/guilds.ts | 9 +- src/interactions/commands/system/reload.ts | 9 +- src/interactions/commands/system/shards.ts | 9 +- .../commands/system/systemstatus.ts | 8 +- .../components/nowplaying-skip-button.ts | 184 ++++----- src/types/commandTypes.ts | 38 -- src/types/interactionTypes.ts | 58 ++- src/utils/registerClientCommands.ts | 11 +- 29 files changed, 694 insertions(+), 442 deletions(-) create mode 100644 src/interactions/autocomplete/lyrics.ts create mode 100644 src/interactions/autocomplete/play.ts delete mode 100644 src/types/commandTypes.ts diff --git a/.gitattributes b/.gitattributes index 0c42f3c..4530571 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ * text=auto eol=crlf +*.js linguist-language=TypeScript diff --git a/src/bot.ts b/src/bot.ts index 6d6acd9..948d967 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -20,17 +20,19 @@ const logger = loggerModule.child({ }); (async () => { - const client: ExtendedClient = await createClient({ executionId }); - const player = await createPlayer({ client, executionId }); - - client.on('allShardsReady', async () => { - client.registerClientCommands = registerClientCommands; - await registerEventListeners({ client, player, executionId }); - await registerClientCommands({ client, executionId }); - client.emit('ready', client as Client); - }); - - client.login(process.env.DISCORD_BOT_TOKEN); -})().catch((error) => { - logger.error(error); -}); + try { + const client: ExtendedClient = await createClient({ executionId }); + const player = await createPlayer({ client, executionId }); + + client.on('allShardsReady', async () => { + client.registerClientCommands = registerClientCommands; + await registerEventListeners({ client, player, executionId }); + await registerClientCommands({ client, executionId }); + client.emit('ready', client as Client); + }); + + client.login(process.env.DISCORD_BOT_TOKEN); + } catch (error) { + logger.error(error); + } +})(); diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index a3a846b..5dd5f50 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -1,5 +1,7 @@ import config from 'config'; import { + AutocompleteInteraction, + ChatInputCommandInteraction, EmbedBuilder, Events, Interaction, @@ -37,136 +39,276 @@ module.exports = { const componentId = interaction.customId.split('_')[0]; const trackId = interaction.customId.split('_')[1]; const componentModule = await import(`../../interactions/components/${componentId}.js`); - componentModule.execute({ interaction, trackId, executionId }); + await componentModule.execute({ interaction, trackId, executionId }); }; - switch (interactionType) { - case InteractionType.ApplicationCommand: - interactionString = 'ApplicationCommand'; - break; - case InteractionType.MessageComponent: - interactionString = 'MessageComponent'; - handleComponent(interaction as MessageComponentInteraction); + const handleAutocomplete = async (interaction: AutocompleteInteraction) => { + //const command = client.commands?.get(interaction.commandName) as Command; + const autocompleteModule = await import(`../../interactions/autocomplete/${interaction.commandName}.js`); + const { default: autocomplete } = autocompleteModule; + await autocomplete.execute({ interaction, executionId }); + }; - break; - case InteractionType.ApplicationCommandAutocomplete: - interactionString = 'ApplicationCommandAutocomplete'; - break; - default: - interactionString = 'Unknown'; - break; - } - - logger.debug(`Interaction of type '${interactionString}' created.`); - - // TODO: separate slash commands and autocomplete into separate files - // /src/interactions/commands and /src/interactions/autocomplete - if (interaction.isChatInputCommand() || interaction.isAutocomplete()) { + const handleCommand = async (interaction: ChatInputCommandInteraction) => { const command = client.commands?.get(interaction.commandName) as Command; + if (!command) { + logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); + return; + } - if (interaction.isChatInputCommand()) { - if (!command) { - logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); - return; - } - logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`); - try { - await interaction.deferReply(); + logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`); + //try { + await interaction.deferReply(); - if (await cannotSendMessageInChannel({ interaction, executionId })) { - return; - } + if (await cannotSendMessageInChannel({ interaction, executionId })) { + return; + } - const inputTime: number = new Date().getTime(); + const inputTime: number = new Date().getTime(); - await command.execute({ interaction, client, executionId }); + await command.execute({ interaction, client, executionId }); - const outputTime: number = new Date().getTime(); - const executionTime: number = outputTime - inputTime; + /* doesnt work because need to find subfolder + /* Update registerClientCommands to registerClientInteractions + /* Add client.interactions with { commandInteractions, componentInteractions, autocompleteInteractions + const commandModule = await import(`../../interactions/commands/SUBFOLDER/${interaction.commandName}.js`); + const { default: command } = commandModule; + await command.execute({ interaction, client, executionId }); + */ - logger.info(`Command '${interaction}' executed in ${executionTime} ms.`); - } catch (error) { - if (error instanceof Error) { - logger.warn( - error, - `Command '${interaction}' throwed an unhandled error and might have failed to execute properly.` - ); + const outputTime: number = new Date().getTime(); + const executionTime: number = outputTime - inputTime; - if ( - error.message === 'Unknown interaction' || - error.message === 'Interaction has already been acknowledged.' - ) { - logger.debug( - 'Command failed to be responded to, unknown interaction or already acknowledged.' - ); - return; - } else { - if (!interaction.deferred || !interaction.replied) { - logger.warn('Interaction was not deferred or replied to, and an error was thrown.'); - return; - } + logger.info(`Command '${interaction}' executed in ${executionTime} ms.`); + /* + } catch (error) { + if (error instanceof Error) { + logger.warn( + error, + `Command '${interaction}' throwed an unhandled error and might have failed to execute properly.` + ); - if (interaction.replied) { - // If the interaction has already been replied to, most likely command executed successfully or error is already handled. - return; - } else if (interaction.deferred) { - logger.info('Interaction was deferred, editing reply and sending Uh-oh message.'); - await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); - } else { - logger.info( - 'Interaction was not deferred or replied, sending new reply with Uh-oh message.' - ); - await interaction.reply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); - } - } - } else { - throw error; - } - } - } else if (interaction.isAutocomplete()) { - logger.debug('Autocomplete interaction created.'); - try { - command?.autocomplete && (await command?.autocomplete({ interaction, executionId })); - } catch (error) { - if (error instanceof Error) { - if ( - error.message === 'Unknown interaction' || - error.message === 'Interaction has already been acknowledged.' - ) { - logger.debug( - 'Autocomplete failed to be responded to, unknown interaction or already acknowledged.' - ); - return; - } else { - logger.warn(error, 'Autocomplete failed to execute.'); - } + if ( + error.message === 'Unknown interaction' || + error.message === 'Interaction has already been acknowledged.' + ) { + logger.debug('Command failed to be responded to, unknown interaction or already acknowledged.'); return; } else { - throw error; + if (!interaction.deferred || !interaction.replied) { + logger.warn('Interaction was not deferred or replied to, and an error was thrown.'); + return; + } + + if (interaction.replied) { + // If the interaction has already been replied to, most likely command executed successfully or error is already handled. + return; + } else if (interaction.deferred) { + logger.info('Interaction was deferred, editing reply and sending Uh-oh message.'); + await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }); + } else { + logger.info( + 'Interaction was not deferred or replied, sending new reply with Uh-oh message.' + ); + await interaction.reply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }); + } } + } else { + throw error; } } - } else { - logger.warn('Interaction created but was not a chat input or autocomplete interaction.'); - logger.trace(interaction); + */ + }; + + try { + switch (interactionType) { + case InteractionType.ApplicationCommand: + interactionString = 'ApplicationCommand'; + handleCommand(interaction as ChatInputCommandInteraction); + break; + + case InteractionType.ApplicationCommandAutocomplete: + interactionString = 'ApplicationCommandAutocomplete'; + handleAutocomplete(interaction as AutocompleteInteraction); + break; + + case InteractionType.MessageComponent: + interactionString = 'MessageComponent'; + handleComponent(interaction as MessageComponentInteraction); + break; + + default: + interactionString = 'Unknown'; + break; + } + + logger.debug(`Interaction of type '${interactionString}' created.`); + } catch (error) { + logger.error(error, `Error handling interaction of type '${interactionString}'`); + + const errorReply = { + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }; + + const handleErrorWithReplyToUser = async (interaction: Interaction, error: Error) => { + logger.error(error, `Error handling interaction of type '${interactionString}'`); + if (interaction.channel) { + // Send message to user in channel where interaction was made + logger.debug(`Sending error reply to channel '${interaction.channel.id}'.`); + await interaction.channel.send(errorReply); + } else { + // Send message to user in DMs + logger.debug(`Sending error reply to user '${interaction.user.id}'.`); + await interaction.user.send(errorReply); + } + }; + + switch (true) { + case interaction instanceof ChatInputCommandInteraction: + await handleErrorWithReplyToUser(interaction, error as Error); + break; + case interaction instanceof AutocompleteInteraction: + await handleErrorWithReplyToUser(interaction, error as Error); + break; + case interaction instanceof MessageComponentInteraction: + await handleErrorWithReplyToUser(interaction, error as Error); + break; + default: + // Something else went wrong + logger.error(error, 'Unhandled error while handling unkown interaction.'); + break; + } } + + /* + if (interaction.isAutocomplete()) { + + try { + command?.autocomplete && (await command?.autocomplete({ interaction, executionId })); + } catch (error) { + if (error instanceof Error) { + if ( + error.message === 'Unknown interaction' || + error.message === 'Interaction has already been acknowledged.' + ) { + logger.debug( + 'Autocomplete failed to be responded to, unknown interaction or already acknowledged.' + ); + return; + } else { + logger.warn(error, 'Autocomplete failed to execute.'); + } + return; + } else { + throw error; + } + } + } + */ + + /* + if (interaction.isChatInputCommand()) { + const command = client.commands?.get(interaction.commandName) as Command; + if (!command) { + logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); + return; + } + logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`); + try { + await interaction.deferReply(); + + if (await cannotSendMessageInChannel({ interaction, executionId })) { + return; + } + + const inputTime: number = new Date().getTime(); + + await command.execute({ interaction, client, executionId }); + + const outputTime: number = new Date().getTime(); + const executionTime: number = outputTime - inputTime; + + logger.info(`Command '${interaction}' executed in ${executionTime} ms.`); + } catch (error) { + if (error instanceof Error) { + logger.warn( + error, + `Command '${interaction}' throwed an unhandled error and might have failed to execute properly.` + ); + + if ( + error.message === 'Unknown interaction' || + error.message === 'Interaction has already been acknowledged.' + ) { + logger.debug('Command failed to be responded to, unknown interaction or already acknowledged.'); + return; + } else { + if (!interaction.deferred || !interaction.replied) { + logger.warn('Interaction was not deferred or replied to, and an error was thrown.'); + return; + } + + if (interaction.replied) { + // If the interaction has already been replied to, most likely command executed successfully or error is already handled. + return; + } else if (interaction.deferred) { + logger.info('Interaction was deferred, editing reply and sending Uh-oh message.'); + await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }); + } else { + logger.info( + 'Interaction was not deferred or replied, sending new reply with Uh-oh message.' + ); + await interaction.reply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }); + } + } + } else { + throw error; + } + } + } + */ } }; diff --git a/src/interactions/autocomplete/lyrics.ts b/src/interactions/autocomplete/lyrics.ts new file mode 100644 index 0000000..6ce99e9 --- /dev/null +++ b/src/interactions/autocomplete/lyrics.ts @@ -0,0 +1,78 @@ +import { useMainPlayer } from 'discord-player'; +import loggerModule from '../../services/logger'; +import { CustomAutocompleteInteraction } from '../../types/interactionTypes'; +import { lyricsExtractor } from '@discord-player/extractor'; + +const loggerTemplate = loggerModule.child({ + source: 'lyrics.js', + module: 'slashCommand', + name: '/lyrics' +}); + +const recentQueries = new Map(); + +const autocomplete: CustomAutocompleteInteraction = { + execute: async ({ interaction, executionId }) => { + // TODO: Extract autocomplete logic + const logger = loggerTemplate.child({ + executionId: executionId, + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id + }); + + const query = interaction.options.getString('query', true); + + const { lastQuery, result, timestamp } = recentQueries.get(interaction.user.id) || {}; + + if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) { + logger.debug(`Responding with results from lastQuery for query '${query}'`); + return interaction.respond(result); + } + + if (query.length < 3) { + logger.debug(`Responding with empty results due to < 3 length for query '${query}'`); + return interaction.respond([]); + } + + const genius = lyricsExtractor(); + const lyricsResult = await genius.search(query).catch(() => null); + let response = []; + + if (!lyricsResult) { + logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`); + const player = useMainPlayer()!; + const searchResults = await player.search(query); + response = searchResults.tracks.slice(0, 1).map((track) => ({ + name: + `${track.title} [Artist: ${track.author}]`.length > 100 + ? `${track.title}`.slice(0, 100) + : `${track.title} [Artist: ${track.author}]`, + value: track.title.slice(0, 100) + })); + } else { + logger.debug(`Found Genius lyrics for query '${query}'.`); + response = [ + { + name: `${lyricsResult.title} [Artist: ${lyricsResult.artist.name}]`.slice(0, 100), + value: lyricsResult.title.slice(0, 100) + } + ]; + } + + if (!response || response.length === 0) { + logger.debug(`Responding with empty results for query '${query}'`); + return interaction.respond([]); + } + + recentQueries.set(interaction.user.id, { + lastQuery: query, + result: response, + timestamp: Date.now() + }); + + logger.debug(`Responding to autocomplete with results for query: '${query}'.`); + return interaction.respond(response); + } +}; + +export default autocomplete; diff --git a/src/interactions/autocomplete/play.ts b/src/interactions/autocomplete/play.ts new file mode 100644 index 0000000..4f501d8 --- /dev/null +++ b/src/interactions/autocomplete/play.ts @@ -0,0 +1,68 @@ +import { useMainPlayer } from 'discord-player'; +import loggerModule from '../../services/logger'; +import { CustomAutocompleteInteraction } from '../../types/interactionTypes'; + +const loggerTemplate = loggerModule.child({ + source: 'play.js', + module: 'slashCommand', + name: '/play' +}); + +const recentQueries = new Map(); + +const autocomplete: CustomAutocompleteInteraction = { + execute: async ({ interaction, executionId }) => { + const logger = loggerTemplate.child({ + executionId: executionId, + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id + }); + + const player = useMainPlayer()!; + const query = interaction.options.getString('query', true); + + const { lastQuery, results, timestamp } = recentQueries.get(interaction.user.id) || {}; + + if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) { + logger.debug(`Responding with results from lastQuery for query '${query}'`); + return interaction.respond(results); + } + + if (query.length < 3) { + logger.debug(`Responding with empty results due to < 3 length for query '${query}'`); + return interaction.respond([]); + } + const searchResults = await player.search(query); + + let response = []; + + response = searchResults.tracks.slice(0, 5).map((track) => { + if (track.url.length > 100) { + track.url = track.title.slice(0, 100); + } + return { + name: + `${track.title} [Author: ${track.author}]`.length > 100 + ? `${track.title}`.slice(0, 100) + : `${track.title} [Author: ${track.author}]`, + value: track.url + }; + }); + + recentQueries.set(interaction.user.id, { + lastQuery: query, + results: response, + timestamp: Date.now() + }); + + if (!response || response.length === 0) { + logger.debug(`Responding with empty results for query '${query}'`); + return interaction.respond([]); + } + + logger.debug(`Responding to autocomplete with results for query: '${query}'.`); + return interaction.respond(response); + } +}; + +export default autocomplete; diff --git a/src/interactions/commands/info/help.ts b/src/interactions/commands/info/help.ts index 693c21b..5caedc7 100644 --- a/src/interactions/commands/info/help.ts +++ b/src/interactions/commands/info/help.ts @@ -2,12 +2,13 @@ import config from 'config'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { BotOptions, EmbedOptions } from '../../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -15,7 +16,7 @@ module.exports = { .setDescription('Show a list of commands and their usage.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }: CommandParams) => { + execute: async ({ interaction, client, executionId }) => { const logger = loggerModule.child({ source: 'help.js', module: 'slashCommand', @@ -69,3 +70,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/info/status.ts b/src/interactions/commands/info/status.ts index 619cff7..68022a7 100644 --- a/src/interactions/commands/info/status.ts +++ b/src/interactions/commands/info/status.ts @@ -5,12 +5,13 @@ import osu from 'node-os-utils'; // @ts-ignore import { version } from '../../../../package.json'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -18,7 +19,7 @@ module.exports = { .setDescription('Show the bot and system status.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }: CommandParams) => { + execute: async ({ interaction, client, executionId }) => { const logger = loggerModule.child({ source: 'status.js', module: 'slashCommand', @@ -133,3 +134,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/filters.ts b/src/interactions/commands/player/filters.ts index 454dbb4..1d632d8 100644 --- a/src/interactions/commands/player/filters.ts +++ b/src/interactions/commands/player/filters.ts @@ -15,14 +15,15 @@ import { } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams, CustomError } from '../../../types/commandTypes'; +import { CustomError, CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -30,7 +31,7 @@ module.exports = { .setDescription('Toggle various audio filters during playback.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'filters.js', module: 'slashCommand', @@ -237,3 +238,5 @@ module.exports = { } } }; + +export default command; diff --git a/src/interactions/commands/player/leave.ts b/src/interactions/commands/player/leave.ts index 894a0df..a4bab4e 100644 --- a/src/interactions/commands/player/leave.ts +++ b/src/interactions/commands/player/leave.ts @@ -3,12 +3,13 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -16,7 +17,7 @@ module.exports = { .setDescription('Clear the track queue and remove the bot from voice channel.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'leave.js', module: 'slashCommand', @@ -80,3 +81,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/loop.ts b/src/interactions/commands/player/loop.ts index 3f6a42d..46528b7 100644 --- a/src/interactions/commands/player/loop.ts +++ b/src/interactions/commands/player/loop.ts @@ -1,16 +1,17 @@ import config from 'config'; import { NodeResolvable, useQueue } from 'discord-player'; -import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; +import { EmbedBuilder, GuildMember, SlashCommandBuilder, SlashCommandStringOption } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { BotOptions, EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -18,8 +19,8 @@ module.exports = { .setDescription('Toggle looping a track, the whole queue or autoplay.') .setDMPermission(false) .setNSFW(false) - .addStringOption((option) => - option + .addStringOption(() => + new SlashCommandStringOption() .setName('mode') .setDescription('Mode to set for looping.') .setRequired(false) @@ -30,7 +31,7 @@ module.exports = { { name: 'Disabled', value: '0' } ) ), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'loop.js', module: 'slashCommand', @@ -184,3 +185,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/lyrics.ts b/src/interactions/commands/player/lyrics.ts index 4f90ec1..f8b99f3 100644 --- a/src/interactions/commands/player/lyrics.ts +++ b/src/interactions/commands/player/lyrics.ts @@ -5,13 +5,12 @@ import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { lyricsExtractor } from '@discord-player/extractor'; import loggerModule from '../../../services/logger'; -import { CommandAutocompleteParams, CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const recentQueries = new Map(); const loggerTemplate = loggerModule.child({ source: 'lyrics.js', @@ -19,7 +18,7 @@ const loggerTemplate = loggerModule.child({ name: '/lyrics' }); -module.exports = { +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -36,67 +35,7 @@ module.exports = { .setMaxLength(500) .setAutocomplete(true) ), - autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => { - const logger = loggerTemplate.child({ - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); - - const query = interaction.options.getString('query', true); - - const { lastQuery, result, timestamp } = recentQueries.get(interaction.user.id) || {}; - - if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) { - logger.debug(`Responding with results from lastQuery for query '${query}'`); - return interaction.respond(result); - } - - if (query.length < 3) { - logger.debug(`Responding with empty results due to < 3 length for query '${query}'`); - return interaction.respond([]); - } - - const genius = lyricsExtractor(); - const lyricsResult = await genius.search(query).catch(() => null); - let response = []; - - if (!lyricsResult) { - logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`); - const player = useMainPlayer()!; - const searchResults = await player.search(query); - response = searchResults.tracks.slice(0, 1).map((track) => ({ - name: - `${track.title} [Artist: ${track.author}]`.length > 100 - ? `${track.title}`.slice(0, 100) - : `${track.title} [Artist: ${track.author}]`, - value: track.title.slice(0, 100) - })); - } else { - logger.debug(`Found Genius lyrics for query '${query}'.`); - response = [ - { - name: `${lyricsResult.title} [Artist: ${lyricsResult.artist.name}]`.slice(0, 100), - value: lyricsResult.title.slice(0, 100) - } - ]; - } - - if (!response || response.length === 0) { - logger.debug(`Responding with empty results for query '${query}'`); - return interaction.respond([]); - } - - recentQueries.set(interaction.user.id, { - lastQuery: query, - result: response, - timestamp: Date.now() - }); - - logger.debug(`Responding to autocomplete with results for query: '${query}'.`); - return interaction.respond(response); - }, - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerTemplate.child({ executionId: executionId, shardId: interaction.guild?.shardId, @@ -267,3 +206,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/nowplaying.ts b/src/interactions/commands/player/nowplaying.ts index 9154b1d..e456db7 100644 --- a/src/interactions/commands/player/nowplaying.ts +++ b/src/interactions/commands/player/nowplaying.ts @@ -11,7 +11,7 @@ import { } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams, TrackMetadata } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction, TrackMetadata } from '../../../types/interactionTypes'; import { EmbedOptions, PlayerOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; @@ -19,7 +19,7 @@ import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validat const embedOptions: EmbedOptions = config.get('embedOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); -module.exports = { +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -27,7 +27,7 @@ module.exports = { .setDescription('Show information about the track currently playing.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'nowplaying.js', module: 'slashCommand', @@ -136,7 +136,7 @@ module.exports = { logger.debug('Successfully retrieved information about the current track.'); logger.debug('Sending info embed with action row components.'); - await interaction.editReply({ + return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ @@ -185,7 +185,7 @@ module.exports = { ], components: [nowPlayingActionRow as APIActionRowComponent] }); - - logger.debug('Finished sending response.'); } }; + +export default command; diff --git a/src/interactions/commands/player/pause.ts b/src/interactions/commands/player/pause.ts index 0b8c484..3c014cf 100644 --- a/src/interactions/commands/player/pause.ts +++ b/src/interactions/commands/player/pause.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -17,7 +18,7 @@ module.exports = { .setDescription('Pause or resume the current track.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'pause.js', module: 'slashCommand', @@ -87,3 +88,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/play.ts b/src/interactions/commands/player/play.ts index 53ac4d5..5c4bb75 100644 --- a/src/interactions/commands/player/play.ts +++ b/src/interactions/commands/player/play.ts @@ -3,7 +3,7 @@ import { useMainPlayer, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandAutocompleteParams, CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { BotOptions, EmbedOptions, PlayerOptions } from '../../../types/configTypes'; import { cannotJoinVoiceOrTalk } from '../../../utils/validation/permissionValidator'; import { transformQuery } from '../../../utils/validation/searchQueryValidator'; @@ -12,7 +12,6 @@ import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validat const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); -const recentQueries = new Map(); const loggerTemplate = loggerModule.child({ source: 'play.js', @@ -20,7 +19,7 @@ const loggerTemplate = loggerModule.child({ name: '/play' }); -module.exports = { +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -37,59 +36,7 @@ module.exports = { .setMaxLength(500) .setAutocomplete(true) ), - autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => { - const logger = loggerTemplate.child({ - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); - - const player = useMainPlayer()!; - const query = interaction.options.getString('query', true); - - const { lastQuery, results, timestamp } = recentQueries.get(interaction.user.id) || {}; - - if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) { - logger.debug(`Responding with results from lastQuery for query '${query}'`); - return interaction.respond(results); - } - - if (query.length < 3) { - logger.debug(`Responding with empty results due to < 3 length for query '${query}'`); - return interaction.respond([]); - } - const searchResults = await player.search(query); - - let response = []; - - response = searchResults.tracks.slice(0, 5).map((track) => { - if (track.url.length > 100) { - track.url = track.title.slice(0, 100); - } - return { - name: - `${track.title} [Author: ${track.author}]`.length > 100 - ? `${track.title}`.slice(0, 100) - : `${track.title} [Author: ${track.author}]`, - value: track.url - }; - }); - - recentQueries.set(interaction.user.id, { - lastQuery: query, - results: response, - timestamp: Date.now() - }); - - if (!response || response.length === 0) { - logger.debug(`Responding with empty results for query '${query}'`); - return interaction.respond([]); - } - - logger.debug(`Responding to autocomplete with results for query: '${query}'.`); - return interaction.respond(response); - }, - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerTemplate.child({ executionId: executionId, shardId: interaction.guild?.shardId, @@ -411,3 +358,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/queue.ts b/src/interactions/commands/player/queue.ts index 62a3896..8b27b7d 100644 --- a/src/interactions/commands/player/queue.ts +++ b/src/interactions/commands/player/queue.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions, PlayerOptions } from '../../../types/configTypes'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -18,7 +19,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false) .addNumberOption((option) => option.setName('page').setDescription('Page number of the queue').setMinValue(1)), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'queue.js', module: 'slashCommand', @@ -207,3 +208,5 @@ module.exports = { } } }; + +export default command; diff --git a/src/interactions/commands/player/remove.ts b/src/interactions/commands/player/remove.ts index 511e448..1e3275c 100644 --- a/src/interactions/commands/player/remove.ts +++ b/src/interactions/commands/player/remove.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -24,7 +25,7 @@ module.exports = { .setMinValue(1) .setRequired(true) ), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'remove.js', module: 'slashCommand', @@ -104,3 +105,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/seek.ts b/src/interactions/commands/player/seek.ts index b88198e..cf3e6ec 100644 --- a/src/interactions/commands/player/seek.ts +++ b/src/interactions/commands/player/seek.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -23,7 +24,7 @@ module.exports = { .setDescription('Duration in format 00:00:00 (HH:mm:ss) to seek to.') .setRequired(true) ), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'seek.js', module: 'slashCommand', @@ -186,3 +187,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/shuffle.ts b/src/interactions/commands/player/shuffle.ts index 82a9dd8..81e4027 100644 --- a/src/interactions/commands/player/shuffle.ts +++ b/src/interactions/commands/player/shuffle.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueIsEmpty } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -17,7 +18,7 @@ module.exports = { .setDescription('Shuffle tracks in the queue randomly.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'shuffle.js', module: 'slashCommand', @@ -72,3 +73,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/skip.ts b/src/interactions/commands/player/skip.ts index a284b26..ffd4664 100644 --- a/src/interactions/commands/player/skip.ts +++ b/src/interactions/commands/player/skip.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -20,7 +21,7 @@ module.exports = { .addNumberOption((option) => option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1) ), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'skip.js', module: 'slashCommand', @@ -181,3 +182,5 @@ module.exports = { } } }; + +export default command; diff --git a/src/interactions/commands/player/stop.ts b/src/interactions/commands/player/stop.ts index f5e3564..dcc2cb8 100644 --- a/src/interactions/commands/player/stop.ts +++ b/src/interactions/commands/player/stop.ts @@ -3,12 +3,13 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -16,7 +17,7 @@ module.exports = { .setDescription('Stop playing audio and clear the track queue.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'stop.js', module: 'slashCommand', @@ -82,3 +83,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/player/volume.ts b/src/interactions/commands/player/volume.ts index 6cb9cc3..88e2b98 100644 --- a/src/interactions/commands/player/volume.ts +++ b/src/interactions/commands/player/volume.ts @@ -3,13 +3,14 @@ import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isNew: false, isBeta: false, data: new SlashCommandBuilder() @@ -24,7 +25,7 @@ module.exports = { .setMinValue(0) .setMaxValue(100) ), - execute: async ({ interaction, executionId }: CommandParams) => { + execute: async ({ interaction, executionId }) => { const logger = loggerModule.child({ source: 'volume.js', module: 'slashCommand', @@ -126,3 +127,5 @@ module.exports = { } } }; + +export default command; diff --git a/src/interactions/commands/system/guilds.ts b/src/interactions/commands/system/guilds.ts index 292bfda..1f5609f 100644 --- a/src/interactions/commands/system/guilds.ts +++ b/src/interactions/commands/system/guilds.ts @@ -2,12 +2,13 @@ import config from 'config'; import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isSystemCommand: true, isNew: false, isBeta: false, @@ -16,7 +17,7 @@ module.exports = { .setDescription('Show list of guilds where bot is added.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }: CommandParams) => { + execute: async ({ interaction, client, executionId }) => { const logger = loggerModule.child({ source: 'guilds.js', module: 'slashCommand', @@ -86,3 +87,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/system/reload.ts b/src/interactions/commands/system/reload.ts index d3ac0c4..551eb63 100644 --- a/src/interactions/commands/system/reload.ts +++ b/src/interactions/commands/system/reload.ts @@ -3,12 +3,13 @@ import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; import { ExtendedClient } from '../../../types/clientTypes'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isSystemCommand: true, isNew: false, isBeta: false, @@ -17,7 +18,7 @@ module.exports = { .setDescription('Reload the bot commands.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }: CommandParams) => { + execute: async ({ interaction, client, executionId }) => { const logger = loggerModule.child({ source: 'reload.js', module: 'slashCommand', @@ -82,3 +83,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/system/shards.ts b/src/interactions/commands/system/shards.ts index efc9204..56a894c 100644 --- a/src/interactions/commands/system/shards.ts +++ b/src/interactions/commands/system/shards.ts @@ -3,12 +3,13 @@ import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; import { ExtendedClient } from '../../../types/clientTypes'; -import { CommandParams, ShardInfo } from '../../../types/commandTypes'; +import { ShardInfo, CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { + +const command: CustomSlashCommandInteraction = { isSystemCommand: true, isNew: false, isBeta: false, @@ -34,7 +35,7 @@ module.exports = { ) .addNumberOption((option) => option.setName('page').setDescription('Page number to show').setMinValue(1)), - execute: async ({ interaction, client, executionId }: CommandParams) => { + execute: async ({ interaction, client, executionId }) => { const logger = loggerModule.child({ source: 'shards.js', module: 'slashCommand', @@ -198,3 +199,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/commands/system/systemstatus.ts b/src/interactions/commands/system/systemstatus.ts index c1d957c..fe32b4e 100644 --- a/src/interactions/commands/system/systemstatus.ts +++ b/src/interactions/commands/system/systemstatus.ts @@ -5,14 +5,14 @@ import osu from 'node-os-utils'; // @ts-ignore import { dependencies, version } from '../../../../package.json'; import loggerModule from '../../../services/logger'; -import { CommandParams } from '../../../types/commandTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted'; import { notValidGuildId } from '../../../utils/validation/systemCommandValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); -module.exports = { +const command: CustomSlashCommandInteraction = { isSystemCommand: true, isNew: false, isBeta: false, @@ -21,7 +21,7 @@ module.exports = { .setDescription('Show the bot and system status.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }: CommandParams) => { + execute: async ({ interaction, client, executionId }) => { const logger = loggerModule.child({ source: 'systemstatus.js', module: 'slashCommand', @@ -171,3 +171,5 @@ module.exports = { }); } }; + +export default command; diff --git a/src/interactions/components/nowplaying-skip-button.ts b/src/interactions/components/nowplaying-skip-button.ts index 7b2c489..9b5ecc0 100644 --- a/src/interactions/components/nowplaying-skip-button.ts +++ b/src/interactions/components/nowplaying-skip-button.ts @@ -4,108 +4,112 @@ import { EmbedBuilder, GuildMember } from 'discord.js'; import loggerModule from '../../services/logger'; import { EmbedOptions } from '../../types/configTypes'; -import { ComponentInteractionParams } from '../../types/interactionTypes'; +import { CustomComponentInteraction } from '../../types/interactionTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -export const execute = async ({ interaction, trackId, executionId }: ComponentInteractionParams) => { - const logger = loggerModule.child({ - source: 'nowplaying-skip.js', - module: 'componentInteraction', - name: 'nowplaying-skip', - executionId: executionId, - shardId: interaction.guild?.shardId, - guildId: interaction.guild?.id - }); +const component: CustomComponentInteraction = { + execute: async ({ interaction, trackId, executionId }) => { + const logger = loggerModule.child({ + source: 'nowplaying-skip.js', + module: 'componentInteraction', + name: 'nowplaying-skip', + executionId: executionId, + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id + }); - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; - logger.debug(`Received skip confirmation for track id ${trackId}.`); - if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { - logger.debug('Tried skipping track but there was no queue.'); + logger.debug(`Received skip confirmation for track id ${trackId}.`); + if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { + logger.debug('Tried skipping track but there was no queue.'); - logger.debug('Responding with warning embed.'); + logger.debug('Responding with warning embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + ) + .setColor(embedOptions.colors.warning) + ], + components: [] + }); + } + + if (queue.currentTrack!.id !== trackId) { + logger.debug('Tried skipping track but it is not the current track and therefore already skipped/removed.'); + + logger.debug('Responding with warning embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.` + ) + .setColor(embedOptions.colors.warning) + ], + components: [] + }); + } + + const skippedTrack = queue.currentTrack!; + let durationFormat = + Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00' + ? '' + : `\`${skippedTrack.duration}\``; + + if (skippedTrack.raw.live) { + durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; + } + queue.node.skip(); + logger.debug('Skipped the track.'); + + const loopModesFormatted = new Map([ + [0, 'disabled'], + [1, 'track'], + [2, 'queue'], + [3, 'autoplay'] + ]); + + const repeatModeUserString = loopModesFormatted.get(queue.repeatMode); + + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() + .setAuthor({ + name: authorName, + iconURL: interaction.user.avatarURL() || '' + }) .setDescription( - `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${ + skippedTrack.raw.url ?? skippedTrack.url + })**` + + `${ + queue.repeatMode === 0 + ? '' + : `\n\n**${ + queue.repeatMode === 3 + ? embedOptions.icons.autoplaying + : embedOptions.icons.looping + } Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.` + }` ) - .setColor(embedOptions.colors.warning) + .setThumbnail(skippedTrack.thumbnail) + .setColor(embedOptions.colors.success) ], components: [] }); } - - if (queue.currentTrack!.id !== trackId) { - logger.debug('Tried skipping track but it is not the current track and therefore already skipped/removed.'); - - logger.debug('Responding with warning embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.` - ) - .setColor(embedOptions.colors.warning) - ], - components: [] - }); - } - - const skippedTrack = queue.currentTrack!; - let durationFormat = - Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00' - ? '' - : `\`${skippedTrack.duration}\``; - - if (skippedTrack.raw.live) { - durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; - } - queue.node.skip(); - logger.debug('Skipped the track.'); - - const loopModesFormatted = new Map([ - [0, 'disabled'], - [1, 'track'], - [2, 'queue'], - [3, 'autoplay'] - ]); - - const repeatModeUserString = loopModesFormatted.get(queue.repeatMode); - - let authorName: string; - - if (interaction.member instanceof GuildMember) { - authorName = interaction.member.nickname || interaction.user.username; - } else { - authorName = interaction.user.username; - } - - logger.debug('Responding with success embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setAuthor({ - name: authorName, - iconURL: interaction.user.avatarURL() || '' - }) - .setDescription( - `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${ - skippedTrack.raw.url ?? skippedTrack.url - })**` + - `${ - queue.repeatMode === 0 - ? '' - : `\n\n**${ - queue.repeatMode === 3 - ? embedOptions.icons.autoplaying - : embedOptions.icons.looping - } Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.` - }` - ) - .setThumbnail(skippedTrack.thumbnail) - .setColor(embedOptions.colors.success) - ], - components: [] - }); }; + +export default component; diff --git a/src/types/commandTypes.ts b/src/types/commandTypes.ts deleted file mode 100644 index d5a1316..0000000 --- a/src/types/commandTypes.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { AutocompleteInteraction, ChatInputCommandInteraction } from 'discord.js'; - -import { ExtendedClient } from './clientTypes'; - -export interface CommandParams { - interaction: ChatInputCommandInteraction; - client: ExtendedClient | undefined; - executionId: string; -} - -export interface CommandAutocompleteParams { - interaction: AutocompleteInteraction; - client: ExtendedClient | undefined; - executionId: string; -} - -export interface ShardInfo { - shardId: number; - memUsage: number; - guildCount: number; - guildMemberCount: number; - playerStatistics: { - activeVoiceConnections: number; - totalTracks: number; - totalListeners: number; - }; -} - -export interface TrackMetadata { - bridge: { - views: number; - }; -} - -export class CustomError extends Error { - type?: string; - code?: string; -} diff --git a/src/types/interactionTypes.ts b/src/types/interactionTypes.ts index 7aa72a7..2f1c59e 100644 --- a/src/types/interactionTypes.ts +++ b/src/types/interactionTypes.ts @@ -1,7 +1,61 @@ -import { MessageComponentInteraction } from 'discord.js'; +import { AutocompleteInteraction, ChatInputCommandInteraction, Message, MessageComponentInteraction, SlashCommandBuilder } from 'discord.js'; +import { ExtendedClient } from './clientTypes'; -export interface ComponentInteractionParams { +// Local types +interface CommandParams { + client?: ExtendedClient; + executionId: string; + interaction: ChatInputCommandInteraction; +} + +interface AutocompleteParams { + executionId: string; + interaction: AutocompleteInteraction; +} + +interface ComponentParams { interaction: MessageComponentInteraction; trackId?: string; executionId: string; } + +// Interaction types +export interface CustomSlashCommandInteraction { + isNew: boolean; + isBeta: boolean; + isSystemCommand?: boolean; + data: Omit; + execute(params: CommandParams): Promise | undefined>; +} + +export interface CustomAutocompleteInteraction { + execute(params: AutocompleteParams): Promise; +} + +export interface CustomComponentInteraction { + execute(params: ComponentParams): Promise | undefined>; +} + +// Command specific types +export interface ShardInfo { + shardId: number; + memUsage: number; + guildCount: number; + guildMemberCount: number; + playerStatistics: { + activeVoiceConnections: number; + totalTracks: number; + totalListeners: number; + }; +} + +export interface TrackMetadata { + bridge: { + views: number; + }; +} + +export class CustomError extends Error { + type?: string; + code?: string; +} diff --git a/src/utils/registerClientCommands.ts b/src/utils/registerClientCommands.ts index ef16c69..fcaa279 100644 --- a/src/utils/registerClientCommands.ts +++ b/src/utils/registerClientCommands.ts @@ -5,7 +5,7 @@ import path from 'node:path'; import loggerModule from '../services/logger'; import { RegisterClientCommandsParams } from '../types/utilTypes'; -export const registerClientCommands = ({ client, executionId }: RegisterClientCommandsParams) => { +export const registerClientCommands = async ({ client, executionId }: RegisterClientCommandsParams) => { const logger = loggerModule.child({ source: 'registerClientCommands.js', module: 'register', @@ -30,10 +30,11 @@ export const registerClientCommands = ({ client, executionId }: RegisterClientCo delete require.cache[require.resolve(`../interactions/commands/${folder}/${file}`)]; // register command - /* eslint-disable @typescript-eslint/no-var-requires */ - const command = require(`../interactions/commands/${folder}/${file}`); - client.commands.delete(command.data.name); - client.commands.set(command.data.name, command); + //const command = require(`../interactions/commands/${folder}/${file}`); + const commandModule = await import(`../interactions/commands/${folder}/${file}`); + + client.commands.delete(commandModule.default.data.name); + client.commands.set(commandModule.default.data.name, commandModule.default); } catch (error) { if (error instanceof Error) { logger.error(`Error registering command ${folder}/${file}: ${error.message}`); From f231c53fe87de5e912135a90a50bf8bac9b714dd Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 15:16:55 +0200 Subject: [PATCH 05/14] feat!: better handling and error handling for interaction events --- src/events/interactions/interactionCreate.ts | 317 ++++++------------ src/interactions/commands/player/filters.ts | 134 +------- .../components/filters-disable-button.ts | 57 ++++ .../components/filters-select-menu.ts | 100 ++++++ .../components/nowplaying-skip-button.ts | 6 +- src/types/interactionTypes.ts | 17 +- 6 files changed, 270 insertions(+), 361 deletions(-) create mode 100644 src/interactions/components/filters-disable-button.ts create mode 100644 src/interactions/components/filters-select-menu.ts diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index 5dd5f50..d5aeedc 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -14,6 +14,7 @@ import loggerModule from '../../services/logger'; import { Command, ExtendedClient } from '../../types/clientTypes'; import { BotOptions, EmbedOptions } from '../../types/configTypes'; import { cannotSendMessageInChannel } from '../../utils/validation/permissionValidator'; +import { CustomError } from '../../types/interactionTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); @@ -21,6 +22,7 @@ module.exports = { name: Events.InteractionCreate, isDebug: false, execute: async (interaction: Interaction, { client }: { client: ExtendedClient }) => { + const inputTime: number = new Date().getTime(); const executionId = uuidv4(); const logger = loggerModule.child({ source: 'interactionCreate.js', @@ -31,25 +33,39 @@ module.exports = { guildId: interaction.guild?.id }); - let interactionString: string = ''; - const interactionType: InteractionType = interaction.type; + logger.debug('Interaction received.'); + let interactionString: string = ''; + + // Todo: Extract to own file const handleComponent = async (interaction: MessageComponentInteraction) => { await interaction.deferReply(); + logger.debug('Interaction deferred.'); + const componentId = interaction.customId.split('_')[0]; - const trackId = interaction.customId.split('_')[1]; + const referenceId = interaction.customId.split('_')[1]; + + logger.debug(`Parsed componentId: ${componentId}`); + const componentModule = await import(`../../interactions/components/${componentId}.js`); - await componentModule.execute({ interaction, trackId, executionId }); + const { default: component } = componentModule; + + logger.debug('Executing component interaction.'); + await component.execute({ interaction, referenceId, executionId }); }; const handleAutocomplete = async (interaction: AutocompleteInteraction) => { - //const command = client.commands?.get(interaction.commandName) as Command; const autocompleteModule = await import(`../../interactions/autocomplete/${interaction.commandName}.js`); const { default: autocomplete } = autocompleteModule; + + logger.debug('Executing autocomplete interaction.'); await autocomplete.execute({ interaction, executionId }); }; const handleCommand = async (interaction: ChatInputCommandInteraction) => { + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + const command = client.commands?.get(interaction.commandName) as Command; if (!command) { logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); @@ -57,258 +73,113 @@ module.exports = { } logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`); - //try { - await interaction.deferReply(); if (await cannotSendMessageInChannel({ interaction, executionId })) { return; } - const inputTime: number = new Date().getTime(); - + logger.debug('Executing command interaction.'); await command.execute({ interaction, client, executionId }); + }; - /* doesnt work because need to find subfolder - /* Update registerClientCommands to registerClientInteractions - /* Add client.interactions with { commandInteractions, componentInteractions, autocompleteInteractions - const commandModule = await import(`../../interactions/commands/SUBFOLDER/${interaction.commandName}.js`); - const { default: command } = commandModule; - await command.execute({ interaction, client, executionId }); - */ + // TODO: Extract the text to a config file? + const errorReply = { + 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})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }; - const outputTime: number = new Date().getTime(); - const executionTime: number = outputTime - inputTime; + // TODO: extract handlError to own file (create errorHandler and export handleInteractionError?) + const handleError = async (interaction: Interaction, error: CustomError) => { + logger.error(error, `Error handling interaction of type '${interactionString}'`); - logger.info(`Command '${interaction}' executed in ${executionTime} ms.`); - /* - } catch (error) { - if (error instanceof Error) { - logger.warn( - error, - `Command '${interaction}' throwed an unhandled error and might have failed to execute properly.` - ); - - if ( - error.message === 'Unknown interaction' || - error.message === 'Interaction has already been acknowledged.' - ) { - logger.debug('Command failed to be responded to, unknown interaction or already acknowledged.'); + if (interaction instanceof ChatInputCommandInteraction && interaction.deferred) { + switch (interaction.replied) { + case true: + // This means interaction has received a reply already. + // Most likely command executed successfully or error is already handled. + logger.warn( + error, + `Interaction '${interaction.id}' threw an error but has already been replied to.` + ); return; - } else { - if (!interaction.deferred || !interaction.replied) { - logger.warn('Interaction was not deferred or replied to, and an error was thrown.'); - return; - } - - if (interaction.replied) { - // If the interaction has already been replied to, most likely command executed successfully or error is already handled. - return; - } else if (interaction.deferred) { - logger.info('Interaction was deferred, editing reply and sending Uh-oh message.'); - await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); - } else { - logger.info( - 'Interaction was not deferred or replied, sending new reply with Uh-oh message.' - ); - await interaction.reply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); - } - } - } else { - throw error; + case false: + // If the interaction has not been replied to, most likely command execution failed. + logger.debug('Responding with error embed'); + return await interaction.editReply(errorReply); } + } else if (interaction instanceof MessageComponentInteraction && interaction.deferred) { + switch (interaction.replied) { + case true: + // This means interaction has received a reply already. + // Most likely command executed successfully or error is already handled. + logger.warn( + error, + `Interaction '${interaction.id}' threw an error but has already been replied to.` + ); + return; + case false: + // If the interaction has not been replied to, most likely command execution failed. + logger.debug('Responding with error embed'); + return await interaction.editReply(errorReply); + } + } else { + logger.warn( + 'Interaction threw an error but was not deferred or replied to, or was an autocomplete interaction. Cannot send error reply.' + ); + + if ( + error.code === 'InteractionCollectorError' || + error.message === 'Collector received no interactions before ending with reason: time' + ) { + logger.debug('Interaction response timed out.'); + return; + } + + // If this code is reached there is an error that is not handled at all. + // This should not happen, but if it does, we log it with 'fatal' level to investigate. + // This is to prevent the bot from crashing or doing something very unexpected. + logger.fatal(error, 'Unhandled error while awaiting or handling component interaction.'); + return; } - */ }; try { - switch (interactionType) { + logger.debug('Started handling interaction.'); + switch (interaction.type as InteractionType) { case InteractionType.ApplicationCommand: interactionString = 'ApplicationCommand'; - handleCommand(interaction as ChatInputCommandInteraction); + await handleCommand(interaction as ChatInputCommandInteraction); break; case InteractionType.ApplicationCommandAutocomplete: interactionString = 'ApplicationCommandAutocomplete'; - handleAutocomplete(interaction as AutocompleteInteraction); + await handleAutocomplete(interaction as AutocompleteInteraction); break; case InteractionType.MessageComponent: interactionString = 'MessageComponent'; - handleComponent(interaction as MessageComponentInteraction); + await handleComponent(interaction as MessageComponentInteraction); break; default: interactionString = 'Unknown'; break; } - - logger.debug(`Interaction of type '${interactionString}' created.`); } catch (error) { - logger.error(error, `Error handling interaction of type '${interactionString}'`); - - const errorReply = { - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }; - - const handleErrorWithReplyToUser = async (interaction: Interaction, error: Error) => { - logger.error(error, `Error handling interaction of type '${interactionString}'`); - if (interaction.channel) { - // Send message to user in channel where interaction was made - logger.debug(`Sending error reply to channel '${interaction.channel.id}'.`); - await interaction.channel.send(errorReply); - } else { - // Send message to user in DMs - logger.debug(`Sending error reply to user '${interaction.user.id}'.`); - await interaction.user.send(errorReply); - } - }; - - switch (true) { - case interaction instanceof ChatInputCommandInteraction: - await handleErrorWithReplyToUser(interaction, error as Error); - break; - case interaction instanceof AutocompleteInteraction: - await handleErrorWithReplyToUser(interaction, error as Error); - break; - case interaction instanceof MessageComponentInteraction: - await handleErrorWithReplyToUser(interaction, error as Error); - break; - default: - // Something else went wrong - logger.error(error, 'Unhandled error while handling unkown interaction.'); - break; - } + logger.debug('Error while handling received interaction.'); + await handleError(interaction, error as CustomError); } - /* - if (interaction.isAutocomplete()) { + const outputTime: number = new Date().getTime(); + const executionTime: number = outputTime - inputTime; - try { - command?.autocomplete && (await command?.autocomplete({ interaction, executionId })); - } catch (error) { - if (error instanceof Error) { - if ( - error.message === 'Unknown interaction' || - error.message === 'Interaction has already been acknowledged.' - ) { - logger.debug( - 'Autocomplete failed to be responded to, unknown interaction or already acknowledged.' - ); - return; - } else { - logger.warn(error, 'Autocomplete failed to execute.'); - } - return; - } else { - throw error; - } - } - } - */ - - /* - if (interaction.isChatInputCommand()) { - const command = client.commands?.get(interaction.commandName) as Command; - if (!command) { - logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); - return; - } - logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`); - try { - await interaction.deferReply(); - - if (await cannotSendMessageInChannel({ interaction, executionId })) { - return; - } - - const inputTime: number = new Date().getTime(); - - await command.execute({ interaction, client, executionId }); - - const outputTime: number = new Date().getTime(); - const executionTime: number = outputTime - inputTime; - - logger.info(`Command '${interaction}' executed in ${executionTime} ms.`); - } catch (error) { - if (error instanceof Error) { - logger.warn( - error, - `Command '${interaction}' throwed an unhandled error and might have failed to execute properly.` - ); - - if ( - error.message === 'Unknown interaction' || - error.message === 'Interaction has already been acknowledged.' - ) { - logger.debug('Command failed to be responded to, unknown interaction or already acknowledged.'); - return; - } else { - if (!interaction.deferred || !interaction.replied) { - logger.warn('Interaction was not deferred or replied to, and an error was thrown.'); - return; - } - - if (interaction.replied) { - // If the interaction has already been replied to, most likely command executed successfully or error is already handled. - return; - } else if (interaction.deferred) { - logger.info('Interaction was deferred, editing reply and sending Uh-oh message.'); - await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); - } else { - logger.info( - 'Interaction was not deferred or replied, sending new reply with Uh-oh message.' - ); - await interaction.reply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); - } - } - } else { - throw error; - } - } - } - */ + logger.info(`Interaction of type '${interactionString}' handled in ${executionTime} ms.`); + return; } }; diff --git a/src/interactions/commands/player/filters.ts b/src/interactions/commands/player/filters.ts index 1d632d8..9aabc74 100644 --- a/src/interactions/commands/player/filters.ts +++ b/src/interactions/commands/player/filters.ts @@ -7,15 +7,13 @@ import { ButtonStyle, ComponentType, EmbedBuilder, - GuildMember, - Interaction, SlashCommandBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CustomError, CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; @@ -79,7 +77,7 @@ const command: CustomSlashCommandInteraction = { }); const filterSelect = new StringSelectMenuBuilder() - .setCustomId('filters') + .setCustomId('filters-select-menu') .setPlaceholder('Select multiple options.') .setMinValues(0) .setMaxValues(filterOptions.length) @@ -92,7 +90,7 @@ const command: CustomSlashCommandInteraction = { }; const disableButton = new ButtonBuilder() - .setCustomId('disable-filters') + .setCustomId('filters-disable-button') .setLabel('Disable all filters') .setStyle(ButtonStyle.Secondary) .setEmoji(embedOptions.icons.disable) @@ -104,7 +102,7 @@ const command: CustomSlashCommandInteraction = { }; logger.debug('Sending info embed with action row components.'); - const response = await interaction.editReply({ + return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription('**Toggle filters**\nEnable or disable audio filters for playback from the menu.') @@ -112,130 +110,6 @@ const command: CustomSlashCommandInteraction = { ], components: [filterActionRow, disableFiltersActionRow] }); - - const collectorFilter = (i: Interaction) => i.user.id === interaction.user.id; - try { - const confirmation = await response.awaitMessageComponent({ - filter: collectorFilter, - time: 300_000 - }); - - confirmation.deferUpdate(); - - logger.debug('Received component interaction response.'); - - queue.filters.ffmpeg.setInputArgs([ - '-threads', - ffmpegFilterOptions.threadAmount, - '-reconnect', - '1', - '-reconnect_streamed', - '1', - '-reconnect_delay_max', - '10', - '-vn' - ]); - - // Reset filters before enabling provided filters - if (queue.filters.ffmpeg.filters.length > 0) { - queue.filters.ffmpeg.setFilters(false); - logger.debug('Reset queue filters.'); - } - - let authorName: string; - - if (interaction.member instanceof GuildMember) { - authorName = interaction.member.nickname || interaction.user.username; - } else { - authorName = interaction.user.username; - } - - if ('values' in confirmation) { - // if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion - if ( - (confirmation.values.includes('bassboost_low') || confirmation.values.includes('bassboost')) && - !confirmation.values.includes('normalizer') - ) { - confirmation.values.push('normalizer'); - } - - // Enable provided filters - queue.filters.ffmpeg.toggle(confirmation.values as (keyof QueueFilters)[]); - logger.debug(`Enabled filters ${confirmation.values.join(', ')}.`); - - logger.debug('Responding with success embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setAuthor({ - name: authorName, - iconURL: interaction.user.avatarURL() || '' - }) - .setDescription( - `**${ - embedOptions.icons.success - } Filters toggled**\nNow using these filters:\n${confirmation.values - .map((enabledFilter: string) => { - const filter = ffmpegFilterOptions.availableFilters.find( - (filter) => enabledFilter == filter.value - ); - - if (!filter) { - return enabledFilter; - } - - return `- **${filter.emoji} ${filter.label}**`; - }) - .join('\n')}` - ) - .setColor(embedOptions.colors.success) - ], - components: [] - }); - } else if (confirmation.customId === 'disable-filters') { - logger.debug('Responding with success embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setAuthor({ - name: authorName, - iconURL: interaction.user.avatarURL() || '' - }) - .setDescription( - `**${embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.` - ) - .setColor(embedOptions.colors.success) - ], - components: [] - }); - } else { - logger.warn('Unhandled component interaction response.'); - } - } catch (error) { - if (error instanceof CustomError) { - if (error.code === 'InteractionCollectorError') { - logger.debug('Interaction response timed out.'); - return; - } - - if (error.message === 'Collector received no interactions before ending with reason: time') { - logger.debug('Interaction response timed out.'); - return; - } - - logger.error(error, 'Unhandled error while awaiting or handling component interaction.'); - return; - } else { - if ( - error instanceof Error && - error.message === 'Collector received no interactions before ending with reason: time' - ) { - logger.debug('Interaction response timed out.'); - return; - } - throw error; - } - } } }; diff --git a/src/interactions/components/filters-disable-button.ts b/src/interactions/components/filters-disable-button.ts new file mode 100644 index 0000000..9b0395e --- /dev/null +++ b/src/interactions/components/filters-disable-button.ts @@ -0,0 +1,57 @@ +import config from 'config'; + +import loggerModule from '../../services/logger'; +import { EmbedOptions } from '../../types/configTypes'; +import { CustomComponentInteraction } from '../../types/interactionTypes'; +import { useQueue } from 'discord-player'; +import { EmbedBuilder, GuildMember } from 'discord.js'; +const embedOptions: EmbedOptions = config.get('embedOptions'); + +const component: CustomComponentInteraction = { + execute: async ({ interaction, executionId }) => { + const logger = loggerModule.child({ + source: 'filters-disable-button.js', + module: 'componentInteraction', + name: 'filters-disable-button', + executionId: executionId, + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id + }); + + logger.info('Received disable confirmation.'); + + const queue = useQueue(interaction.guild!.id)!; + + // Reset filters before enabling provided filters + if (queue.filters.ffmpeg.filters.length > 0) { + queue.filters.ffmpeg.setFilters(false); + logger.debug('Reset queue filters.'); + } + + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + + logger.debug('Responding with success embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setAuthor({ + name: authorName, + iconURL: interaction.user.avatarURL() || '' + }) + .setDescription( + `**${embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.` + ) + .setColor(embedOptions.colors.success) + ], + components: [] + }); + } +}; + +export default component; diff --git a/src/interactions/components/filters-select-menu.ts b/src/interactions/components/filters-select-menu.ts new file mode 100644 index 0000000..600e10b --- /dev/null +++ b/src/interactions/components/filters-select-menu.ts @@ -0,0 +1,100 @@ +import config from 'config'; + +import loggerModule from '../../services/logger'; +import { EmbedOptions, FFmpegFilterOptions } from '../../types/configTypes'; +import { CustomComponentInteraction } from '../../types/interactionTypes'; +import { QueueFilters, useQueue } from 'discord-player'; +import { EmbedBuilder, GuildMember, StringSelectMenuInteraction } from 'discord.js'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions'); + +const component: CustomComponentInteraction = { + execute: async ({ interaction, executionId }) => { + const logger = loggerModule.child({ + source: 'filters-select-menu.js', + module: 'componentInteraction', + name: 'filters-select-menu', + executionId: executionId, + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id + }); + + logger.info('Received select menu confirmation.'); + + const queue = useQueue(interaction.guild!.id)!; + + queue.filters.ffmpeg.setInputArgs([ + '-threads', + ffmpegFilterOptions.threadAmount, + '-reconnect', + '1', + '-reconnect_streamed', + '1', + '-reconnect_delay_max', + '10', + '-vn' + ]); + + // Reset filters before enabling provided filters + if (queue.filters.ffmpeg.filters.length > 0) { + queue.filters.ffmpeg.setFilters(false); + logger.debug('Reset queue filters.'); + } + + if (!(interaction instanceof StringSelectMenuInteraction)) { + return; + } + + // if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion + if ( + (interaction.values.includes('bassboost_low') || interaction.values.includes('bassboost')) && + !interaction.values.includes('normalizer') + ) { + interaction.values.push('normalizer'); + } + + // Enable provided filters + queue.filters.ffmpeg.toggle(interaction.values as (keyof QueueFilters)[]); + logger.debug(`Enabled filters ${interaction.values.join(', ')}.`); + + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + + logger.debug('Responding with success embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setAuthor({ + name: authorName, + iconURL: interaction.user.avatarURL() || '' + }) + .setDescription( + `**${ + embedOptions.icons.success + } Filters toggled**\nNow using these filters:\n${interaction.values + .map((enabledFilter: string) => { + const filter = ffmpegFilterOptions.availableFilters.find( + (filter) => enabledFilter == filter.value + ); + + if (!filter) { + return enabledFilter; + } + + return `- **${filter.emoji} ${filter.label}**`; + }) + .join('\n')}` + ) + .setColor(embedOptions.colors.success) + ], + components: [] + }); + } +}; + +export default component; diff --git a/src/interactions/components/nowplaying-skip-button.ts b/src/interactions/components/nowplaying-skip-button.ts index 9b5ecc0..92f4e80 100644 --- a/src/interactions/components/nowplaying-skip-button.ts +++ b/src/interactions/components/nowplaying-skip-button.ts @@ -8,7 +8,7 @@ import { CustomComponentInteraction } from '../../types/interactionTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); const component: CustomComponentInteraction = { - execute: async ({ interaction, trackId, executionId }) => { + execute: async ({ interaction, referenceId, executionId }) => { const logger = loggerModule.child({ source: 'nowplaying-skip.js', module: 'componentInteraction', @@ -20,7 +20,7 @@ const component: CustomComponentInteraction = { const queue: NodeResolvable = useQueue(interaction.guild!.id)!; - logger.debug(`Received skip confirmation for track id ${trackId}.`); + logger.debug(`Received skip confirmation for track id ${referenceId}.`); if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { logger.debug('Tried skipping track but there was no queue.'); @@ -37,7 +37,7 @@ const component: CustomComponentInteraction = { }); } - if (queue.currentTrack!.id !== trackId) { + if (queue.currentTrack!.id !== referenceId) { logger.debug('Tried skipping track but it is not the current track and therefore already skipped/removed.'); logger.debug('Responding with warning embed.'); diff --git a/src/types/interactionTypes.ts b/src/types/interactionTypes.ts index 2f1c59e..c7113da 100644 --- a/src/types/interactionTypes.ts +++ b/src/types/interactionTypes.ts @@ -1,4 +1,11 @@ -import { AutocompleteInteraction, ChatInputCommandInteraction, Message, MessageComponentInteraction, SlashCommandBuilder } from 'discord.js'; +import { + ApplicationCommandOptionChoiceData, + AutocompleteInteraction, + ChatInputCommandInteraction, + Message, + MessageComponentInteraction, + SlashCommandBuilder +} from 'discord.js'; import { ExtendedClient } from './clientTypes'; // Local types @@ -15,7 +22,7 @@ interface AutocompleteParams { interface ComponentParams { interaction: MessageComponentInteraction; - trackId?: string; + referenceId?: string; executionId: string; } @@ -25,15 +32,15 @@ export interface CustomSlashCommandInteraction { isBeta: boolean; isSystemCommand?: boolean; data: Omit; - execute(params: CommandParams): Promise | undefined>; + execute(params: CommandParams): Promise | void>; } export interface CustomAutocompleteInteraction { - execute(params: AutocompleteParams): Promise; + execute(params: AutocompleteParams): Promise; } export interface CustomComponentInteraction { - execute(params: ComponentParams): Promise | undefined>; + execute(params: ComponentParams): Promise | void>; } // Command specific types From 14cb6b4936f5e005081d713104398e187e3fccd8 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 15:31:54 +0200 Subject: [PATCH 06/14] fix: Ensure promise is returned where applicable --- src/interactions/commands/info/help.ts | 7 +---- src/interactions/commands/info/status.ts | 11 ++------ src/interactions/commands/player/filters.ts | 8 +++--- src/interactions/commands/player/leave.ts | 4 +-- src/interactions/commands/player/loop.ts | 6 ++-- src/interactions/commands/player/lyrics.ts | 10 +++---- .../commands/player/nowplaying.ts | 8 +++--- src/interactions/commands/player/pause.ts | 8 +++--- src/interactions/commands/player/play.ts | 6 ++-- src/interactions/commands/player/queue.ts | 4 +-- src/interactions/commands/player/remove.ts | 6 ++-- src/interactions/commands/player/seek.ts | 8 +++--- src/interactions/commands/player/shuffle.ts | 8 +++--- src/interactions/commands/player/skip.ts | 8 +++--- src/interactions/commands/player/stop.ts | 4 +-- src/interactions/commands/player/volume.ts | 6 ++-- src/interactions/commands/system/guilds.ts | 9 ++---- src/interactions/commands/system/reload.ts | 19 ++++--------- src/interactions/commands/system/shards.ts | 19 ++++--------- .../commands/system/systemstatus.ts | 17 ++++------- .../components/filters-select-menu.ts | 28 +++++++++---------- src/utils/other/postBotStats.ts | 5 ++-- src/utils/other/startLoadTest.ts | 2 +- 23 files changed, 86 insertions(+), 125 deletions(-) diff --git a/src/interactions/commands/info/help.ts b/src/interactions/commands/info/help.ts index 5caedc7..d9f77fc 100644 --- a/src/interactions/commands/info/help.ts +++ b/src/interactions/commands/info/help.ts @@ -26,12 +26,7 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - if (!client || !client.commands) { - logger.error('Client is undefined or does not have commands property.'); - return; - } - - const commandList = client.commands + const commandList = client!.commands! .filter((command) => { // don't include system commands if (command.isSystemCommand) { diff --git a/src/interactions/commands/info/status.ts b/src/interactions/commands/info/status.ts index 68022a7..e4422bd 100644 --- a/src/interactions/commands/info/status.ts +++ b/src/interactions/commands/info/status.ts @@ -39,12 +39,7 @@ const command: CustomSlashCommandInteraction = { let totalTracks: number = 0; let totalListeners: number = 0; - if (!client || !client.shard) { - logger.error('Client is undefined or does not have shard property.'); - return; - } - - await client.shard + await client!.shard! .broadcastEval(() => { /* eslint-disable no-undef */ return player.generateStatistics(); @@ -73,7 +68,7 @@ const command: CustomSlashCommandInteraction = { logger.error(error, 'Failed to fetch player statistics from shards.'); }); - await client.shard + await client!.shard! .fetchClientValues('guilds.cache') .then((results) => { const guildCaches = results as Guild[][]; @@ -103,7 +98,7 @@ const command: CustomSlashCommandInteraction = { const systemStatusString = `**${uptimeString}** Uptime\n` + `**${cpuUsage}%** CPU usage\n` + `**${usedMemoryInMB} MB** Memory usage`; - const discordStatusString = `**${client.ws.ping} ms** Discord API latency`; + const discordStatusString = `**${client!.ws.ping} ms** Discord API latency`; logger.debug('Transformed status into into embed description.'); diff --git a/src/interactions/commands/player/filters.ts b/src/interactions/commands/player/filters.ts index 9aabc74..a1dad46 100644 --- a/src/interactions/commands/player/filters.ts +++ b/src/interactions/commands/player/filters.ts @@ -40,21 +40,21 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } const filterOptions: StringSelectMenuOptionBuilder[] = []; diff --git a/src/interactions/commands/player/leave.ts b/src/interactions/commands/player/leave.ts index a4bab4e..071c18b 100644 --- a/src/interactions/commands/player/leave.ts +++ b/src/interactions/commands/player/leave.ts @@ -28,7 +28,7 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } const queue: NodeResolvable = useQueue(interaction.guild!.id)!; @@ -49,7 +49,7 @@ const command: CustomSlashCommandInteraction = { } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (!queue.deleted) { diff --git a/src/interactions/commands/player/loop.ts b/src/interactions/commands/player/loop.ts index 46528b7..f2a16bd 100644 --- a/src/interactions/commands/player/loop.ts +++ b/src/interactions/commands/player/loop.ts @@ -42,17 +42,17 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } const loopModesFormatted = new Map([ diff --git a/src/interactions/commands/player/lyrics.ts b/src/interactions/commands/player/lyrics.ts index f8b99f3..261288e 100644 --- a/src/interactions/commands/player/lyrics.ts +++ b/src/interactions/commands/player/lyrics.ts @@ -48,19 +48,19 @@ const command: CustomSlashCommandInteraction = { if (!query) { if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } geniusSearchQuery = queue.currentTrack!.title.slice(0, 50); @@ -188,7 +188,7 @@ const command: CustomSlashCommandInteraction = { } } - return; + return Promise.resolve(); } logger.debug('Responding with info embed.'); diff --git a/src/interactions/commands/player/nowplaying.ts b/src/interactions/commands/player/nowplaying.ts index e456db7..5e2efcc 100644 --- a/src/interactions/commands/player/nowplaying.ts +++ b/src/interactions/commands/player/nowplaying.ts @@ -38,21 +38,21 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } const sourceStringsFormatted = new Map([ diff --git a/src/interactions/commands/player/pause.ts b/src/interactions/commands/player/pause.ts index 3c014cf..312d499 100644 --- a/src/interactions/commands/player/pause.ts +++ b/src/interactions/commands/player/pause.ts @@ -29,21 +29,21 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } const currentTrack = queue.currentTrack!; diff --git a/src/interactions/commands/player/play.ts b/src/interactions/commands/player/play.ts index 5c4bb75..87a7458 100644 --- a/src/interactions/commands/player/play.ts +++ b/src/interactions/commands/player/play.ts @@ -44,16 +44,16 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } if (await cannotJoinVoiceOrTalk({ interaction, executionId })) { - return; + return Promise.resolve(); } let queue = useQueue(interaction.guild!.id); if (queue && (await notInSameVoiceChannel({ interaction, queue, executionId }))) { - return; + return Promise.resolve(); } const player = useMainPlayer()!; diff --git a/src/interactions/commands/player/queue.ts b/src/interactions/commands/player/queue.ts index 8b27b7d..ef4c26e 100644 --- a/src/interactions/commands/player/queue.ts +++ b/src/interactions/commands/player/queue.ts @@ -30,13 +30,13 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } const pageIndex = (interaction.options.getNumber('page') || 1) - 1; diff --git a/src/interactions/commands/player/remove.ts b/src/interactions/commands/player/remove.ts index 1e3275c..f5a5071 100644 --- a/src/interactions/commands/player/remove.ts +++ b/src/interactions/commands/player/remove.ts @@ -36,17 +36,17 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } const removeTrackNumber = interaction.options.getNumber('tracknumber')!; diff --git a/src/interactions/commands/player/seek.ts b/src/interactions/commands/player/seek.ts index cf3e6ec..4ff8589 100644 --- a/src/interactions/commands/player/seek.ts +++ b/src/interactions/commands/player/seek.ts @@ -35,21 +35,21 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } const durationInput = interaction.options.getString('duration'); diff --git a/src/interactions/commands/player/shuffle.ts b/src/interactions/commands/player/shuffle.ts index 81e4027..a64c05f 100644 --- a/src/interactions/commands/player/shuffle.ts +++ b/src/interactions/commands/player/shuffle.ts @@ -29,21 +29,21 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await queueIsEmpty({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } queue.tracks.shuffle(); diff --git a/src/interactions/commands/player/skip.ts b/src/interactions/commands/player/skip.ts index ffd4664..aa98e20 100644 --- a/src/interactions/commands/player/skip.ts +++ b/src/interactions/commands/player/skip.ts @@ -32,21 +32,21 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } const skipToTrack = interaction.options.getNumber('tracknumber'); diff --git a/src/interactions/commands/player/stop.ts b/src/interactions/commands/player/stop.ts index dcc2cb8..3737f14 100644 --- a/src/interactions/commands/player/stop.ts +++ b/src/interactions/commands/player/stop.ts @@ -28,7 +28,7 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } const queue: NodeResolvable = useQueue(interaction.guild!.id)!; @@ -49,7 +49,7 @@ const command: CustomSlashCommandInteraction = { } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (!queue.deleted) { diff --git a/src/interactions/commands/player/volume.ts b/src/interactions/commands/player/volume.ts index 88e2b98..8e97159 100644 --- a/src/interactions/commands/player/volume.ts +++ b/src/interactions/commands/player/volume.ts @@ -36,17 +36,17 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return; + return Promise.resolve(); } const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + return Promise.resolve(); } const volume = interaction.options.getNumber('percentage'); diff --git a/src/interactions/commands/system/guilds.ts b/src/interactions/commands/system/guilds.ts index 1f5609f..696b89b 100644 --- a/src/interactions/commands/system/guilds.ts +++ b/src/interactions/commands/system/guilds.ts @@ -28,19 +28,14 @@ const command: CustomSlashCommandInteraction = { }); if (await notValidGuildId({ interaction, executionId })) { - return; + return Promise.resolve(); } let shardGuilds: Guild[] = []; let totalGuildCount = 0; - if (!client || !client.shard) { - logger.error('Client is undefined or does not have shard property.'); - return; - } - logger.debug('Fetching guilds from all shards.'); - await client.shard + await client!.shard! .broadcastEval((c) => { return c.guilds.cache.map((guild) => { return guild; diff --git a/src/interactions/commands/system/reload.ts b/src/interactions/commands/system/reload.ts index 551eb63..52b67d7 100644 --- a/src/interactions/commands/system/reload.ts +++ b/src/interactions/commands/system/reload.ts @@ -29,24 +29,15 @@ const command: CustomSlashCommandInteraction = { }); if (await notValidGuildId({ interaction, executionId })) { - return; - } - - if (!client || !client.shard) { - logger.error('Client is undefined or does not have shard property.'); - return; + return Promise.resolve(); } try { logger.debug('Reloading commands across all shards.'); - await client.shard - .broadcastEval( + await client! + .shard!.broadcastEval( async (shardClient: ExtendedClient, { executionId }) => { - if (!shardClient.registerClientCommands) { - return; - } - - shardClient.registerClientCommands({ client: shardClient, executionId }); + shardClient.registerClientCommands!({ client: shardClient, executionId }); }, { context: { executionId: executionId } } ) @@ -70,7 +61,7 @@ const command: CustomSlashCommandInteraction = { }); } - const commands = client.commands?.map((command) => { + const commands = client!.commands?.map((command) => { const params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : ''; return `- **\`/${command.data.name}\`** ${params}- ${command.data.description}`; }); diff --git a/src/interactions/commands/system/shards.ts b/src/interactions/commands/system/shards.ts index 56a894c..9985d04 100644 --- a/src/interactions/commands/system/shards.ts +++ b/src/interactions/commands/system/shards.ts @@ -46,24 +46,15 @@ const command: CustomSlashCommandInteraction = { }); if (await notValidGuildId({ interaction, executionId })) { - return; + return Promise.resolve(); } let shardInfoList: ShardInfo[] = []; - if (!client || !client.shard) { - logger.error('Client is undefined or does not have shard property.'); - return; - } - logger.debug('Fetching player statistics and client values from each shard.'); try { - await client.shard - .broadcastEval((shardClient: ExtendedClient) => { - if (!shardClient.shard) { - return; - } - + await client! + .shard!.broadcastEval((shardClient: ExtendedClient) => { /* eslint-disable no-undef */ const playerStats = player.generateStatistics(); const nodeProcessMemUsageInMb = parseFloat( @@ -71,7 +62,7 @@ const command: CustomSlashCommandInteraction = { ); const shardInfo = { - shardId: shardClient.shard.ids[0], + shardId: shardClient.shard!.ids[0], memUsage: nodeProcessMemUsageInMb, guildCount: shardClient.guilds.cache.size, guildMemberCount: shardClient.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0), @@ -194,7 +185,7 @@ const command: CustomSlashCommandInteraction = { .setDescription(`**${embedOptions.icons.server} Shard overview - ${shardCount} total shards**\n`) .addFields(...embedFields) .setColor(embedOptions.colors.info) - .setFooter({ text: `Shard id: ${client.shard.ids[0]}, page ${pageIndex + 1} of ${totalPages}` }) + .setFooter({ text: `Shard id: ${client!.shard!.ids[0]}, page ${pageIndex + 1} of ${totalPages}` }) ] }); } diff --git a/src/interactions/commands/system/systemstatus.ts b/src/interactions/commands/system/systemstatus.ts index fe32b4e..2996ab4 100644 --- a/src/interactions/commands/system/systemstatus.ts +++ b/src/interactions/commands/system/systemstatus.ts @@ -32,7 +32,7 @@ const command: CustomSlashCommandInteraction = { }); if (await notValidGuildId({ interaction, executionId })) { - return; + return Promise.resolve(); } // from normal /status command @@ -61,13 +61,8 @@ const command: CustomSlashCommandInteraction = { logger.debug('Fetching player statistics from all shards.'); - if (!client || !client.shard) { - logger.error('Client is undefined or does not have shard property.'); - return; - } - - await client.shard - .broadcastEval(() => { + await client! + .shard!.broadcastEval(() => { /* eslint-disable no-undef */ return player.generateStatistics(); }) @@ -93,8 +88,8 @@ const command: CustomSlashCommandInteraction = { }); logger.debug('Fetching client values from all shards.'); - await client.shard - .fetchClientValues('guilds.cache') + await client! + .shard!.fetchClientValues('guilds.cache') .then((results) => { const guildCaches = results as Guild[][]; guildCaches.map((guildCache: Guild[]) => { @@ -135,7 +130,7 @@ const command: CustomSlashCommandInteraction = { `**${mediaplexVersion}** mediaplex\n` + `**${distubeYtdlVersion}** @distube/ytdl-core`; - const discordStatusString = `**${client.ws.ping} ms** Discord API latency`; + const discordStatusString = `**${client!.ws.ping} ms** Discord API latency`; logger.debug('Transformed system status into embed description.'); diff --git a/src/interactions/components/filters-select-menu.ts b/src/interactions/components/filters-select-menu.ts index 600e10b..70a4c5a 100644 --- a/src/interactions/components/filters-select-menu.ts +++ b/src/interactions/components/filters-select-menu.ts @@ -21,7 +21,8 @@ const component: CustomComponentInteraction = { logger.info('Received select menu confirmation.'); - const queue = useQueue(interaction.guild!.id)!; + const selectMenuInteraction = interaction as StringSelectMenuInteraction; + const queue = useQueue(selectMenuInteraction.guild!.id)!; queue.filters.ffmpeg.setInputArgs([ '-threads', @@ -41,42 +42,39 @@ const component: CustomComponentInteraction = { logger.debug('Reset queue filters.'); } - if (!(interaction instanceof StringSelectMenuInteraction)) { - return; - } // if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion if ( - (interaction.values.includes('bassboost_low') || interaction.values.includes('bassboost')) && - !interaction.values.includes('normalizer') + (selectMenuInteraction.values.includes('bassboost_low') || selectMenuInteraction.values.includes('bassboost')) && + !selectMenuInteraction.values.includes('normalizer') ) { - interaction.values.push('normalizer'); + selectMenuInteraction.values.push('normalizer'); } // Enable provided filters - queue.filters.ffmpeg.toggle(interaction.values as (keyof QueueFilters)[]); - logger.debug(`Enabled filters ${interaction.values.join(', ')}.`); + queue.filters.ffmpeg.toggle(selectMenuInteraction.values as (keyof QueueFilters)[]); + logger.debug(`Enabled filters ${selectMenuInteraction.values.join(', ')}.`); let authorName: string; - if (interaction.member instanceof GuildMember) { - authorName = interaction.member.nickname || interaction.user.username; + if (selectMenuInteraction.member instanceof GuildMember) { + authorName = selectMenuInteraction.member.nickname || selectMenuInteraction.user.username; } else { - authorName = interaction.user.username; + authorName = selectMenuInteraction.user.username; } logger.debug('Responding with success embed.'); - return await interaction.editReply({ + return await selectMenuInteraction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ name: authorName, - iconURL: interaction.user.avatarURL() || '' + iconURL: selectMenuInteraction.user.avatarURL() || '' }) .setDescription( `**${ embedOptions.icons.success - } Filters toggled**\nNow using these filters:\n${interaction.values + } Filters toggled**\nNow using these filters:\n${selectMenuInteraction.values .map((enabledFilter: string) => { const filter = ffmpegFilterOptions.availableFilters.find( (filter) => enabledFilter == filter.value diff --git a/src/utils/other/postBotStats.ts b/src/utils/other/postBotStats.ts index e85aaa5..89e083e 100644 --- a/src/utils/other/postBotStats.ts +++ b/src/utils/other/postBotStats.ts @@ -15,7 +15,7 @@ export const postBotStats = async ({ client, executionId }: PostBotStatsParams) try { if (client.shard?.ids[0] !== 0) { - return; + return Promise.resolve(); } let guildCount = 0; @@ -128,7 +128,8 @@ export const postBotStats = async ({ client, executionId }: PostBotStatsParams) sites.map((site) => { if (!site.enabled) { - return; + // return if site is disabled + return Promise.resolve(); } const options = { diff --git a/src/utils/other/startLoadTest.ts b/src/utils/other/startLoadTest.ts index a29ef40..91cdb65 100644 --- a/src/utils/other/startLoadTest.ts +++ b/src/utils/other/startLoadTest.ts @@ -18,7 +18,7 @@ export const startLoadTest = async ({ client, executionId }: StartLoadTestParams if (!loadTestOptions.enabled) { logger.debug('Load test is disabled in options, cancelling.'); - return; + return Promise.resolve(); } const channelIds = loadTestOptions.channelIdsToJoin; From 931c6eb1403febf98acfbc2de38ac26c571cd0ef Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 15:46:25 +0200 Subject: [PATCH 07/14] fix: Small adjustments --- config/default.js | 2 +- src/interactions/commands/player/nowplaying.ts | 2 +- src/interactions/commands/player/queue.ts | 2 +- src/interactions/commands/player/skip.ts | 2 +- src/interactions/components/filters-disable-button.ts | 2 +- src/interactions/components/filters-select-menu.ts | 2 +- src/interactions/components/nowplaying-skip-button.ts | 3 ++- 7 files changed, 8 insertions(+), 7 deletions(-) diff --git a/config/default.js b/config/default.js index 739450f..ecb1573 100644 --- a/config/default.js +++ b/config/default.js @@ -121,7 +121,7 @@ module.exports.playerOptions = { maxQueueSize: 10_000, maxHistorySize: 100, bufferingTimeout: 3_000, - connectionTimeout: 30_000, + connectionTimeout: 20_000, progressBar: { length: 14, timecodes: false, diff --git a/src/interactions/commands/player/nowplaying.ts b/src/interactions/commands/player/nowplaying.ts index 5e2efcc..41cc816 100644 --- a/src/interactions/commands/player/nowplaying.ts +++ b/src/interactions/commands/player/nowplaying.ts @@ -155,7 +155,7 @@ const command: CustomSlashCommandInteraction = { ? '' : `**${ queue.repeatMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop - } Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.` + } Looping**\nLoop mode is set to **\`${loopModeUserString}\`**. You can change it with **\`/loop\`**.` }` ) .addFields( diff --git a/src/interactions/commands/player/queue.ts b/src/interactions/commands/player/queue.ts index ef4c26e..0ebc12c 100644 --- a/src/interactions/commands/player/queue.ts +++ b/src/interactions/commands/player/queue.ts @@ -137,7 +137,7 @@ const command: CustomSlashCommandInteraction = { ? '' : `**${ queue.repeatMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop - } Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.\n\n` + } Looping**\nLoop mode is set to **\`${loopModeUserString}\`**. You can change it with **\`/loop\`**.\n\n` }`; if (!currentTrack) { diff --git a/src/interactions/commands/player/skip.ts b/src/interactions/commands/player/skip.ts index aa98e20..7b67823 100644 --- a/src/interactions/commands/player/skip.ts +++ b/src/interactions/commands/player/skip.ts @@ -172,7 +172,7 @@ const command: CustomSlashCommandInteraction = { queue.repeatMode === 3 ? embedOptions.icons.autoplaying : embedOptions.icons.looping - } Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.` + } Looping**\nLoop mode is set to **\`${loopModeUserString}\`**. You can change it with **\`/loop\`**.` }` ) .setThumbnail(skippedTrack.thumbnail) diff --git a/src/interactions/components/filters-disable-button.ts b/src/interactions/components/filters-disable-button.ts index 9b0395e..3597ee1 100644 --- a/src/interactions/components/filters-disable-button.ts +++ b/src/interactions/components/filters-disable-button.ts @@ -18,7 +18,7 @@ const component: CustomComponentInteraction = { guildId: interaction.guild?.id }); - logger.info('Received disable confirmation.'); + logger.debug('Received disable confirmation.'); const queue = useQueue(interaction.guild!.id)!; diff --git a/src/interactions/components/filters-select-menu.ts b/src/interactions/components/filters-select-menu.ts index 70a4c5a..f8a85d5 100644 --- a/src/interactions/components/filters-select-menu.ts +++ b/src/interactions/components/filters-select-menu.ts @@ -19,7 +19,7 @@ const component: CustomComponentInteraction = { guildId: interaction.guild?.id }); - logger.info('Received select menu confirmation.'); + logger.debug('Received select menu confirmation.'); const selectMenuInteraction = interaction as StringSelectMenuInteraction; const queue = useQueue(selectMenuInteraction.guild!.id)!; diff --git a/src/interactions/components/nowplaying-skip-button.ts b/src/interactions/components/nowplaying-skip-button.ts index 92f4e80..3d8d895 100644 --- a/src/interactions/components/nowplaying-skip-button.ts +++ b/src/interactions/components/nowplaying-skip-button.ts @@ -18,9 +18,10 @@ const component: CustomComponentInteraction = { guildId: interaction.guild?.id }); + logger.debug(`Received skip confirmation for track id ${referenceId}.`); + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; - logger.debug(`Received skip confirmation for track id ${referenceId}.`); if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { logger.debug('Tried skipping track but there was no queue.'); From 35047ca8be088ff40fd531d8e8f64801e1fa5d02 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 16:21:17 +0200 Subject: [PATCH 08/14] fix: log interaction identifier (name) instead of type --- src/events/interactions/interactionCreate.ts | 28 +++++++++++++++----- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index d5aeedc..3d7b048 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -35,7 +35,16 @@ module.exports = { logger.debug('Interaction received.'); - let interactionString: string = ''; + let interactionIdentifier = 'Unknown'; + + if ( + interaction.type === InteractionType.ApplicationCommand || + interaction.type === InteractionType.ApplicationCommandAutocomplete + ) { + interactionIdentifier = (interaction as ChatInputCommandInteraction).commandName; + } else if (interaction.type === InteractionType.MessageComponent) { + interactionIdentifier = (interaction as MessageComponentInteraction).customId; + } // Todo: Extract to own file const handleComponent = async (interaction: MessageComponentInteraction) => { @@ -96,7 +105,7 @@ module.exports = { // TODO: extract handlError to own file (create errorHandler and export handleInteractionError?) const handleError = async (interaction: Interaction, error: CustomError) => { - logger.error(error, `Error handling interaction of type '${interactionString}'`); + logger.error(error, `Error handling interaction '${interactionIdentifier}'`); if (interaction instanceof ChatInputCommandInteraction && interaction.deferred) { switch (interaction.replied) { @@ -153,22 +162,22 @@ module.exports = { logger.debug('Started handling interaction.'); switch (interaction.type as InteractionType) { case InteractionType.ApplicationCommand: - interactionString = 'ApplicationCommand'; await handleCommand(interaction as ChatInputCommandInteraction); break; case InteractionType.ApplicationCommandAutocomplete: - interactionString = 'ApplicationCommandAutocomplete'; await handleAutocomplete(interaction as AutocompleteInteraction); break; case InteractionType.MessageComponent: - interactionString = 'MessageComponent'; await handleComponent(interaction as MessageComponentInteraction); break; default: - interactionString = 'Unknown'; + logger.error( + interaction, + `Interaction of type '${interaction.type}' was not handled, interaction attached as object.` + ); break; } } catch (error) { @@ -179,7 +188,12 @@ module.exports = { const outputTime: number = new Date().getTime(); const executionTime: number = outputTime - inputTime; - logger.info(`Interaction of type '${interactionString}' handled in ${executionTime} ms.`); + logger.info(`Interaction '${interactionIdentifier}' handled in ${executionTime} ms.`); + + if (executionTime > 10000) { + logger.warn(`Interaction '${interactionIdentifier}' took ${executionTime} ms to execute.`); + } + return; } }; From cd3947c22bcbe08512a1cd1999a26bc297b5379f Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 16:21:34 +0200 Subject: [PATCH 09/14] fix: set module correctly for autocomplete interactions --- src/interactions/autocomplete/lyrics.ts | 2 +- src/interactions/autocomplete/play.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/interactions/autocomplete/lyrics.ts b/src/interactions/autocomplete/lyrics.ts index 6ce99e9..3f7cab1 100644 --- a/src/interactions/autocomplete/lyrics.ts +++ b/src/interactions/autocomplete/lyrics.ts @@ -5,7 +5,7 @@ import { lyricsExtractor } from '@discord-player/extractor'; const loggerTemplate = loggerModule.child({ source: 'lyrics.js', - module: 'slashCommand', + module: 'autocompleteInteraction', name: '/lyrics' }); diff --git a/src/interactions/autocomplete/play.ts b/src/interactions/autocomplete/play.ts index 4f501d8..6e0b014 100644 --- a/src/interactions/autocomplete/play.ts +++ b/src/interactions/autocomplete/play.ts @@ -4,7 +4,7 @@ import { CustomAutocompleteInteraction } from '../../types/interactionTypes'; const loggerTemplate = loggerModule.child({ source: 'play.js', - module: 'slashCommand', + module: 'autocompleteInteraction', name: '/play' }); From 1e1170099e823335a428d29284cbdaee77bf2053 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 16:21:44 +0200 Subject: [PATCH 10/14] fix: listen for more shard events --- src/index.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/index.ts b/src/index.ts index 8cba544..a28141f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -37,6 +37,22 @@ manager.on('shardCreate', (shard: Shard) => { logger.info('All shards ready, bot is now online.'); } }); + + shard.on(ShardEvents.Death, (event) => { + logger.fatal(event, 'SHARD CLOSED UNEXPECTEDLY.'); + }); + + shard.on(ShardEvents.Error, (error) => { + logger.error(error, 'Shard experienced an error, most likely related to websocket connection error.'); + }); + + shard.on(ShardEvents.Disconnect, () => { + logger.warn('Shard disconnected.'); + }); + + shard.on(ShardEvents.Reconnecting, () => { + logger.warn('Shard reconnecting.'); + }); }); manager.spawn(); From a248452f2ce725f602807a34eda81243975a66f6 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 16:25:22 +0200 Subject: [PATCH 11/14] fix: add executionTime property to logging for interactions --- src/events/interactions/interactionCreate.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index 3d7b048..f4755bc 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -188,7 +188,12 @@ module.exports = { const outputTime: number = new Date().getTime(); const executionTime: number = outputTime - inputTime; - logger.info(`Interaction '${interactionIdentifier}' handled in ${executionTime} ms.`); + logger.info( + { + executionTime: executionTime + }, + `Interaction '${interactionIdentifier}' successfully handled in ${executionTime} ms.` + ); if (executionTime > 10000) { logger.warn(`Interaction '${interactionIdentifier}' took ${executionTime} ms to execute.`); From 8e9cb308e97f98174e414e258ad384a1659a88de Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 16:31:49 +0200 Subject: [PATCH 12/14] fix: some logging changes to permission validator --- src/utils/validation/permissionValidator.ts | 30 ++++++++++++--------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/src/utils/validation/permissionValidator.ts b/src/utils/validation/permissionValidator.ts index ff60aa1..1e28d35 100644 --- a/src/utils/validation/permissionValidator.ts +++ b/src/utils/validation/permissionValidator.ts @@ -3,9 +3,7 @@ import { EmbedBuilder, GuildMember, TextChannel, VoiceChannel } from 'discord.js import loggerModule from '../../services/logger'; import { EmbedOptions } from '../../types/configTypes'; -import { - CannotJoinVoiceOrTalkParams, CannotSendMessageInChannelParams -} from '../../types/utilTypes'; +import { CannotJoinVoiceOrTalkParams, CannotSendMessageInChannelParams } from '../../types/utilTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: CannotJoinVoiceOrTalkParams) => { @@ -61,17 +59,24 @@ export const cannotSendMessageInChannel = async ({ interaction, executionId }: C try { // we can still send ephemeral replies in channels we can't view, so sending message to user instead if (!interaction.deferred && !interaction.replied) { + logger.debug('Interaction was not deferred or replied to yet. Deferring reply as ephemeral.'); await interaction.deferReply({ ephemeral: true }); + + logger.debug( + 'Sending ephemeral message in channel about insufficient permissions to send message in channel.' + ); + return await interaction.editReply({ + 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.` + ) + .setColor(embedOptions.colors.warning) + ] + }); + } else { + return Promise.resolve(); } - await interaction.editReply({ - 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.` - ) - .setColor(embedOptions.colors.warning) - ] - }); } catch (error) { if (error instanceof Error) { if (error.message == 'The reply to this interaction has already been sent or deferred.') { @@ -86,6 +91,7 @@ export const cannotSendMessageInChannel = async ({ interaction, executionId }: C ); } } else { + logger.debug('Throwing error'); throw error; } } From 780e20d4195a1dbd011931ee49d762a6301e797d Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 17:21:52 +0200 Subject: [PATCH 13/14] feat!: Extracted handling of interactions into separate files --- package.json | 4 +- src/events/interactions/interactionCreate.ts | 144 +++--------------- .../interactionAutocompleteHandler.ts | 16 ++ src/handlers/interactionCommandHandler.ts | 32 ++++ src/handlers/interactionComponentHandler.ts | 24 +++ src/handlers/interactionErrorHandler.ts | 69 +++++++++ src/interactions/commands/player/play.ts | 30 +--- 7 files changed, 166 insertions(+), 153 deletions(-) create mode 100644 src/handlers/interactionAutocompleteHandler.ts create mode 100644 src/handlers/interactionCommandHandler.ts create mode 100644 src/handlers/interactionComponentHandler.ts create mode 100644 src/handlers/interactionErrorHandler.ts diff --git a/package.json b/package.json index 98773e5..d34fa4e 100644 --- a/package.json +++ b/package.json @@ -20,10 +20,10 @@ "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node ./dist/index.js", - "start-pretty": "node ./dist/index.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId", + "start-pretty": "node ./dist/index.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,executionTime,shardId,guildId,interactionType", "start-pretty-no-ignore": "node ./dist/index.js | pino-pretty", "deploy": "node ./dist/utils/deploySlashCommands.js", - "deploy-pretty": "node ./dist/utils/deploySlashCommands.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId", + "deploy-pretty": "node ./dist/utils/deploySlashCommands.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,executionTime,shardId,guildId,interactionType", "eslint": "eslint ./src", "build": "tsc" }, diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index f4755bc..f141997 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -1,8 +1,6 @@ -import config from 'config'; import { AutocompleteInteraction, ChatInputCommandInteraction, - EmbedBuilder, Events, Interaction, InteractionType, @@ -10,14 +8,14 @@ import { } from 'discord.js'; import { v4 as uuidv4 } from 'uuid'; +import { handleAutocomplete } from '../../handlers/interactionAutocompleteHandler'; +import { handleCommand } from '../../handlers/interactionCommandHandler'; +import { handleComponent } from '../../handlers/interactionComponentHandler'; +import { handleError } from '../../handlers/interactionErrorHandler'; import loggerModule from '../../services/logger'; -import { Command, ExtendedClient } from '../../types/clientTypes'; -import { BotOptions, EmbedOptions } from '../../types/configTypes'; -import { cannotSendMessageInChannel } from '../../utils/validation/permissionValidator'; +import { ExtendedClient } from '../../types/clientTypes'; import { CustomError } from '../../types/interactionTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -const botOptions: BotOptions = config.get('botOptions'); module.exports = { name: Events.InteractionCreate, isDebug: false, @@ -46,131 +44,19 @@ module.exports = { interactionIdentifier = (interaction as MessageComponentInteraction).customId; } - // Todo: Extract to own file - const handleComponent = async (interaction: MessageComponentInteraction) => { - await interaction.deferReply(); - logger.debug('Interaction deferred.'); - - const componentId = interaction.customId.split('_')[0]; - const referenceId = interaction.customId.split('_')[1]; - - logger.debug(`Parsed componentId: ${componentId}`); - - const componentModule = await import(`../../interactions/components/${componentId}.js`); - const { default: component } = componentModule; - - logger.debug('Executing component interaction.'); - await component.execute({ interaction, referenceId, executionId }); - }; - - const handleAutocomplete = async (interaction: AutocompleteInteraction) => { - const autocompleteModule = await import(`../../interactions/autocomplete/${interaction.commandName}.js`); - const { default: autocomplete } = autocompleteModule; - - logger.debug('Executing autocomplete interaction.'); - await autocomplete.execute({ interaction, executionId }); - }; - - const handleCommand = async (interaction: ChatInputCommandInteraction) => { - await interaction.deferReply(); - logger.debug('Interaction deferred.'); - - const command = client.commands?.get(interaction.commandName) as Command; - if (!command) { - logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); - return; - } - - logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`); - - if (await cannotSendMessageInChannel({ interaction, executionId })) { - return; - } - - logger.debug('Executing command interaction.'); - await command.execute({ interaction, client, executionId }); - }; - - // TODO: Extract the text to a config file? - const errorReply = { - 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})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }; - - // TODO: extract handlError to own file (create errorHandler and export handleInteractionError?) - const handleError = async (interaction: Interaction, error: CustomError) => { - logger.error(error, `Error handling interaction '${interactionIdentifier}'`); - - if (interaction instanceof ChatInputCommandInteraction && interaction.deferred) { - switch (interaction.replied) { - case true: - // This means interaction has received a reply already. - // Most likely command executed successfully or error is already handled. - logger.warn( - error, - `Interaction '${interaction.id}' threw an error but has already been replied to.` - ); - return; - case false: - // If the interaction has not been replied to, most likely command execution failed. - logger.debug('Responding with error embed'); - return await interaction.editReply(errorReply); - } - } else if (interaction instanceof MessageComponentInteraction && interaction.deferred) { - switch (interaction.replied) { - case true: - // This means interaction has received a reply already. - // Most likely command executed successfully or error is already handled. - logger.warn( - error, - `Interaction '${interaction.id}' threw an error but has already been replied to.` - ); - return; - case false: - // If the interaction has not been replied to, most likely command execution failed. - logger.debug('Responding with error embed'); - return await interaction.editReply(errorReply); - } - } else { - logger.warn( - 'Interaction threw an error but was not deferred or replied to, or was an autocomplete interaction. Cannot send error reply.' - ); - - if ( - error.code === 'InteractionCollectorError' || - error.message === 'Collector received no interactions before ending with reason: time' - ) { - logger.debug('Interaction response timed out.'); - return; - } - - // If this code is reached there is an error that is not handled at all. - // This should not happen, but if it does, we log it with 'fatal' level to investigate. - // This is to prevent the bot from crashing or doing something very unexpected. - logger.fatal(error, 'Unhandled error while awaiting or handling component interaction.'); - return; - } - }; - try { logger.debug('Started handling interaction.'); - switch (interaction.type as InteractionType) { + switch (interaction.type) { case InteractionType.ApplicationCommand: - await handleCommand(interaction as ChatInputCommandInteraction); + await handleCommand(interaction as ChatInputCommandInteraction, client, executionId); break; case InteractionType.ApplicationCommandAutocomplete: - await handleAutocomplete(interaction as AutocompleteInteraction); + await handleAutocomplete(interaction as AutocompleteInteraction, executionId); break; case InteractionType.MessageComponent: - await handleComponent(interaction as MessageComponentInteraction); + await handleComponent(interaction as MessageComponentInteraction, executionId); break; default: @@ -182,21 +68,25 @@ module.exports = { } } catch (error) { logger.debug('Error while handling received interaction.'); - await handleError(interaction, error as CustomError); + await handleError(interaction, error as CustomError, interactionIdentifier, executionId); } const outputTime: number = new Date().getTime(); const executionTime: number = outputTime - inputTime; + const interactionType = InteractionType[interaction.type]; logger.info( { - executionTime: executionTime + executionTime: executionTime, + interactionType: interactionType }, - `Interaction '${interactionIdentifier}' successfully handled in ${executionTime} ms.` + `${interactionType} interaction '${interactionIdentifier}' successfully handled in ${executionTime} ms.` ); if (executionTime > 10000) { - logger.warn(`Interaction '${interactionIdentifier}' took ${executionTime} ms to execute.`); + logger.warn( + `${interactionType} interaction '${interactionIdentifier}' took ${executionTime} ms to execute.` + ); } return; diff --git a/src/handlers/interactionAutocompleteHandler.ts b/src/handlers/interactionAutocompleteHandler.ts new file mode 100644 index 0000000..1d70551 --- /dev/null +++ b/src/handlers/interactionAutocompleteHandler.ts @@ -0,0 +1,16 @@ +import { AutocompleteInteraction } from 'discord.js'; +import loggerModule from '../services/logger'; + +const logger = loggerModule.child({ + source: 'interactionCutocompleteHandler.ts', + module: 'handler', + name: 'interactionAutocompleteHandler' +}); + +export const handleAutocomplete = async (interaction: AutocompleteInteraction, executionId: string) => { + const autocompleteModule = await import(`../interactions/autocomplete/${interaction.commandName}.js`); + const { default: autocomplete } = autocompleteModule; + + logger.debug('Executing autocomplete interaction.'); + await autocomplete.execute({ interaction, executionId }); +}; diff --git a/src/handlers/interactionCommandHandler.ts b/src/handlers/interactionCommandHandler.ts new file mode 100644 index 0000000..e345f7a --- /dev/null +++ b/src/handlers/interactionCommandHandler.ts @@ -0,0 +1,32 @@ +import { ChatInputCommandInteraction } from 'discord.js'; +import { Command, ExtendedClient } from '../types/clientTypes'; +import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator'; +import loggerModule from '../services/logger'; + +const logger = loggerModule.child({ + source: 'interactionCommandHandler.ts', + module: 'handler', + name: 'interactionCommandHandler' +}); + +export const handleCommand = async ( + interaction: ChatInputCommandInteraction, + client: ExtendedClient, + executionId: string +) => { + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + + const command = client.commands?.get(interaction.commandName) as Command; + if (!command) { + logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); + return; + } + + if (await cannotSendMessageInChannel({ interaction, executionId })) { + return Promise.resolve(); + } + + logger.debug('Executing command interaction.'); + await command.execute({ interaction, client, executionId }); +}; diff --git a/src/handlers/interactionComponentHandler.ts b/src/handlers/interactionComponentHandler.ts new file mode 100644 index 0000000..8a11711 --- /dev/null +++ b/src/handlers/interactionComponentHandler.ts @@ -0,0 +1,24 @@ +import { MessageComponentInteraction } from 'discord.js'; +import loggerModule from '../services/logger'; + +const logger = loggerModule.child({ + source: 'interactionComponentHandler.js', + module: 'handler', + name: 'interactionComponentHandler' +}); + +export const handleComponent = async (interaction: MessageComponentInteraction, executionId: string) => { + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + + const componentId = interaction.customId.split('_')[0]; + const referenceId = interaction.customId.split('_')[1]; + + logger.debug(`Parsed componentId: ${componentId}`); + + const componentModule = await import(`../interactions/components/${componentId}.js`); + const { default: component } = componentModule; + + logger.debug('Executing component interaction.'); + await component.execute({ interaction, referenceId, executionId }); +}; diff --git a/src/handlers/interactionErrorHandler.ts b/src/handlers/interactionErrorHandler.ts new file mode 100644 index 0000000..b7dd344 --- /dev/null +++ b/src/handlers/interactionErrorHandler.ts @@ -0,0 +1,69 @@ +import config from 'config'; +import { ChatInputCommandInteraction, EmbedBuilder, Interaction, MessageComponentInteraction } from 'discord.js'; +import { BotOptions, EmbedOptions } from '../types/configTypes'; +import loggerModule from '../services/logger'; +import { CustomError } from '../types/interactionTypes'; + +const embedOptions: EmbedOptions = config.get('embedOptions'); +const botOptions: BotOptions = config.get('botOptions'); + +const logger = loggerModule.child({ + source: 'interactionErrorHandler.ts', + module: 'handler', + name: 'interactionErrorHandler' +}); + +export const handleError = async ( + interaction: Interaction, + error: CustomError, + interactionIdentifier: string, + executionId: string +) => { + const errorReply = { + 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})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }; + + logger.error(error, `Error handling interaction '${interactionIdentifier}'`); + + if (interaction instanceof ChatInputCommandInteraction && interaction.deferred) { + switch (interaction.replied) { + case true: + logger.warn(error, `Interaction '${interaction.id}' threw an error but has already been replied to.`); + return; + case false: + logger.debug('Responding with error embed'); + return await interaction.editReply(errorReply); + } + } else if (interaction instanceof MessageComponentInteraction && interaction.deferred) { + switch (interaction.replied) { + case true: + logger.warn(error, `Interaction '${interaction.id}' threw an error but has already been replied to.`); + return; + case false: + logger.debug('Responding with error embed'); + return await interaction.editReply(errorReply); + } + } else { + logger.warn( + 'Interaction threw an error but was not deferred or replied to, or was an autocomplete interaction. Cannot send error reply.' + ); + + if ( + error.code === 'InteractionCollectorError' || + error.message === 'Collector received no interactions before ending with reason: time' + ) { + logger.debug('Interaction response timed out.'); + return; + } + + logger.fatal(error, 'Unhandled error while awaiting or handling component interaction.'); + return; + } +}; diff --git a/src/interactions/commands/player/play.ts b/src/interactions/commands/player/play.ts index 87a7458..bfcdb48 100644 --- a/src/interactions/commands/player/play.ts +++ b/src/interactions/commands/player/play.ts @@ -3,7 +3,7 @@ import { useMainPlayer, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; -import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; +import { CustomError, CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { BotOptions, EmbedOptions, PlayerOptions } from '../../../types/configTypes'; import { cannotJoinVoiceOrTalk } from '../../../utils/validation/permissionValidator'; import { transformQuery } from '../../../utils/validation/searchQueryValidator'; @@ -132,7 +132,7 @@ const command: CustomSlashCommandInteraction = { } })); } catch (error) { - if (error instanceof Error) { + if (error instanceof CustomError) { if (error.message.includes('Sign in to confirm your age')) { logger.debug('Found track but failed to retrieve audio due to age confirmation warning.'); @@ -166,12 +166,14 @@ const command: CustomSlashCommandInteraction = { } if ( - error.message.includes("Cannot read properties of null (reading 'createStream')") || + error.message === "Cannot read properties of null (reading 'createStream')" || error.message.includes('Failed to fetch resources for ytdl streaming') || error.message.includes('Could not extract stream for this track') ) { logger.debug(error, `Found track but failed to retrieve audio. Query: ${query}.`); + // note: reading 'createStream' error can happen if queue is destroyed before track starts playing, e.g. /leave quickly after /play + logger.debug('Responding with error embed.'); return await interaction.editReply({ embeds: [ @@ -201,26 +203,6 @@ const command: CustomSlashCommandInteraction = { }); } - if (error.message === "Cannot read properties of null (reading 'createStream')") { - // Can happen if /play then /leave before track starts playing - logger.warn( - error, - 'Found track but failed to play back audio. Voice connection might be unavailable.' - ); - - logger.debug('Responding with error embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nSomething unexpected happened and it was not possible to start playing the track. This could happen if the voice connection is lost or queue is destroyed while adding 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})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); - } - logger.error(error, 'Failed to play track with player.play(), unhandled error.'); } else { throw error; @@ -299,7 +281,7 @@ const command: CustomSlashCommandInteraction = { }); } - if (queue.currentTrack === track && queue.tracks.data.length === 0) { + if (queue && queue.currentTrack === track && queue.tracks.data.length === 0) { logger.debug(`Track found and added with player.play(), started playing. Query: '${query}'.`); let authorName: string; From 92a535d83719113b7b4aeb8f7294ea9908405e89 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 28 Aug 2023 18:23:12 +0200 Subject: [PATCH 14/14] fix!: fixed logging service not logging to file, removed app-info log file. --- src/events/interactions/interactionCreate.ts | 2 +- src/services/logger.ts | 19 ++++++------------- src/types/configTypes.ts | 10 +++++----- src/types/serviceTypes.ts | 4 +++- 4 files changed, 15 insertions(+), 20 deletions(-) diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index f141997..2baf1f8 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -34,7 +34,6 @@ module.exports = { logger.debug('Interaction received.'); let interactionIdentifier = 'Unknown'; - if ( interaction.type === InteractionType.ApplicationCommand || interaction.type === InteractionType.ApplicationCommandAutocomplete @@ -73,6 +72,7 @@ module.exports = { const outputTime: number = new Date().getTime(); const executionTime: number = outputTime - inputTime; + const interactionType = InteractionType[interaction.type]; logger.info( diff --git a/src/services/logger.ts b/src/services/logger.ts index ee33d1e..c02ddd6 100644 --- a/src/services/logger.ts +++ b/src/services/logger.ts @@ -9,28 +9,19 @@ const loggerOptions: LoggerOptions = config.get('loggerOptions'); const targets: TargetOptions[] = [ { + // This target is used for logging everything above specified minimumLogLevel target: 'pino/file', level: loggerOptions.minimumLogLevel, options: { destination: './logs/app-all.log', mkdir: true, - sync: false, - minLength: 4096 + sync: false } }, { + // This target is used for logging errors separately target: 'pino/file', - level: pino.levels.values.info.toString(), - options: { - destination: './logs/app-info.log', - mkdir: true, - sync: false, - minLength: 4096 - } - }, - { - target: 'pino/file', - level: pino.levels.values.error.toString(), + level: 'error', options: { destination: './logs/app-error.log', mkdir: true, @@ -38,6 +29,7 @@ const targets: TargetOptions[] = [ } }, { + // This target is used for logging to the console target: 'pino/file', level: loggerOptions.minimumLogLevelConsole, options: { @@ -57,6 +49,7 @@ if (process.env.LOKI_AUTH_PASSWORD && process.env.LOKI_AUTH_USERNAME) { batching: false, interval: 5, + // Loki host and credentials are retrieved from environment variables host: process.env.LOKI_HOST || 'http://localhost:3100', basicAuth: { username: process.env.LOKI_AUTH_USERNAME || '', diff --git a/src/types/configTypes.ts b/src/types/configTypes.ts index d5e4f7e..491b10b 100644 --- a/src/types/configTypes.ts +++ b/src/types/configTypes.ts @@ -1,6 +1,6 @@ -import { - ActivityType, ColorResolvable, PresenceUpdateStatus, ShardingManagerOptions -} from 'discord.js'; +import { ActivityType, ColorResolvable, PresenceUpdateStatus, ShardingManagerOptions } from 'discord.js'; + +import { LogLevel } from './serviceTypes'; export interface BotOptions { name: string; @@ -11,8 +11,8 @@ export interface BotOptions { export interface ShardingOptions extends ShardingManagerOptions {} export interface LoggerOptions { - minimumLogLevel: string; - minimumLogLevelConsole: string; + minimumLogLevel: LogLevel; + minimumLogLevelConsole: LogLevel; discordPlayerDebug: boolean; } diff --git a/src/types/serviceTypes.ts b/src/types/serviceTypes.ts index 1b449fe..0546662 100644 --- a/src/types/serviceTypes.ts +++ b/src/types/serviceTypes.ts @@ -1,6 +1,8 @@ +export type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent'; + export type TargetOptions = { target: string; - level: string; + level: LogLevel; options: { destination?: string; mkdir?: boolean;