Im trying to assign code a discord bot to give someone a role whenever they enter a server. This is my code right now:
client.on('guildMemberAdd', (member) => {
let role = guild.roles.cache.find(r => r.name === "Admin");
console.log(role);
if(!role){
console.log("Role doesen't exist.");
}
member.roles.add(role);
});
I tried running it, and this line executed: console.log("Role doesen't exist.");
. I then went on to print the role variable, and it was undefined. What's the problem?
Everything might not be available in cache, so you need to fetch it, the only issue is that you need to fetch via the ID.
let role = guild.roles.cache.find(r => r.name === 'ADMIN') || await guild.roles.fetch('ROLEID');
Source: https://discord.js.org/#/docs/main/stable/class/RoleManager?scrollTo=fetch
This is a rather hacky solution, but you can fetch all roles on ready event.
client.guilds.cache.forEach(g => {
g.roles.fetch();
});
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.