简体   繁体   English

Discord.js guild.roles.cache.find 返回未定义

[英]Discord.js guild.roles.cache.find returning undefined

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.");我尝试运行它,并执行了这一行: console.log("Role doesen't exist."); . . I then went on to print the role variable, and it was undefined.然后我继续打印角色变量,它是未定义的。 What's the problem?有什么问题?

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.缓存中可能无法获取所有内容,因此您需要获取它,唯一的问题是您需要通过 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来源: 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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM