【问题标题】:roles.cache.find() for finding a role returning undefinedroles.cache.find() 用于查找返回未定义的角色
【发布时间】:2021-07-01 19:55:38
【问题描述】:

我有以下代码:

collector.on('collect', async (reaction, user) => {
    if (!user.bot) {
        let role = reaction.message.guild.roles.cache.find((role) => { return role.name === '️announcements-ping' });
        console.log(role);
        /* let userMember = await reaction.message.guild.members.fetch(user);
        userMember.roles.add(role); */
    }
});

它应该将announcements-ping 角色添加到对消息作出反应的任何人,但是当我控制台记录变量role 时,它返回未定义。

我做错了什么?

谢谢!

【问题讨论】:

  • 表示角色announcements-ping不存在。不建议使用角色名称,因为它们可以快速更改。相反,使用role = reaction.message.guild.roles.cache.find(role => role.id === 'RoleID');
  • 如果您使用的是 ID,建议使用 .get()

标签: javascript node.js discord discord.js bots


【解决方案1】:

确保角色名称正确。如果正确,则该角色可能未缓存,您需要获取它。 .fetch() 返回一个承诺,所以请确保你 await 得到结果。

查看以下代码:

collector.on('collect', async (reaction, user) => {
  if (user.bot) return;

  try {
    let roles = await reaction.message.guild.roles.fetch();
    // you can also get the role by id
    // let role = roles.cache.get('872088xxxxx0194211');
    let role = roles.cache.find((r) => r.name.toLowerCase() === '️announcements-ping');

    if (!role) return console.log(`Oops, I can't find the role`);

    let member = await reaction.message.guild.members.fetch(user);
    member.roles.add(role);
  } catch (error) {
    console.log(error);
  }
});

【讨论】:

  • 这对我不起作用,我收到了错误消息。
  • "哎呀我找不到角色"
  • 那么服务器上不存在名为announcements-ping的角色。您是否仔细检查了它是否是正确的名称?
  • 是的。我什至复制粘贴了它以确保
  • 您是否尝试过创建一个具有不同名称的新角色并在代码中对其进行更新以进行检查?我的想法已经不多了。
【解决方案2】:

您的代码似乎有效,请确保您的角色名称有效。 (也区分大小写)

如果不和谐,建议改用 ID。如果您不知道如何收集它们,请访问此page

let role = reaction.message.guild.roles.cache.find(role => role.id === '️roleID');
// OR
let role = reaction.message.guild.roles.cache.get('️roleID');

【讨论】:

  • 有没有办法使用 DiscordJS 而不是手动获取 ID?
  • 通过使用角色名来收集,然后使用id getter。
  • 您能否链接一个解释如何执行此操作或编辑您的代码或其他内容的站点?没有压力,只是想知道 C:
猜你喜欢
  • 2021-01-12
  • 2019-10-09
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 2016-03-20
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
相关资源
最近更新 更多