Search code examples
discorddiscord.jsbots

Discord JS - If the user reacting to message has a specific role I want to add a role


I'm attempting to create a more complex reaction role function.

Basically I want to achieve that if a user has 2 roles, it should have access to some channels. So the way I'm trying to do this is by checking if the user has one of the roles when clicking on a reaction that grants the member the second role. If the user has the other role, he should get a third role that unlocks these channels.

But, I haven't been able to figure out how to look at the roles of the person reacting to the message.

    client.on('messageReactionAdd', async (reaction, user) => {
  const message = await reaction.message.fetch(true);
  const channelAccess = '918617193988649002';
  const foodSweden = message.guild.roles.cache.find(role => role.name === 'πŸ²πŸ‡ΈπŸ‡ͺ');
  const foodCategoryReaction = '🍲';
    if (reaction.message.partial) await reaction.message.fetch();
    if (reaction.partial) await reaction.fetch();
    if (user.bot) return;
    if (!reaction.message.guild) return;
    if (reaction.message.channel.id === channelAccess) {
      if (reaction.emoji.name === foodCategoryReaction && message.member.roles.has('πŸ‡ΈπŸ‡ͺ')) {
        await reaction.message.guild.members.cache.get(user.id).roles.add(foodSweden);
      } else {
        return;
      }
    }
  });

So this is the code. I'm uncertain how message.member.roles.has('πŸ‡ΈπŸ‡ͺ') should be coded. I've tried reaction.message.member.roles.has('πŸ‡ΈπŸ‡ͺ'), reaction.member.roles.has('πŸ‡ΈπŸ‡ͺ'), user.roles.has('πŸ‡ΈπŸ‡ͺ') and shifted out member for user.


Solution

  • I'm uncertain how message.member.roles.has('πŸ‡ΈπŸ‡ͺ') should be coded. I've tried reaction.message.member.roles.has('πŸ‡ΈπŸ‡ͺ'), reaction.member.roles.has('πŸ‡ΈπŸ‡ͺ'), user.roles.has('πŸ‡ΈπŸ‡ͺ') and shifted out member for user.

    None of those are existing methods. member.roles does not have a .has() method. And users represent general discord users outside of guilds; users do not have roles, only guild members have roles. The .has() method of any manager in discord.js also usually utilizes IDs (which is what they are mapped to in the underlying Collection cache), not names or other properties. See the docs.

    Here is how you check if the member who reacted has a specific role:

    const hasRole = reaction.message.member.roles.cache.some(role => role.name == "πŸ‡ΈπŸ‡ͺ");
    

    The role cache for guild members is almost always up-to-date, so you don't really need to do any fetching. You can rely on the role cache here.