(buttons): Implement role-button button.

This commit is contained in:
2026-10-14 11:58:27 +08:00
parent e87be791eb
commit f92a650536
+29 -23
View File
@@ -1,32 +1,38 @@
import { ButtonInteraction, Client, MessageFlags } from 'discord.js'; import { ButtonInteraction, Client, MessageFlags } from 'discord.js';
import { Button } from '../types';
import { Database } from '../shared/Database'; import { Database } from '../shared/Database';
export default { class RoleButtonButton implements Button<Client> {
name: 'role-button', id = 'role-button';
handler: async function (client: Client, interaction: ButtonInteraction) {
await interaction.deferReply({ flags: [MessageFlags.Ephemeral] });
const roleId = await Database.getRoleFromButton(interaction.message.id); async execute(context: Client<boolean>, interaction: ButtonInteraction, ...args: any[]): Promise<void> {
if (!interaction.inGuild()) return;
if (!roleId) await interaction.editReply({ content: 'Could not find role button.' }); await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const guild = await interaction.guild?.fetch();
const member = await guild?.members.fetch(interaction.user.id);
if (!member) return interaction.editReply({ content: 'Member not found.' });
try { try {
if (member.roles.cache.has(roleId!)) { const roleId = await Database.getRoleFromButton(interaction.message.id);
await member.roles.remove(roleId!); if (!roleId) throw new Error("I couldn't find an associated role ID with this button.");
interaction.editReply({ content: 'Role removed.' });
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 { } else {
await member.roles.add(roleId!); await member.roles.add(roleId);
interaction.editReply({ content: 'Role added.' }); await interaction.editReply({ content: 'Role Added' });
}
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
} }
} catch (e) { export default new RoleButtonButton();
console.error(e);
interaction.editReply({ content: 'Could not add role. Is it higher than mine?' });
}
}
};