Merge pull request #392 from pryzmian/settings-command

feat(settings): Implement settings command
This commit is contained in:
Marius Begby authored and GitHub committed 2024-02-25 13:01:13 +01:00
commit 227134cc7b
5 files changed
+401 -15

No files matched your search

+27 -6
View File
@@ -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",
+63 -1
View File
@@ -290,10 +290,72 @@
"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%."
}
}
},
"default-search-engine": {
"name": "motor-de-busqueda-predeterminado",
"description": "Establece el proveedor de búsqueda predeterminado para usar en el bot.",
"options": {
"provider": {
"name": "proveedor",
"description": "Proveedor de búsqueda para usar en el bot.",
"choices": {
"youtube": "YouTube",
"spotify": "Spotify"
}
}
}
},
"view": {
"name": "ver",
"description": "Muestra la configuración actual del servidor."
}
}
},
"botLanguageChanged": "{{icon}} **Idioma del bot cambiado**\nEl idioma del bot se ha cambiado a **`{{language}}`**.",
"botLanguageInformation": "{{icon}} **Idioma del bot**\nEl idioma del bot actualmente está configurado en **`{{language}}`**.",
"botLanguageError": "{{icon}} **¡Vaya!**\nHubo un error al intentar cambiar el idioma del bot. Por favor, inténtalo de nuevo más tarde.",
"noDatabaseFound": "{{icon}} **¡Vaya!**\nNo se encontró ninguna base de datos para este servidor. Por favor, inténtalo de nuevo más tarde.",
"errorGettingSettings": "{{icon}} **¡Vaya!**\nHubo un error al intentar obtener la configuración de este servidor. Por favor, inténtalo de nuevo más tarde.",
"invalidDefaultVolume": "{{icon}} **¡Vaya!**\nNo puedes establecer el volumen predeterminado en **`{{wrongVolume}}%`**, por favor elige un valor entre **`0%`** y **`100%`**.",
"defaultVolumeError": "{{icon}} **¡Vaya!**\nHubo un error al intentar cambiar el volumen predeterminado. Por favor, inténtalo de nuevo más tarde.",
"defaultVolumeChanged": "{{icon}} **Volumen predeterminado cambiado**\nEl volumen predeterminado se ha cambiado a **`{{volume}}%`**.",
"defaultSearchEngineError": "{{icon}} **¡Vaya!**\nHubo un error al intentar cambiar el motor de búsqueda predeterminado. Por favor, inténtalo de nuevo más tarde.",
"defaultSearchEngineChanged": "{{icon}} **Motor de búsqueda predeterminado cambiado**\nEl motor de búsqueda predeterminado se ha cambiado a **`{{provider}}`**."
},
"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",
+5 -4
View File
@@ -4,15 +4,16 @@ generator client {
datasource db {
provider = "sqlite"
url = "file:./dev.db"
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
+12 -4
View File
@@ -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,9 +28,15 @@ 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 }
});
const config = await prisma.guildConfig
.findUnique({
where: { guildId: guildId }
})
.catch((error) => {
logger.error(error, 'Error getting guild config from database.');
return null;
});
if (!config) {
logger.debug(`No config found for guild ${guildId}.`);
@@ -87,7 +94,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,6 +103,7 @@ export function validateGuildConfig(logger: Logger, configData: GuildConfig) {
const validConfig = {
defaultVolume: configData.defaultVolume,
defaultSearchEngine: configData.defaultSearchEngine,
locale: configData.locale,
actionPermissions: serializeActionPermissions(configData.actionPermissions ?? {})
};
+294
View File
@@ -0,0 +1,294 @@
import { ChatInputCommandInteraction, EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import { BaseSlashCommandInteraction } from '../../common/classes/interactions';
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
import { localizeCommand, useServerTranslator } from '../../common/utils/localeUtil';
import guildDatabaseClient 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();