使用作者ID添加角色

时间:2020-10-16 16:27:05

标签: javascript discord discord.js

每当我尝试使用此命令时,它都会产生错误,我尝试了几种方法,但它始终会出现错误,我在做什么错了?

我的代码:

exports.run = async (database, client, message, args) => {
    const roleadd = await message.guild.roles.cache.find(r => r.name === 'Sem Whitelist')

    client.users.fetch(message.author.id).then(user => {
        user.roles.add(roleadd)
    })
    
    message.reply('done.')
}

错误代码:

(node:2248) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'add' of undefined

编辑

用户日志:

User {
  id: '354395231002820608',
  username: 'Pinheiro',
  bot: false,
  discriminator: '2202',
  avatar: 'a_c0697e7f736cb3fac9ef44a33f23ee6a',
  flags: UserFlags { bitfield: 256 },
  lastMessageID: '766703250878627891',
  lastMessageChannelID: '765642688162299905'
}

2 个答案:

答案 0 :(得分:0)

用户没有角色对象。您将需要获得guildMember。
您可以通过以下方式获取guildMember对象:

message.guild.member('userID');

要向消息作者添加角色,您将使用:

exports.run = async (database, client, message, args) => {
    const role = await message.guild.roles.cache.find(r => r.name === 'Sem Whitelist')

    let user = message.author;
    user = message.guild.member(user);
    user.roles.add(role).then({
        message.reply('done.')
    });
}

答案 1 :(得分:0)

如果您要为用户添加角色,请使用以下代码。

exports.run = async (database, client, message, args) => {
    const roleadd = await message.guild.roles.cache.find(r => r.name === 'Sem Whitelist')

    client.users.fetch(message.author.id).then(user => {
        user.roles = roleadd;
    })
    
    message.reply('done.')
}