discord.js |从成员中删除一个角色,并将该角色赋予另一个成员



我试图从一个人身上删除一个角色,并将该角色交给启动命令的人。

当人A第一次调用该命令时,它就起作用了。但当其他人第二次尝试调用该命令,代码就找不到人A。任何帮助都很酷。

//Just some startup stuff
const { error, timeStamp } = require('console'),
client = new Discord.Client(),
client.login('How About No?')
var command, role, person
//Check if it's alive
client.once('ready', () => {
console.log(`${client.user.tag} is online`)
})
//When a message is sent
client.on('message', message => {
command = message.content.toLowerCase()
if(command === 'test' && message.guild.id === 'the server ID'){
role = message.guild.roles.cache.find(r => r.id === 'the role ID') //Find the correct role
person = role.members.first()
/* I can use ".first()" here, because there's never supposed to be more than one person with this role.
The problem is here. On the second run, it outputs "undefined" even though a person has the role. */
//If a person has the role, remove it from them.
if(typeof person !== 'undefined') person.roles.remove(role).catch(error => console.log(error))
//Give the role
person = message.member
person.roles.add(role).catch(error => console.log(error))
}
})

有时会发生这种情况,因为缓存更新速度不够快。

您可以做的是使用API请求获取角色。

message.guild.roles.fetch('the role ID',true,true)

最新更新