【问题标题】:How do you give a specific member a role? Discord.js您如何赋予特定成员角色?不和谐.js
【发布时间】:2020-12-05 16:51:20
【问题描述】:

我必须创建一个帐户才能发布此消息,但我正在向我的机器人发出 !addrole 命令,并且在弄清楚如何将角色添加到成员时遇到了一些麻烦,它一直给我这个错误

TypeError: Cannot read property ‘roles’ of undefined

这是我一直在做的事情:

if (!message.content.startswith(prefix) || message.author.client) return;
const arguments = message.content.slice(prefix.length).split(‘‘);
const command = arguments.shift().toLowerCase();

if (command === ‘addrole’) {
    const role = message.guild.roles.cache.find(role => role.name === ‘ROLE’)
    const userId = arguments[0].slice(2, 19) // users id from the message
    const user = message.guild.members.cache.get(userId) // user itself 
    user.roles.add(role)
}

但它一直给我上面的错误,请帮助。 另外,请原谅我的大写和索引,我只是将代码从我的计算机复制到我的手机,我的浏览器有点小故障。 您也可以在 Ralphiboy22#7118 上私信

【问题讨论】:

  • 您是否在有效的公会中发送消息?
  • 是的,我很确定
  • 试试console.log(userId),它会返回你期望的结果吗?
  • 它准确地记录了我除了我的 id 之外的内容。

标签: javascript node.js discord discord.js


【解决方案1】:

有一个非常好的方法可以做到这一点,而不是做userId和user等,你可以使用message.mentions.members.first()这样:

const role = message.guild.roles.cache.find(role => role.name === ‘Insert role here’)
const target = message.mentions.members.first();
target.roles.cache.add(role)

您也可以在目标行的底部添加:

if(!target) message.channel.send(‘User not found!’)

【讨论】:

    【解决方案2】:

    discord.js v12 及更高版本使用Managers,这意味着您必须通过cache 属性传递它。

    user.roles.cache.add(role)
    

    GuildMemberRoleManager

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 1970-01-01
      • 2021-02-16
      • 2021-10-11
      • 2018-10-22
      • 2020-11-25
      • 2021-06-19
      • 2021-05-15
      • 2020-10-24
      相关资源
      最近更新 更多