From 6f561f3b4458ff5cc4a597e824cfb6e8f7253c99 Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 20 Dec 2024 02:12:27 -0500 Subject: [PATCH] MessagePinReactionHandler.ts /** * Handles both 'messageReactionAdd' and 'messageReactionRemove' events. * When a reaction is added or removed: * - If the reaction matches the specified emoji and the user has the required role, * the message will be pinned or unpinned in the channel accordingly. */ Signed-off-by: Harry --- discord/events/MessagePinReactionHandler.ts | 66 +++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 discord/events/MessagePinReactionHandler.ts diff --git a/discord/events/MessagePinReactionHandler.ts b/discord/events/MessagePinReactionHandler.ts new file mode 100644 index 0000000..d11e52e --- /dev/null +++ b/discord/events/MessagePinReactionHandler.ts @@ -0,0 +1,66 @@ +import DiscordEvent from "../../util/DiscordEvent"; +import { Client, MessageReaction, PartialMessageReaction, PartialUser, User, Events } from "discord.js"; + +const ROLE_ID = '446104438969466890'; // Allowed role ID +const PUSH_PIN_EMOJI = '📌'; // Unicode + +export default class MessageReactionHandler extends DiscordEvent { + constructor(client: Client) { + super(Events.MessageReactionAdd, client); // Register the "messageReactionAdd" event + client.on(Events.MessageReactionRemove, this.handleRemove.bind(this)); // Register "messageReactionRemove" within the same class + } + + public async execute(reaction: MessageReaction | PartialMessageReaction, user: User | PartialUser): Promise { + // Handle reaction add (pinning a message) + if (reaction.partial) { + try { + await reaction.fetch(); + } catch (error) { + console.error('Error fetching reaction:', error); + return; + } + } + + if (reaction.emoji.name !== PUSH_PIN_EMOJI) return; + + const guild = reaction.message.guild; + if (!guild) return; + + const member = await guild.members.fetch(user.id); + if (!member.roles.cache.has(ROLE_ID)) return; + + try { + await reaction.message.pin(); + console.log(`Pinned message: ${reaction.message.id}`); + } catch (error) { + console.error('Failed to pin message:', error); + } + } + + private async handleRemove(reaction: MessageReaction | PartialMessageReaction, user: User | PartialUser): Promise { + // Handle reaction remove (unpinning a message) + if (reaction.partial) { + try { + await reaction.fetch(); + } catch (error) { + console.error('Error fetching reaction:', error); + return; + } + } + + if (reaction.emoji.name !== PUSH_PIN_EMOJI) return; + + const guild = reaction.message.guild; + if (!guild) return; + + const member = await guild.members.fetch(user.id); + if (!member.roles.cache.has(ROLE_ID)) return; + + try { + await reaction.message.unpin(); + console.log(`Unpinned message: ${reaction.message.id}`); + } catch (error) { + console.error('Failed to unpin message:', error); + } + } +}