im trying to make a basic bot add/remove role when add/remove reaction from a post on discord.
The code works if i add the role first and then remove it, but lets say i already have the role and restart the script. When i remove the reaction the script gives me the error saying: "Cannot read properties of undefined (reading 'roles')"
client.on('messageReactionRemove', async (reaction, user) => {
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.error('Something went wrong when fetching the message:', error);
return;
}
}
if (reaction.message.id != pinnedMsg) {
return;
}
var role = reaction.message.guild.roles.cache.find(role => role.name === "ROLENAME");
const guild = reaction.message.guild;
const member = await guild.members.cache.find(member => member.id === user.id);
member.roles.remove(role); }); //var member is undefined here
CodePudding user response:
You need to fetch members with <Guild>.members.fetch
because they are not cached. Don't forget to use await
when needed, to find in cache it's not necessary.
Example for your case:
await guild.members.fetch();
const member = guild.members.cache.find(member => member.id === user.id);