1
votes

I have the code below:

collector.on('collect', async (reaction, user) => {
    if (!user.bot) {
        let role = reaction.message.guild.roles.cache.find((role) => { return role.name === '️announcements-ping' });
        console.log(role);
        /* let userMember = await reaction.message.guild.members.fetch(user);
        userMember.roles.add(role); */
    }
});

It's supposed to add the announcements-ping role to whoever reacts to the message, but when I console log the variable role it returns undefined.

What am I doing wrong?

Thanks!

2
It means role announcements-ping does not exist. It's not recommended to use role names, as they can change rapidly. Instead, use role = reaction.message.guild.roles.cache.find(role => role.id === 'RoleID');KifoPL
It's recommend to use .get() if you're using an IDElitezen

2 Answers

1
votes

Make sure that the role name is correct. If it's correct, maybe the role is not cached and you'll need to fetch it. .fetch() returns a promise, so make sure you await the results.

Check out the code below:

collector.on('collect', async (reaction, user) => {
  if (user.bot) return;

  try {
    let roles = await reaction.message.guild.roles.fetch();
    // you can also get the role by id
    // let role = roles.cache.get('872088xxxxx0194211');
    let role = roles.cache.find((r) => r.name.toLowerCase() === '️announcements-ping');

    if (!role) return console.log(`Oops, I can't find the role`);

    let member = await reaction.message.guild.members.fetch(user);
    member.roles.add(role);
  } catch (error) {
    console.log(error);
  }
});

enter image description here

0
votes

Your code seems valid, make sure that your role name is valid. (Case sensitive too)

With discord, it's recommended to use Ids instead. Visit this page if you don't know how to collect them.

let role = reaction.message.guild.roles.cache.find(role => role.id === '️roleID');
// OR
let role = reaction.message.guild.roles.cache.get('️roleID');