mirror of
https://github.com/darksaid98/cadence-discord-bot.git
synced 2026-12-01 14:38:48 +00:00
start of settings command
This commit is contained in:
1 parent
321a9664ce
commit
8af2384502
4 files changed
+197
-83
No files matched your search
+37
-1
@@ -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": {
|
||||
|
||||
+5
-20
@@ -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
|
||||
|
||||
@@ -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)
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,16 +17,10 @@ function getLogger(executionId: string, interaction?: Interaction | MessageCompo
|
||||
export type GuildSettings = {
|
||||
defaultVolume?: number;
|
||||
locale?: string;
|
||||
privilegedRoles?: string[];
|
||||
actionPermissions?: Record<string, string[]>;
|
||||
};
|
||||
|
||||
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, string[]>): string {
|
||||
return JSON.stringify(permissions);
|
||||
}
|
||||
|
||||
function deserializeRoleIds(serializedRoles: string): string[] {
|
||||
return serializedRoles.split(',').filter((role) => role.trim() !== '');
|
||||
function deserializeActionPermissions(serializedPermissions: string): Record<string, string[]> {
|
||||
return JSON.parse(serializedPermissions);
|
||||
}
|
||||
|
||||
export default guildDatabaseService;
|
||||
Reference in new issue
Block a user