【问题标题】:Add / Remove user from role by ID [DISCORD.JS]按 ID [DISCORD.JS] 从角色中添加/删除用户
【发布时间】:2020-10-15 14:50:10
【问题描述】:

嘿,今天我想通过用户 ID 授予和删除用户角色

第一次尝试:

const user = '5454654687868768'
const role = '451079228381724672'

user.roles.remove(role)

第二次尝试:

const user = '5454654687868768'
const role = '451079228381724672'

user.removeRole(role)

然而,这些方法中的任何一种似乎都不起作用。

【问题讨论】:

标签: discord.js


【解决方案1】:
const user = '5454654687868768'
const role = '451079228381724672'

这些只是恰好是您的用户和角色对象的 id 的数字。它们本身什么都不是,你不能在它们上调用任何 Discordjs 方法。要获取用户和角色对象,您首先必须使用它们各自的 ID 获取它们。

假设您想在有人加入服务器时添加角色,您可以在任何类型的事件中执行相同的操作,但我们将使用 guildMemberAdd 事件作为示例:

bot.on('guildMemberAdd', async member => {
    const memberID = '5454654687868768';   // you want to add/remove roles. Only members have roles not users. So, that's why I named the variable memberID for keeping it clear.
    const roleID = '451079228381724672';

    const guild = bot.guilds.cache.get('guild-ID');   // copy the id of the server your bot is in and paste it in place of guild-ID.
    const role = guild.roles.cache.get(roleID);  // here we are getting the role object using the id of that role.
    const member = await guild.members.fetch(memberID); // here we are getting the member object using the id of that member. This is the member we will add the role to.
    member.roles.add(role);   // here we just added the role to the member we got.
}

看到这些方法之所以有效,是因为它们是真正的 discordjs 对象,而不是您尝试做的一些数字。还有 async/await 的东西,因为我们需要等待机器人从 API 中获取成员对象,然后才能为其添加角色。

【讨论】:

    【解决方案2】:

    您的第一次尝试实际上并没有那么遥远。唯一的问题是roles.remove() 是一个guildMember 函数。

    所以首先我们需要定义成员。

    const member = message.guild.members.cache.get("member ID here");
    

    现在我们可以删除或添加角色。 Source

    member.roles.remove("role ID here");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-04
      • 2022-01-18
      • 2021-08-12
      • 2020-08-24
      • 2021-12-13
      • 2020-12-27
      • 2018-11-29
      • 2019-12-11
      相关资源
      最近更新 更多