mirror of
https://github.com/darksaid98/cadence-discord-bot.git
synced 2026-12-01 14:38:48 +00:00
feat(settings): created settings command.
This commit is contained in:
1 parent
8621e25183
commit
1c98fd6c41
5 files changed
+395
-14
No files matched your search
+27
-6
@@ -306,7 +306,7 @@
|
||||
"en-US": "English",
|
||||
"no": "Norwegian",
|
||||
"ro": "Romanian",
|
||||
"en-ES": "Spanish"
|
||||
"es-ES": "Spanish"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -321,16 +321,36 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"action-permissions": {
|
||||
"name": "action-permissions",
|
||||
"description": "Set the roles required to perform certain actions."
|
||||
"default-search-engine": {
|
||||
"name": "default-search-engine",
|
||||
"description": "Set the default search engine for the bot.",
|
||||
"options": {
|
||||
"provider": {
|
||||
"name": "provider",
|
||||
"description": "Search engine provider to use.",
|
||||
"choices": {
|
||||
"youtube": "YouTube",
|
||||
"spotify": "Spotify"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"view": {
|
||||
"name": "view",
|
||||
"description": "View the current settings for the bot."
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"botLanguageChanged": "{{icon}} **Bot language changed**\nBot language has been changed to **`{{language}}`**.",
|
||||
"botLanguageInformation": "{{icon}} **Bot language**\nThe bot language is currently set to **`{{language}}`**.",
|
||||
"botLanguageError": "{{icon}} **Oops!**\nThere was an error while trying to change the bot language. Please try again later.",
|
||||
"noDatabaseFound": "{{icon}} **Oops!**\nThere is no database found for this server. Please try again later.",
|
||||
"errorGettingSettings": "{{icon}} **Oops!**\nThere was an error while trying to get the settings for this server. Please try again later.",
|
||||
"invalidDefaultVolume": "{{icon}} **Oops!**\nYou cannot set the default volume to **`{{wrongVolume}}%`**, please pick a value between **`0%`** and **`100%`**.",
|
||||
"defaultVolumeError": "{{icon}} **Oops!**\nThere was an error while trying to change the default volume. Please try again later.",
|
||||
"defaultVolumeChanged": "{{icon}} **Default volume changed**\nDefault volume has been changed to **`{{volume}}%`**.",
|
||||
"defaultSearchEngineError": "{{icon}} **Oops!**\nThere was an error while trying to change the default search engine. Please try again later.",
|
||||
"defaultSearchEngineChanged": "{{icon}} **Default search engine changed**\nDefault search engine has been changed to **`{{provider}}`**."
|
||||
},
|
||||
"shards": {
|
||||
"metadata": {
|
||||
@@ -441,7 +461,8 @@
|
||||
"off": "Disabled",
|
||||
"track": "Track",
|
||||
"queue": "Queue",
|
||||
"autoplay": "Autoplay"
|
||||
"autoplay": "Autoplay",
|
||||
"set": "{{icon}} **Repeat mode**\nLoop mode is set to **{{mode}}**."
|
||||
},
|
||||
"requestedBy": "**Requested by:** {{user}}",
|
||||
"unavailableAuthor": "Unavailable",
|
||||
|
||||
+48
-1
@@ -290,10 +290,57 @@
|
||||
"durationLongerThanTrackDuration": "{{icon}} **Oops!**\nIngresaste **`{{wrongDuration}}`**, que es una marca de tiempo más larga que la duración de la canción actual.\n\nPor favor, intenta con una marca de tiempo que sea menor que la duración de la canción (**{{trackDuration}}**).",
|
||||
"seekingToTimestamp": "{{icon}} **Adelantando a la marca de tiempo**\nAdelantando a **`{{duration}}`** en la pista actual."
|
||||
},
|
||||
"settings": {
|
||||
"metadata": {
|
||||
"name": "configuracion",
|
||||
"description": "Configura varias opciones para el comportamiento del bot en el servidor.",
|
||||
"options": {
|
||||
"bot-language": {
|
||||
"name": "lenguaje-del-bot",
|
||||
"description": "Cambia el idioma del bot",
|
||||
"options": {
|
||||
"language": {
|
||||
"name": "language",
|
||||
"description": "Idioma a utilizar para el bot en los mensajes.",
|
||||
"choices": {
|
||||
"en-US": "English",
|
||||
"no": "Norwegian",
|
||||
"ro": "Romanian",
|
||||
"es-ES": "Spanish"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default-volume": {
|
||||
"name": "volumen-predeterminado",
|
||||
"description": "Establece el volumen de reproducción predeterminado.",
|
||||
"options": {
|
||||
"percentage": {
|
||||
"name": "percentage",
|
||||
"description": "Volume percentage: From 0% to 100%."
|
||||
}
|
||||
}
|
||||
},
|
||||
"view": {
|
||||
"name": "ver",
|
||||
"description": "Muestra la configuración actual del servidor."
|
||||
}
|
||||
}
|
||||
},
|
||||
"botLanguageChanged": "{{icon}} **Idioma del bot cambiado**\nEl idioma del bot ha sido cambiado a **`{{language}}`**.",
|
||||
"botLanguageInformation": "{{icon}} **Idioma del bot**\nEl idioma del bot está actualmente configurado en **`{{language}}`**.",
|
||||
"botLanguageError": "{{icon}} **Oops!**\nHubo un problema al cambiar el idioma del bot a **`{{language}}`**.\n\nPor favor, intenta de nuevo.",
|
||||
"noDatabaseFound": "{{icon}} **Oops!**\nNo se encontró una base de datos para este servidor. Por favor, inténtalo de nuevo.",
|
||||
"errorGettingSettings": "{{icon}} **Oops!**\nHubo un problema al obtener la configuración actual del servidor. Por favor, inténtalo de nuevo.",
|
||||
"noRequestChannelFound": "{{icon}} **Oops!**\nUn canal de solicitudes ha sido guardado en la base de datos, pero no pude encontrarlo en el servidor. Por favor, ejecuta este comando de nuevo para establecer un nuevo canal de solicitudes.",
|
||||
"requestChannelSet": "{{icon}} **Canal de solicitudes establecido**\nEl canal de texto **`{{channel}}`** ha sido establecido como el canal de solicitudes para las canciones.",
|
||||
"requestChannelCleared": "{{icon}} **Canal de solicitudes eliminado**\nEl canal de solicitudes para las canciones ha sido eliminado.",
|
||||
"invalidDefaultVolume": "{{icon}} **Oops!**\nNo puedes ajustar el volumen predeterminado a **`{{wrongVolume}}%`**, por favor elige un valor entre **`1%`** y **`100%`**."
|
||||
},
|
||||
"shards": {
|
||||
"metadata": {
|
||||
"name": "shards",
|
||||
"description": "Mostrar información sobre todos los fragmentos conectados.",
|
||||
"description": "Mostrar información sobre todos los shards conectados.",
|
||||
"options": {
|
||||
"sort": {
|
||||
"name": "ordenar",
|
||||
|
||||
@@ -3,16 +3,17 @@ generator client {
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = "file:./dev.db"
|
||||
provider = "mongodb"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model GuildConfig {
|
||||
guildId String @id @map("_id")
|
||||
|
||||
defaultVolume Int @default(50)
|
||||
locale String @default("en-US")
|
||||
actionPermissions String?
|
||||
defaultVolume Int @default(50)
|
||||
defaultSearchEngine String @default("spotify")
|
||||
locale String @default("en-US")
|
||||
actionPermissions String?
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -15,6 +15,7 @@ function getLogger(executionId: string, interaction?: Interaction | MessageCompo
|
||||
|
||||
export type GuildConfig = {
|
||||
defaultVolume?: number;
|
||||
defaultSearchEngine?: string;
|
||||
locale?: string;
|
||||
actionPermissions?: Record<string, string[]>;
|
||||
};
|
||||
@@ -27,8 +28,12 @@ const guildDatabaseClient = {
|
||||
) {
|
||||
const logger = getLogger(executionId, interaction);
|
||||
logger.debug(`Getting config for guild ${guildId} from database.`);
|
||||
|
||||
const config = await prisma.guildConfig.findUnique({
|
||||
where: { guildId: guildId }
|
||||
}).catch((error) => {
|
||||
logger.error(error, 'Error getting guild config from database.')
|
||||
return null;
|
||||
});
|
||||
|
||||
if (!config) {
|
||||
@@ -87,7 +92,7 @@ export function validateGuildConfig(logger: Logger, configData: GuildConfig) {
|
||||
}
|
||||
|
||||
// get available locale from i18next?
|
||||
if (configData.locale && !['en-US', 'no', 'ro', 'en-ES'].includes(configData.locale)) {
|
||||
if (configData.locale && !['en-US', 'no', 'ro', 'es-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`);
|
||||
}
|
||||
@@ -96,8 +101,9 @@ export function validateGuildConfig(logger: Logger, configData: GuildConfig) {
|
||||
|
||||
const validConfig = {
|
||||
defaultVolume: configData.defaultVolume,
|
||||
defaultSearchEngine: configData.defaultSearchEngine,
|
||||
locale: configData.locale,
|
||||
actionPermissions: serializeActionPermissions(configData.actionPermissions ?? {})
|
||||
actionPermissions: serializeActionPermissions(configData.actionPermissions ?? {}),
|
||||
};
|
||||
|
||||
return validConfig;
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
import {
|
||||
ButtonBuilder,
|
||||
APIButtonComponent,
|
||||
ButtonStyle,
|
||||
ChannelType,
|
||||
ChatInputCommandInteraction,
|
||||
EmbedBuilder,
|
||||
APIMessageActionRowComponent,
|
||||
APIActionRowComponent,
|
||||
ComponentType,
|
||||
SlashCommandBuilder,
|
||||
BaseGuildTextChannel
|
||||
} from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../common/classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { Translator, localizeCommand, useServerTranslator } from '../../common/utils/localeUtil';
|
||||
import guildDatabaseClient, { GuildConfig } from '../../common/services/guildDatabaseClient';
|
||||
import { Logger } from '../../common/services/logger';
|
||||
|
||||
class SettingsCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('settings')
|
||||
.addSubcommand((subcommand) => subcommand.setName('view'))
|
||||
.addSubcommand((subcommand) =>
|
||||
subcommand
|
||||
.setName('bot-language')
|
||||
.addStringOption((option) =>
|
||||
option
|
||||
.setName('language')
|
||||
.setRequired(true)
|
||||
.addChoices(
|
||||
{ name: 'English', value: 'en-US' },
|
||||
{ name: 'Spanish', value: 'es-ES' },
|
||||
{ name: 'Norwegian', value: 'no' },
|
||||
{ name: 'Romanian', value: 'ro' }
|
||||
)
|
||||
)
|
||||
)
|
||||
.addSubcommand((subcommand) =>
|
||||
subcommand
|
||||
.setName('default-volume')
|
||||
.addIntegerOption((option) =>
|
||||
option.setName('percentage').setRequired(true).setMinValue(1).setMaxValue(100)
|
||||
)
|
||||
)
|
||||
.addSubcommand((subcommand) =>
|
||||
subcommand
|
||||
.setName('default-search-engine')
|
||||
.addStringOption((option) =>
|
||||
option
|
||||
.setName('provider')
|
||||
.setRequired(true)
|
||||
.addChoices(
|
||||
{ name: 'YouTube', value: 'youtube' },
|
||||
{ name: 'Spotify', value: 'spotify' }
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
|
||||
await interaction.deferReply();
|
||||
logger.debug('Interaction deferred.');
|
||||
|
||||
const subcommand = interaction.options.getSubcommand();
|
||||
|
||||
switch (subcommand) {
|
||||
case 'view':
|
||||
await this.showSettings(logger, executionId, interaction);
|
||||
break;
|
||||
|
||||
case 'bot-language':
|
||||
await this.handleBotLanguageChange(logger, executionId, interaction);
|
||||
break;
|
||||
case 'default-volume':
|
||||
await this.handleDefaultVolumeChange(logger, executionId, interaction);
|
||||
break;
|
||||
case 'defaul-search-engine':
|
||||
await this.handleDefaultSearchEngineChange(logger, executionId, interaction);
|
||||
break;
|
||||
default:
|
||||
await Promise.resolve();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches settings from the database and displays them in an embed message.
|
||||
* @param logger - The logger instance for logging debug information.
|
||||
* @param executionId - The execution ID for tracking the execution of the function.
|
||||
* @param interaction - The ChatInputCommandInteraction object representing the user interaction.
|
||||
* @returns A Promise that resolves once the settings are displayed.
|
||||
*/
|
||||
private async showSettings(
|
||||
logger: Logger,
|
||||
executionId: string,
|
||||
interaction: ChatInputCommandInteraction
|
||||
): Promise<void> {
|
||||
logger.debug('Fetching settings from database.');
|
||||
|
||||
const translator = useServerTranslator(interaction);
|
||||
const guildId = interaction.guildId;
|
||||
|
||||
try {
|
||||
const database = await guildDatabaseClient.getGuildConfig(guildId!, executionId, interaction);
|
||||
const settingsArray = [
|
||||
`> ・**${translator('commands.settings.metadata.options.bot-language.name')}**: ${database?.locale ?? 'English'}`,
|
||||
`> ・**${translator('commands.settings.metadata.options.default-volume.name')}**: ${database?.defaultVolume ?? 50}%`,
|
||||
`> ・**${translator('commands.settings.metadata.options.default-search-engine.name')}**: ${database?.defaultSearchEngine}`
|
||||
];
|
||||
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
.setDescription(settingsArray.join('\n'))
|
||||
.setFooter({
|
||||
text: interaction.user.username,
|
||||
iconURL: interaction.user.displayAvatarURL()
|
||||
})
|
||||
]
|
||||
});
|
||||
|
||||
logger.debug('Settings shown.');
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error(error, 'Error fetching settings from database.');
|
||||
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder().setColor(this.embedOptions.colors.error).setDescription(
|
||||
translator('commands.settings.botLanguageError', {
|
||||
icon: this.embedOptions.icons.error
|
||||
})
|
||||
)
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the change of the bot's language.
|
||||
*
|
||||
* @param logger - The logger instance.
|
||||
* @param executionId - The execution ID.
|
||||
* @param interaction - The chat input command interaction.
|
||||
* @returns A promise that resolves when the language change is handled.
|
||||
*/
|
||||
private async handleBotLanguageChange(
|
||||
logger: Logger,
|
||||
executionId: string,
|
||||
interaction: ChatInputCommandInteraction
|
||||
): Promise<void> {
|
||||
const language = interaction.options.getString('language')!;
|
||||
const translator = useServerTranslator(interaction);
|
||||
const guildId = interaction.guildId;
|
||||
|
||||
try {
|
||||
await guildDatabaseClient.createOrUpdateGuildConfig(
|
||||
executionId,
|
||||
guildId!,
|
||||
{ locale: language },
|
||||
interaction
|
||||
);
|
||||
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder().setColor(this.embedOptions.colors.success).setDescription(
|
||||
translator('commands.settings.botLanguageChanged', {
|
||||
icon: this.embedOptions.icons.success,
|
||||
language: language
|
||||
})
|
||||
)
|
||||
]
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error(error, 'Error setting bot language.');
|
||||
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder().setColor(this.embedOptions.colors.error).setDescription(
|
||||
translator('commands.settings.botLanguageError', {
|
||||
icon: this.embedOptions.icons.error
|
||||
})
|
||||
)
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the change of the default volume.
|
||||
*
|
||||
* @param logger - The logger instance.
|
||||
* @param executionId - The execution ID.
|
||||
* @param interaction - The chat input command interaction.
|
||||
* @returns A promise that resolves when the volume change is handled.
|
||||
*/
|
||||
private async handleDefaultVolumeChange(
|
||||
logger: Logger,
|
||||
executionId: string,
|
||||
interaction: ChatInputCommandInteraction
|
||||
): Promise<void> {
|
||||
const volume = interaction.options.getInteger('percentage')!;
|
||||
const translator = useServerTranslator(interaction);
|
||||
const guildId = interaction.guildId;
|
||||
|
||||
try {
|
||||
await guildDatabaseClient.createOrUpdateGuildConfig(
|
||||
executionId,
|
||||
guildId!,
|
||||
{ defaultVolume: volume },
|
||||
interaction
|
||||
);
|
||||
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder().setColor(this.embedOptions.colors.success).setDescription(
|
||||
translator('commands.settings.defaultVolumeChanged', {
|
||||
icon: this.embedOptions.icons.success,
|
||||
volume: volume
|
||||
})
|
||||
)
|
||||
]
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error(error, 'Error setting default volume.');
|
||||
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder().setColor(this.embedOptions.colors.error).setDescription(
|
||||
translator('commands.settings.defaultVolumeError', {
|
||||
icon: this.embedOptions.icons.error
|
||||
})
|
||||
)
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the change of the default search engine.
|
||||
*
|
||||
* @param logger - The logger instance.
|
||||
* @param executionId - The execution ID.
|
||||
* @param interaction - The chat input command interaction.
|
||||
* @returns A promise that resolves when the search engine change is handled.
|
||||
*/
|
||||
private async handleDefaultSearchEngineChange(
|
||||
logger: Logger,
|
||||
executionId: string,
|
||||
interaction: ChatInputCommandInteraction
|
||||
): Promise<void> {
|
||||
const engine = interaction.options.getString('provider')!;
|
||||
const translator = useServerTranslator(interaction);
|
||||
const guildId = interaction.guildId;
|
||||
|
||||
try {
|
||||
await guildDatabaseClient.createOrUpdateGuildConfig(
|
||||
executionId,
|
||||
guildId!,
|
||||
{ defaultSearchEngine: engine },
|
||||
interaction
|
||||
);
|
||||
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder().setColor(this.embedOptions.colors.success).setDescription(
|
||||
translator('commands.settings.defaultSearchEngineChanged', {
|
||||
icon: this.embedOptions.icons.success,
|
||||
provider: engine
|
||||
})
|
||||
)
|
||||
]
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error(error, 'Error setting default search engine.');
|
||||
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder().setColor(this.embedOptions.colors.error).setDescription(
|
||||
translator('commands.settings.defaultSearchEngineError', {
|
||||
icon: this.embedOptions.icons.error
|
||||
})
|
||||
)
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new SettingsCommand();
|
||||
Reference in new issue
Block a user