按ID[DISCORD.JS]从角色中添加/删除用户

按ID[DISCORD.JS]从角色中添加/删除用户,discord.js,Discord.js,嘿,今天我想根据用户的ID从用户中授予和删除角色 第一次尝试: const user='5454654687868768' 常量角色='451079228381724672' user.roles.remove(角色) 第二次尝试: const user='5454654687868768' 常量角色='451079228381724672' user.ole(角色) 然而,这两种方法似乎都不起作用。您的第一次尝试实际上并不遥远。唯一的问题是roles.remove()是一个函数 所以首先我

嘿,今天我想根据用户的ID从用户中授予和删除角色

第一次尝试:

const user='5454654687868768'
常量角色='451079228381724672'
user.roles.remove(角色)
第二次尝试:

const user='5454654687868768'
常量角色='451079228381724672'
user.ole(角色)

然而,这两种方法似乎都不起作用。

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

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

const member = message.guild.members.cache.get("member ID here");
现在我们可以删除或添加角色

这些数字恰好是用户和角色对象的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,因为我们需要等待bot从API获取成员对象,然后才能向其添加角色。

您是否尝试过读取或?是的,但是文档记录了“信息提及成员”,我看不出有什么问题。谢谢。即使我链接的页面没有准确回答你的问题,一般来说,阅读指南会让你对图书馆有更深入的了解。
const user = '5454654687868768'
const role = '451079228381724672'
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.
}