implement reaction add/remove events

This commit is contained in:
Baipyrus 2024-02-05 02:56:18 +01:00
parent d7409ed0f7
commit afa958b557
2 changed files with 70 additions and 7 deletions

View File

@ -1,11 +1,43 @@
import { Events } from 'discord.js';
import { config } from 'dotenv'; import { config } from 'dotenv';
import { Events } from 'discord.js';
import { Message, RoleEmojiPair } from '../database.js';
config(); config();
export const name = Events.MessageReactionAdd; export const name = Events.MessageReactionAdd;
export async function execute(reaction, user) { export async function execute(reaction, user) {
if (user.id === process.env.CLIENT) return; if (user.id === process.env.CLIENT) return;
const uname = user.username;
const rname = reaction._emoji.name; // Get message
console.debug(`[DEBUG] User '${uname}' reacted with emoji '${rname}'.`); const msgID = reaction.message.id;
const message = await Message.findOne({
where: {
id: msgID,
}
});
// Ignore if unregistered
if (message === null) return;
// Get emoji
const emoji = reaction.emoji.toString();
const rep = await RoleEmojiPair.findOne({
where: {
message: msgID,
emoji,
}
});
// Deny if unregistered
if (rep === null) {
// Remove reaction and quit
await reaction.remove();
return;
}
// Fetch role from guild
const guild = reaction.message.guild;
const role = await guild.roles.fetch(rep.role);
if (role === null) return;
// Add role to user
await guild.members.addRole({ role, user });
console.info(`[INFO] Added role with id '${role.id}' to user '${user.username}'.`);
} }

View File

@ -1,8 +1,39 @@
import { config } from 'dotenv';
import { Events } from 'discord.js'; import { Events } from 'discord.js';
import { Message, RoleEmojiPair } from '../database.js';
config();
export const name = Events.MessageReactionRemove; export const name = Events.MessageReactionRemove;
export async function execute(reaction, user) { export async function execute(reaction, user) {
const uname = user.username; if (user.id === process.env.CLIENT) return;
const rname = reaction._emoji.name;
console.debug(`[DEBUG] User '${uname}' removed reaction of emoji '${rname}'.`); // Get message
const msgID = reaction.message.id;
const message = await Message.findOne({
where: {
id: msgID,
}
});
// Ignore if unregistered
if (message === null) return;
// Get emoji
const emoji = reaction.emoji.toString();
const rep = await RoleEmojiPair.findOne({
where: {
message: msgID,
emoji,
}
});
// Deny if unregistered
if (rep === null) return;
// Fetch role from guild
const guild = reaction.message.guild;
const role = await guild.roles.fetch(rep.role);
if (role === null) return;
// Add role to user
await guild.members.removeRole({ role, user });
console.info(`[INFO] Removed role with id '${role.id}' from user '${user.username}'.`);
} }