From 72eb148ac81a2e8a09e3401095a87786cbce799d Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 25 Dec 2023 14:52:35 +0100 Subject: [PATCH 01/15] update prisma schema --- prisma/schema.prisma | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 5297f7d..6fe28d1 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -1,19 +1,36 @@ generator client { - provider = "prisma-client-js" + provider = "prisma-client-js" } datasource db { - provider = "sqlite" - url = "file:./dev.db" + provider = "sqlite" + url = "file:./dev.db" } model Guild { - id String @id @default(cuid()) - guildId String @unique + guildId String @id - locale String @default("en-US") - defaultVolume Int @default(50) + settings GuildSettings @relation(fields: [settingsId], references: [id]) + settingsId String @unique - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@map("guilds") +} + +model GuildSettings { + id String @id @default(cuid()) + + defaultVolume Int @default(50) + locale String @default("en-US") + privilegedRoles String? + + guild Guild? @relation() + guildId String @unique + + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@map("guild_settings") } From 1b4cef808bba262bd8d1e3020016911f63545276 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 25 Dec 2023 14:52:50 +0100 Subject: [PATCH 02/15] create boilerplate code for settings command --- locales/en/bot.json | 6 +++++ src/interactions/commands/config/settings.ts | 24 ++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 src/interactions/commands/config/settings.ts diff --git a/locales/en/bot.json b/locales/en/bot.json index 9b66415..5e01da1 100644 --- a/locales/en/bot.json +++ b/locales/en/bot.json @@ -290,6 +290,12 @@ "durationLongerThanTrackDuration": "{{icon}} **Oops!**\nYou entered **`{{wrongDuration}}`**, which is a timestamp longer than the duration of the current track.\n\nPlease try a timestamp that is less than the duration of the track (**{{trackDuration}}**).", "seekingToTimestamp": "{{icon}} **Seeking to timestamp**\nSeeking to **`{{duration}}`** in current track." }, + "settings": { + "metadata": { + "name": "settings", + "description": "Configure various options for bot behavior in this server." + } + }, "shards": { "metadata": { "name": "shards", diff --git a/src/interactions/commands/config/settings.ts b/src/interactions/commands/config/settings.ts new file mode 100644 index 0000000..c667528 --- /dev/null +++ b/src/interactions/commands/config/settings.ts @@ -0,0 +1,24 @@ +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { BaseSlashCommandInteraction } from '../../../classes/interactions'; +import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../../types/interactionTypes'; +import { localizeCommand } from '../../../common/localeUtil'; + +class SettingsCommand extends BaseSlashCommandInteraction { + constructor() { + const data = localizeCommand(new SlashCommandBuilder().setName('settings')); + super(data); + } + + async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { + const { executionId, interaction } = params; + const logger = this.getLogger(this.name, executionId, interaction); + //const translator = useServerTranslator(interaction); + + logger.debug('Sending embed'); + return await interaction.editReply({ + embeds: [new EmbedBuilder().setDescription('Settings').setColor(this.embedOptions.colors.info)] + }); + } +} + +export default new SettingsCommand(); From 321a9664ce98f4fa4832ea29525e0098194500a7 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Mon, 25 Dec 2023 14:53:10 +0100 Subject: [PATCH 03/15] start of guildDatabaseService --- src/services/guildDatabaseService.ts | 145 ++++++++++++++++++++++++++- 1 file changed, 144 insertions(+), 1 deletion(-) diff --git a/src/services/guildDatabaseService.ts b/src/services/guildDatabaseService.ts index 79409ec..3614322 100644 --- a/src/services/guildDatabaseService.ts +++ b/src/services/guildDatabaseService.ts @@ -1,11 +1,154 @@ import { getPrismaClient } from './prismaClient'; +import loggerModule from './logger'; +import { Logger } from 'pino'; +import { Interaction, MessageComponentInteraction } from 'discord.js'; const prisma = getPrismaClient(); +function getLogger(executionId: string, interaction?: Interaction | MessageComponentInteraction): Logger { + return loggerModule.child({ + module: 'databaseService', + name: 'guildDatabaseService', + executionId: executionId, + shardId: interaction?.guild?.shardId ?? 'N/A' + }); +} + +export type GuildSettings = { + defaultVolume?: number; + locale?: string; + privilegedRoles?: string[]; +}; + const guildDatabaseService = { - async getAllGuilds() { + async getAllGuilds(executionId: string, interaction?: Interaction | MessageComponentInteraction) { + const logger = getLogger(executionId, interaction); + logger.debug('Getting all guilds from database.'); return await prisma.guild.findMany(); + }, + + async getGuildSettings( + guildId: string, + executionId: string, + interaction?: Interaction | MessageComponentInteraction + ) { + const logger = getLogger(executionId, interaction); + logger.debug(`Getting settings for guild ${guildId} from database.`); + const settings = await prisma.guildSettings.findUnique({ + where: { guildId: guildId } + }); + + if (!settings) { + logger.debug(`No settings found for guild ${guildId}.`); + return null; + } + + const response = { + ...settings, + privilegedRoles: deserializeRoleIds(settings.privilegedRoles ?? '') + }; + + return response; + }, + + async createOrUpdateGuild( + executionId: string, + guildId: string, + settingsData: GuildSettings, + interaction?: Interaction | MessageComponentInteraction + ) { + const logger = getLogger(executionId, interaction); + logger.debug(`Creating or updating guild ${guildId} in database.`); + + const validSettings = validateGuildSettings(logger, settingsData); + return await prisma.guild.upsert({ + where: { guildId: guildId }, + update: { + settings: { + update: validSettings + } + }, + create: { + guildId: guildId, + settings: { + create: { + ...validSettings, + guildId: guildId + } + } + } + }); + }, + + async updateGuildSettings( + executionId: string, + guildId: string, + settingsData: GuildSettings, + interaction?: Interaction | MessageComponentInteraction + ) { + const logger = getLogger(executionId, interaction); + logger.debug(`Updating settings for guild ${guildId} in database.`); + const validSettings = validateGuildSettings(logger, settingsData); + return await prisma.guildSettings.update({ + where: { + guildId: guildId + }, + data: validSettings + }); + }, + + async deleteGuildAndSettings( + executionId: string, + guildId: string, + interaction?: Interaction | MessageComponentInteraction + ) { + const logger = getLogger(executionId, interaction); + logger.debug(`Deleting guild ${guildId} and settings from database.`); + + return await prisma.$transaction(async (prisma) => { + await prisma.guildSettings.delete({ + where: { guildId: guildId } + }); + + await prisma.guild.delete({ + where: { guildId: guildId } + }); + }); } }; +export function validateGuildSettings(logger: Logger, settingsData: GuildSettings) { + if (settingsData.defaultVolume && (settingsData.defaultVolume < 0 || settingsData.defaultVolume > 100)) { + logger.debug(`defaultVolume ${settingsData.defaultVolume} is not between 0 and 100`); + throw new Error('defaultVolume must be between 0 and 100'); + } + + // get available locale from i18next? + if (settingsData.locale && !['en-US', 'no', 'ro', 'en-ES'].includes(settingsData.locale)) { + logger.debug(`locale ${settingsData.locale} is not in list of available locales`); + throw new Error(`locale ${settingsData.locale} is not in list of available locales`); + } + + if (settingsData.privilegedRoles && !settingsData.privilegedRoles.every((role) => role.match(/\d{18}/))) { + logger.debug('privilegedRoles contains invalid Discord role IDs'); + throw new Error('privilegedRoles contains invalid Discord role IDs'); + } + + const validSettings = { + defaultVolume: settingsData.defaultVolume, + locale: settingsData.locale, + privilegedRoles: serializeRoleIds(settingsData.privilegedRoles ?? []) + }; + + return validSettings; +} + +function serializeRoleIds(roleIds: string[]): string { + return roleIds.join(','); +} + +function deserializeRoleIds(serializedRoles: string): string[] { + return serializedRoles.split(',').filter((role) => role.trim() !== ''); +} + export default guildDatabaseService; From 8af2384502abd5a0424d035ff459b511e63ad991 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 26 Dec 2023 00:08:32 +0100 Subject: [PATCH 04/15] start of settings command --- locales/en/bot.json | 38 ++++- prisma/schema.prisma | 25 +--- src/interactions/commands/config/settings.ts | 144 ++++++++++++++++++- src/services/guildDatabaseService.ts | 73 +++------- 4 files changed, 197 insertions(+), 83 deletions(-) diff --git a/locales/en/bot.json b/locales/en/bot.json index 5e01da1..3f91e7c 100644 --- a/locales/en/bot.json +++ b/locales/en/bot.json @@ -293,7 +293,43 @@ "settings": { "metadata": { "name": "settings", - "description": "Configure various options for bot behavior in this server." + "description": "Configure various options for bot behavior in this server.", + "options": { + "bot-language": { + "name": "bot-language", + "description": "Set the language for the bot.", + "options": { + "language": { + "name": "language", + "description": "Language to use for the bot in messages.", + "choices": { + "en-US": "English", + "no": "Norwegian", + "ro": "Romanian", + "en-ES": "Spanish" + } + } + } + }, + "default-volume": { + "name": "default-volume", + "description": "Set the default volume for the bot.", + "options": { + "percentage": { + "name": "percentage", + "description": "Volume percentage: From 0% to 100%." + } + } + }, + "action-permissions": { + "name": "action-permissions", + "description": "Set the roles required to perform certain actions." + }, + "view": { + "name": "view", + "description": "View the current settings for the bot." + } + } } }, "shards": { diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 6fe28d1..777123c 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -7,27 +7,12 @@ datasource db { url = "file:./dev.db" } -model Guild { - guildId String @id +model GuildSetting { + defaultVolume Int @default(50) + locale String @default("en-US") + actionPermissions String? - settings GuildSettings @relation(fields: [settingsId], references: [id]) - settingsId String @unique - - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - @@map("guilds") -} - -model GuildSettings { - id String @id @default(cuid()) - - defaultVolume Int @default(50) - locale String @default("en-US") - privilegedRoles String? - - guild Guild? @relation() - guildId String @unique + guildId String @id @unique createdAt DateTime @default(now()) updatedAt DateTime @updatedAt diff --git a/src/interactions/commands/config/settings.ts b/src/interactions/commands/config/settings.ts index c667528..c4aef6e 100644 --- a/src/interactions/commands/config/settings.ts +++ b/src/interactions/commands/config/settings.ts @@ -1,22 +1,154 @@ -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { EmbedBuilder, SlashCommandBuilder, PermissionFlagsBits, ChatInputCommandInteraction } from 'discord.js'; import { BaseSlashCommandInteraction } from '../../../classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../../types/interactionTypes'; -import { localizeCommand } from '../../../common/localeUtil'; +import { localizeCommand, useServerTranslator } from '../../../common/localeUtil'; +import { Logger } from 'pino'; +import { TFunction } from 'i18next'; +import guildDatabaseService from '../../../services/guildDatabaseService'; class SettingsCommand extends BaseSlashCommandInteraction { constructor() { - const data = localizeCommand(new SlashCommandBuilder().setName('settings')); + const data = localizeCommand( + new SlashCommandBuilder() + .setName('settings') + .setDefaultMemberPermissions(PermissionFlagsBits.Administrator) + .addSubcommand((subcommand) => subcommand.setName('view')) + .addSubcommand((subcommand) => + subcommand + .setName('bot-language') + .addStringOption((option) => + option + .setName('language') + .addChoices( + { value: 'en-US', name: ' ' }, + { value: 'no', name: ' ' }, + { value: 'ro', name: ' ' }, + { value: 'en-ES', name: ' ' } + ) + ) + ) + .addSubcommand((subcommand) => + subcommand + .setName('default-volume') + .addIntegerOption((option) => option.setName('percentage').setMinValue(0).setMaxValue(100)) + ) + .addSubcommand((subcommand) => subcommand.setName('action-permissions')) + ); super(data); } async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { const { executionId, interaction } = params; const logger = this.getLogger(this.name, executionId, interaction); - //const translator = useServerTranslator(interaction); + const translator = useServerTranslator(interaction); + + const subcommand = interaction.options.getSubcommand(); + + switch (subcommand) { + case 'view': + return await this.handleShowSettings(executionId, logger, interaction, translator); + case 'default-volume': + return await this.handleDefaultVolume(executionId, logger, interaction, translator); + default: + return Promise.resolve(); + } + } + + private async handleShowSettings( + executionId: string, + logger: Logger, + interaction: ChatInputCommandInteraction, + translator: TFunction + ) { + logger.debug('Showing settings'); + + // get settings from database + const settings = await guildDatabaseService.getGuildSettings(interaction.guild!.id, executionId, interaction); + + console.log(settings); + + if (!settings) { + logger.debug('No settings found'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription(`Could not find settings for guild id ${interaction.guild!.id}`) + .setColor(this.embedOptions.colors.warning) + ] + }); + } + + const settingsAsString = [ + `Language: ${settings.locale}`, + `Volume: ${settings.defaultVolume}`, + `Action permissions: ${Object.keys(settings.actionPermissions).join(', ')}` + ].join('\n'); - logger.debug('Sending embed'); return await interaction.editReply({ - embeds: [new EmbedBuilder().setDescription('Settings').setColor(this.embedOptions.colors.info)] + embeds: [new EmbedBuilder().setDescription(settingsAsString).setColor(this.embedOptions.colors.info)] + }); + } + + private async handleDefaultVolume( + executionId: string, + logger: Logger, + interaction: ChatInputCommandInteraction, + translator: TFunction + ) { + logger.debug('Setting volume'); + + const volume = interaction.options.getInteger('percentage'); + + const settings = await guildDatabaseService.getGuildSettings(interaction.guild!.id, executionId, interaction); + + if (!volume) { + if (!settings) { + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription(`Could not find settings for guild id ${interaction.guild!.id}`) + .setColor(this.embedOptions.colors.warning) + ] + }); + } + + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription(`Current default volume is ${settings.defaultVolume}`) + .setColor(this.embedOptions.colors.info) + ] + }); + } + + if (volume < 0 || volume > 100) { + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription('Volume must be between 0 and 100') + .setColor(this.embedOptions.colors.error) + ] + }); + } + + const updatedSettings = { + ...settings, + defaultVolume: volume + }; + + await guildDatabaseService.createOrUpdateGuildSettings( + executionId, + interaction.guild!.id, + updatedSettings, + interaction + ); + + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription(`Default volume set to ${volume}`) + .setColor(this.embedOptions.colors.success) + ] }); } } diff --git a/src/services/guildDatabaseService.ts b/src/services/guildDatabaseService.ts index 3614322..23d309e 100644 --- a/src/services/guildDatabaseService.ts +++ b/src/services/guildDatabaseService.ts @@ -17,16 +17,10 @@ function getLogger(executionId: string, interaction?: Interaction | MessageCompo export type GuildSettings = { defaultVolume?: number; locale?: string; - privilegedRoles?: string[]; + actionPermissions?: Record; }; const guildDatabaseService = { - async getAllGuilds(executionId: string, interaction?: Interaction | MessageComponentInteraction) { - const logger = getLogger(executionId, interaction); - logger.debug('Getting all guilds from database.'); - return await prisma.guild.findMany(); - }, - async getGuildSettings( guildId: string, executionId: string, @@ -34,7 +28,7 @@ const guildDatabaseService = { ) { const logger = getLogger(executionId, interaction); logger.debug(`Getting settings for guild ${guildId} from database.`); - const settings = await prisma.guildSettings.findUnique({ + const settings = await prisma.guildSetting.findUnique({ where: { guildId: guildId } }); @@ -45,59 +39,35 @@ const guildDatabaseService = { const response = { ...settings, - privilegedRoles: deserializeRoleIds(settings.privilegedRoles ?? '') + actionPermissions: deserializeActionPermissions(settings.actionPermissions ?? '') }; return response; }, - async createOrUpdateGuild( + async createOrUpdateGuildSettings( executionId: string, guildId: string, settingsData: GuildSettings, interaction?: Interaction | MessageComponentInteraction ) { const logger = getLogger(executionId, interaction); - logger.debug(`Creating or updating guild ${guildId} in database.`); + logger.debug(`Creating or updating guild settings for guild ${guildId} in database.`); const validSettings = validateGuildSettings(logger, settingsData); - return await prisma.guild.upsert({ + return await prisma.guildSetting.upsert({ where: { guildId: guildId }, update: { - settings: { - update: validSettings - } + ...validSettings }, create: { guildId: guildId, - settings: { - create: { - ...validSettings, - guildId: guildId - } - } + ...validSettings } }); }, - async updateGuildSettings( - executionId: string, - guildId: string, - settingsData: GuildSettings, - interaction?: Interaction | MessageComponentInteraction - ) { - const logger = getLogger(executionId, interaction); - logger.debug(`Updating settings for guild ${guildId} in database.`); - const validSettings = validateGuildSettings(logger, settingsData); - return await prisma.guildSettings.update({ - where: { - guildId: guildId - }, - data: validSettings - }); - }, - - async deleteGuildAndSettings( + async deleteGuildSettings( executionId: string, guildId: string, interaction?: Interaction | MessageComponentInteraction @@ -105,14 +75,8 @@ const guildDatabaseService = { const logger = getLogger(executionId, interaction); logger.debug(`Deleting guild ${guildId} and settings from database.`); - return await prisma.$transaction(async (prisma) => { - await prisma.guildSettings.delete({ - where: { guildId: guildId } - }); - - await prisma.guild.delete({ - where: { guildId: guildId } - }); + return await prisma.guildSetting.delete({ + where: { guildId: guildId } }); } }; @@ -129,26 +93,23 @@ export function validateGuildSettings(logger: Logger, settingsData: GuildSetting throw new Error(`locale ${settingsData.locale} is not in list of available locales`); } - if (settingsData.privilegedRoles && !settingsData.privilegedRoles.every((role) => role.match(/\d{18}/))) { - logger.debug('privilegedRoles contains invalid Discord role IDs'); - throw new Error('privilegedRoles contains invalid Discord role IDs'); - } + // TODO: validate actionPermissions const validSettings = { defaultVolume: settingsData.defaultVolume, locale: settingsData.locale, - privilegedRoles: serializeRoleIds(settingsData.privilegedRoles ?? []) + actionPermissions: serializeActionPermissions(settingsData.actionPermissions ?? {}) }; return validSettings; } -function serializeRoleIds(roleIds: string[]): string { - return roleIds.join(','); +function serializeActionPermissions(permissions: Record): string { + return JSON.stringify(permissions); } -function deserializeRoleIds(serializedRoles: string): string[] { - return serializedRoles.split(',').filter((role) => role.trim() !== ''); +function deserializeActionPermissions(serializedPermissions: string): Record { + return JSON.parse(serializedPermissions); } export default guildDatabaseService; From 53d39e221013771e500644b556c75090d257361a Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 30 Jan 2024 11:44:40 +0100 Subject: [PATCH 05/15] rename --- prisma/schema.prisma | 2 +- .../config => slashcommands}/settings.ts | 14 ++--- ...abaseService.ts => guildDatabaseClient.ts} | 62 +++++++++---------- 3 files changed, 39 insertions(+), 39 deletions(-) rename src/interactions/{commands/config => slashcommands}/settings.ts (90%) rename src/services/{guildDatabaseService.ts => guildDatabaseClient.ts} (53%) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 777123c..6bf552c 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -7,7 +7,7 @@ datasource db { url = "file:./dev.db" } -model GuildSetting { +model GuildConfig { defaultVolume Int @default(50) locale String @default("en-US") actionPermissions String? diff --git a/src/interactions/commands/config/settings.ts b/src/interactions/slashcommands/settings.ts similarity index 90% rename from src/interactions/commands/config/settings.ts rename to src/interactions/slashcommands/settings.ts index c4aef6e..74db59c 100644 --- a/src/interactions/commands/config/settings.ts +++ b/src/interactions/slashcommands/settings.ts @@ -1,10 +1,10 @@ import { EmbedBuilder, SlashCommandBuilder, PermissionFlagsBits, ChatInputCommandInteraction } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../../classes/interactions'; -import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../../types/interactionTypes'; -import { localizeCommand, useServerTranslator } from '../../../common/localeUtil'; +import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; +import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; import { Logger } from 'pino'; import { TFunction } from 'i18next'; -import guildDatabaseService from '../../../services/guildDatabaseService'; +import guildDatabaseClient from '../../services/guildDatabaseClient'; class SettingsCommand extends BaseSlashCommandInteraction { constructor() { @@ -63,7 +63,7 @@ class SettingsCommand extends BaseSlashCommandInteraction { logger.debug('Showing settings'); // get settings from database - const settings = await guildDatabaseService.getGuildSettings(interaction.guild!.id, executionId, interaction); + const settings = await guildDatabaseClient.getGuildConfig(interaction.guild!.id, executionId, interaction); console.log(settings); @@ -99,7 +99,7 @@ class SettingsCommand extends BaseSlashCommandInteraction { const volume = interaction.options.getInteger('percentage'); - const settings = await guildDatabaseService.getGuildSettings(interaction.guild!.id, executionId, interaction); + const settings = await guildDatabaseClient.getGuildConfig(interaction.guild!.id, executionId, interaction); if (!volume) { if (!settings) { @@ -136,7 +136,7 @@ class SettingsCommand extends BaseSlashCommandInteraction { defaultVolume: volume }; - await guildDatabaseService.createOrUpdateGuildSettings( + await guildDatabaseClient.createOrUpdateGuildConfig( executionId, interaction.guild!.id, updatedSettings, diff --git a/src/services/guildDatabaseService.ts b/src/services/guildDatabaseClient.ts similarity index 53% rename from src/services/guildDatabaseService.ts rename to src/services/guildDatabaseClient.ts index 23d309e..9c5e986 100644 --- a/src/services/guildDatabaseService.ts +++ b/src/services/guildDatabaseClient.ts @@ -14,94 +14,94 @@ function getLogger(executionId: string, interaction?: Interaction | MessageCompo }); } -export type GuildSettings = { +export type GuildConfig = { defaultVolume?: number; locale?: string; actionPermissions?: Record; }; -const guildDatabaseService = { - async getGuildSettings( +const guildDatabaseClient = { + async getGuildConfig( guildId: string, executionId: string, interaction?: Interaction | MessageComponentInteraction ) { const logger = getLogger(executionId, interaction); - logger.debug(`Getting settings for guild ${guildId} from database.`); - const settings = await prisma.guildSetting.findUnique({ + logger.debug(`Getting config for guild ${guildId} from database.`); + const config = await prisma.guildConfig.findUnique({ where: { guildId: guildId } }); - if (!settings) { - logger.debug(`No settings found for guild ${guildId}.`); + if (!config) { + logger.debug(`No config found for guild ${guildId}.`); return null; } const response = { - ...settings, - actionPermissions: deserializeActionPermissions(settings.actionPermissions ?? '') + ...config, + actionPermissions: deserializeActionPermissions(config.actionPermissions ?? '') }; return response; }, - async createOrUpdateGuildSettings( + async createOrUpdateGuildConfig( executionId: string, guildId: string, - settingsData: GuildSettings, + configData: GuildConfig, interaction?: Interaction | MessageComponentInteraction ) { const logger = getLogger(executionId, interaction); - logger.debug(`Creating or updating guild settings for guild ${guildId} in database.`); + logger.debug(`Creating or updating guild config for guild ${guildId} in database.`); - const validSettings = validateGuildSettings(logger, settingsData); - return await prisma.guildSetting.upsert({ + const validConfig = validateGuildConfig(logger, configData); + return await prisma.guildConfig.upsert({ where: { guildId: guildId }, update: { - ...validSettings + ...validConfig }, create: { guildId: guildId, - ...validSettings + ...validConfig } }); }, - async deleteGuildSettings( + async deleteGuildConfig( executionId: string, guildId: string, interaction?: Interaction | MessageComponentInteraction ) { const logger = getLogger(executionId, interaction); - logger.debug(`Deleting guild ${guildId} and settings from database.`); + logger.debug(`Deleting guild ${guildId} and config from database.`); - return await prisma.guildSetting.delete({ + return await prisma.guildConfig.delete({ where: { guildId: guildId } }); } }; -export function validateGuildSettings(logger: Logger, settingsData: GuildSettings) { - if (settingsData.defaultVolume && (settingsData.defaultVolume < 0 || settingsData.defaultVolume > 100)) { - logger.debug(`defaultVolume ${settingsData.defaultVolume} is not between 0 and 100`); +export function validateGuildConfig(logger: Logger, configData: GuildConfig) { + if (configData.defaultVolume && (configData.defaultVolume < 0 || configData.defaultVolume > 100)) { + logger.debug(`defaultVolume ${configData.defaultVolume} is not between 0 and 100`); throw new Error('defaultVolume must be between 0 and 100'); } // get available locale from i18next? - if (settingsData.locale && !['en-US', 'no', 'ro', 'en-ES'].includes(settingsData.locale)) { - logger.debug(`locale ${settingsData.locale} is not in list of available locales`); - throw new Error(`locale ${settingsData.locale} is not in list of available locales`); + if (configData.locale && !['en-US', 'no', 'ro', 'en-ES'].includes(configData.locale)) { + logger.debug(`locale ${configData.locale} is not in list of available locales`); + throw new Error(`locale ${configData.locale} is not in list of available locales`); } // TODO: validate actionPermissions - const validSettings = { - defaultVolume: settingsData.defaultVolume, - locale: settingsData.locale, - actionPermissions: serializeActionPermissions(settingsData.actionPermissions ?? {}) + const validConfig = { + defaultVolume: configData.defaultVolume, + locale: configData.locale, + actionPermissions: serializeActionPermissions(configData.actionPermissions ?? {}) }; - return validSettings; + return validConfig; } function serializeActionPermissions(permissions: Record): string { @@ -112,4 +112,4 @@ function deserializeActionPermissions(serializedPermissions: string): Record Date: Tue, 30 Jan 2024 14:50:07 +0100 Subject: [PATCH 06/15] rename to config --- prisma/schema.prisma | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 6bf552c..d348d3a 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -17,5 +17,5 @@ model GuildConfig { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt - @@map("guild_settings") + @@map("guild_config") } From d92bd329dc3b99472a10d53c7231188c64308538 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 30 Jan 2024 14:52:40 +0100 Subject: [PATCH 07/15] deps: update prisma --- package-lock.json | 8 ++++---- package.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index f2cad68..9f665c7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,7 @@ "@discord-player/extractor": "^4.4.6", "@discord-player/opus": "^0.1.2", "@discordjs/rest": "^2.2.0", - "@prisma/client": "^5.8.1", + "@prisma/client": "^5.9.0", "config": "^3.3.10", "discord-player": "^6.6.7", "discord-voip": "^0.1.3", @@ -1537,9 +1537,9 @@ } }, "node_modules/@prisma/client": { - "version": "5.8.1", - "resolved": "https://registry.npmjs.org/@prisma/client/-/client-5.8.1.tgz", - "integrity": "sha512-xQtMPfbIwLlbm0VVIVQY2yqQVOxPwRQhvIp7Z3m2900g1bu/zRHKhYZJQWELqmjl6d8YwBy0K2NvMqh47v1ubw==", + "version": "5.9.0", + "resolved": "https://registry.npmjs.org/@prisma/client/-/client-5.9.0.tgz", + "integrity": "sha512-dHvFZgCT0BpRS+gRhk3S+50DstXMmVowxbrPeUJaK7sjNq5OhzfpT/OGE1kq9z5Q8WmOwIXJXyxP8O2CmP+nSg==", "hasInstallScript": true, "engines": { "node": ">=16.13" diff --git a/package.json b/package.json index 5455b3c..b64e15b 100644 --- a/package.json +++ b/package.json @@ -53,7 +53,7 @@ "@discord-player/extractor": "^4.4.6", "@discord-player/opus": "^0.1.2", "@discordjs/rest": "^2.2.0", - "@prisma/client": "^5.8.1", + "@prisma/client": "^5.9.0", "config": "^3.3.10", "discord-player": "^6.6.7", "discord-voip": "^0.1.3", From 39ff5ecb5d2d28b06e161054f0c793531ce06506 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 30 Jan 2024 16:29:17 +0100 Subject: [PATCH 08/15] fix!: New folder structure and organize files --- package.json | 4 ++-- src/bot.ts | 10 +++++----- src/{ => common}/classes/interactions.ts | 6 +++--- src/{utils => common}/factory/createClient.ts | 2 +- src/{utils => common}/factory/createPlayer.ts | 2 +- .../services/guildDatabaseClient.ts | 4 ++-- src/{ => common}/services/logger.ts | 4 ++-- src/{ => common}/services/prismaClient.ts | 2 +- src/common/{ => utils}/autocompleteUtils.ts | 0 src/common/{ => utils}/formattingUtils.ts | 2 +- .../utils}/getUptimeFormatted.ts | 4 ++-- src/common/{ => utils}/localeUtil.ts | 2 ++ src/{ => common}/utils/shardUtils.ts | 2 +- src/common/{ => utils}/statusUtils.ts | 6 +++--- .../validation/permissionValidator.ts | 6 +++--- .../validation/queueValidator.ts | 8 ++++---- .../validation/searchQueryValidator.ts | 2 +- .../validation/systemCommandValidator.ts | 8 ++++---- .../validation/voiceChannelValidator.ts | 6 +++--- src/events/client/debug.ts | 2 +- src/events/client/disconnect.ts | 2 +- src/events/client/error.ts | 2 +- src/events/client/guildCreate.ts | 2 +- src/events/client/guildDelete.ts | 2 +- src/events/client/ready.ts | 6 +++--- src/events/client/reconnecting.ts | 2 +- src/events/client/warn.ts | 2 +- src/events/interactions/interactionCreate.ts | 4 ++-- src/events/player/generalDebug.ts | 2 +- src/events/player/generalError.ts | 4 ++-- src/events/player/playerDebug.ts | 2 +- src/events/player/playerError.ts | 4 ++-- src/events/player/playerFinish.ts | 2 +- src/events/player/playerSkip.ts | 4 ++-- src/events/player/playerStart.ts | 4 ++-- src/events/player/willAutoPlay.ts | 2 +- src/events/process/uncaughtException.ts | 2 +- src/events/process/unhandledRejection.ts | 2 +- .../interactionAutocompleteHandler.ts | 4 ++-- src/handlers/interactionCommandHandler.ts | 6 +++--- src/handlers/interactionComponentHandler.ts | 6 +++--- src/handlers/interactionErrorHandler.ts | 6 +++--- src/index.ts | 6 +++--- src/interactions/autocomplete/lyrics.ts | 6 +++--- src/interactions/autocomplete/play.ts | 8 ++++---- .../components/action-pauseresume-button.ts | 10 +++++----- .../components/action-previous-button.ts | 10 +++++----- .../components/action-skip-button.ts | 10 +++++----- .../components/filters-disable-button.ts | 8 ++++---- .../components/filters-select-menu.ts | 8 ++++---- src/interactions/slashcommands/back.ts | 10 +++++----- src/interactions/slashcommands/filters.ts | 8 ++++---- src/interactions/slashcommands/help.ts | 9 +++++++-- src/interactions/slashcommands/history.ts | 10 +++++----- src/interactions/slashcommands/join.ts | 10 +++++----- src/interactions/slashcommands/leave.ts | 10 +++++----- src/interactions/slashcommands/loop.ts | 10 +++++----- src/interactions/slashcommands/lyrics.ts | 8 ++++---- src/interactions/slashcommands/move.ts | 10 +++++----- src/interactions/slashcommands/nowplaying.ts | 10 +++++----- src/interactions/slashcommands/pause.ts | 8 ++++---- src/interactions/slashcommands/play.ts | 12 ++++++------ src/interactions/slashcommands/queue.ts | 10 +++++----- src/interactions/slashcommands/reload.ts | 6 +++--- src/interactions/slashcommands/remove.ts | 10 +++++----- src/interactions/slashcommands/seek.ts | 10 +++++----- src/interactions/slashcommands/settings.ts | 6 +++--- src/interactions/slashcommands/shards.ts | 6 +++--- src/interactions/slashcommands/shuffle.ts | 10 +++++----- src/interactions/slashcommands/skip.ts | 10 +++++----- src/interactions/slashcommands/status.ts | 11 ++++++++--- src/interactions/slashcommands/stop.ts | 10 +++++----- .../slashcommands/systemstatus.ts | 13 +++++++++---- src/interactions/slashcommands/volume.ts | 8 ++++---- src/{utils => startup}/deploySlashCommands.ts | 4 ++-- src/{utils/other => startup}/postBotStats.ts | 6 +++--- .../registerClientInteractions.ts | 2 +- .../registerEventListeners.ts | 2 +- src/{utils/other => startup}/startLoadTest.ts | 6 +++--- src/tests/help.test.ts | 2 +- src/tests/validation.test.ts | 2 +- src/types/clientTypes.d.ts | 2 +- src/utils/other/cookieParser.ts | 19 ------------------- 83 files changed, 244 insertions(+), 246 deletions(-) rename src/{ => common}/classes/interactions.ts (98%) rename src/{utils => common}/factory/createClient.ts (96%) rename src/{utils => common}/factory/createPlayer.ts (96%) rename src/{ => common}/services/guildDatabaseClient.ts (97%) rename src/{ => common}/services/logger.ts (96%) rename src/{ => common}/services/prismaClient.ts (81%) rename src/common/{ => utils}/autocompleteUtils.ts (100%) rename src/common/{ => utils}/formattingUtils.ts (97%) rename src/{utils/system => common/utils}/getUptimeFormatted.ts (84%) rename src/common/{ => utils}/localeUtil.ts (99%) rename src/{ => common}/utils/shardUtils.ts (97%) rename src/common/{ => utils}/statusUtils.ts (94%) rename src/{utils => common}/validation/permissionValidator.ts (96%) rename src/{utils => common}/validation/queueValidator.ts (96%) rename src/{utils => common}/validation/searchQueryValidator.ts (97%) rename src/{utils => common}/validation/systemCommandValidator.ts (87%) rename src/{utils => common}/validation/voiceChannelValidator.ts (95%) rename src/{utils => startup}/deploySlashCommands.ts (96%) rename src/{utils/other => startup}/postBotStats.ts (97%) rename src/{utils => startup}/registerClientInteractions.ts (98%) rename src/{utils => startup}/registerEventListeners.ts (98%) rename src/{utils/other => startup}/startLoadTest.ts (91%) delete mode 100644 src/utils/other/cookieParser.ts diff --git a/package.json b/package.json index b64e15b..10ff63b 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ }, "scripts": { "start": "node .", - "deploy": "node ./dist/utils/deploySlashCommands.js", + "deploy": "node ./dist/startup/deploySlashCommands.js", "predev": "npx prisma generate && npx prisma db push", "dev": "concurrently --names \"TSC,TOC,BOT\" --prefix-colors \"yellow,blue,green\" \"npx tsc -w\" \"nodemon -w locales/en -x npm run toc\" \"nodemon -x npm run start\"", "eslint": "eslint ./src --fix", @@ -88,4 +88,4 @@ "pino-loki": "^2.2.1", "pino-pretty": "^10.3.1" } -} +} \ No newline at end of file diff --git a/src/bot.ts b/src/bot.ts index 512c42a..c8e3b87 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -6,12 +6,12 @@ import { Player } from 'discord-player'; import { Client } from 'discord.js'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from './services/logger'; +import loggerModule from './common/services/logger'; import { ExtendedClient } from './types/clientTypes'; -import { createClient } from './utils/factory/createClient'; -import { createPlayer } from './utils/factory/createPlayer'; -import { registerClientInteractions } from './utils/registerClientInteractions'; -import { registerEventListeners } from './utils/registerEventListeners'; +import { createClient } from './common/factory/createClient'; +import { createPlayer } from './common/factory/createPlayer'; +import { registerClientInteractions } from './startup/registerClientInteractions'; +import { registerEventListeners } from './startup/registerEventListeners'; const executionId: string = uuidv4(); const logger: Logger = loggerModule.child({ diff --git a/src/classes/interactions.ts b/src/common/classes/interactions.ts similarity index 98% rename from src/classes/interactions.ts rename to src/common/classes/interactions.ts index b169a1c..18297f3 100644 --- a/src/classes/interactions.ts +++ b/src/common/classes/interactions.ts @@ -15,7 +15,7 @@ import { } from 'discord.js'; import { Logger } from 'pino'; import loggerModule from '../services/logger'; -import { BotOptions, EmbedOptions, PlayerOptions } from '../types/configTypes'; +import { BotOptions, EmbedOptions, PlayerOptions } from '../../types/configTypes'; import { BaseAutocompleteParams, BaseAutocompleteReturnType, @@ -24,8 +24,8 @@ import { BaseInteractionParams, BaseSlashCommandParams, BaseSlashCommandReturnType -} from '../types/interactionTypes'; -import { Validator, ValidatorParams } from '../types/utilTypes'; +} from '../../types/interactionTypes'; +import { Validator, ValidatorParams } from '../../types/utilTypes'; import { TFunction } from 'i18next'; abstract class BaseInteraction { diff --git a/src/utils/factory/createClient.ts b/src/common/factory/createClient.ts similarity index 96% rename from src/utils/factory/createClient.ts rename to src/common/factory/createClient.ts index 3e3185f..24436cc 100644 --- a/src/utils/factory/createClient.ts +++ b/src/common/factory/createClient.ts @@ -1,6 +1,6 @@ import Discord, { Client } from 'discord.js'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../services/logger'; export const createClient = async ({ executionId }: { executionId: string }): Promise => { const logger: Logger = loggerModule.child({ diff --git a/src/utils/factory/createPlayer.ts b/src/common/factory/createPlayer.ts similarity index 96% rename from src/utils/factory/createPlayer.ts rename to src/common/factory/createPlayer.ts index 0861795..5e5b393 100644 --- a/src/utils/factory/createPlayer.ts +++ b/src/common/factory/createPlayer.ts @@ -1,7 +1,7 @@ import config from 'config'; import { IPRotationConfig, Player } from 'discord-player'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../services/logger'; import { CreatePlayerParams } from '../../types/playerTypes'; export const createPlayer = async ({ client, executionId }: CreatePlayerParams): Promise => { diff --git a/src/services/guildDatabaseClient.ts b/src/common/services/guildDatabaseClient.ts similarity index 97% rename from src/services/guildDatabaseClient.ts rename to src/common/services/guildDatabaseClient.ts index 9c5e986..419b055 100644 --- a/src/services/guildDatabaseClient.ts +++ b/src/common/services/guildDatabaseClient.ts @@ -1,9 +1,9 @@ -import { getPrismaClient } from './prismaClient'; +import { usePrismaClient } from './prismaClient'; import loggerModule from './logger'; import { Logger } from 'pino'; import { Interaction, MessageComponentInteraction } from 'discord.js'; -const prisma = getPrismaClient(); +const prisma = usePrismaClient(); function getLogger(executionId: string, interaction?: Interaction | MessageComponentInteraction): Logger { return loggerModule.child({ diff --git a/src/services/logger.ts b/src/common/services/logger.ts similarity index 96% rename from src/services/logger.ts rename to src/common/services/logger.ts index eae124e..f10fa75 100644 --- a/src/services/logger.ts +++ b/src/common/services/logger.ts @@ -1,8 +1,8 @@ /* eslint-disable no-console */ import config from 'config'; import pino, { DestinationStream, Logger, LoggerOptions } from 'pino'; -import { CustomLoggerOptions } from '../types/configTypes'; -import { TargetOptions } from '../types/serviceTypes'; +import { CustomLoggerOptions } from '../../types/configTypes'; +import { TargetOptions } from '../../types/serviceTypes'; // Retrieve logger options from config const loggerOptions: CustomLoggerOptions = config.get('loggerOptions'); diff --git a/src/services/prismaClient.ts b/src/common/services/prismaClient.ts similarity index 81% rename from src/services/prismaClient.ts rename to src/common/services/prismaClient.ts index 45ba104..4b67332 100644 --- a/src/services/prismaClient.ts +++ b/src/common/services/prismaClient.ts @@ -2,7 +2,7 @@ import { PrismaClient } from '@prisma/client'; let prisma: PrismaClient | undefined; -export const getPrismaClient = () => { +export const usePrismaClient = () => { if (!prisma) { prisma = new PrismaClient(); } diff --git a/src/common/autocompleteUtils.ts b/src/common/utils/autocompleteUtils.ts similarity index 100% rename from src/common/autocompleteUtils.ts rename to src/common/utils/autocompleteUtils.ts diff --git a/src/common/formattingUtils.ts b/src/common/utils/formattingUtils.ts similarity index 97% rename from src/common/formattingUtils.ts rename to src/common/utils/formattingUtils.ts index 47b33df..b2fbbe8 100644 --- a/src/common/formattingUtils.ts +++ b/src/common/utils/formattingUtils.ts @@ -1,6 +1,6 @@ import { QueueRepeatMode } from 'discord-player'; import { TFunction } from 'i18next'; -import { EmbedOptions } from '../types/configTypes'; +import { EmbedOptions } from '../../types/configTypes'; export function formatDuration(durationMs: number): string { const durationDate: Date = new Date(0); diff --git a/src/utils/system/getUptimeFormatted.ts b/src/common/utils/getUptimeFormatted.ts similarity index 84% rename from src/utils/system/getUptimeFormatted.ts rename to src/common/utils/getUptimeFormatted.ts index f022159..4782d98 100644 --- a/src/utils/system/getUptimeFormatted.ts +++ b/src/common/utils/getUptimeFormatted.ts @@ -1,7 +1,7 @@ import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../services/logger'; import { GetUptimeFormattedParams } from '../../types/utilTypes'; -import { formatDuration } from '../../common/formattingUtils'; +import { formatDuration } from './formattingUtils'; export const getUptimeFormatted = ({ executionId }: GetUptimeFormattedParams): string => { const logger: Logger = loggerModule.child({ diff --git a/src/common/localeUtil.ts b/src/common/utils/localeUtil.ts similarity index 99% rename from src/common/localeUtil.ts rename to src/common/utils/localeUtil.ts index 6dff0a6..03c509f 100644 --- a/src/common/localeUtil.ts +++ b/src/common/utils/localeUtil.ts @@ -13,8 +13,10 @@ import { lstatSync, readdirSync } from 'fs'; import i18n from 'i18next'; import i18nextFsBackend, { FsBackendOptions } from 'i18next-fs-backend'; import { join } from 'path'; + export const translatorInstance = i18n.createInstance(); const localeDir = join(__dirname, '..', '..', 'locales'); + translatorInstance.use(i18nextFsBackend).init({ initImmediate: false, fallbackLng: 'en', diff --git a/src/utils/shardUtils.ts b/src/common/utils/shardUtils.ts similarity index 97% rename from src/utils/shardUtils.ts rename to src/common/utils/shardUtils.ts index 623e842..500e442 100644 --- a/src/utils/shardUtils.ts +++ b/src/common/utils/shardUtils.ts @@ -1,6 +1,6 @@ import { GuildQueueStatisticsMetadata } from 'discord-player'; import { Client, Guild } from 'discord.js'; -import { PlayerStatistics, ShardPlayerStatistics } from '../types/utilTypes'; +import { PlayerStatistics, ShardPlayerStatistics } from '../../types/utilTypes'; async function fetchGuildsPerShard(client?: Client): Promise[]> { if (!client || !client.shard) { diff --git a/src/common/statusUtils.ts b/src/common/utils/statusUtils.ts similarity index 94% rename from src/common/statusUtils.ts rename to src/common/utils/statusUtils.ts index 8a69e9b..f71cd09 100644 --- a/src/common/statusUtils.ts +++ b/src/common/utils/statusUtils.ts @@ -1,7 +1,7 @@ import osu from 'node-os-utils'; -import { ExtendedClient } from '../types/clientTypes'; -import { fetchTotalGuildStatistics, fetchTotalPlayerStatistics } from '../utils/shardUtils'; -import { getUptimeFormatted } from '../utils/system/getUptimeFormatted'; +import { ExtendedClient } from '../../types/clientTypes'; +import { fetchTotalGuildStatistics, fetchTotalPlayerStatistics } from './shardUtils'; +import { getUptimeFormatted } from './getUptimeFormatted'; import { TFunction } from 'i18next'; export async function getBotStatistics( diff --git a/src/utils/validation/permissionValidator.ts b/src/common/validation/permissionValidator.ts similarity index 96% rename from src/utils/validation/permissionValidator.ts rename to src/common/validation/permissionValidator.ts index b1a5997..f12b237 100644 --- a/src/utils/validation/permissionValidator.ts +++ b/src/common/validation/permissionValidator.ts @@ -9,11 +9,11 @@ import { VoiceChannel } from 'discord.js'; import { Logger } from 'pino'; -import { InteractionValidationError } from '../../classes/interactions'; -import loggerModule from '../../services/logger'; +import { InteractionValidationError } from '../classes/interactions'; +import loggerModule from '../services/logger'; import { EmbedOptions } from '../../types/configTypes'; import { ValidatorParams } from '../../types/utilTypes'; -import { useServerTranslator } from '../../common/localeUtil'; +import { useServerTranslator } from '../utils/localeUtil'; const embedOptions: EmbedOptions = config.get('embedOptions'); export const checkVoicePermissionJoinAndTalk = async ({ interaction, executionId }: ValidatorParams) => { diff --git a/src/utils/validation/queueValidator.ts b/src/common/validation/queueValidator.ts similarity index 96% rename from src/utils/validation/queueValidator.ts rename to src/common/validation/queueValidator.ts index ee4068b..487b397 100644 --- a/src/utils/validation/queueValidator.ts +++ b/src/common/validation/queueValidator.ts @@ -1,12 +1,12 @@ import config from 'config'; import { EmbedBuilder, GuildMember, InteractionType } from 'discord.js'; import { Logger } from 'pino'; -import { InteractionValidationError } from '../../classes/interactions'; -import loggerModule from '../../services/logger'; +import { InteractionValidationError } from '../classes/interactions'; +import loggerModule from '../services/logger'; import { EmbedOptions } from '../../types/configTypes'; import { ValidatorParams } from '../../types/utilTypes'; -import { useServerTranslator } from '../../common/localeUtil'; -import { formatSlashCommand } from '../../common/formattingUtils'; +import { useServerTranslator } from '../utils/localeUtil'; +import { formatSlashCommand } from '../utils/formattingUtils'; const embedOptions: EmbedOptions = config.get('embedOptions'); export const checkQueueExists = async ({ interaction, queue, executionId }: ValidatorParams) => { diff --git a/src/utils/validation/searchQueryValidator.ts b/src/common/validation/searchQueryValidator.ts similarity index 97% rename from src/utils/validation/searchQueryValidator.ts rename to src/common/validation/searchQueryValidator.ts index eb5ccaf..2dbe6ab 100644 --- a/src/utils/validation/searchQueryValidator.ts +++ b/src/common/validation/searchQueryValidator.ts @@ -1,5 +1,5 @@ import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../services/logger'; import { TransformQueryParams } from '../../types/utilTypes'; export const transformQuery = ({ query, executionId }: TransformQueryParams) => { diff --git a/src/utils/validation/systemCommandValidator.ts b/src/common/validation/systemCommandValidator.ts similarity index 87% rename from src/utils/validation/systemCommandValidator.ts rename to src/common/validation/systemCommandValidator.ts index 91ad645..e120e96 100644 --- a/src/utils/validation/systemCommandValidator.ts +++ b/src/common/validation/systemCommandValidator.ts @@ -1,12 +1,12 @@ import config from 'config'; import { EmbedBuilder, InteractionType } from 'discord.js'; import { Logger } from 'pino'; -import { InteractionValidationError } from '../../classes/interactions'; -import loggerModule from '../../services/logger'; +import { InteractionValidationError } from '../classes/interactions'; +import loggerModule from '../services/logger'; import { EmbedOptions, SystemOptions } from '../../types/configTypes'; import { ValidatorParams } from '../../types/utilTypes'; -import { useServerTranslator } from '../../common/localeUtil'; -import { formatSlashCommand } from '../../common/formattingUtils'; +import { useServerTranslator } from '../utils/localeUtil'; +import { formatSlashCommand } from '../utils/formattingUtils'; const embedOptions: EmbedOptions = config.get('embedOptions'); const systemOptions: SystemOptions = config.get('systemOptions'); diff --git a/src/utils/validation/voiceChannelValidator.ts b/src/common/validation/voiceChannelValidator.ts similarity index 95% rename from src/utils/validation/voiceChannelValidator.ts rename to src/common/validation/voiceChannelValidator.ts index a2197c3..764ac48 100644 --- a/src/utils/validation/voiceChannelValidator.ts +++ b/src/common/validation/voiceChannelValidator.ts @@ -1,11 +1,11 @@ import config from 'config'; import { EmbedBuilder, GuildMember, InteractionType } from 'discord.js'; import { Logger } from 'pino'; -import { InteractionValidationError } from '../../classes/interactions'; -import loggerModule from '../../services/logger'; +import { InteractionValidationError } from '../classes/interactions'; +import loggerModule from '../services/logger'; import { EmbedOptions } from '../../types/configTypes'; import { ValidatorParams } from '../../types/utilTypes'; -import { useServerTranslator } from '../../common/localeUtil'; +import { useServerTranslator } from '../utils/localeUtil'; const embedOptions: EmbedOptions = config.get('embedOptions'); export const checkInVoiceChannel = async ({ interaction, executionId }: ValidatorParams) => { diff --git a/src/events/client/debug.ts b/src/events/client/debug.ts index b4b3d01..b74c843 100644 --- a/src/events/client/debug.ts +++ b/src/events/client/debug.ts @@ -1,7 +1,7 @@ import { Events } from 'discord.js'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; module.exports = { name: Events.Debug, diff --git a/src/events/client/disconnect.ts b/src/events/client/disconnect.ts index ca36557..aeec562 100644 --- a/src/events/client/disconnect.ts +++ b/src/events/client/disconnect.ts @@ -2,7 +2,7 @@ import config from 'config'; import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; import { ExtendedClient } from '../../types/clientTypes'; import { EmbedOptions, SystemOptions } from '../../types/configTypes'; diff --git a/src/events/client/error.ts b/src/events/client/error.ts index 7e54553..31ba1ef 100644 --- a/src/events/client/error.ts +++ b/src/events/client/error.ts @@ -1,7 +1,7 @@ import { Events } from 'discord.js'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; module.exports = { name: Events.Error, diff --git a/src/events/client/guildCreate.ts b/src/events/client/guildCreate.ts index 7639d93..9c97e28 100644 --- a/src/events/client/guildCreate.ts +++ b/src/events/client/guildCreate.ts @@ -1,7 +1,7 @@ import { Events, Guild } from 'discord.js'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; module.exports = { name: Events.GuildCreate, diff --git a/src/events/client/guildDelete.ts b/src/events/client/guildDelete.ts index 8c4b029..d1d6266 100644 --- a/src/events/client/guildDelete.ts +++ b/src/events/client/guildDelete.ts @@ -1,7 +1,7 @@ import { Events, Guild } from 'discord.js'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; module.exports = { name: Events.GuildDelete, diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index 546f917..526055b 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -2,11 +2,11 @@ import config from 'config'; import { BaseGuildTextChannel, EmbedBuilder, Events, PresenceData } from 'discord.js'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; import { ExtendedClient } from '../../types/clientTypes'; import { EmbedOptions, LoadTestOptions, SystemOptions } from '../../types/configTypes'; -import { postBotStats } from '../../utils/other/postBotStats'; -import { startLoadTest } from '../../utils/other/startLoadTest'; +import { postBotStats } from '../../startup/postBotStats'; +import { startLoadTest } from '../../startup/startLoadTest'; const embedOptions: EmbedOptions = config.get('embedOptions'); const systemOptions: SystemOptions = config.get('systemOptions'); diff --git a/src/events/client/reconnecting.ts b/src/events/client/reconnecting.ts index c3e2658..2e04f22 100644 --- a/src/events/client/reconnecting.ts +++ b/src/events/client/reconnecting.ts @@ -2,7 +2,7 @@ import config from 'config'; import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; import { ExtendedClient } from '../../types/clientTypes'; import { EmbedOptions, SystemOptions } from '../../types/configTypes'; diff --git a/src/events/client/warn.ts b/src/events/client/warn.ts index 30c5bfc..9f13259 100644 --- a/src/events/client/warn.ts +++ b/src/events/client/warn.ts @@ -1,7 +1,7 @@ import { Events } from 'discord.js'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; module.exports = { name: Events.Warn, diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index b64618a..24dfa0b 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -8,12 +8,12 @@ import { } from 'discord.js'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import { CustomError } from '../../classes/interactions'; +import { CustomError } from '../../common/classes/interactions'; 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 loggerModule from '../../common/services/logger'; import { ExtendedClient } from '../../types/clientTypes'; module.exports = { diff --git a/src/events/player/generalDebug.ts b/src/events/player/generalDebug.ts index 7afb6e1..023185b 100644 --- a/src/events/player/generalDebug.ts +++ b/src/events/player/generalDebug.ts @@ -1,6 +1,6 @@ import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; module.exports = { name: 'debug', diff --git a/src/events/player/generalError.ts b/src/events/player/generalError.ts index 6f4d809..84298f3 100644 --- a/src/events/player/generalError.ts +++ b/src/events/player/generalError.ts @@ -2,10 +2,10 @@ import config from 'config'; import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes'; import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; -import { useLanguageTranslator } from '../../common/localeUtil'; +import { useLanguageTranslator } from '../../common/utils/localeUtil'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); diff --git a/src/events/player/playerDebug.ts b/src/events/player/playerDebug.ts index 0764870..edda9e4 100644 --- a/src/events/player/playerDebug.ts +++ b/src/events/player/playerDebug.ts @@ -1,6 +1,6 @@ import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; module.exports = { name: 'error', diff --git a/src/events/player/playerError.ts b/src/events/player/playerError.ts index 42c0f1b..d0d2379 100644 --- a/src/events/player/playerError.ts +++ b/src/events/player/playerError.ts @@ -2,10 +2,10 @@ import config from 'config'; import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes'; import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; -import { useLanguageTranslator } from '../../common/localeUtil'; +import { useLanguageTranslator } from '../../common/utils/localeUtil'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); diff --git a/src/events/player/playerFinish.ts b/src/events/player/playerFinish.ts index 8aa8769..47f7b16 100644 --- a/src/events/player/playerFinish.ts +++ b/src/events/player/playerFinish.ts @@ -1,6 +1,6 @@ import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; import { randomUUID as uuidv4 } from 'node:crypto'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; import { Track } from 'discord-player'; import { Snowflake } from 'discord.js'; import { Logger } from 'pino'; diff --git a/src/events/player/playerSkip.ts b/src/events/player/playerSkip.ts index f140e8c..c17849a 100644 --- a/src/events/player/playerSkip.ts +++ b/src/events/player/playerSkip.ts @@ -3,10 +3,10 @@ import { Track, TrackSkipReason } from 'discord-player'; import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes'; import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; -import { useLanguageTranslator } from '../../common/localeUtil'; +import { useLanguageTranslator } from '../../common/utils/localeUtil'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); diff --git a/src/events/player/playerStart.ts b/src/events/player/playerStart.ts index 5c55f0e..53df3b1 100644 --- a/src/events/player/playerStart.ts +++ b/src/events/player/playerStart.ts @@ -1,9 +1,9 @@ import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; -import { useLanguageTranslator } from '../../common/localeUtil'; +import { useLanguageTranslator } from '../../common/utils/localeUtil'; import { EmbedBuilder, LocaleString } from 'discord.js'; import { EmbedOptions } from '../../types/configTypes'; import { randomUUID as uuidv4 } from 'node:crypto'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; import { Track } from 'discord-player'; import { Logger } from 'pino'; import config from 'config'; diff --git a/src/events/player/willAutoPlay.ts b/src/events/player/willAutoPlay.ts index 2f9a8a8..fcdc8ab 100644 --- a/src/events/player/willAutoPlay.ts +++ b/src/events/player/willAutoPlay.ts @@ -1,7 +1,7 @@ import { Track } from 'discord-player'; import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; import { User } from 'discord.js'; diff --git a/src/events/process/uncaughtException.ts b/src/events/process/uncaughtException.ts index 0a01d55..ec72927 100644 --- a/src/events/process/uncaughtException.ts +++ b/src/events/process/uncaughtException.ts @@ -1,6 +1,6 @@ import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; module.exports = { name: 'uncaughtException', diff --git a/src/events/process/unhandledRejection.ts b/src/events/process/unhandledRejection.ts index d982b94..8ce3c1d 100644 --- a/src/events/process/unhandledRejection.ts +++ b/src/events/process/unhandledRejection.ts @@ -1,6 +1,6 @@ import { randomUUID as uuidv4 } from 'node:crypto'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; +import loggerModule from '../../common/services/logger'; module.exports = { name: 'unhandledRejection', diff --git a/src/handlers/interactionAutocompleteHandler.ts b/src/handlers/interactionAutocompleteHandler.ts index 2030b10..806b906 100644 --- a/src/handlers/interactionAutocompleteHandler.ts +++ b/src/handlers/interactionAutocompleteHandler.ts @@ -1,7 +1,7 @@ import { AutocompleteInteraction } from 'discord.js'; import { Logger } from 'pino'; -import { BaseAutocompleteInteraction } from '../classes/interactions'; -import loggerModule from '../services/logger'; +import { BaseAutocompleteInteraction } from '../common/classes/interactions'; +import loggerModule from '../common/services/logger'; import { ExtendedClient } from '../types/clientTypes'; export const handleAutocomplete = async ( diff --git a/src/handlers/interactionCommandHandler.ts b/src/handlers/interactionCommandHandler.ts index ae8f205..d63ef87 100644 --- a/src/handlers/interactionCommandHandler.ts +++ b/src/handlers/interactionCommandHandler.ts @@ -1,9 +1,9 @@ import { ChatInputCommandInteraction } from 'discord.js'; import { Logger } from 'pino'; -import { BaseSlashCommandInteraction } from '../classes/interactions'; -import loggerModule from '../services/logger'; +import { BaseSlashCommandInteraction } from '../common/classes/interactions'; +import loggerModule from '../common/services/logger'; import { ExtendedClient } from '../types/clientTypes'; -import { checkChannelPermissionViewable } from '../utils/validation/permissionValidator'; +import { checkChannelPermissionViewable } from '../common/validation/permissionValidator'; export const handleCommand = async ( interaction: ChatInputCommandInteraction, diff --git a/src/handlers/interactionComponentHandler.ts b/src/handlers/interactionComponentHandler.ts index 8418e5f..9147faf 100644 --- a/src/handlers/interactionComponentHandler.ts +++ b/src/handlers/interactionComponentHandler.ts @@ -1,9 +1,9 @@ import { MessageComponentInteraction } from 'discord.js'; import { Logger } from 'pino'; -import { BaseComponentInteraction } from '../classes/interactions'; -import loggerModule from '../services/logger'; +import { BaseComponentInteraction } from '../common/classes/interactions'; +import loggerModule from '../common/services/logger'; import { ExtendedClient } from '../types/clientTypes'; -import { checkChannelPermissionViewable } from '../utils/validation/permissionValidator'; +import { checkChannelPermissionViewable } from '../common/validation/permissionValidator'; export const handleComponent = async ( interaction: MessageComponentInteraction, diff --git a/src/handlers/interactionErrorHandler.ts b/src/handlers/interactionErrorHandler.ts index 0ba7c56..7bc5d50 100644 --- a/src/handlers/interactionErrorHandler.ts +++ b/src/handlers/interactionErrorHandler.ts @@ -8,10 +8,10 @@ import { MessageComponentInteraction } from 'discord.js'; import { Logger } from 'pino'; -import { CustomError, InteractionValidationError } from '../classes/interactions'; -import loggerModule from '../services/logger'; +import { CustomError, InteractionValidationError } from '../common/classes/interactions'; +import loggerModule from '../common/services/logger'; import { BotOptions, EmbedOptions } from '../types/configTypes'; -import { useServerTranslator } from '../common/localeUtil'; +import { useServerTranslator } from '../common/utils/localeUtil'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); diff --git a/src/index.ts b/src/index.ts index 00d254a..1e375ab 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,8 +6,8 @@ import { Client, Shard, ShardEvents, ShardingManager, ShardingManagerOptions } f import { randomUUID as uuidv4 } from 'node:crypto'; import { exec } from 'child_process'; import { Logger } from 'pino'; -import loggerModule from './services/logger'; -import { getPrismaClient } from './services/prismaClient'; +import loggerModule from './common/services/logger'; +import { usePrismaClient } from './common/services/prismaClient'; const shardingOptions: ShardingManagerOptions = config.get('shardingOptions'); const manager: ShardingManager = new ShardingManager('./dist/bot.js', { @@ -27,7 +27,7 @@ manager.on('shardCreate', (shard: Shard) => { shardId: 'manager' }); - const prisma = getPrismaClient(); + const prisma = usePrismaClient(); process.on('SIGINT', async () => { await prisma.$disconnect(); diff --git a/src/interactions/autocomplete/lyrics.ts b/src/interactions/autocomplete/lyrics.ts index 5c0a47c..abb9296 100644 --- a/src/interactions/autocomplete/lyrics.ts +++ b/src/interactions/autocomplete/lyrics.ts @@ -2,11 +2,11 @@ import { LyricsData, lyricsExtractor } from '@discord-player/extractor'; import { Player, SearchResult, useMainPlayer } from 'discord-player'; import { ApplicationCommandOptionChoiceData } from 'discord.js'; import { Logger } from 'pino'; -import { BaseAutocompleteInteraction } from '../../classes/interactions'; -import { getTrackName, isQueryTooShort, shouldUseLastQuery } from '../../common/autocompleteUtils'; +import { BaseAutocompleteInteraction } from '../../common/classes/interactions'; +import { getTrackName, isQueryTooShort, shouldUseLastQuery } from '../../common/utils/autocompleteUtils'; import { BaseAutocompleteParams, BaseAutocompleteReturnType, RecentQuery } from '../../types/interactionTypes'; import { TFunction } from 'i18next'; -import { useUserTranslator } from '../../common/localeUtil'; +import { useUserTranslator } from '../../common/utils/localeUtil'; class LyricsAutocomplete extends BaseAutocompleteInteraction { private recentQueries = new Map(); diff --git a/src/interactions/autocomplete/play.ts b/src/interactions/autocomplete/play.ts index 2984af2..e81df59 100644 --- a/src/interactions/autocomplete/play.ts +++ b/src/interactions/autocomplete/play.ts @@ -1,11 +1,11 @@ import { Player, SearchResult, useMainPlayer } from 'discord-player'; import { ApplicationCommandOptionChoiceData } from 'discord.js'; -import { BaseAutocompleteInteraction } from '../../classes/interactions'; -import { getTrackName, isQueryTooShort, shouldUseLastQuery } from '../../common/autocompleteUtils'; +import { BaseAutocompleteInteraction } from '../../common/classes/interactions'; +import { getTrackName, isQueryTooShort, shouldUseLastQuery } from '../../common/utils/autocompleteUtils'; import { BaseAutocompleteParams, BaseAutocompleteReturnType, RecentQuery } from '../../types/interactionTypes'; import { TFunction } from 'i18next'; -import { useUserTranslator } from '../../common/localeUtil'; -import { transformQuery } from '../../utils/validation/searchQueryValidator'; +import { useUserTranslator } from '../../common/utils/localeUtil'; +import { transformQuery } from '../../common/validation/searchQueryValidator'; class PlayAutocomplete extends BaseAutocompleteInteraction { private recentQueries = new Map(); diff --git a/src/interactions/components/action-pauseresume-button.ts b/src/interactions/components/action-pauseresume-button.ts index f0c82c2..4ebe309 100644 --- a/src/interactions/components/action-pauseresume-button.ts +++ b/src/interactions/components/action-pauseresume-button.ts @@ -1,12 +1,12 @@ import { GuildQueue, Track, useQueue } from 'discord-player'; import { EmbedBuilder, MessageComponentInteraction } from 'discord.js'; -import { BaseComponentInteraction } from '../../classes/interactions'; +import { BaseComponentInteraction } from '../../common/classes/interactions'; import { BaseComponentParams, BaseComponentReturnType } from '../../types/interactionTypes'; -import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { checkQueueCurrentTrack, checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; import { TFunction } from 'i18next'; -import { useServerTranslator } from '../../common/localeUtil'; -import { formatRepeatModeDetailed, formatSlashCommand } from '../../common/formattingUtils'; +import { useServerTranslator } from '../../common/utils/localeUtil'; +import { formatRepeatModeDetailed, formatSlashCommand } from '../../common/utils/formattingUtils'; class ActionPauseResumeButton extends BaseComponentInteraction { constructor() { diff --git a/src/interactions/components/action-previous-button.ts b/src/interactions/components/action-previous-button.ts index f2bb339..bf423e2 100644 --- a/src/interactions/components/action-previous-button.ts +++ b/src/interactions/components/action-previous-button.ts @@ -1,13 +1,13 @@ import { GuildQueue, GuildQueueHistory, Track, useHistory, useQueue } from 'discord-player'; import { EmbedBuilder, MessageComponentInteraction } from 'discord.js'; -import { BaseComponentInteraction } from '../../classes/interactions'; +import { BaseComponentInteraction } from '../../common/classes/interactions'; import { BaseComponentParams, BaseComponentReturnType } from '../../types/interactionTypes'; -import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { checkQueueCurrentTrack, checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; import { Logger } from 'pino'; import { TFunction } from 'i18next'; -import { useServerTranslator } from '../../common/localeUtil'; -import { formatSlashCommand } from '../../common/formattingUtils'; +import { useServerTranslator } from '../../common/utils/localeUtil'; +import { formatSlashCommand } from '../../common/utils/formattingUtils'; class ActionPreviousButton extends BaseComponentInteraction { constructor() { diff --git a/src/interactions/components/action-skip-button.ts b/src/interactions/components/action-skip-button.ts index 553328a..9635a83 100644 --- a/src/interactions/components/action-skip-button.ts +++ b/src/interactions/components/action-skip-button.ts @@ -1,12 +1,12 @@ import { GuildQueue, Track, useQueue } from 'discord-player'; import { EmbedBuilder, MessageComponentInteraction } from 'discord.js'; -import { BaseComponentInteraction } from '../../classes/interactions'; +import { BaseComponentInteraction } from '../../common/classes/interactions'; import { BaseComponentParams, BaseComponentReturnType } from '../../types/interactionTypes'; -import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { checkQueueCurrentTrack, checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; import { TFunction } from 'i18next'; -import { useServerTranslator } from '../../common/localeUtil'; -import { formatRepeatModeDetailed, formatSlashCommand } from '../../common/formattingUtils'; +import { useServerTranslator } from '../../common/utils/localeUtil'; +import { formatRepeatModeDetailed, formatSlashCommand } from '../../common/utils/formattingUtils'; class ActionSkipButton extends BaseComponentInteraction { constructor() { diff --git a/src/interactions/components/filters-disable-button.ts b/src/interactions/components/filters-disable-button.ts index 4e29e9c..c710d56 100644 --- a/src/interactions/components/filters-disable-button.ts +++ b/src/interactions/components/filters-disable-button.ts @@ -1,11 +1,11 @@ import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder } from 'discord.js'; import { Logger } from 'pino'; -import { BaseComponentInteraction } from '../../classes/interactions'; +import { BaseComponentInteraction } from '../../common/classes/interactions'; import { BaseComponentParams, BaseComponentReturnType } from '../../types/interactionTypes'; -import { checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { useServerTranslator } from '../../common/localeUtil'; +import { checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { useServerTranslator } from '../../common/utils/localeUtil'; class FiltersDisableButtonComponent extends BaseComponentInteraction { constructor() { diff --git a/src/interactions/components/filters-select-menu.ts b/src/interactions/components/filters-select-menu.ts index b9fd5fb..2d237f5 100644 --- a/src/interactions/components/filters-select-menu.ts +++ b/src/interactions/components/filters-select-menu.ts @@ -2,7 +2,7 @@ import config from 'config'; import { BiquadFilters, EqualizerConfigurationPreset, GuildQueue, QueueFilters, useQueue } from 'discord-player'; import { EmbedBuilder, Message, StringSelectMenuInteraction } from 'discord.js'; import { Logger } from 'pino'; -import { BaseComponentInteraction } from '../../classes/interactions'; +import { BaseComponentInteraction } from '../../common/classes/interactions'; import { EqualizerFilterOptions, BiquadFilterOptions, @@ -10,9 +10,9 @@ import { FilterOption } from '../../types/configTypes'; import { BaseComponentParams, BaseComponentReturnType } from '../../types/interactionTypes'; -import { checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { useServerTranslator } from '../../common/localeUtil'; +import { checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions'); diff --git a/src/interactions/slashcommands/back.ts b/src/interactions/slashcommands/back.ts index 29290e1..74e058b 100644 --- a/src/interactions/slashcommands/back.ts +++ b/src/interactions/slashcommands/back.ts @@ -1,13 +1,13 @@ import { GuildQueue, GuildQueueHistory, Track, useHistory, useQueue } from 'discord-player'; import { ChatInputCommandInteraction, EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkHistoryExists, checkQueueCurrentTrack } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { checkHistoryExists, checkQueueCurrentTrack } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; import { Logger } from 'pino'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; -import { formatSlashCommand } from '../../common/formattingUtils'; +import { formatSlashCommand } from '../../common/utils/formattingUtils'; class BackCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/filters.ts b/src/interactions/slashcommands/filters.ts index bb5b8d0..e7fd27c 100644 --- a/src/interactions/slashcommands/filters.ts +++ b/src/interactions/slashcommands/filters.ts @@ -16,7 +16,7 @@ import { StringSelectMenuOptionBuilder } from 'discord.js'; import { Logger } from 'pino'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BiquadFilterOptions, EqualizerFilterOptions, @@ -24,9 +24,9 @@ import { FilterOption } from '../../types/configTypes'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { checkQueueCurrentTrack, checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions'); diff --git a/src/interactions/slashcommands/help.ts b/src/interactions/slashcommands/help.ts index 14d66e6..c3b8df4 100644 --- a/src/interactions/slashcommands/help.ts +++ b/src/interactions/slashcommands/help.ts @@ -13,9 +13,14 @@ import { SlashCommandNumberOption, SlashCommandStringOption } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { CommandMetadata, localizeCommand, translatorInstance, useServerTranslator } from '../../common/localeUtil'; +import { + CommandMetadata, + localizeCommand, + translatorInstance, + useServerTranslator +} from '../../common/utils/localeUtil'; import { ExtendedClient } from '../../types/clientTypes'; class HelpCommand extends BaseSlashCommandInteraction { diff --git a/src/interactions/slashcommands/history.ts b/src/interactions/slashcommands/history.ts index b812541..ea4abf5 100644 --- a/src/interactions/slashcommands/history.ts +++ b/src/interactions/slashcommands/history.ts @@ -12,13 +12,13 @@ import { SlashCommandBuilder } from 'discord.js'; import { Logger } from 'pino'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkHistoryExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { checkHistoryExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; -import { formatRepeatModeDetailed, formatSlashCommand } from '../../common/formattingUtils'; +import { formatRepeatModeDetailed, formatSlashCommand } from '../../common/utils/formattingUtils'; class HistoryCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/join.ts b/src/interactions/slashcommands/join.ts index 3174d04..847cbac 100644 --- a/src/interactions/slashcommands/join.ts +++ b/src/interactions/slashcommands/join.ts @@ -1,12 +1,12 @@ import { GuildQueue, useMainPlayer, useQueue } from 'discord-player'; import { ChatInputCommandInteraction, EmbedBuilder, GuildMember, Message, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { checkVoicePermissionJoinAndTalk } from '../../utils/validation/permissionValidator'; +import { checkInVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { checkVoicePermissionJoinAndTalk } from '../../common/validation/permissionValidator'; import { Logger } from 'pino'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; -import { formatSlashCommand } from '../../common/formattingUtils'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; +import { formatSlashCommand } from '../../common/utils/formattingUtils'; import { TFunction } from 'i18next'; class JoinCommand extends BaseSlashCommandInteraction { diff --git a/src/interactions/slashcommands/leave.ts b/src/interactions/slashcommands/leave.ts index bfa410f..985a181 100644 --- a/src/interactions/slashcommands/leave.ts +++ b/src/interactions/slashcommands/leave.ts @@ -1,11 +1,11 @@ import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; -import { formatSlashCommand } from '../../common/formattingUtils'; +import { checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; +import { formatSlashCommand } from '../../common/utils/formattingUtils'; class LeaveCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/loop.ts b/src/interactions/slashcommands/loop.ts index 9702e3e..a526a3f 100644 --- a/src/interactions/slashcommands/loop.ts +++ b/src/interactions/slashcommands/loop.ts @@ -7,13 +7,13 @@ import { SlashCommandIntegerOption } from 'discord.js'; import { Logger } from 'pino'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; -import { formatRepeatMode } from '../../common/formattingUtils'; +import { formatRepeatMode } from '../../common/utils/formattingUtils'; class LoopCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/lyrics.ts b/src/interactions/slashcommands/lyrics.ts index 8f795c8..0d87da3 100644 --- a/src/interactions/slashcommands/lyrics.ts +++ b/src/interactions/slashcommands/lyrics.ts @@ -2,11 +2,11 @@ import { LyricsData, lyricsExtractor } from '@discord-player/extractor'; import { GuildQueue, Player, QueryType, SearchResult, Track, useMainPlayer, useQueue } from 'discord-player'; import { ChatInputCommandInteraction, EmbedBuilder, Message, SlashCommandBuilder } from 'discord.js'; import { Logger } from 'pino'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { checkQueueCurrentTrack, checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; class LyricsCommand extends BaseSlashCommandInteraction { diff --git a/src/interactions/slashcommands/move.ts b/src/interactions/slashcommands/move.ts index 456d65e..e5da5d0 100644 --- a/src/interactions/slashcommands/move.ts +++ b/src/interactions/slashcommands/move.ts @@ -1,13 +1,13 @@ import { GuildQueue, Track, useQueue } from 'discord-player'; import { ChatInputCommandInteraction, EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { checkQueueCurrentTrack, checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; import { Logger } from 'pino'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; -import { formatSlashCommand } from '../../common/formattingUtils'; +import { formatSlashCommand } from '../../common/utils/formattingUtils'; class MoveCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/nowplaying.ts b/src/interactions/slashcommands/nowplaying.ts index 93db9b8..1d8988c 100644 --- a/src/interactions/slashcommands/nowplaying.ts +++ b/src/interactions/slashcommands/nowplaying.ts @@ -10,13 +10,13 @@ import { EmbedField, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType, TrackMetadata } from '../../types/interactionTypes'; -import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { checkQueueCurrentTrack, checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; -import { formatRepeatModeDetailed } from '../../common/formattingUtils'; +import { formatRepeatModeDetailed } from '../../common/utils/formattingUtils'; class NowPlayingCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/pause.ts b/src/interactions/slashcommands/pause.ts index e43f9f9..da0a867 100644 --- a/src/interactions/slashcommands/pause.ts +++ b/src/interactions/slashcommands/pause.ts @@ -1,11 +1,11 @@ import { GuildQueue, Track, useQueue } from 'discord-player'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { Logger } from 'pino'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { checkQueueCurrentTrack, checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; class PauseCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/play.ts b/src/interactions/slashcommands/play.ts index 792ee3b..20cd9ff 100644 --- a/src/interactions/slashcommands/play.ts +++ b/src/interactions/slashcommands/play.ts @@ -8,14 +8,14 @@ import { SlashCommandBuilder } from 'discord.js'; import { Logger } from 'pino'; -import { BaseSlashCommandInteraction, CustomError } from '../../classes/interactions'; +import { BaseSlashCommandInteraction, CustomError } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkVoicePermissionJoinAndTalk } from '../../utils/validation/permissionValidator'; -import { transformQuery } from '../../utils/validation/searchQueryValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { checkVoicePermissionJoinAndTalk } from '../../common/validation/permissionValidator'; +import { transformQuery } from '../../common/validation/searchQueryValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; -import { formatSlashCommand } from '../../common/formattingUtils'; +import { formatSlashCommand } from '../../common/utils/formattingUtils'; class PlayCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/queue.ts b/src/interactions/slashcommands/queue.ts index 27a3c7e..1abb3b7 100644 --- a/src/interactions/slashcommands/queue.ts +++ b/src/interactions/slashcommands/queue.ts @@ -12,12 +12,12 @@ import { SlashCommandBuilder } from 'discord.js'; import { Logger } from 'pino'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { formatDuration, formatRepeatModeDetailed, formatSlashCommand } from '../../common/formattingUtils'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { formatDuration, formatRepeatModeDetailed, formatSlashCommand } from '../../common/utils/formattingUtils'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; class QueueCommand extends BaseSlashCommandInteraction { diff --git a/src/interactions/slashcommands/reload.ts b/src/interactions/slashcommands/reload.ts index c109992..896ed39 100644 --- a/src/interactions/slashcommands/reload.ts +++ b/src/interactions/slashcommands/reload.ts @@ -6,11 +6,11 @@ import { SlashCommandBuilder } from 'discord.js'; import { Logger } from 'pino'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { ExtendedClient } from '../../types/clientTypes'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkValidGuildId } from '../../utils/validation/systemCommandValidator'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { checkValidGuildId } from '../../common/validation/systemCommandValidator'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; class ReloadCommand extends BaseSlashCommandInteraction { diff --git a/src/interactions/slashcommands/remove.ts b/src/interactions/slashcommands/remove.ts index 9d1fcc9..a085007 100644 --- a/src/interactions/slashcommands/remove.ts +++ b/src/interactions/slashcommands/remove.ts @@ -1,13 +1,13 @@ import { GuildQueue, Track, useQueue } from 'discord-player'; import { ChatInputCommandInteraction, EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; import { Logger } from 'pino'; import { TFunction } from 'i18next'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; -import { formatSlashCommand } from '../../common/formattingUtils'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; +import { formatSlashCommand } from '../../common/utils/formattingUtils'; class RemoveCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/seek.ts b/src/interactions/slashcommands/seek.ts index 362c795..997d6f2 100644 --- a/src/interactions/slashcommands/seek.ts +++ b/src/interactions/slashcommands/seek.ts @@ -1,13 +1,13 @@ import { GuildQueue, useQueue } from 'discord-player'; import { ChatInputCommandInteraction, EmbedBuilder, Message, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { checkQueueCurrentTrack, checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; import { Logger } from 'pino'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; -import { formatSlashCommand } from '../../common/formattingUtils'; +import { formatSlashCommand } from '../../common/utils/formattingUtils'; class SeekCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/settings.ts b/src/interactions/slashcommands/settings.ts index 74db59c..8d71117 100644 --- a/src/interactions/slashcommands/settings.ts +++ b/src/interactions/slashcommands/settings.ts @@ -1,10 +1,10 @@ import { EmbedBuilder, SlashCommandBuilder, PermissionFlagsBits, ChatInputCommandInteraction } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { Logger } from 'pino'; import { TFunction } from 'i18next'; -import guildDatabaseClient from '../../services/guildDatabaseClient'; +import guildDatabaseClient from '../../common/services/guildDatabaseClient'; class SettingsCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/shards.ts b/src/interactions/slashcommands/shards.ts index 30bb2ee..2183db1 100644 --- a/src/interactions/slashcommands/shards.ts +++ b/src/interactions/slashcommands/shards.ts @@ -5,12 +5,12 @@ import { EmbedFooterData, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { ExtendedClient } from '../../types/clientTypes'; import { BaseSlashCommandParams, BaseSlashCommandReturnType, ShardInfo } from '../../types/interactionTypes'; -import { checkValidGuildId } from '../../utils/validation/systemCommandValidator'; +import { checkValidGuildId } from '../../common/validation/systemCommandValidator'; import { Logger } from 'pino'; -import { localizeCommand } from '../../common/localeUtil'; +import { localizeCommand } from '../../common/utils/localeUtil'; class ShardsCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/shuffle.ts b/src/interactions/slashcommands/shuffle.ts index 8520d36..15ec8ed 100644 --- a/src/interactions/slashcommands/shuffle.ts +++ b/src/interactions/slashcommands/shuffle.ts @@ -1,11 +1,11 @@ import { GuildQueue, useQueue } from 'discord-player'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkQueueEmpty, checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; -import { formatSlashCommand } from '../../common/formattingUtils'; +import { checkQueueEmpty, checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; +import { formatSlashCommand } from '../../common/utils/formattingUtils'; class ShuffleCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/skip.ts b/src/interactions/slashcommands/skip.ts index 32a7f33..1520593 100644 --- a/src/interactions/slashcommands/skip.ts +++ b/src/interactions/slashcommands/skip.ts @@ -1,13 +1,13 @@ import { GuildQueue, Track, useQueue } from 'discord-player'; import { ChatInputCommandInteraction, EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { checkQueueCurrentTrack, checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; import { Logger } from 'pino'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; -import { formatRepeatModeDetailed, formatSlashCommand } from '../../common/formattingUtils'; +import { formatRepeatModeDetailed, formatSlashCommand } from '../../common/utils/formattingUtils'; class SkipCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/status.ts b/src/interactions/slashcommands/status.ts index 5d1d514..338d9da 100644 --- a/src/interactions/slashcommands/status.ts +++ b/src/interactions/slashcommands/status.ts @@ -10,10 +10,15 @@ import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; -import { getBotStatistics, getDiscordStatus, getPlayerStatistics, getSystemStatus } from '../../common/statusUtils'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; +import { + getBotStatistics, + getDiscordStatus, + getPlayerStatistics, + getSystemStatus +} from '../../common/utils/statusUtils'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; class StatusCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/stop.ts b/src/interactions/slashcommands/stop.ts index 355ed07..4c99128 100644 --- a/src/interactions/slashcommands/stop.ts +++ b/src/interactions/slashcommands/stop.ts @@ -1,11 +1,11 @@ import { GuildQueue, QueueRepeatMode, useQueue } from 'discord-player'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; -import { formatSlashCommand } from '../../common/formattingUtils'; +import { checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; +import { formatSlashCommand } from '../../common/utils/formattingUtils'; class StopCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/systemstatus.ts b/src/interactions/slashcommands/systemstatus.ts index e148bec..7096a7b 100644 --- a/src/interactions/slashcommands/systemstatus.ts +++ b/src/interactions/slashcommands/systemstatus.ts @@ -1,11 +1,16 @@ // @ts-ignore import { dependencies, version } from '../../../package.json'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; -import { getBotStatistics, getDiscordStatus, getPlayerStatistics, getSystemStatus } from '../../common/statusUtils'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; +import { + getBotStatistics, + getDiscordStatus, + getPlayerStatistics, + getSystemStatus +} from '../../common/utils/statusUtils'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkValidGuildId } from '../../utils/validation/systemCommandValidator'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { checkValidGuildId } from '../../common/validation/systemCommandValidator'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; class SystemStatusCommand extends BaseSlashCommandInteraction { constructor() { diff --git a/src/interactions/slashcommands/volume.ts b/src/interactions/slashcommands/volume.ts index 3c8307d..af3f612 100644 --- a/src/interactions/slashcommands/volume.ts +++ b/src/interactions/slashcommands/volume.ts @@ -1,11 +1,11 @@ import { GuildQueue, useQueue } from 'discord-player'; import { ChatInputCommandInteraction, EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../classes/interactions'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { checkQueueExists } from '../../utils/validation/queueValidator'; -import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { checkQueueExists } from '../../common/validation/queueValidator'; +import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; import { Logger } from 'pino'; -import { localizeCommand, useServerTranslator } from '../../common/localeUtil'; +import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; import { TFunction } from 'i18next'; class VolumeCommand extends BaseSlashCommandInteraction { diff --git a/src/utils/deploySlashCommands.ts b/src/startup/deploySlashCommands.ts similarity index 96% rename from src/utils/deploySlashCommands.ts rename to src/startup/deploySlashCommands.ts index 77dff7e..f2037aa 100644 --- a/src/utils/deploySlashCommands.ts +++ b/src/startup/deploySlashCommands.ts @@ -5,8 +5,8 @@ import { randomUUID as uuidv4 } from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { Logger } from 'pino'; -import { BaseSlashCommandInteraction } from '../classes/interactions'; -import loggerModule from '../services/logger'; +import { BaseSlashCommandInteraction } from '../common/classes/interactions'; +import loggerModule from '../common/services/logger'; import { SystemOptions } from '../types/configTypes'; const systemOptions: SystemOptions = config.get('systemOptions'); diff --git a/src/utils/other/postBotStats.ts b/src/startup/postBotStats.ts similarity index 97% rename from src/utils/other/postBotStats.ts rename to src/startup/postBotStats.ts index 271f207..b1febbb 100644 --- a/src/utils/other/postBotStats.ts +++ b/src/startup/postBotStats.ts @@ -2,9 +2,9 @@ import { Client } from 'discord.js'; import { ClientRequest, ClientRequestArgs, IncomingMessage } from 'node:http'; import https from 'node:https'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; -import { PostBotStatsParams, PostBotStatsSite } from '../../types/utilTypes'; -import { fetchTotalGuildStatistics } from '../shardUtils'; +import loggerModule from '../common/services/logger'; +import { PostBotStatsParams, PostBotStatsSite } from '../types/utilTypes'; +import { fetchTotalGuildStatistics } from '../common/utils/shardUtils'; export const postBotStats = async ({ client, executionId }: PostBotStatsParams) => { const logger: Logger = loggerModule.child({ diff --git a/src/utils/registerClientInteractions.ts b/src/startup/registerClientInteractions.ts similarity index 98% rename from src/utils/registerClientInteractions.ts rename to src/startup/registerClientInteractions.ts index 149a3b2..ef702c7 100644 --- a/src/utils/registerClientInteractions.ts +++ b/src/startup/registerClientInteractions.ts @@ -2,7 +2,7 @@ import { Collection } from 'discord.js'; import fs from 'node:fs'; import path from 'node:path'; import { Logger } from 'pino'; -import loggerModule from '../services/logger'; +import loggerModule from '../common/services/logger'; import { ExtendedClient } from '../types/clientTypes'; import { RegisterClientInteractionsParams } from '../types/utilTypes'; diff --git a/src/utils/registerEventListeners.ts b/src/startup/registerEventListeners.ts similarity index 98% rename from src/utils/registerEventListeners.ts rename to src/startup/registerEventListeners.ts index aac0226..b2fed06 100644 --- a/src/utils/registerEventListeners.ts +++ b/src/startup/registerEventListeners.ts @@ -4,7 +4,7 @@ import { Client } from 'discord.js'; import fs from 'node:fs'; import path from 'node:path'; import { Logger } from 'pino'; -import loggerModule from '../services/logger'; +import loggerModule from '../common/services/logger'; import { CustomLoggerOptions } from '../types/configTypes'; import { ClientEventArguments, PlayerEventArguments, ProcessEventArguments } from '../types/eventTypes'; import { CustomEvent, RegisterEventListenersParams } from '../types/utilTypes'; diff --git a/src/utils/other/startLoadTest.ts b/src/startup/startLoadTest.ts similarity index 91% rename from src/utils/other/startLoadTest.ts rename to src/startup/startLoadTest.ts index 23952bd..75d7900 100644 --- a/src/utils/other/startLoadTest.ts +++ b/src/startup/startLoadTest.ts @@ -1,9 +1,9 @@ import config from 'config'; import { Channel, Client } from 'discord.js'; import { Logger } from 'pino'; -import loggerModule from '../../services/logger'; -import { LoadTestOptions } from '../../types/configTypes'; -import { StartLoadTestParams } from '../../types/utilTypes'; +import loggerModule from '../common/services/logger'; +import { LoadTestOptions } from '../types/configTypes'; +import { StartLoadTestParams } from '../types/utilTypes'; const loadTestOptions: LoadTestOptions = config.get('loadTestOptions'); diff --git a/src/tests/help.test.ts b/src/tests/help.test.ts index a74f1fa..ac230f8 100644 --- a/src/tests/help.test.ts +++ b/src/tests/help.test.ts @@ -1,6 +1,6 @@ import helpCommand from '../interactions/slashcommands/help'; import { SlashCommandNumberOption } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../classes/interactions'; +import { BaseSlashCommandInteraction } from '../common/classes/interactions'; describe('HelpCommand', () => { describe('getCommandParams', () => { diff --git a/src/tests/validation.test.ts b/src/tests/validation.test.ts index 0f50e04..4f9394e 100644 --- a/src/tests/validation.test.ts +++ b/src/tests/validation.test.ts @@ -1,4 +1,4 @@ -import { transformQuery } from '../utils/validation/searchQueryValidator'; +import { transformQuery } from '../common/validation/searchQueryValidator'; describe('searchQueryValidator', () => { it.each(['us', 'nb', 'intl', 'en-us', 'long-code'])( diff --git a/src/types/clientTypes.d.ts b/src/types/clientTypes.d.ts index 01281e0..99a5919 100644 --- a/src/types/clientTypes.d.ts +++ b/src/types/clientTypes.d.ts @@ -3,7 +3,7 @@ import { BaseAutocompleteInteraction, BaseComponentInteraction, BaseSlashCommandInteraction -} from '../classes/interactions'; +} from '../common/classes/interactions'; type RegisterClientInteractionsFunction = (params: { client: Client; executionId: string }) => void; diff --git a/src/utils/other/cookieParser.ts b/src/utils/other/cookieParser.ts deleted file mode 100644 index ff4f474..0000000 --- a/src/utils/other/cookieParser.ts +++ /dev/null @@ -1,19 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; - -/* eslint-disable @typescript-eslint/no-var-requires */ -const cookies: { name: string; value: string }[] = require(path.resolve('./cookies.json')); - -try { - const cookieString: string = cookies - .map(({ name, value }: { name: string; value: string }) => { - return `${name}=${value}`; - }) - .join('; '); - - fs.writeFile(path.resolve('./cookies.txt'), cookieString, () => { - return process.exit(0); - }); -} catch (error) { - process.exit(1); -} From 374c85f9a7be181260f3e6373b3286cde3ef333e Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 30 Jan 2024 16:52:23 +0100 Subject: [PATCH 09/15] update locales folder path in util --- src/common/utils/localeUtil.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/common/utils/localeUtil.ts b/src/common/utils/localeUtil.ts index 03c509f..cfe6f98 100644 --- a/src/common/utils/localeUtil.ts +++ b/src/common/utils/localeUtil.ts @@ -15,7 +15,7 @@ import i18nextFsBackend, { FsBackendOptions } from 'i18next-fs-backend'; import { join } from 'path'; export const translatorInstance = i18n.createInstance(); -const localeDir = join(__dirname, '..', '..', 'locales'); +const localeDir = join(__dirname, '..', '..', '..', 'locales'); translatorInstance.use(i18nextFsBackend).init({ initImmediate: false, From a7aefd085f33b59cbe17ea7e49a5a2b05b443673 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 30 Jan 2024 16:52:40 +0100 Subject: [PATCH 10/15] update tests folder structure to match files tested --- src/tests/{ => common/validation}/validation.test.ts | 2 +- src/tests/{ => interactions/slashcommands}/help.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) rename src/tests/{ => common/validation}/validation.test.ts (96%) rename src/tests/{ => interactions/slashcommands}/help.test.ts (88%) diff --git a/src/tests/validation.test.ts b/src/tests/common/validation/validation.test.ts similarity index 96% rename from src/tests/validation.test.ts rename to src/tests/common/validation/validation.test.ts index 4f9394e..bbe842b 100644 --- a/src/tests/validation.test.ts +++ b/src/tests/common/validation/validation.test.ts @@ -1,4 +1,4 @@ -import { transformQuery } from '../common/validation/searchQueryValidator'; +import { transformQuery } from '../../../common/validation/searchQueryValidator'; describe('searchQueryValidator', () => { it.each(['us', 'nb', 'intl', 'en-us', 'long-code'])( diff --git a/src/tests/help.test.ts b/src/tests/interactions/slashcommands/help.test.ts similarity index 88% rename from src/tests/help.test.ts rename to src/tests/interactions/slashcommands/help.test.ts index ac230f8..dc32f7e 100644 --- a/src/tests/help.test.ts +++ b/src/tests/interactions/slashcommands/help.test.ts @@ -1,6 +1,6 @@ -import helpCommand from '../interactions/slashcommands/help'; +import helpCommand from '../../../interactions/slashcommands/help'; import { SlashCommandNumberOption } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../common/classes/interactions'; +import { BaseSlashCommandInteraction } from '../../../common/classes/interactions'; describe('HelpCommand', () => { describe('getCommandParams', () => { From f3329fceee42152ac5cafa93af52f16a94c2f162 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 30 Jan 2024 19:21:42 +0100 Subject: [PATCH 11/15] Move deferring into the specific interactions where required. Makes especially validation warnings ephemeral. --- src/common/validation/permissionValidator.ts | 54 +++++++++---------- src/common/validation/queueValidator.ts | 20 ++++--- .../validation/systemCommandValidator.ts | 5 +- .../validation/voiceChannelValidator.ts | 10 ++-- src/handlers/interactionCommandHandler.ts | 3 -- src/handlers/interactionComponentHandler.ts | 3 -- .../components/action-pauseresume-button.ts | 29 ++-------- .../components/action-previous-button.ts | 27 ++-------- .../components/action-skip-button.ts | 29 ++-------- .../components/filters-disable-button.ts | 2 +- .../components/filters-select-menu.ts | 16 +++--- src/interactions/slashcommands/back.ts | 12 +++-- src/interactions/slashcommands/filters.ts | 3 ++ src/interactions/slashcommands/help.ts | 2 +- src/interactions/slashcommands/history.ts | 12 +++-- src/interactions/slashcommands/join.ts | 3 ++ src/interactions/slashcommands/leave.ts | 3 ++ src/interactions/slashcommands/loop.ts | 17 +++--- src/interactions/slashcommands/lyrics.ts | 3 ++ src/interactions/slashcommands/move.ts | 7 +-- src/interactions/slashcommands/nowplaying.ts | 2 +- src/interactions/slashcommands/pause.ts | 2 +- src/interactions/slashcommands/play.ts | 3 ++ src/interactions/slashcommands/queue.ts | 12 +++-- src/interactions/slashcommands/reload.ts | 3 ++ src/interactions/slashcommands/remove.ts | 19 ++++--- src/interactions/slashcommands/seek.ts | 3 ++ src/interactions/slashcommands/settings.ts | 3 ++ src/interactions/slashcommands/shards.ts | 3 ++ src/interactions/slashcommands/shuffle.ts | 2 +- src/interactions/slashcommands/skip.ts | 12 +++-- src/interactions/slashcommands/status.ts | 3 ++ src/interactions/slashcommands/stop.ts | 2 +- .../slashcommands/systemstatus.ts | 3 ++ src/interactions/slashcommands/volume.ts | 3 ++ src/types/interactionTypes.d.ts | 4 +- 36 files changed, 164 insertions(+), 175 deletions(-) diff --git a/src/common/validation/permissionValidator.ts b/src/common/validation/permissionValidator.ts index f12b237..51e7328 100644 --- a/src/common/validation/permissionValidator.ts +++ b/src/common/validation/permissionValidator.ts @@ -32,7 +32,7 @@ export const checkVoicePermissionJoinAndTalk = async ({ interaction, executionId interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; if (channel instanceof VoiceChannel && (!channel.joinable || !channel.speakable)) { - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -49,7 +49,8 @@ export const checkVoicePermissionJoinAndTalk = async ({ interaction, executionId : interaction.user.username, iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl }) - ] + ], + ephemeral: true }); logger.debug( @@ -83,34 +84,29 @@ export const checkChannelPermissionViewable = async ({ interaction, executionId ); 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.' - ); - await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - translator('validation.cannotSendMessageInChannel', { - icon: embedOptions.icons.warning, - channel: `<#${channel.id}>` - }) - ) - .setColor(embedOptions.colors.warning) - .setFooter({ - text: - interaction.member instanceof GuildMember - ? interaction.member.nickname || interaction.user.username - : interaction.user.username, - iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + logger.debug( + 'Sending ephemeral message in channel about insufficient permissions to send message in channel.' + ); + await interaction.reply({ + embeds: [ + new EmbedBuilder() + .setDescription( + translator('validation.cannotSendMessageInChannel', { + icon: embedOptions.icons.warning, + channel: `<#${channel.id}>` }) - ] - }); - } + ) + .setColor(embedOptions.colors.warning) + .setFooter({ + text: + interaction.member instanceof GuildMember + ? interaction.member.nickname || interaction.user.username + : interaction.user.username, + iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl + }) + ], + ephemeral: true + }); } catch (error) { if (error instanceof Error) { if (error.message == 'The reply to this interaction has already been sent or deferred.') { diff --git a/src/common/validation/queueValidator.ts b/src/common/validation/queueValidator.ts index 487b397..fd03746 100644 --- a/src/common/validation/queueValidator.ts +++ b/src/common/validation/queueValidator.ts @@ -23,7 +23,7 @@ export const checkQueueExists = async ({ interaction, queue, executionId }: Vali interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; if (!queue) { - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -40,7 +40,8 @@ export const checkQueueExists = async ({ interaction, queue, executionId }: Vali : interaction.user.username, iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl }) - ] + ], + ephemeral: true }); logger.debug(`User tried to use command '${interactionIdentifier}' but there was no queue.`); @@ -64,7 +65,7 @@ export const checkHistoryExists = async ({ interaction, history, executionId }: interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; if (!history) { - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -81,7 +82,8 @@ export const checkHistoryExists = async ({ interaction, history, executionId }: : interaction.user.username, iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl }) - ] + ], + ephemeral: true }); logger.debug(`User tried to use command '${interactionIdentifier}' but there was no history.`); @@ -105,7 +107,7 @@ export const checkQueueCurrentTrack = async ({ interaction, queue, executionId } interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; if (queue && !queue.currentTrack) { - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -122,7 +124,8 @@ export const checkQueueCurrentTrack = async ({ interaction, queue, executionId } : interaction.user.username, iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl }) - ] + ], + ephemeral: true }); logger.debug(`User tried to use command '${interactionIdentifier}' but there was no current track.`); @@ -146,7 +149,7 @@ export const checkQueueEmpty = async ({ interaction, queue, executionId }: Valid interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; if (queue && queue.tracks.data.length === 0) { - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -163,7 +166,8 @@ export const checkQueueEmpty = async ({ interaction, queue, executionId }: Valid : interaction.user.username, iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl }) - ] + ], + ephemeral: true }); logger.debug(`User tried to use command '${interactionIdentifier}' but there was no tracks in the queue.`); diff --git a/src/common/validation/systemCommandValidator.ts b/src/common/validation/systemCommandValidator.ts index e120e96..d65763d 100644 --- a/src/common/validation/systemCommandValidator.ts +++ b/src/common/validation/systemCommandValidator.ts @@ -24,7 +24,7 @@ export const checkValidGuildId = async ({ interaction, executionId }: ValidatorP interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; if (interaction.guildId && !systemOptions.systemGuildIds.includes(interaction.guildId)) { - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -34,7 +34,8 @@ export const checkValidGuildId = async ({ interaction, executionId }: ValidatorP }) ) .setColor(embedOptions.colors.warning) - ] + ], + ephemeral: true }); logger.debug( diff --git a/src/common/validation/voiceChannelValidator.ts b/src/common/validation/voiceChannelValidator.ts index 764ac48..799f282 100644 --- a/src/common/validation/voiceChannelValidator.ts +++ b/src/common/validation/voiceChannelValidator.ts @@ -22,7 +22,7 @@ export const checkInVoiceChannel = async ({ interaction, executionId }: Validato interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId; if (interaction.member instanceof GuildMember && !interaction.member.voice.channel) { - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -35,7 +35,8 @@ export const checkInVoiceChannel = async ({ interaction, executionId }: Validato text: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl }) - ] + ], + ephemeral: true }); logger.debug(`User tried to use command '${interactionIdentifier}' but was not in a voice channel.`); @@ -67,7 +68,7 @@ export const checkSameVoiceChannel = async ({ interaction, queue, executionId }: interaction.member instanceof GuildMember && interaction.member.voice.channel?.id !== queue.dispatcher.channel.id ) { - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -81,7 +82,8 @@ export const checkSameVoiceChannel = async ({ interaction, queue, executionId }: text: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl }) - ] + ], + ephemeral: true }); logger.debug(`User tried to use command '${interactionIdentifier}' but was not in the same voice channel.`); diff --git a/src/handlers/interactionCommandHandler.ts b/src/handlers/interactionCommandHandler.ts index d63ef87..78d6e9c 100644 --- a/src/handlers/interactionCommandHandler.ts +++ b/src/handlers/interactionCommandHandler.ts @@ -17,9 +17,6 @@ export const handleCommand = async ( executionId: executionId }); - await interaction.deferReply(); - logger.debug('Interaction deferred.'); - await checkChannelPermissionViewable({ interaction, executionId }); const slashCommand: BaseSlashCommandInteraction = client.slashCommandInteractions!.get( diff --git a/src/handlers/interactionComponentHandler.ts b/src/handlers/interactionComponentHandler.ts index 9147faf..1013ed0 100644 --- a/src/handlers/interactionComponentHandler.ts +++ b/src/handlers/interactionComponentHandler.ts @@ -17,9 +17,6 @@ export const handleComponent = async ( executionId: executionId }); - await interaction.deferReply(); - logger.debug('Interaction deferred.'); - const componentId: string = interactionIdentifier.split('_')[0]; const referenceId: string = interactionIdentifier.split('_')[1]; diff --git a/src/interactions/components/action-pauseresume-button.ts b/src/interactions/components/action-pauseresume-button.ts index 4ebe309..e2b1ad6 100644 --- a/src/interactions/components/action-pauseresume-button.ts +++ b/src/interactions/components/action-pauseresume-button.ts @@ -6,7 +6,7 @@ import { checkQueueCurrentTrack, checkQueueExists } from '../../common/validatio import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; import { TFunction } from 'i18next'; import { useServerTranslator } from '../../common/utils/localeUtil'; -import { formatRepeatModeDetailed, formatSlashCommand } from '../../common/utils/formattingUtils'; +import { formatRepeatModeDetailed } from '../../common/utils/formattingUtils'; class ActionPauseResumeButton extends BaseComponentInteraction { constructor() { @@ -27,10 +27,6 @@ class ActionPauseResumeButton extends BaseComponentInteraction { checkQueueCurrentTrack ]); - if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { - return await this.handleNoQueue(interaction, translator); - } - if (queue.currentTrack!.id !== referenceId) { return await this.handleAlreadySkipped(interaction, translator); } @@ -48,24 +44,8 @@ class ActionPauseResumeButton extends BaseComponentInteraction { return await this.handleSuccess(interaction, currentTrack, queue, translator); } - private async handleNoQueue(interaction: MessageComponentInteraction, translator: TFunction) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - translator('validation.queueNoCurrentTrack', { - icon: this.embedOptions.icons.warning, - playCommand: formatSlashCommand('play', translator) - }) - ) - .setColor(this.embedOptions.colors.warning) - ], - components: [] - }); - } - private async handleAlreadySkipped(interaction: MessageComponentInteraction, translator: TFunction) { - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -75,7 +55,8 @@ class ActionPauseResumeButton extends BaseComponentInteraction { ) .setColor(this.embedOptions.colors.warning) ], - components: [] + components: [], + ephemeral: true }); } @@ -98,7 +79,7 @@ class ActionPauseResumeButton extends BaseComponentInteraction { .setThumbnail(track.thumbnail) .setColor(this.embedOptions.colors.success); - return await interaction.editReply({ + return await interaction.reply({ embeds: [successEmbed], components: [] }); diff --git a/src/interactions/components/action-previous-button.ts b/src/interactions/components/action-previous-button.ts index bf423e2..87d2260 100644 --- a/src/interactions/components/action-previous-button.ts +++ b/src/interactions/components/action-previous-button.ts @@ -29,10 +29,6 @@ class ActionPreviousButton extends BaseComponentInteraction { checkQueueCurrentTrack ]); - if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { - return await this.handleNoQueue(interaction, translator); - } - if (queue.currentTrack!.id !== referenceId) { return await this.handleAlreadySkipped(interaction, translator); } @@ -76,24 +72,8 @@ class ActionPreviousButton extends BaseComponentInteraction { }); } - private async handleNoQueue(interaction: MessageComponentInteraction, translator: TFunction) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - translator('validation.queueNoCurrentTrack', { - icon: this.embedOptions.icons.warning, - playCommand: formatSlashCommand('play', translator) - }) - ) - .setColor(this.embedOptions.colors.warning) - ], - components: [] - }); - } - private async handleAlreadySkipped(interaction: MessageComponentInteraction, translator: TFunction) { - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -103,7 +83,8 @@ class ActionPreviousButton extends BaseComponentInteraction { ) .setColor(this.embedOptions.colors.warning) ], - components: [] + components: [], + ephemeral: true }); } @@ -123,7 +104,7 @@ class ActionPreviousButton extends BaseComponentInteraction { .setThumbnail(recoveredTrack.thumbnail) .setColor(this.embedOptions.colors.success); - return await interaction.editReply({ + return await interaction.reply({ embeds: [successEmbed], components: [] }); diff --git a/src/interactions/components/action-skip-button.ts b/src/interactions/components/action-skip-button.ts index 9635a83..05562e3 100644 --- a/src/interactions/components/action-skip-button.ts +++ b/src/interactions/components/action-skip-button.ts @@ -6,7 +6,7 @@ import { checkQueueCurrentTrack, checkQueueExists } from '../../common/validatio import { checkInVoiceChannel, checkSameVoiceChannel } from '../../common/validation/voiceChannelValidator'; import { TFunction } from 'i18next'; import { useServerTranslator } from '../../common/utils/localeUtil'; -import { formatRepeatModeDetailed, formatSlashCommand } from '../../common/utils/formattingUtils'; +import { formatRepeatModeDetailed } from '../../common/utils/formattingUtils'; class ActionSkipButton extends BaseComponentInteraction { constructor() { @@ -27,10 +27,6 @@ class ActionSkipButton extends BaseComponentInteraction { checkQueueCurrentTrack ]); - if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { - return await this.handleNoQueue(interaction, translator); - } - if (queue.currentTrack!.id !== referenceId) { return await this.handleAlreadySkipped(interaction, translator); } @@ -43,24 +39,8 @@ class ActionSkipButton extends BaseComponentInteraction { return await this.handleSuccess(interaction, skippedTrack, queue, translator); } - private async handleNoQueue(interaction: MessageComponentInteraction, translator: TFunction) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - translator('validation.queueNoCurrentTrack', { - icon: this.embedOptions.icons.warning, - playCommand: formatSlashCommand('play', translator) - }) - ) - .setColor(this.embedOptions.colors.warning) - ], - components: [] - }); - } - private async handleAlreadySkipped(interaction: MessageComponentInteraction, translator: TFunction) { - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -70,7 +50,8 @@ class ActionSkipButton extends BaseComponentInteraction { ) .setColor(this.embedOptions.colors.warning) ], - components: [] + components: [], + ephemeral: true }); } @@ -93,7 +74,7 @@ class ActionSkipButton extends BaseComponentInteraction { .setThumbnail(skippedTrack.thumbnail) .setColor(this.embedOptions.colors.success); - return await interaction.editReply({ + return await interaction.reply({ embeds: [successEmbed], components: [] }); diff --git a/src/interactions/components/filters-disable-button.ts b/src/interactions/components/filters-disable-button.ts index c710d56..274a102 100644 --- a/src/interactions/components/filters-disable-button.ts +++ b/src/interactions/components/filters-disable-button.ts @@ -28,7 +28,7 @@ class FiltersDisableButtonComponent extends BaseComponentInteraction { this.resetFilters(queue, logger); logger.debug('Responding with success embed.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedUserAuthor(interaction)) diff --git a/src/interactions/components/filters-select-menu.ts b/src/interactions/components/filters-select-menu.ts index 2d237f5..e7ed46b 100644 --- a/src/interactions/components/filters-select-menu.ts +++ b/src/interactions/components/filters-select-menu.ts @@ -1,6 +1,6 @@ import config from 'config'; import { BiquadFilters, EqualizerConfigurationPreset, GuildQueue, QueueFilters, useQueue } from 'discord-player'; -import { EmbedBuilder, Message, StringSelectMenuInteraction } from 'discord.js'; +import { EmbedBuilder, InteractionResponse, StringSelectMenuInteraction } from 'discord.js'; import { Logger } from 'pino'; import { BaseComponentInteraction } from '../../common/classes/interactions'; import { @@ -84,7 +84,7 @@ class FiltersSelectMenuComponent extends BaseComponentInteraction { queue: GuildQueue, filterType: string, translator: TFunction - ): Promise { + ): Promise> { this.addFfmpegNormalizerIfRequired(selectMenuInteraction); this.toggleFfmpegFilters(selectMenuInteraction, queue, logger); @@ -98,7 +98,7 @@ class FiltersSelectMenuComponent extends BaseComponentInteraction { queue: GuildQueue, filterType: string, translator: TFunction - ): Promise { + ): Promise> { this.toggleBiquadFilter(selectMenuInteraction, queue, logger); logger.debug('Responding with success embed.'); @@ -111,7 +111,7 @@ class FiltersSelectMenuComponent extends BaseComponentInteraction { queue: GuildQueue, filterType: string, translator: TFunction - ): Promise { + ): Promise> { this.toggleEqualizerFilter(selectMenuInteraction, queue, logger); logger.debug('Responding with success embed.'); @@ -198,9 +198,9 @@ class FiltersSelectMenuComponent extends BaseComponentInteraction { interaction: StringSelectMenuInteraction, filterType: string, translator: TFunction - ): Promise { + ): Promise> { logger.debug('Responding with success embed.'); - return interaction.editReply({ + return interaction.reply({ embeds: [this.buildSuccessEmbed(interaction, filterType, translator)], components: [] }); @@ -277,9 +277,9 @@ class FiltersSelectMenuComponent extends BaseComponentInteraction { logger: Logger, interaction: StringSelectMenuInteraction, translator: TFunction - ): Promise { + ): Promise> { logger.debug('Responding with success embed.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedUserAuthor(interaction)) diff --git a/src/interactions/slashcommands/back.ts b/src/interactions/slashcommands/back.ts index 74e058b..74957f9 100644 --- a/src/interactions/slashcommands/back.ts +++ b/src/interactions/slashcommands/back.ts @@ -73,7 +73,7 @@ class BackCommand extends BaseSlashCommandInteraction { translator: TFunction ) { logger.debug('Specified track position was higher than total tracks.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -85,7 +85,8 @@ class BackCommand extends BaseSlashCommandInteraction { }) ) .setColor(this.embedOptions.colors.warning) - ] + ], + ephemeral: true }); } @@ -111,7 +112,7 @@ class BackCommand extends BaseSlashCommandInteraction { translator: TFunction ) { logger.debug('No tracks in history.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -121,7 +122,8 @@ class BackCommand extends BaseSlashCommandInteraction { }) ) .setColor(this.embedOptions.colors.warning) - ] + ], + ephemeral: true }); } @@ -130,7 +132,7 @@ class BackCommand extends BaseSlashCommandInteraction { interaction: ChatInputCommandInteraction, translator: TFunction ) { - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedUserAuthor(interaction)) diff --git a/src/interactions/slashcommands/filters.ts b/src/interactions/slashcommands/filters.ts index e7fd27c..949bc11 100644 --- a/src/interactions/slashcommands/filters.ts +++ b/src/interactions/slashcommands/filters.ts @@ -68,6 +68,9 @@ class FiltersCommand extends BaseSlashCommandInteraction { checkQueueCurrentTrack ]); + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + const filterProvider: string = interaction.options.getString('type') || 'ffmpeg'; switch (filterProvider) { diff --git a/src/interactions/slashcommands/help.ts b/src/interactions/slashcommands/help.ts index c3b8df4..3028056 100644 --- a/src/interactions/slashcommands/help.ts +++ b/src/interactions/slashcommands/help.ts @@ -64,7 +64,7 @@ class HelpCommand extends BaseSlashCommandInteraction { }; logger.debug('Responding with info embed.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( diff --git a/src/interactions/slashcommands/history.ts b/src/interactions/slashcommands/history.ts index ea4abf5..54f0d1f 100644 --- a/src/interactions/slashcommands/history.ts +++ b/src/interactions/slashcommands/history.ts @@ -125,7 +125,7 @@ class HistoryCommand extends BaseSlashCommandInteraction { }; logger.debug('Responding with info embed.'); - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedQueueAuthor(interaction, queue, translator)) @@ -169,7 +169,7 @@ class HistoryCommand extends BaseSlashCommandInteraction { logger.debug('History exists but there is no current track.'); logger.debug('Responding with info embed.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedQueueAuthor(interaction, queue, translator)) @@ -182,7 +182,8 @@ class HistoryCommand extends BaseSlashCommandInteraction { ) .setFooter(this.getDisplayFullFooterInfo(interaction, history, translator)) .setColor(this.embedOptions.colors.info) - ] + ], + ephemeral: true }); } @@ -196,7 +197,7 @@ class HistoryCommand extends BaseSlashCommandInteraction { logger.debug('Specified page was higher than total pages.'); logger.debug('Responding with warning embed.'); - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -207,7 +208,8 @@ class HistoryCommand extends BaseSlashCommandInteraction { }) ) .setColor(this.embedOptions.colors.warning) - ] + ], + ephemeral: true }); return Promise.resolve(); } diff --git a/src/interactions/slashcommands/join.ts b/src/interactions/slashcommands/join.ts index 847cbac..94573a6 100644 --- a/src/interactions/slashcommands/join.ts +++ b/src/interactions/slashcommands/join.ts @@ -22,6 +22,9 @@ class JoinCommand extends BaseSlashCommandInteraction { await this.runValidators({ interaction, executionId }, [checkInVoiceChannel, checkVoicePermissionJoinAndTalk]); + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + const existingQueue = useQueue(interaction.guild!.id); if (existingQueue) { diff --git a/src/interactions/slashcommands/leave.ts b/src/interactions/slashcommands/leave.ts index 985a181..7d78ec0 100644 --- a/src/interactions/slashcommands/leave.ts +++ b/src/interactions/slashcommands/leave.ts @@ -26,6 +26,9 @@ class LeaveCommand extends BaseSlashCommandInteraction { checkQueueExists ]); + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + logger.debug('Deleting queue.'); this.deleteQueue(queue); diff --git a/src/interactions/slashcommands/loop.ts b/src/interactions/slashcommands/loop.ts index a526a3f..9cba7c7 100644 --- a/src/interactions/slashcommands/loop.ts +++ b/src/interactions/slashcommands/loop.ts @@ -2,7 +2,7 @@ import { GuildQueue, QueueRepeatMode, useQueue } from 'discord-player'; import { ChatInputCommandInteraction, EmbedBuilder, - Message, + InteractionResponse, SlashCommandBuilder, SlashCommandIntegerOption } from 'discord.js'; @@ -74,7 +74,7 @@ class LoopCommand extends BaseSlashCommandInteraction { interaction: ChatInputCommandInteraction, currentRepeatMode: QueueRepeatMode, translator: TFunction - ): Promise { + ): Promise> { logger.debug('No repeat mode was provided, responding with current repeat mode.'); const repeatModeEmbedIcon = @@ -82,7 +82,7 @@ class LoopCommand extends BaseSlashCommandInteraction { const repeatModeEmbedName = formatRepeatMode(currentRepeatMode, translator); logger.debug('Responding with info embed.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -101,11 +101,11 @@ class LoopCommand extends BaseSlashCommandInteraction { interaction: ChatInputCommandInteraction, currentRepeatMode: QueueRepeatMode, translator: TFunction - ): Promise { + ): Promise> { const repeatModeEmbedName = formatRepeatMode(currentRepeatMode, translator); logger.debug(`Loop mode is already set to '${repeatModeEmbedName}'.`); logger.debug('Responding with warning embed.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -115,7 +115,8 @@ class LoopCommand extends BaseSlashCommandInteraction { }) ) .setColor(this.embedOptions.colors.warning) - ] + ], + ephemeral: true }); } @@ -126,7 +127,7 @@ class LoopCommand extends BaseSlashCommandInteraction { fromRepeatMode: QueueRepeatMode, toRepeatMode: QueueRepeatMode, translator: TFunction - ): Promise { + ): Promise> { const newRepeatModeEmbedName = formatRepeatMode(toRepeatMode, translator); const getChangedRepeatModeEmbedReply = this.getChangedRepeatModeEmbedReply( fromRepeatMode, @@ -138,7 +139,7 @@ class LoopCommand extends BaseSlashCommandInteraction { logger.debug(`Loop mode changed to '${newRepeatModeEmbedName}'.`); logger.debug('Responding with success embed.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedUserAuthor(interaction)) diff --git a/src/interactions/slashcommands/lyrics.ts b/src/interactions/slashcommands/lyrics.ts index 0d87da3..8422d85 100644 --- a/src/interactions/slashcommands/lyrics.ts +++ b/src/interactions/slashcommands/lyrics.ts @@ -38,6 +38,9 @@ class LyricsCommand extends BaseSlashCommandInteraction { ]); } + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + const geniusSearchQuery: string = this.getGeniusSearchQuery(logger, query, queue); const [playerSearchResult, geniusLyricsResult] = await Promise.all([ this.getPlayerSearchResult(logger, query), diff --git a/src/interactions/slashcommands/move.ts b/src/interactions/slashcommands/move.ts index e5da5d0..c7e2851 100644 --- a/src/interactions/slashcommands/move.ts +++ b/src/interactions/slashcommands/move.ts @@ -81,7 +81,7 @@ class MoveCommand extends BaseSlashCommandInteraction { translator: TFunction ) { logger.debug('One of the specified track positions was higher than total tracks.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -94,7 +94,8 @@ class MoveCommand extends BaseSlashCommandInteraction { }) ) .setColor(this.embedOptions.colors.warning) - ] + ], + ephemeral: true }); } @@ -105,7 +106,7 @@ class MoveCommand extends BaseSlashCommandInteraction { toPosition: number, translator: TFunction ) { - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedUserAuthor(interaction)) diff --git a/src/interactions/slashcommands/nowplaying.ts b/src/interactions/slashcommands/nowplaying.ts index 1d8988c..ebfad00 100644 --- a/src/interactions/slashcommands/nowplaying.ts +++ b/src/interactions/slashcommands/nowplaying.ts @@ -88,7 +88,7 @@ class NowPlayingCommand extends BaseSlashCommandInteraction { }; logger.debug('Sending info embed with action row components.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedQueueAuthor(interaction, queue, translator)) diff --git a/src/interactions/slashcommands/pause.ts b/src/interactions/slashcommands/pause.ts index da0a867..685c9c5 100644 --- a/src/interactions/slashcommands/pause.ts +++ b/src/interactions/slashcommands/pause.ts @@ -32,7 +32,7 @@ class PauseCommand extends BaseSlashCommandInteraction { this.togglePauseState(logger, queue); logger.debug('Responding with success embed.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedUserAuthor(interaction)) diff --git a/src/interactions/slashcommands/play.ts b/src/interactions/slashcommands/play.ts index 20cd9ff..fb579ed 100644 --- a/src/interactions/slashcommands/play.ts +++ b/src/interactions/slashcommands/play.ts @@ -43,6 +43,9 @@ class PlayCommand extends BaseSlashCommandInteraction { await this.runValidators({ interaction, executionId }, [checkVoicePermissionJoinAndTalk]); } + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + const player = useMainPlayer()!; const searchQuery = interaction.options.getString('query')!; const transformedQuery = transformQuery({ query: searchQuery, executionId }); diff --git a/src/interactions/slashcommands/queue.ts b/src/interactions/slashcommands/queue.ts index 1abb3b7..9698b4f 100644 --- a/src/interactions/slashcommands/queue.ts +++ b/src/interactions/slashcommands/queue.ts @@ -115,7 +115,7 @@ class QueueCommand extends BaseSlashCommandInteraction { }; logger.debug('Responding with info embed.'); - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedQueueAuthor(interaction, queue, translator)) @@ -160,7 +160,7 @@ class QueueCommand extends BaseSlashCommandInteraction { logger.debug('Queue exists but there is no current track.'); logger.debug('Responding with info embed.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedQueueAuthor(interaction, queue, translator)) @@ -173,7 +173,8 @@ class QueueCommand extends BaseSlashCommandInteraction { ) .setFooter(this.getDisplayFullFooterInfo(interaction, queue, translator)) .setColor(this.embedOptions.colors.info) - ] + ], + ephemeral: true }); } @@ -187,7 +188,7 @@ class QueueCommand extends BaseSlashCommandInteraction { logger.debug('Specified page was higher than total pages.'); logger.debug('Responding with warning embed.'); - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -198,7 +199,8 @@ class QueueCommand extends BaseSlashCommandInteraction { }) ) .setColor(this.embedOptions.colors.warning) - ] + ], + ephemeral: true }); return Promise.resolve(); } diff --git a/src/interactions/slashcommands/reload.ts b/src/interactions/slashcommands/reload.ts index 896ed39..51ce816 100644 --- a/src/interactions/slashcommands/reload.ts +++ b/src/interactions/slashcommands/reload.ts @@ -27,6 +27,9 @@ class ReloadCommand extends BaseSlashCommandInteraction { await this.runValidators({ interaction, executionId }, [checkValidGuildId]); + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + try { await this.reloadInteractionsAcrossShards(logger, executionId, client!); } catch (error) { diff --git a/src/interactions/slashcommands/remove.ts b/src/interactions/slashcommands/remove.ts index a085007..39752d7 100644 --- a/src/interactions/slashcommands/remove.ts +++ b/src/interactions/slashcommands/remove.ts @@ -134,7 +134,7 @@ class RemoveCommand extends BaseSlashCommandInteraction { logger.debug('Start position is higher than end position.'); logger.debug('Responding with warning embed.'); - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -146,7 +146,8 @@ class RemoveCommand extends BaseSlashCommandInteraction { }) ) .setColor(this.embedOptions.colors.warning) - ] + ], + ephemeral: true }); return Promise.resolve(); } @@ -208,7 +209,7 @@ class RemoveCommand extends BaseSlashCommandInteraction { logger.debug(`Removed track '${removedTrack.url}' from queue.`); logger.debug('Responding with success embed.'); - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedUserAuthor(interaction)) @@ -232,7 +233,7 @@ class RemoveCommand extends BaseSlashCommandInteraction { translator: TFunction ) { logger.debug('Responding with warning embed.'); - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedUserAuthor(interaction)) @@ -242,7 +243,8 @@ class RemoveCommand extends BaseSlashCommandInteraction { }) ) .setColor(this.embedOptions.colors.warning) - ] + ], + ephemeral: true }); return Promise.resolve(); } @@ -254,7 +256,7 @@ class RemoveCommand extends BaseSlashCommandInteraction { translator: TFunction ) { logger.debug('Responding with success embed.'); - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedUserAuthor(interaction)) @@ -280,7 +282,7 @@ class RemoveCommand extends BaseSlashCommandInteraction { logger.debug('Specified track position is higher than total tracks.'); logger.debug('Responding with warning embed.'); - await interaction.editReply({ + await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -292,7 +294,8 @@ class RemoveCommand extends BaseSlashCommandInteraction { }) ) .setColor(this.embedOptions.colors.warning) - ] + ], + ephemeral: true }); return Promise.resolve(); } diff --git a/src/interactions/slashcommands/seek.ts b/src/interactions/slashcommands/seek.ts index 997d6f2..272c8f7 100644 --- a/src/interactions/slashcommands/seek.ts +++ b/src/interactions/slashcommands/seek.ts @@ -33,6 +33,9 @@ class SeekCommand extends BaseSlashCommandInteraction { checkQueueCurrentTrack ]); + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + const durationInputSplit: string[] = interaction.options.getString('duration')!.split(':'); const formattedDurationString: string = this.parseDurationArray(durationInputSplit); diff --git a/src/interactions/slashcommands/settings.ts b/src/interactions/slashcommands/settings.ts index 8d71117..f53ae9b 100644 --- a/src/interactions/slashcommands/settings.ts +++ b/src/interactions/slashcommands/settings.ts @@ -42,6 +42,9 @@ class SettingsCommand extends BaseSlashCommandInteraction { const logger = this.getLogger(this.name, executionId, interaction); const translator = useServerTranslator(interaction); + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + const subcommand = interaction.options.getSubcommand(); switch (subcommand) { diff --git a/src/interactions/slashcommands/shards.ts b/src/interactions/slashcommands/shards.ts index 2183db1..d46d33e 100644 --- a/src/interactions/slashcommands/shards.ts +++ b/src/interactions/slashcommands/shards.ts @@ -43,6 +43,9 @@ class ShardsCommand extends BaseSlashCommandInteraction { await this.runValidators({ interaction, executionId }, [checkValidGuildId]); + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + const shardInfoList: ShardInfo[] = await this.fetchShardInfo( client!, logger, diff --git a/src/interactions/slashcommands/shuffle.ts b/src/interactions/slashcommands/shuffle.ts index 15ec8ed..746ab1c 100644 --- a/src/interactions/slashcommands/shuffle.ts +++ b/src/interactions/slashcommands/shuffle.ts @@ -31,7 +31,7 @@ class ShuffleCommand extends BaseSlashCommandInteraction { logger.debug('Shuffled queue tracks.'); logger.debug('Responding with success embed.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedUserAuthor(interaction)) diff --git a/src/interactions/slashcommands/skip.ts b/src/interactions/slashcommands/skip.ts index 1520593..d5b1d71 100644 --- a/src/interactions/slashcommands/skip.ts +++ b/src/interactions/slashcommands/skip.ts @@ -73,7 +73,7 @@ class SkipCommand extends BaseSlashCommandInteraction { translator: TFunction ) { logger.debug('Specified track position was higher than total tracks.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -85,7 +85,8 @@ class SkipCommand extends BaseSlashCommandInteraction { }) ) .setColor(this.embedOptions.colors.warning) - ] + ], + ephemeral: true }); } @@ -111,7 +112,7 @@ class SkipCommand extends BaseSlashCommandInteraction { translator: TFunction ) { logger.debug('No tracks in queue and no current track.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -121,7 +122,8 @@ class SkipCommand extends BaseSlashCommandInteraction { }) ) .setColor(this.embedOptions.colors.warning) - ] + ], + ephemeral: true }); } @@ -131,7 +133,7 @@ class SkipCommand extends BaseSlashCommandInteraction { queue: GuildQueue, translator: TFunction ) { - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedUserAuthor(interaction)) diff --git a/src/interactions/slashcommands/status.ts b/src/interactions/slashcommands/status.ts index 338d9da..7a80f7e 100644 --- a/src/interactions/slashcommands/status.ts +++ b/src/interactions/slashcommands/status.ts @@ -31,6 +31,9 @@ class StatusCommand extends BaseSlashCommandInteraction { const logger = this.getLogger(this.name, executionId, interaction); const translator = useServerTranslator(interaction); + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + const [botStatisticsEmbedString, playerStatisticsEmbedString, systemStatusEmbedString] = await Promise.all([ getBotStatistics(client!, version, translator), getPlayerStatistics(client!, translator), diff --git a/src/interactions/slashcommands/stop.ts b/src/interactions/slashcommands/stop.ts index 4c99128..dabc773 100644 --- a/src/interactions/slashcommands/stop.ts +++ b/src/interactions/slashcommands/stop.ts @@ -33,7 +33,7 @@ class StopCommand extends BaseSlashCommandInteraction { } logger.debug('Responding with success embed.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setAuthor(this.getEmbedUserAuthor(interaction)) diff --git a/src/interactions/slashcommands/systemstatus.ts b/src/interactions/slashcommands/systemstatus.ts index 7096a7b..743b134 100644 --- a/src/interactions/slashcommands/systemstatus.ts +++ b/src/interactions/slashcommands/systemstatus.ts @@ -26,6 +26,9 @@ class SystemStatusCommand extends BaseSlashCommandInteraction { await this.runValidators({ interaction, executionId }, [checkValidGuildId]); + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + const [botStatisticsEmbedString, playerStatisticsEmbedString, systemStatusEmbedString] = await Promise.all([ getBotStatistics(client!, version, translator), getPlayerStatistics(client!, translator), diff --git a/src/interactions/slashcommands/volume.ts b/src/interactions/slashcommands/volume.ts index af3f612..178f858 100644 --- a/src/interactions/slashcommands/volume.ts +++ b/src/interactions/slashcommands/volume.ts @@ -31,6 +31,9 @@ class VolumeCommand extends BaseSlashCommandInteraction { checkQueueExists ]); + await interaction.deferReply(); + logger.debug('Interaction deferred.'); + const volume: number = interaction.options.getInteger('percentage')!; if (!volume && volume !== 0) { diff --git a/src/types/interactionTypes.d.ts b/src/types/interactionTypes.d.ts index 08ea632..1e74c76 100644 --- a/src/types/interactionTypes.d.ts +++ b/src/types/interactionTypes.d.ts @@ -47,11 +47,11 @@ export type BaseComponentParams = { referenceId?: string; } & BaseInteractionParams; -export type BaseSlashCommandReturnType = Promise | void>; +export type BaseSlashCommandReturnType = Promise | InteractionResponse | void>; export type BaseAutocompleteReturnType = Promise; -export type BaseComponentReturnType = Promise | void>; +export type BaseComponentReturnType = Promise | InteractionResponse | void>; export enum FilterType { FFmpeg = 'ffmpeg', From 30abb470b9b5598f623241dbe13ce424ebbd345f Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 30 Jan 2024 19:28:09 +0100 Subject: [PATCH 12/15] fix defer --- src/handlers/interactionErrorHandler.ts | 6 ++++-- src/interactions/components/action-previous-button.ts | 5 +++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/handlers/interactionErrorHandler.ts b/src/handlers/interactionErrorHandler.ts index 7bc5d50..66635f8 100644 --- a/src/handlers/interactionErrorHandler.ts +++ b/src/handlers/interactionErrorHandler.ts @@ -62,7 +62,8 @@ export const handleError = async ( return; case false: logger.debug('Responding with error embed'); - return await interaction.editReply(errorReply); + interaction.deferred ? await interaction.editReply(errorReply) : await interaction.reply(errorReply); + return; } } else if (interaction instanceof MessageComponentInteraction) { switch (interaction.replied) { @@ -74,7 +75,8 @@ export const handleError = async ( return; case false: logger.debug('Responding with error embed'); - return await interaction.editReply(errorReply); + interaction.deferred ? await interaction.editReply(errorReply) : await interaction.reply(errorReply); + return; } } else { logger.debug( diff --git a/src/interactions/components/action-previous-button.ts b/src/interactions/components/action-previous-button.ts index 87d2260..2a66152 100644 --- a/src/interactions/components/action-previous-button.ts +++ b/src/interactions/components/action-previous-button.ts @@ -58,7 +58,7 @@ class ActionPreviousButton extends BaseComponentInteraction { translator: TFunction ) { logger.debug('No tracks in history.'); - return await interaction.editReply({ + return await interaction.reply({ embeds: [ new EmbedBuilder() .setDescription( @@ -68,7 +68,8 @@ class ActionPreviousButton extends BaseComponentInteraction { }) ) .setColor(this.embedOptions.colors.warning) - ] + ], + ephemeral: true }); } From 664fa50dfe65d85a86808e6aa712d821025bc8c1 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 30 Jan 2024 20:02:32 +0100 Subject: [PATCH 13/15] fix: Fix playlist added position being incorrect in some cases --- src/interactions/slashcommands/play.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/interactions/slashcommands/play.ts b/src/interactions/slashcommands/play.ts index fb579ed..2c7a385 100644 --- a/src/interactions/slashcommands/play.ts +++ b/src/interactions/slashcommands/play.ts @@ -188,10 +188,8 @@ class PlayCommand extends BaseSlashCommandInteraction { count: searchResult.tracks.length, queueCommand: formatSlashCommand('queue', translator) }); - if (queue.tracks.data.length != searchResult.tracks.length) { - const posistionFirstTrackInPlaylist = queue.tracks.data.length - searchResult.tracks.length + 1; - embedFooter = this.getDisplayFooterTrackPosition(posistionFirstTrackInPlaylist, translator); - } + const posistionFirstTrackInPlaylist = queue.tracks.data.length - searchResult.tracks.length + 1; + embedFooter = this.getDisplayFooterTrackPosition(posistionFirstTrackInPlaylist, translator); } else if (queue.currentTrack === track && queue.tracks.data.length === 0) { if (!this.embedOptions.behavior.enablePlayerStartMessages) { message = From 2679cdc4639f57b5b120daeb213ec4f0c0a44aca Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sat, 3 Feb 2024 11:05:38 +0100 Subject: [PATCH 14/15] add unit test for help command --- src/interactions/slashcommands/help.ts | 2 +- .../interactions/slashcommands/help.test.ts | 38 +++++++++++++++++-- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/src/interactions/slashcommands/help.ts b/src/interactions/slashcommands/help.ts index 3028056..1c2247f 100644 --- a/src/interactions/slashcommands/help.ts +++ b/src/interactions/slashcommands/help.ts @@ -122,7 +122,7 @@ class HelpCommand extends BaseSlashCommandInteraction { }`; } - private getCommandParams(command: BaseSlashCommandInteraction, locale: LocaleString): string { + public getCommandParams(command: BaseSlashCommandInteraction, locale: LocaleString): string { const commandName = command.data.name; const option = command.data.options[0]; diff --git a/src/tests/interactions/slashcommands/help.test.ts b/src/tests/interactions/slashcommands/help.test.ts index dc32f7e..f075760 100644 --- a/src/tests/interactions/slashcommands/help.test.ts +++ b/src/tests/interactions/slashcommands/help.test.ts @@ -1,6 +1,38 @@ import helpCommand from '../../../interactions/slashcommands/help'; -import { SlashCommandNumberOption } from 'discord.js'; +import Discord, { Client, SlashCommandNumberOption, ChatInputCommandInteraction } from 'discord.js'; import { BaseSlashCommandInteraction } from '../../../common/classes/interactions'; +import { ExtendedClient } from '../../../types/clientTypes'; + +describe('Discord bot command test', () => { + let client: ExtendedClient; + let mockInteraction: ChatInputCommandInteraction; + + beforeEach(() => { + client = new Client({ + intents: [Discord.GatewayIntentBits.Guilds, Discord.GatewayIntentBits.GuildVoiceStates] + }); + + client.slashCommandInteractions = new Discord.Collection(); + client.slashCommandInteractions.set('help', helpCommand); + + mockInteraction = { + reply: jest.fn(), + commandName: 'help' + } as unknown as ChatInputCommandInteraction; + }); + + it('should reply when receiving a valid help command', async () => { + // Execute the help command with the mock interaction + await helpCommand.execute({ + executionId: '123', + client, + interaction: mockInteraction as ChatInputCommandInteraction + }); + + // Check if the reply method was called + expect(mockInteraction.reply).toHaveBeenCalledWith(expect.anything()); + }); +}); describe('HelpCommand', () => { describe('getCommandParams', () => { @@ -17,7 +49,7 @@ describe('HelpCommand', () => { } as unknown as BaseSlashCommandInteraction; const locale = 'en-US'; - const commandParams = helpCommand['getCommandParams'](command, locale); + const commandParams = helpCommand.getCommandParams(command, locale); expect(commandParams).toBe('**`optionname`** '); }); @@ -30,7 +62,7 @@ describe('HelpCommand', () => { } as unknown as BaseSlashCommandInteraction; const locale = 'en-US'; - const commandParams = helpCommand['getCommandParams'](command, locale); + const commandParams = helpCommand.getCommandParams(command, locale); expect(commandParams).toBe(''); }); From c755bfbc30a426bb91d1763e2441146f0f47ab6c Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sat, 3 Feb 2024 11:05:46 +0100 Subject: [PATCH 15/15] delete settings command for now --- src/interactions/slashcommands/settings.ts | 159 --------------------- 1 file changed, 159 deletions(-) delete mode 100644 src/interactions/slashcommands/settings.ts diff --git a/src/interactions/slashcommands/settings.ts b/src/interactions/slashcommands/settings.ts deleted file mode 100644 index f53ae9b..0000000 --- a/src/interactions/slashcommands/settings.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { EmbedBuilder, SlashCommandBuilder, PermissionFlagsBits, ChatInputCommandInteraction } from 'discord.js'; -import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; -import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes'; -import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil'; -import { Logger } from 'pino'; -import { TFunction } from 'i18next'; -import guildDatabaseClient from '../../common/services/guildDatabaseClient'; - -class SettingsCommand extends BaseSlashCommandInteraction { - constructor() { - const data = localizeCommand( - new SlashCommandBuilder() - .setName('settings') - .setDefaultMemberPermissions(PermissionFlagsBits.Administrator) - .addSubcommand((subcommand) => subcommand.setName('view')) - .addSubcommand((subcommand) => - subcommand - .setName('bot-language') - .addStringOption((option) => - option - .setName('language') - .addChoices( - { value: 'en-US', name: ' ' }, - { value: 'no', name: ' ' }, - { value: 'ro', name: ' ' }, - { value: 'en-ES', name: ' ' } - ) - ) - ) - .addSubcommand((subcommand) => - subcommand - .setName('default-volume') - .addIntegerOption((option) => option.setName('percentage').setMinValue(0).setMaxValue(100)) - ) - .addSubcommand((subcommand) => subcommand.setName('action-permissions')) - ); - super(data); - } - - async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType { - const { executionId, interaction } = params; - const logger = this.getLogger(this.name, executionId, interaction); - const translator = useServerTranslator(interaction); - - await interaction.deferReply(); - logger.debug('Interaction deferred.'); - - const subcommand = interaction.options.getSubcommand(); - - switch (subcommand) { - case 'view': - return await this.handleShowSettings(executionId, logger, interaction, translator); - case 'default-volume': - return await this.handleDefaultVolume(executionId, logger, interaction, translator); - default: - return Promise.resolve(); - } - } - - private async handleShowSettings( - executionId: string, - logger: Logger, - interaction: ChatInputCommandInteraction, - translator: TFunction - ) { - logger.debug('Showing settings'); - - // get settings from database - const settings = await guildDatabaseClient.getGuildConfig(interaction.guild!.id, executionId, interaction); - - console.log(settings); - - if (!settings) { - logger.debug('No settings found'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription(`Could not find settings for guild id ${interaction.guild!.id}`) - .setColor(this.embedOptions.colors.warning) - ] - }); - } - - const settingsAsString = [ - `Language: ${settings.locale}`, - `Volume: ${settings.defaultVolume}`, - `Action permissions: ${Object.keys(settings.actionPermissions).join(', ')}` - ].join('\n'); - - return await interaction.editReply({ - embeds: [new EmbedBuilder().setDescription(settingsAsString).setColor(this.embedOptions.colors.info)] - }); - } - - private async handleDefaultVolume( - executionId: string, - logger: Logger, - interaction: ChatInputCommandInteraction, - translator: TFunction - ) { - logger.debug('Setting volume'); - - const volume = interaction.options.getInteger('percentage'); - - const settings = await guildDatabaseClient.getGuildConfig(interaction.guild!.id, executionId, interaction); - - if (!volume) { - if (!settings) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription(`Could not find settings for guild id ${interaction.guild!.id}`) - .setColor(this.embedOptions.colors.warning) - ] - }); - } - - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription(`Current default volume is ${settings.defaultVolume}`) - .setColor(this.embedOptions.colors.info) - ] - }); - } - - if (volume < 0 || volume > 100) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription('Volume must be between 0 and 100') - .setColor(this.embedOptions.colors.error) - ] - }); - } - - const updatedSettings = { - ...settings, - defaultVolume: volume - }; - - await guildDatabaseClient.createOrUpdateGuildConfig( - executionId, - interaction.guild!.id, - updatedSettings, - interaction - ); - - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription(`Default volume set to ${volume}`) - .setColor(this.embedOptions.colors.success) - ] - }); - } -} - -export default new SettingsCommand();