DiscordJS-Example/events/messages/reactionAdd.js

67 lines
1.6 KiB
JavaScript
Raw Normal View History

2024-02-11 01:04:12 +00:00
import { Events, MessageReaction, User } from 'discord.js';
import { Messages, RoleEmojiPairs } from '../../database.js';
2024-02-11 01:04:12 +00:00
import { config } from 'dotenv';
2024-02-06 20:25:47 +00:00
2024-02-04 22:41:04 +00:00
config();
2024-01-26 19:23:45 +00:00
export const name = Events.MessageReactionAdd;
2024-02-11 01:04:12 +00:00
/**
* @param {MessageReaction} reaction
* @param {User} user
*/
2024-01-28 17:33:03 +00:00
export async function execute(reaction, user) {
2024-02-04 22:41:04 +00:00
if (user.id === process.env.CLIENT) return;
2024-02-05 01:56:18 +00:00
// Get message
const msgID = reaction.message.id;
/** @type {import('../../models/messages.js').Message|null} */
const message = await Messages.findOne({
2024-02-05 01:56:18 +00:00
where: {
2024-02-06 15:18:06 +00:00
id: msgID
2024-02-05 01:56:18 +00:00
}
});
// Ignore if unregistered
if (message === null) return;
// Get emoji
const emoji = reaction.emoji.toString();
/** @type {import('../../models/roleEmojiPairs.js').RoleEmojiPair|null} */
const rep = await RoleEmojiPairs.findOne({
2024-02-05 01:56:18 +00:00
where: {
message: msgID,
2024-02-06 15:18:06 +00:00
emoji
2024-02-05 01:56:18 +00:00
}
});
// Deny if unregistered
if (rep === null) {
// Remove reaction and quit
2024-02-16 17:26:25 +00:00
try {
2024-04-04 07:40:23 +00:00
await reaction.remove();
2024-02-16 17:26:25 +00:00
} catch (error) {
// Missing permissions
2024-02-28 19:43:36 +00:00
console.error(error);
2024-02-16 17:26:25 +00:00
await user.send('Unable to remove reaction. Please contact server staff.');
}
2024-02-05 01:56:18 +00:00
return;
}
// Fetch role from guild
const guild = reaction.message.guild;
const role = await guild.roles.fetch(rep.role);
2024-02-05 20:19:47 +00:00
// Role not found
if (role === null) {
await user.send('Could not fetch role! Please contact server staff.');
return;
}
2024-02-05 01:56:18 +00:00
2024-02-05 20:11:59 +00:00
try {
// Add role to user
await guild.members.addRole({ role, user });
console.info(`[INFO] Added role with id '${role.id}' to user '${user.username}'.`);
} catch (error) {
// Missing permissions
console.error(error);
await user.send('Unable to assign role. Please contact server staff.');
}
2024-01-26 19:23:45 +00:00
}