Skip to content

Instantly share code, notes, and snippets.

@harishkotra
Created April 20, 2024 17:54
Show Gist options
  • Save harishkotra/363754215b669d73f0a6c6d87b68e06e to your computer and use it in GitHub Desktop.
Save harishkotra/363754215b669d73f0a6c6d87b68e06e to your computer and use it in GitHub Desktop.
✅ Discord.js v14.14.1: Add Role on Reaction Add
/**
* Easily add roles from Discord users when they add a specific reactions using discord.js v14.14.1. (discord.js 14+)
*/
const { Client, Events, GatewayIntentBits, Partials } = require('discord.js');
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessageReactions],
partials: [Partials.Message, Partials.Channel, Partials.Reaction],
});
client.on(Events.MessageReactionAdd, async (reaction, user) => {
// **Error Handling:** Check for partial reactions
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.error('Error fetching message:', error);
return; // Prevent potential errors by stopping execution
}
}
// **Configuration:** Replace these placeholders with your actual values
const channelID = 'YOUR_CHANNEL_ID'; // Channel ID where the reaction is added
const targetMessageID = 'YOUR_MESSAGE_ID'; // Message ID where the reaction is added
const reactionEmoji = 'YOUR_REACTION_EMOJI'; // Name of the emoji to add role on
const roleID = 'YOUR_ROLE_ID'; // Role ID to be assigned
// **Conditional Check:** Ensure correct channel, message, and emoji
if (
reaction.message.channelId === channelID &&
reaction.message.id === targetMessageID &&
reaction.emoji.name === reactionEmoji
) {
const guildMember = reaction.message.guild.members.cache.get(user.id);
const role = reaction.message.guild.roles.cache.get(roleID);
// **Grant Role:** Add role if user isn't a bot and doesn't already have it
if (!user.bot && !guildMember.roles.cache.find(role => role.id === roleID)) {
await guildMember.roles.add(role);
console.log(`${user.username} granted role ${role.name}`);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment