From f92a650536b9c77ed913ca3a04f991751084582a Mon Sep 17 00:00:00 2001 From: Nix Krystik Date: Wed, 14 Oct 2026 11:58:27 +0800 Subject: [PATCH] (buttons): Implement `role-button` button. --- src/buttons/role-button.ts | 52 +++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 23 deletions(-) diff --git a/src/buttons/role-button.ts b/src/buttons/role-button.ts index c20fc36..327c893 100644 --- a/src/buttons/role-button.ts +++ b/src/buttons/role-button.ts @@ -1,32 +1,38 @@ import { ButtonInteraction, Client, MessageFlags } from 'discord.js'; +import { Button } from '../types'; import { Database } from '../shared/Database'; -export default { - name: 'role-button', - handler: async function (client: Client, interaction: ButtonInteraction) { - await interaction.deferReply({ flags: [MessageFlags.Ephemeral] }); +class RoleButtonButton implements Button { + id = 'role-button'; - const roleId = await Database.getRoleFromButton(interaction.message.id); - - if (!roleId) await interaction.editReply({ content: 'Could not find role button.' }); - - const guild = await interaction.guild?.fetch(); - const member = await guild?.members.fetch(interaction.user.id); - - if (!member) return interaction.editReply({ content: 'Member not found.' }); + async execute(context: Client, interaction: ButtonInteraction, ...args: any[]): Promise { + if (!interaction.inGuild()) return; + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); try { - if (member.roles.cache.has(roleId!)) { - await member.roles.remove(roleId!); - interaction.editReply({ content: 'Role removed.' }); - } else { - await member.roles.add(roleId!); - interaction.editReply({ content: 'Role added.' }); - } + const roleId = await Database.getRoleFromButton(interaction.message.id); + if (!roleId) throw new Error("I couldn't find an associated role ID with this button."); - } catch (e) { - console.error(e); - interaction.editReply({ content: 'Could not add role. Is it higher than mine?' }); + const guild = await context.guilds.fetch(interaction.guildId); + const member = await guild.members.fetch(interaction.user.id); + if (!member) throw new Error('I was unable to fetch you as a member.'); + + const bot = await guild.members.fetchMe(); + const role = await guild.roles.fetch(roleId); + if (!role) throw new Error("The configured role for this button doesn't exist."); + if (role.position > bot.roles.highest.position) throw new Error(`The configured role (\`${role.name}\`) is higher than my highest role.`); + + if (member.roles.cache.has(roleId)) { + await member.roles.remove(roleId); + await interaction.editReply({ content: 'Role removed.' }); + } else { + await member.roles.add(roleId); + await interaction.editReply({ content: 'Role Added' }); + } + } catch (error: Error | any) { + await interaction.editReply({ content: error.message }).catch(() => {}); } } -}; \ No newline at end of file +} + +export default new RoleButtonButton(); \ No newline at end of file