简体   繁体   中英

Discord.js : reaction.message.guild.members.find is not a function

I am trying to make a Discord.js bot that add the "Joueur" role to the user who reacted with the ✅ emoji. I am new to JS and I found the reaction.message.guild.members.find function on the Internet but I somehow get the error TypeError: reaction.message.guild.members.find is not a function and the role is not added. Here is the part of my code:

client.on('messageReactionAdd', async (reaction, user) => {
    if (reaction.emoji.name === "✅") {
      try {
        reaction.message.guild.members.find('id', user.id).addRole(reaction.message.guild.roles.find('name', 'Joueur'));
      } catch {
        console.log('Error : can\'t add the role');
      }
   }
});

If you're using Discord.js v12 (the latest version), Guild#members is a GuildMemberManager , not a Collection like in v11.

To access the collection use the cache property.

Another difference is that Collection does not support finding something by key and value like that. You would need to use this:

reaction.message.guild.members.cache.find(member => member.id === user.id)

You might also want to check that the reaction was done in a guild (unless you're using intents and aren't using the DIRECT_MESSAGE_REACTIONS intent). People can add reactions to messages in DMs as well, so reaction.message.guild may be undefined .

If you are using latest version, here is an example:

They have also changed addRole to: roles.add in v12

let role = message.guild.roles.cache.find(role => role.name === 'somerolename');
reaction.message.guild.member(user).roles.add(role.id).catch(console.error);

https://discordjs.guide/additional-info/changes-in-v12.html#roles

According to the doc , you can use reaction.users to get a collection of users who reacted to the message. The collection will look something like this:

Collection(n)[Map] {
    'id_of_user_who_reacted' => <ref*1> ClientUser{
        id: 'id_of_user_who_reacted',
        username: String,
        discriminator:String
        ...
    }
}

Then you can use the map() method of the Collector type to get the user id

console.log(reaction.users.map(user => user.id))

which will return an array that will look like this: ['id', 'id', 'id'] Then you can change the role of those users.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM