问题
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?
回答1:
First Method
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
Second Method
This is a rather hacky solution, but you can fetch all roles on ready event.
client.guilds.cache.forEach(g => {
g.roles.fetch();
});
来源:https://stackoverflow.com/questions/64611779/discord-js-guild-roles-cache-find-returning-undefined