From 67e45729a3739c461d3844f506c7504d2d88e822 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 29 Aug 2023 15:04:37 +0200 Subject: [PATCH 1/5] fix: remove Promise.resolve() return and fix queue type --- src/handlers/interactionCommandHandler.ts | 2 +- src/interactions/commands/info/status.ts | 27 +++++++------------ src/interactions/commands/player/filters.ts | 12 ++++----- src/interactions/commands/player/leave.ts | 8 +++--- src/interactions/commands/player/loop.ts | 11 ++++---- src/interactions/commands/player/lyrics.ts | 14 +++++----- .../commands/player/nowplaying.ts | 12 ++++----- src/interactions/commands/player/pause.ts | 12 ++++----- src/interactions/commands/player/play.ts | 15 ++++++----- src/interactions/commands/player/queue.ts | 8 +++--- src/interactions/commands/player/seek.ts | 12 ++++----- src/interactions/commands/player/shuffle.ts | 12 ++++----- src/interactions/commands/player/skip.ts | 12 ++++----- src/interactions/commands/player/stop.ts | 8 +++--- src/interactions/commands/player/volume.ts | 10 +++---- src/interactions/commands/system/guilds.ts | 2 +- src/interactions/commands/system/reload.ts | 2 +- src/interactions/commands/system/shards.ts | 2 +- .../commands/system/systemstatus.ts | 24 +++++++---------- .../components/nowplaying-skip-button.ts | 4 +-- src/utils/other/postBotStats.ts | 4 +-- src/utils/other/startLoadTest.ts | 2 +- src/utils/validation/permissionValidator.ts | 4 +-- 23 files changed, 102 insertions(+), 117 deletions(-) diff --git a/src/handlers/interactionCommandHandler.ts b/src/handlers/interactionCommandHandler.ts index e345f7a..4bef498 100644 --- a/src/handlers/interactionCommandHandler.ts +++ b/src/handlers/interactionCommandHandler.ts @@ -24,7 +24,7 @@ export const handleCommand = async ( } if (await cannotSendMessageInChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } logger.debug('Executing command interaction.'); diff --git a/src/interactions/commands/info/status.ts b/src/interactions/commands/info/status.ts index e4422bd..5b439b7 100644 --- a/src/interactions/commands/info/status.ts +++ b/src/interactions/commands/info/status.ts @@ -39,37 +39,28 @@ const command: CustomSlashCommandInteraction = { let totalTracks: number = 0; let totalListeners: number = 0; - await client!.shard! - .broadcastEval(() => { + await client! + .shard!.broadcastEval(() => { /* eslint-disable no-undef */ return player.generateStatistics(); }) .then((results) => { - const queueCountList: number[] = []; - const trackCountList: number[] = []; - const listenerCountList: number[] = []; results.map((result) => { - queueCountList.push(result.queues.length); - if (result.queues.length > 0) { - result.queues.map((queue) => { - trackCountList.push(queue.status.playing ? queue.tracksCount + 1 : queue.tracksCount); - listenerCountList.push(queue.listeners); - }); - } + activeVoiceConnections += result.queues.length; + result.queues.map((queue) => { + totalTracks += queue.status.playing ? queue.tracksCount + 1 : queue.tracksCount; + totalListeners += queue.listeners; + }); }); - activeVoiceConnections = queueCountList.reduce((acc, queueAmount) => acc + queueAmount, 0); - totalTracks = trackCountList.reduce((acc, trackAmount) => acc + trackAmount, 0); - totalListeners = listenerCountList.reduce((acc, listenerAmount) => acc + listenerAmount, 0); - logger.debug('Successfully fetched player statistics from shards.'); }) .catch((error) => { logger.error(error, 'Failed to fetch player statistics from shards.'); }); - await client!.shard! - .fetchClientValues('guilds.cache') + await client! + .shard!.fetchClientValues('guilds.cache') .then((results) => { const guildCaches = results as Guild[][]; guildCaches.map((guildCache: Guild[]) => { diff --git a/src/interactions/commands/player/filters.ts b/src/interactions/commands/player/filters.ts index a1dad46..50050d0 100644 --- a/src/interactions/commands/player/filters.ts +++ b/src/interactions/commands/player/filters.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, QueueFilters, useQueue } from 'discord-player'; +import { GuildQueue, QueueFilters, useQueue } from 'discord-player'; import { APIActionRowComponent, APIMessageActionRowComponent, @@ -40,21 +40,21 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } const filterOptions: StringSelectMenuOptionBuilder[] = []; diff --git a/src/interactions/commands/player/leave.ts b/src/interactions/commands/player/leave.ts index 071c18b..0ea3a53 100644 --- a/src/interactions/commands/player/leave.ts +++ b/src/interactions/commands/player/leave.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, useQueue } from 'discord-player'; +import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; @@ -28,10 +28,10 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; if (!queue) { logger.debug('There is already no queue.'); @@ -49,7 +49,7 @@ const command: CustomSlashCommandInteraction = { } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (!queue.deleted) { diff --git a/src/interactions/commands/player/loop.ts b/src/interactions/commands/player/loop.ts index f2a16bd..d4c3aee 100644 --- a/src/interactions/commands/player/loop.ts +++ b/src/interactions/commands/player/loop.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, useQueue } from 'discord-player'; +import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder, SlashCommandStringOption } from 'discord.js'; import loggerModule from '../../../services/logger'; @@ -42,17 +42,17 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } const loopModesFormatted = new Map([ @@ -132,6 +132,7 @@ const command: CustomSlashCommandInteraction = { if (queue.repeatMode === 0) { logger.debug('Disabled loop mode.'); + // TODO: Different text when disabling autoplay. logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ diff --git a/src/interactions/commands/player/lyrics.ts b/src/interactions/commands/player/lyrics.ts index 261288e..bd3dec8 100644 --- a/src/interactions/commands/player/lyrics.ts +++ b/src/interactions/commands/player/lyrics.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, QueryType, useMainPlayer, useQueue } from 'discord-player'; +import { GuildQueue, QueryType, useMainPlayer, useQueue } from 'discord-player'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { lyricsExtractor } from '@discord-player/extractor'; @@ -43,24 +43,24 @@ const command: CustomSlashCommandInteraction = { }); const query = interaction.options.getString('query'); - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; let geniusSearchQuery = ''; if (!query) { if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } if (await queueDoesNotExist({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } geniusSearchQuery = queue.currentTrack!.title.slice(0, 50); @@ -188,7 +188,7 @@ const command: CustomSlashCommandInteraction = { } } - return Promise.resolve(); + return; } logger.debug('Responding with info embed.'); diff --git a/src/interactions/commands/player/nowplaying.ts b/src/interactions/commands/player/nowplaying.ts index 41cc816..eba6e86 100644 --- a/src/interactions/commands/player/nowplaying.ts +++ b/src/interactions/commands/player/nowplaying.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, Track, useQueue } from 'discord-player'; +import { GuildQueue, Track, useQueue } from 'discord-player'; import { APIActionRowComponent, APIMessageActionRowComponent, @@ -38,21 +38,21 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } const sourceStringsFormatted = new Map([ diff --git a/src/interactions/commands/player/pause.ts b/src/interactions/commands/player/pause.ts index 312d499..9d564bd 100644 --- a/src/interactions/commands/player/pause.ts +++ b/src/interactions/commands/player/pause.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, useQueue } from 'discord-player'; +import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; @@ -29,21 +29,21 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } const currentTrack = queue.currentTrack!; diff --git a/src/interactions/commands/player/play.ts b/src/interactions/commands/player/play.ts index bfcdb48..7b92682 100644 --- a/src/interactions/commands/player/play.ts +++ b/src/interactions/commands/player/play.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { useMainPlayer, useQueue } from 'discord-player'; +import { GuildQueue, useMainPlayer, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; @@ -43,17 +43,18 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); + if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } if (await cannotJoinVoiceOrTalk({ interaction, executionId })) { - return Promise.resolve(); + return; } - let queue = useQueue(interaction.guild!.id); + let queue: GuildQueue = useQueue(interaction.guild!.id)!; if (queue && (await notInSameVoiceChannel({ interaction, queue, executionId }))) { - return Promise.resolve(); + return; } const player = useMainPlayer()!; @@ -86,7 +87,7 @@ const command: CustomSlashCommandInteraction = { }); } - queue = useQueue(interaction.guild!.id); + queue = useQueue(interaction.guild!.id)!; const queueSize = queue?.size ?? 0; if ((searchResult.playlist! && searchResult.tracks.length) > playerOptions.maxQueueSize - queueSize) { @@ -211,7 +212,7 @@ const command: CustomSlashCommandInteraction = { logger.debug(`Successfully added track with player.play(). Query: '${query}'.`); - queue = useQueue(interaction.guild!.id); + queue = useQueue(interaction.guild!.id)!; if (!queue || !track) { logger.warn(`After player.play(), queue is undefined. Query: '${query}'.`); diff --git a/src/interactions/commands/player/queue.ts b/src/interactions/commands/player/queue.ts index 0ebc12c..2dab6a7 100644 --- a/src/interactions/commands/player/queue.ts +++ b/src/interactions/commands/player/queue.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, useQueue } from 'discord-player'; +import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; @@ -30,13 +30,13 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } const pageIndex = (interaction.options.getNumber('page') || 1) - 1; diff --git a/src/interactions/commands/player/seek.ts b/src/interactions/commands/player/seek.ts index 4ff8589..8815c91 100644 --- a/src/interactions/commands/player/seek.ts +++ b/src/interactions/commands/player/seek.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, useQueue } from 'discord-player'; +import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; @@ -35,21 +35,21 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } const durationInput = interaction.options.getString('duration'); diff --git a/src/interactions/commands/player/shuffle.ts b/src/interactions/commands/player/shuffle.ts index a64c05f..fd42828 100644 --- a/src/interactions/commands/player/shuffle.ts +++ b/src/interactions/commands/player/shuffle.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, useQueue } from 'discord-player'; +import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; @@ -29,21 +29,21 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await queueIsEmpty({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } queue.tracks.shuffle(); diff --git a/src/interactions/commands/player/skip.ts b/src/interactions/commands/player/skip.ts index 7b67823..64e1268 100644 --- a/src/interactions/commands/player/skip.ts +++ b/src/interactions/commands/player/skip.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, useQueue } from 'discord-player'; +import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; @@ -32,21 +32,21 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } const skipToTrack = interaction.options.getNumber('tracknumber'); diff --git a/src/interactions/commands/player/stop.ts b/src/interactions/commands/player/stop.ts index 3737f14..36e4d0e 100644 --- a/src/interactions/commands/player/stop.ts +++ b/src/interactions/commands/player/stop.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, useQueue } from 'discord-player'; +import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; @@ -28,10 +28,10 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; if (!queue) { logger.debug('There is no queue.'); @@ -49,7 +49,7 @@ const command: CustomSlashCommandInteraction = { } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (!queue.deleted) { diff --git a/src/interactions/commands/player/volume.ts b/src/interactions/commands/player/volume.ts index 8e97159..d5f59e6 100644 --- a/src/interactions/commands/player/volume.ts +++ b/src/interactions/commands/player/volume.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, useQueue } from 'discord-player'; +import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; @@ -36,17 +36,17 @@ const command: CustomSlashCommandInteraction = { }); if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); + return; } - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return Promise.resolve(); + return; } const volume = interaction.options.getNumber('percentage'); diff --git a/src/interactions/commands/system/guilds.ts b/src/interactions/commands/system/guilds.ts index 696b89b..5de87b0 100644 --- a/src/interactions/commands/system/guilds.ts +++ b/src/interactions/commands/system/guilds.ts @@ -28,7 +28,7 @@ const command: CustomSlashCommandInteraction = { }); if (await notValidGuildId({ interaction, executionId })) { - return Promise.resolve(); + return; } let shardGuilds: Guild[] = []; diff --git a/src/interactions/commands/system/reload.ts b/src/interactions/commands/system/reload.ts index 52b67d7..c5d6340 100644 --- a/src/interactions/commands/system/reload.ts +++ b/src/interactions/commands/system/reload.ts @@ -29,7 +29,7 @@ const command: CustomSlashCommandInteraction = { }); if (await notValidGuildId({ interaction, executionId })) { - return Promise.resolve(); + return; } try { diff --git a/src/interactions/commands/system/shards.ts b/src/interactions/commands/system/shards.ts index 9985d04..36ae2ad 100644 --- a/src/interactions/commands/system/shards.ts +++ b/src/interactions/commands/system/shards.ts @@ -46,7 +46,7 @@ const command: CustomSlashCommandInteraction = { }); if (await notValidGuildId({ interaction, executionId })) { - return Promise.resolve(); + return; } let shardInfoList: ShardInfo[] = []; diff --git a/src/interactions/commands/system/systemstatus.ts b/src/interactions/commands/system/systemstatus.ts index 2996ab4..e686403 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 Promise.resolve(); + return; } // from normal /status command @@ -67,24 +67,18 @@ const command: CustomSlashCommandInteraction = { return player.generateStatistics(); }) .then((results) => { - const queueCountList: number[] = []; - const trackCountList: number[] = []; - const listenerCountList: number[] = []; results.map((result) => { - queueCountList.push(result.queues.length); - if (result.queues.length > 0) { - result.queues.map((queue) => { - trackCountList.push(queue.status.playing ? queue.tracksCount + 1 : queue.tracksCount); - listenerCountList.push(queue.listeners); - }); - } + activeVoiceConnections += result.queues.length; + result.queues.map((queue) => { + totalTracks += queue.status.playing ? queue.tracksCount + 1 : queue.tracksCount; + totalListeners += queue.listeners; + }); }); - activeVoiceConnections = queueCountList.reduce((acc, queueAmount) => acc + queueAmount, 0); - totalTracks = trackCountList.reduce((acc, trackAmount) => acc + trackAmount, 0); - totalListeners = listenerCountList.reduce((acc, listenerAmount) => acc + listenerAmount, 0); - logger.debug('Successfully fetched player statistics from shards.'); + }) + .catch((error) => { + logger.error(error, 'Failed to fetch player statistics from shards.'); }); logger.debug('Fetching client values from all shards.'); diff --git a/src/interactions/components/nowplaying-skip-button.ts b/src/interactions/components/nowplaying-skip-button.ts index 3d8d895..cf87a91 100644 --- a/src/interactions/components/nowplaying-skip-button.ts +++ b/src/interactions/components/nowplaying-skip-button.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, useQueue } from 'discord-player'; +import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember } from 'discord.js'; import loggerModule from '../../services/logger'; @@ -20,7 +20,7 @@ const component: CustomComponentInteraction = { logger.debug(`Received skip confirmation for track id ${referenceId}.`); - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { logger.debug('Tried skipping track but there was no queue.'); diff --git a/src/utils/other/postBotStats.ts b/src/utils/other/postBotStats.ts index 89e083e..94b67db 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 Promise.resolve(); + return; } let guildCount = 0; @@ -129,7 +129,7 @@ export const postBotStats = async ({ client, executionId }: PostBotStatsParams) sites.map((site) => { if (!site.enabled) { // return if site is disabled - return Promise.resolve(); + return; } const options = { diff --git a/src/utils/other/startLoadTest.ts b/src/utils/other/startLoadTest.ts index 91cdb65..a29ef40 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 Promise.resolve(); + return; } const channelIds = loadTestOptions.channelIdsToJoin; diff --git a/src/utils/validation/permissionValidator.ts b/src/utils/validation/permissionValidator.ts index 1e28d35..3ffcef2 100644 --- a/src/utils/validation/permissionValidator.ts +++ b/src/utils/validation/permissionValidator.ts @@ -65,7 +65,7 @@ export const cannotSendMessageInChannel = async ({ interaction, executionId }: C logger.debug( 'Sending ephemeral message in channel about insufficient permissions to send message in channel.' ); - return await interaction.editReply({ + await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( @@ -74,8 +74,6 @@ export const cannotSendMessageInChannel = async ({ interaction, executionId }: C .setColor(embedOptions.colors.warning) ] }); - } else { - return Promise.resolve(); } } catch (error) { if (error instanceof Error) { From e44e0b23f3db26fe9cb8f62fdedc88f4f39e0102 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 29 Aug 2023 15:19:39 +0200 Subject: [PATCH 2/5] fix: fixed bug with not being able to read command data --- src/utils/deploySlashCommands.ts | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/src/utils/deploySlashCommands.ts b/src/utils/deploySlashCommands.ts index 4e4c839..e3de23a 100644 --- a/src/utils/deploySlashCommands.ts +++ b/src/utils/deploySlashCommands.ts @@ -20,22 +20,11 @@ const logger = loggerModule.child({ executionId: executionId }); +//TODO: Fix deploying not working with require() + const slashCommands: SlashCommandBuilder[] = []; const systemCommands: SlashCommandBuilder[] = []; -const commandFolders = fs.readdirSync(path.resolve('./dist/commands')); -for (const folder of commandFolders) { - const commandFiles = fs - .readdirSync(path.resolve(`./dist/commands/${folder}`)) - .filter((file) => file.endsWith('.js')); - - for (const file of commandFiles) { - /* eslint-disable @typescript-eslint/no-var-requires */ - const command = require(`../commands/${folder}/${file}`); - command.isSystemCommand - ? systemCommands.push(command.data.toJSON()) - : slashCommands.push(command.data.toJSON()); - } -} +const commandFolders = fs.readdirSync(path.resolve('./dist/interactions/commands')); if (!process.env.DISCORD_BOT_TOKEN) { throw new Error('DISCORD_BOT_TOKEN environment variable is not set.'); @@ -54,6 +43,20 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN) ); } + for (const folder of commandFolders) { + const commandFiles = fs + .readdirSync(path.resolve(`./dist/interactions/commands/${folder}`)) + .filter((file) => file.endsWith('.js')); + + for (const file of commandFiles) { + const commandModule = await import(`../interactions/commands/${folder}/${file}`); + const command = commandModule.default; + command.isSystemCommand + ? systemCommands.push(command.data.toJSON()) + : slashCommands.push(command.data.toJSON()); + } + } + try { logger.debug(`Bot user slash commands found: ${slashCommands.map((command) => `/${command.name}`).join(', ')}`); From 37546405e204cbc73429cedae80d144a88156a8c Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 29 Aug 2023 15:22:21 +0200 Subject: [PATCH 3/5] fix: exit script if env vars not provided --- src/utils/deploySlashCommands.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/utils/deploySlashCommands.ts b/src/utils/deploySlashCommands.ts index e3de23a..dcab343 100644 --- a/src/utils/deploySlashCommands.ts +++ b/src/utils/deploySlashCommands.ts @@ -41,6 +41,7 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN) logger.error( 'Missing required environment variables for deployment.\nPlease provide valid DISCORD_APPLICATION_ID and DISCORD_BOT_TOKEN in .env file.' ); + process.exit(1); } for (const folder of commandFolders) { From 5bc0239cdf818507f3ecd838f1dead1081d7ac4e Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 29 Aug 2023 15:42:29 +0200 Subject: [PATCH 4/5] fix: update validation in interactions --- src/handlers/interactionComponentHandler.ts | 5 ++ src/interactions/commands/player/filters.ts | 23 ++++---- src/interactions/commands/player/leave.ts | 30 ++++------ src/interactions/commands/player/loop.ts | 18 +++--- src/interactions/commands/player/lyrics.ts | 24 ++++---- .../commands/player/nowplaying.ts | 23 ++++---- src/interactions/commands/player/pause.ts | 23 ++++---- src/interactions/commands/player/play.ts | 20 ++++--- src/interactions/commands/player/queue.ts | 55 ++++--------------- src/interactions/commands/player/remove.ts | 22 ++++---- src/interactions/commands/player/seek.ts | 23 ++++---- src/interactions/commands/player/shuffle.ts | 23 ++++---- src/interactions/commands/player/skip.ts | 23 ++++---- src/interactions/commands/player/stop.ts | 30 ++++------ src/interactions/commands/player/volume.ts | 18 +++--- src/types/utilTypes.ts | 4 +- src/utils/validation/permissionValidator.ts | 15 ++++- 17 files changed, 162 insertions(+), 217 deletions(-) diff --git a/src/handlers/interactionComponentHandler.ts b/src/handlers/interactionComponentHandler.ts index 8a11711..bf4109a 100644 --- a/src/handlers/interactionComponentHandler.ts +++ b/src/handlers/interactionComponentHandler.ts @@ -1,5 +1,6 @@ import { MessageComponentInteraction } from 'discord.js'; import loggerModule from '../services/logger'; +import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator'; const logger = loggerModule.child({ source: 'interactionComponentHandler.js', @@ -16,6 +17,10 @@ export const handleComponent = async (interaction: MessageComponentInteraction, logger.debug(`Parsed componentId: ${componentId}`); + if (await cannotSendMessageInChannel({ interaction, executionId })) { + return; + } + const componentModule = await import(`../interactions/components/${componentId}.js`); const { default: component } = componentModule; diff --git a/src/interactions/commands/player/filters.ts b/src/interactions/commands/player/filters.ts index 50050d0..8131c7e 100644 --- a/src/interactions/commands/player/filters.ts +++ b/src/interactions/commands/player/filters.ts @@ -39,22 +39,19 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - if (await notInVoiceChannel({ interaction, executionId })) { - return; - } - const queue: GuildQueue = useQueue(interaction.guild!.id)!; - if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; - } + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }), + () => queueNoCurrentTrack({ interaction, queue, executionId }) + ]; - if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; - } - - if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return; + for (const validator of validators) { + if (await validator()) { + return; + } } const filterOptions: StringSelectMenuOptionBuilder[] = []; diff --git a/src/interactions/commands/player/leave.ts b/src/interactions/commands/player/leave.ts index 0ea3a53..0c5af31 100644 --- a/src/interactions/commands/player/leave.ts +++ b/src/interactions/commands/player/leave.ts @@ -6,6 +6,7 @@ import loggerModule from '../../../services/logger'; import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); @@ -27,29 +28,18 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - if (await notInVoiceChannel({ interaction, executionId })) { - return; - } - const queue: GuildQueue = useQueue(interaction.guild!.id)!; - if (!queue) { - logger.debug('There is already no queue.'); + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }) + ]; - logger.debug('Responding with warning embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.warning} Oops!**\n_Hmm.._ It seems I am not in a voice channel!` - ) - .setColor(embedOptions.colors.warning) - ] - }); - } - - if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + for (const validator of validators) { + if (await validator()) { + return; + } } if (!queue.deleted) { diff --git a/src/interactions/commands/player/loop.ts b/src/interactions/commands/player/loop.ts index d4c3aee..287200a 100644 --- a/src/interactions/commands/player/loop.ts +++ b/src/interactions/commands/player/loop.ts @@ -41,18 +41,18 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - if (await notInVoiceChannel({ interaction, executionId })) { - return; - } - const queue: GuildQueue = useQueue(interaction.guild!.id)!; - if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; - } + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }) + ]; - if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + for (const validator of validators) { + if (await validator()) { + return; + } } const loopModesFormatted = new Map([ diff --git a/src/interactions/commands/player/lyrics.ts b/src/interactions/commands/player/lyrics.ts index bd3dec8..23a9172 100644 --- a/src/interactions/commands/player/lyrics.ts +++ b/src/interactions/commands/player/lyrics.ts @@ -47,21 +47,19 @@ const command: CustomSlashCommandInteraction = { let geniusSearchQuery = ''; if (!query) { - if (await notInVoiceChannel({ interaction, executionId })) { - return; + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }), + () => queueNoCurrentTrack({ interaction, queue, executionId }) + ]; + + for (const validator of validators) { + if (await validator()) { + return; + } } - if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; - } - - if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; - } - - if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return; - } geniusSearchQuery = queue.currentTrack!.title.slice(0, 50); logger.debug( diff --git a/src/interactions/commands/player/nowplaying.ts b/src/interactions/commands/player/nowplaying.ts index eba6e86..1003e29 100644 --- a/src/interactions/commands/player/nowplaying.ts +++ b/src/interactions/commands/player/nowplaying.ts @@ -37,22 +37,19 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - if (await notInVoiceChannel({ interaction, executionId })) { - return; - } - const queue: GuildQueue = useQueue(interaction.guild!.id)!; - if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; - } + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }), + () => queueNoCurrentTrack({ interaction, queue, executionId }) + ]; - if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; - } - - if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return; + for (const validator of validators) { + if (await validator()) { + return; + } } const sourceStringsFormatted = new Map([ diff --git a/src/interactions/commands/player/pause.ts b/src/interactions/commands/player/pause.ts index 9d564bd..c850ca9 100644 --- a/src/interactions/commands/player/pause.ts +++ b/src/interactions/commands/player/pause.ts @@ -28,22 +28,19 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - if (await notInVoiceChannel({ interaction, executionId })) { - return; - } - const queue: GuildQueue = useQueue(interaction.guild!.id)!; - if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; - } + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }), + () => queueNoCurrentTrack({ interaction, queue, executionId }) + ]; - if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; - } - - if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return; + for (const validator of validators) { + if (await validator()) { + return; + } } const currentTrack = queue.currentTrack!; diff --git a/src/interactions/commands/player/play.ts b/src/interactions/commands/player/play.ts index 7b92682..dcb0176 100644 --- a/src/interactions/commands/player/play.ts +++ b/src/interactions/commands/player/play.ts @@ -43,20 +43,22 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - - if (await notInVoiceChannel({ interaction, executionId })) { - return; - } - - if (await cannotJoinVoiceOrTalk({ interaction, executionId })) { - return; - } - let queue: GuildQueue = useQueue(interaction.guild!.id)!; if (queue && (await notInSameVoiceChannel({ interaction, queue, executionId }))) { return; } + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => cannotJoinVoiceOrTalk({ interaction, executionId }) + ]; + + for (const validator of validators) { + if (await validator()) { + return; + } + } + const player = useMainPlayer()!; const query = interaction.options.getString('query')!; diff --git a/src/interactions/commands/player/queue.ts b/src/interactions/commands/player/queue.ts index 2dab6a7..672280d 100644 --- a/src/interactions/commands/player/queue.ts +++ b/src/interactions/commands/player/queue.ts @@ -6,6 +6,7 @@ import loggerModule from '../../../services/logger'; import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions, PlayerOptions } from '../../../types/configTypes'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); @@ -29,57 +30,23 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - if (await notInVoiceChannel({ interaction, executionId })) { - return; - } - const queue: GuildQueue = useQueue(interaction.guild!.id)!; - if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }) + ]; + + for (const validator of validators) { + if (await validator()) { + return; + } } const pageIndex = (interaction.options.getNumber('page') || 1) - 1; let queueString = ''; - if (!queue) { - if (pageIndex >= 1) { - logger.debug(`There is no queue and user tried to access page ${pageIndex + 1}.`); - - logger.debug('Responding with warning embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.warning} Oops!**\nPage **\`${ - pageIndex + 1 - }\`** is not a valid page number.\n\nThe queue is currently empty, first add some tracks with **\`/play\`**!` - ) - .setColor(embedOptions.colors.warning) - ] - }); - } - - logger.debug('There is no queue, displaying empty queue.'); - queueString = 'The queue is empty, add some tracks with **`/play`**!'; - - logger.debug('Responding with info embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setAuthor({ - name: interaction.guild!.name, - iconURL: interaction.guild!.iconURL() || '' - }) - .setDescription(`**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`) - .setColor(embedOptions.colors.info) - .setFooter({ - text: 'Page 1 of 1 (0 tracks)' - }) - ] - }); - } - const queueLength = queue.tracks.data.length; const totalPages = Math.ceil(queueLength / 10) || 1; diff --git a/src/interactions/commands/player/remove.ts b/src/interactions/commands/player/remove.ts index f5a5071..5bab22f 100644 --- a/src/interactions/commands/player/remove.ts +++ b/src/interactions/commands/player/remove.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { NodeResolvable, useQueue } from 'discord-player'; +import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../../services/logger'; @@ -35,18 +35,18 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - if (await notInVoiceChannel({ interaction, executionId })) { - return Promise.resolve(); - } + const queue: GuildQueue = useQueue(interaction.guild!.id)!; - const queue: NodeResolvable = useQueue(interaction.guild!.id)!; + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }) + ]; - if (await queueDoesNotExist({ interaction, queue, executionId })) { - return Promise.resolve(); - } - - if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return Promise.resolve(); + for (const validator of validators) { + if (await validator()) { + return; + } } const removeTrackNumber = interaction.options.getNumber('tracknumber')!; diff --git a/src/interactions/commands/player/seek.ts b/src/interactions/commands/player/seek.ts index 8815c91..86270a1 100644 --- a/src/interactions/commands/player/seek.ts +++ b/src/interactions/commands/player/seek.ts @@ -34,22 +34,19 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - if (await notInVoiceChannel({ interaction, executionId })) { - return; - } - const queue: GuildQueue = useQueue(interaction.guild!.id)!; - if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; - } + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }), + () => queueNoCurrentTrack({ interaction, queue, executionId }) + ]; - if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; - } - - if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return; + for (const validator of validators) { + if (await validator()) { + return; + } } const durationInput = interaction.options.getString('duration'); diff --git a/src/interactions/commands/player/shuffle.ts b/src/interactions/commands/player/shuffle.ts index fd42828..56c0af7 100644 --- a/src/interactions/commands/player/shuffle.ts +++ b/src/interactions/commands/player/shuffle.ts @@ -28,22 +28,19 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - if (await notInVoiceChannel({ interaction, executionId })) { - return; - } - const queue: GuildQueue = useQueue(interaction.guild!.id)!; - if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; - } + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }), + () => queueIsEmpty({ interaction, queue, executionId }) + ]; - if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; - } - - if (await queueIsEmpty({ interaction, queue, executionId })) { - return; + for (const validator of validators) { + if (await validator()) { + return; + } } queue.tracks.shuffle(); diff --git a/src/interactions/commands/player/skip.ts b/src/interactions/commands/player/skip.ts index 64e1268..511f868 100644 --- a/src/interactions/commands/player/skip.ts +++ b/src/interactions/commands/player/skip.ts @@ -31,22 +31,19 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - if (await notInVoiceChannel({ interaction, executionId })) { - return; - } - const queue: GuildQueue = useQueue(interaction.guild!.id)!; - if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; - } + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }), + () => queueNoCurrentTrack({ interaction, queue, executionId }) + ]; - if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; - } - - if (await queueNoCurrentTrack({ interaction, queue, executionId })) { - return; + for (const validator of validators) { + if (await validator()) { + return; + } } const skipToTrack = interaction.options.getNumber('tracknumber'); diff --git a/src/interactions/commands/player/stop.ts b/src/interactions/commands/player/stop.ts index 36e4d0e..a797167 100644 --- a/src/interactions/commands/player/stop.ts +++ b/src/interactions/commands/player/stop.ts @@ -6,6 +6,7 @@ import loggerModule from '../../../services/logger'; import { CustomSlashCommandInteraction } from '../../../types/interactionTypes'; import { EmbedOptions } from '../../../types/configTypes'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist } from '../../../utils/validation/queueValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); @@ -27,29 +28,18 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - if (await notInVoiceChannel({ interaction, executionId })) { - return; - } - const queue: GuildQueue = useQueue(interaction.guild!.id)!; - if (!queue) { - logger.debug('There is no queue.'); + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }) + ]; - logger.debug('Responding with warning embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.warning} Oops!**\n_Hmm.._ It seems I am not in a voice channel!` - ) - .setColor(embedOptions.colors.warning) - ] - }); - } - - if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + for (const validator of validators) { + if (await validator()) { + return; + } } if (!queue.deleted) { diff --git a/src/interactions/commands/player/volume.ts b/src/interactions/commands/player/volume.ts index d5f59e6..2ebb189 100644 --- a/src/interactions/commands/player/volume.ts +++ b/src/interactions/commands/player/volume.ts @@ -35,18 +35,18 @@ const command: CustomSlashCommandInteraction = { guildId: interaction.guild?.id }); - if (await notInVoiceChannel({ interaction, executionId })) { - return; - } - const queue: GuildQueue = useQueue(interaction.guild!.id)!; - if (await queueDoesNotExist({ interaction, queue, executionId })) { - return; - } + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }) + ]; - if (await notInSameVoiceChannel({ interaction, queue, executionId })) { - return; + for (const validator of validators) { + if (await validator()) { + return; + } } const volume = interaction.options.getNumber('percentage'); diff --git a/src/types/utilTypes.ts b/src/types/utilTypes.ts index 64d3b6a..9965040 100644 --- a/src/types/utilTypes.ts +++ b/src/types/utilTypes.ts @@ -1,5 +1,5 @@ import { GuildQueue, Player } from 'discord-player'; -import { ChatInputCommandInteraction } from 'discord.js'; +import { ChatInputCommandInteraction, MessageComponentInteraction } from 'discord.js'; import { ExtendedClient } from './clientTypes'; @@ -68,7 +68,7 @@ export interface CannotJoinVoiceOrTalkParams { } export interface CannotSendMessageInChannelParams { - interaction: ChatInputCommandInteraction; + interaction: ChatInputCommandInteraction | MessageComponentInteraction; executionId: string; } diff --git a/src/utils/validation/permissionValidator.ts b/src/utils/validation/permissionValidator.ts index 3ffcef2..3921c2f 100644 --- a/src/utils/validation/permissionValidator.ts +++ b/src/utils/validation/permissionValidator.ts @@ -1,5 +1,13 @@ import config from 'config'; -import { EmbedBuilder, GuildMember, TextChannel, VoiceChannel } from 'discord.js'; +import { + ChatInputCommandInteraction, + EmbedBuilder, + GuildMember, + InteractionType, + MessageComponentInteraction, + TextChannel, + VoiceChannel +} from 'discord.js'; import loggerModule from '../../services/logger'; import { EmbedOptions } from '../../types/configTypes'; @@ -50,10 +58,13 @@ export const cannotSendMessageInChannel = async ({ interaction, executionId }: C const channel = interaction.channel; + const interactionIdentifier = + interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; + // only checks if channel is viewable, as bot will have permission to send interaction replies if channel is viewable if (channel instanceof TextChannel && !channel.viewable) { logger.info( - `User tried to use command '${interaction.commandName}' but the bot had no permission to send reply in text channel.` + `User tried to use interaction '${interactionIdentifier}' but the bot has permission to send reply in text channel.` ); try { From 7053f01bc58c9e39ca5cd40d4403aed540852d5b Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 29 Aug 2023 15:48:53 +0200 Subject: [PATCH 5/5] fix: add validation to component interactions --- .../components/filters-disable-button.ts | 18 +++++++++++++-- .../components/filters-select-menu.ts | 22 +++++++++++++++---- .../components/nowplaying-skip-button.ts | 15 +++++++++++++ src/types/utilTypes.ts | 14 ++++++------ src/utils/validation/permissionValidator.ts | 14 ++++-------- src/utils/validation/queueValidator.ts | 21 ++++++++++++------ .../validation/systemCommandValidator.ts | 9 +++++--- src/utils/validation/voiceChannelValidator.ts | 12 +++++++--- 8 files changed, 89 insertions(+), 36 deletions(-) diff --git a/src/interactions/components/filters-disable-button.ts b/src/interactions/components/filters-disable-button.ts index 3597ee1..8fa4520 100644 --- a/src/interactions/components/filters-disable-button.ts +++ b/src/interactions/components/filters-disable-button.ts @@ -3,8 +3,10 @@ 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 { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember } from 'discord.js'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist } from '../../utils/validation/queueValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const component: CustomComponentInteraction = { @@ -20,7 +22,19 @@ const component: CustomComponentInteraction = { logger.debug('Received disable confirmation.'); - const queue = useQueue(interaction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; + + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }) + ]; + + for (const validator of validators) { + if (await validator()) { + return; + } + } // Reset filters before enabling provided filters if (queue.filters.ffmpeg.filters.length > 0) { diff --git a/src/interactions/components/filters-select-menu.ts b/src/interactions/components/filters-select-menu.ts index f8a85d5..15acbfc 100644 --- a/src/interactions/components/filters-select-menu.ts +++ b/src/interactions/components/filters-select-menu.ts @@ -3,8 +3,10 @@ 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 { GuildQueue, QueueFilters, useQueue } from 'discord-player'; import { EmbedBuilder, GuildMember, StringSelectMenuInteraction } from 'discord.js'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist } from '../../utils/validation/queueValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions'); @@ -22,7 +24,19 @@ const component: CustomComponentInteraction = { logger.debug('Received select menu confirmation.'); const selectMenuInteraction = interaction as StringSelectMenuInteraction; - const queue = useQueue(selectMenuInteraction.guild!.id)!; + const queue: GuildQueue = useQueue(interaction.guild!.id)!; + + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }) + ]; + + for (const validator of validators) { + if (await validator()) { + return; + } + } queue.filters.ffmpeg.setInputArgs([ '-threads', @@ -42,10 +56,10 @@ const component: CustomComponentInteraction = { logger.debug('Reset queue filters.'); } - // if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion if ( - (selectMenuInteraction.values.includes('bassboost_low') || selectMenuInteraction.values.includes('bassboost')) && + (selectMenuInteraction.values.includes('bassboost_low') || + selectMenuInteraction.values.includes('bassboost')) && !selectMenuInteraction.values.includes('normalizer') ) { selectMenuInteraction.values.push('normalizer'); diff --git a/src/interactions/components/nowplaying-skip-button.ts b/src/interactions/components/nowplaying-skip-button.ts index cf87a91..c18cf7d 100644 --- a/src/interactions/components/nowplaying-skip-button.ts +++ b/src/interactions/components/nowplaying-skip-button.ts @@ -5,6 +5,8 @@ import { EmbedBuilder, GuildMember } from 'discord.js'; import loggerModule from '../../services/logger'; import { EmbedOptions } from '../../types/configTypes'; import { CustomComponentInteraction } from '../../types/interactionTypes'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; const embedOptions: EmbedOptions = config.get('embedOptions'); const component: CustomComponentInteraction = { @@ -22,6 +24,19 @@ const component: CustomComponentInteraction = { const queue: GuildQueue = useQueue(interaction.guild!.id)!; + const validators = [ + () => notInVoiceChannel({ interaction, executionId }), + () => notInSameVoiceChannel({ interaction, queue, executionId }), + () => queueDoesNotExist({ interaction, queue, executionId }), + () => queueNoCurrentTrack({ interaction, queue, executionId }) + ]; + + for (const validator of validators) { + if (await validator()) { + return; + } + } + if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { logger.debug('Tried skipping track but there was no queue.'); diff --git a/src/types/utilTypes.ts b/src/types/utilTypes.ts index 9965040..86e5eb0 100644 --- a/src/types/utilTypes.ts +++ b/src/types/utilTypes.ts @@ -24,18 +24,18 @@ export interface CustomEvent { } export interface NotInVoiceChannelParams { - interaction: ChatInputCommandInteraction; + interaction: ChatInputCommandInteraction | MessageComponentInteraction; executionId: string; } export interface NotInSameVoiceChannelParams { - interaction: ChatInputCommandInteraction; + interaction: ChatInputCommandInteraction | MessageComponentInteraction; queue: GuildQueue; executionId: string; } export interface NotValidGuildIdParams { - interaction: ChatInputCommandInteraction; + interaction: ChatInputCommandInteraction | MessageComponentInteraction; executionId: string; } @@ -45,25 +45,25 @@ export interface TransformQueryParams { } export interface QueueDoesNotExistParams { - interaction: ChatInputCommandInteraction; + interaction: ChatInputCommandInteraction | MessageComponentInteraction; queue: GuildQueue; executionId: string; } export interface QueueNoCurrentTrackParams { - interaction: ChatInputCommandInteraction; + interaction: ChatInputCommandInteraction | MessageComponentInteraction; queue: GuildQueue; executionId: string; } export interface QueueIsEmptyParams { - interaction: ChatInputCommandInteraction; + interaction: ChatInputCommandInteraction | MessageComponentInteraction; queue: GuildQueue; executionId: string; } export interface CannotJoinVoiceOrTalkParams { - interaction: ChatInputCommandInteraction; + interaction: ChatInputCommandInteraction | MessageComponentInteraction; executionId: string; } diff --git a/src/utils/validation/permissionValidator.ts b/src/utils/validation/permissionValidator.ts index 3921c2f..316395f 100644 --- a/src/utils/validation/permissionValidator.ts +++ b/src/utils/validation/permissionValidator.ts @@ -1,13 +1,5 @@ import config from 'config'; -import { - ChatInputCommandInteraction, - EmbedBuilder, - GuildMember, - InteractionType, - MessageComponentInteraction, - TextChannel, - VoiceChannel -} from 'discord.js'; +import { EmbedBuilder, GuildMember, InteractionType, TextChannel, VoiceChannel } from 'discord.js'; import loggerModule from '../../services/logger'; import { EmbedOptions } from '../../types/configTypes'; @@ -25,6 +17,8 @@ export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: Cannot }); const channel = interaction.member instanceof GuildMember ? interaction.member.voice.channel : null; + const interactionIdentifier = + interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; if (channel instanceof VoiceChannel && (!channel.joinable || !channel.speakable)) { await interaction.editReply({ @@ -38,7 +32,7 @@ export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: Cannot }); logger.debug( - `User tried to use command '${interaction.commandName}' but the bot had no permission to join/speak in the voice channel.` + `User tried to use command '${interactionIdentifier}' but the bot had no permission to join/speak in the voice channel.` ); return true; } diff --git a/src/utils/validation/queueValidator.ts b/src/utils/validation/queueValidator.ts index e762d7a..0929b0b 100644 --- a/src/utils/validation/queueValidator.ts +++ b/src/utils/validation/queueValidator.ts @@ -1,11 +1,9 @@ import config from 'config'; -import { EmbedBuilder } from 'discord.js'; +import { EmbedBuilder, InteractionType } from 'discord.js'; import loggerModule from '../../services/logger'; import { EmbedOptions } from '../../types/configTypes'; -import { - QueueDoesNotExistParams, QueueIsEmptyParams, QueueNoCurrentTrackParams -} from '../../types/utilTypes'; +import { QueueDoesNotExistParams, QueueIsEmptyParams, QueueNoCurrentTrackParams } from '../../types/utilTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); export const queueDoesNotExist = async ({ interaction, queue, executionId }: QueueDoesNotExistParams) => { @@ -18,6 +16,9 @@ export const queueDoesNotExist = async ({ interaction, queue, executionId }: Que guildId: interaction.guild?.id }); + const interactionIdentifier = + interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; + if (!queue) { await interaction.editReply({ embeds: [ @@ -29,7 +30,7 @@ export const queueDoesNotExist = async ({ interaction, queue, executionId }: Que ] }); - logger.debug(`User tried to use command '${interaction.commandName}' but there was no queue.`); + logger.debug(`User tried to use command '${interactionIdentifier}' but there was no queue.`); return true; } @@ -46,6 +47,9 @@ export const queueNoCurrentTrack = async ({ interaction, queue, executionId }: Q guildId: interaction.guild?.id }); + const interactionIdentifier = + interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; + if (!queue.currentTrack) { await interaction.editReply({ embeds: [ @@ -57,7 +61,7 @@ export const queueNoCurrentTrack = async ({ interaction, queue, executionId }: Q ] }); - logger.debug(`User tried to use command '${interaction.commandName}' but there was no current track.`); + logger.debug(`User tried to use command '${interactionIdentifier}' but there was no current track.`); return true; } @@ -74,6 +78,9 @@ export const queueIsEmpty = async ({ interaction, queue, executionId }: QueueIsE guildId: interaction.guild?.id }); + const interactionIdentifier = + interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; + if (queue.tracks.data.length === 0) { await interaction.editReply({ embeds: [ @@ -85,7 +92,7 @@ export const queueIsEmpty = async ({ interaction, queue, executionId }: QueueIsE ] }); - logger.debug(`User tried to use command '${interaction.commandName}' but there was no tracks in the queue.`); + logger.debug(`User tried to use command '${interactionIdentifier}' but there was no tracks in the queue.`); return true; } diff --git a/src/utils/validation/systemCommandValidator.ts b/src/utils/validation/systemCommandValidator.ts index cdcb647..056b871 100644 --- a/src/utils/validation/systemCommandValidator.ts +++ b/src/utils/validation/systemCommandValidator.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { EmbedBuilder } from 'discord.js'; +import { EmbedBuilder, InteractionType } from 'discord.js'; import loggerModule from '../../services/logger'; import { EmbedOptions, SystemOptions } from '../../types/configTypes'; @@ -17,19 +17,22 @@ export const notValidGuildId = async ({ interaction, executionId }: NotValidGuil guildId: interaction.guild?.id }); + const interactionIdentifier = + interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; + if (interaction.guildId && !systemOptions.systemGuildIds.includes(interaction.guildId)) { await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command **\`/${interaction.commandName}\`** cannot be executed in this server.` + `**${embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command **\`/${interactionIdentifier}\`** cannot be executed in this server.` ) .setColor(embedOptions.colors.warning) ] }); logger.debug( - `User tried to use command '${interaction.commandName}' but system command cannot be executed in the specified guild.` + `User tried to use command '${interactionIdentifier}' but system command cannot be executed in the specified guild.` ); return true; } diff --git a/src/utils/validation/voiceChannelValidator.ts b/src/utils/validation/voiceChannelValidator.ts index 8bb3cf2..599922e 100644 --- a/src/utils/validation/voiceChannelValidator.ts +++ b/src/utils/validation/voiceChannelValidator.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { EmbedBuilder, GuildMember } from 'discord.js'; +import { EmbedBuilder, GuildMember, InteractionType } from 'discord.js'; import loggerModule from '../../services/logger'; import { EmbedOptions } from '../../types/configTypes'; @@ -16,6 +16,9 @@ export const notInVoiceChannel = async ({ interaction, executionId }: NotInVoice guildId: interaction.guild?.id }); + const interactionIdentifier = + interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; + if (interaction.member instanceof GuildMember && !interaction.member.voice.channel) { await interaction.editReply({ embeds: [ @@ -27,7 +30,7 @@ export const notInVoiceChannel = async ({ interaction, executionId }: NotInVoice ] }); - logger.debug(`User tried to use command '${interaction.commandName}' but was not in a voice channel.`); + logger.debug(`User tried to use command '${interactionIdentifier}' but was not in a voice channel.`); return true; } @@ -44,6 +47,9 @@ export const notInSameVoiceChannel = async ({ interaction, queue, executionId }: guildId: interaction.guild?.id }); + const interactionIdentifier = + interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; + if (!queue || !queue.dispatcher) { // If there is no queue or bot is not in voice channel, then there is no need to check if user is in same voice channel. return false; @@ -63,7 +69,7 @@ export const notInSameVoiceChannel = async ({ interaction, queue, executionId }: ] }); - logger.debug(`User tried to use command '${interaction.commandName}' but was not in the same voice channel.`); + logger.debug(`User tried to use command '${interactionIdentifier}' but was not in the same voice channel.`); return true; }