Discord.js guild.roles.cache.find returning undefined

余生颓废 提交于 2021-02-11 12:46:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!