问题
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');
}
}
});
回答1:
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
.
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/61455173/discord-js-reaction-message-guild-members-find-is-not-a-function