【问题标题】:discord.js - Newly added reaction is instantly removeddiscord.js - 立即删除新添加的反应
【发布时间】:2021-01-03 22:40:55
【问题描述】:

我正在使用 discord.js 版本 12.3.1 并尝试创建一个系统,用户可以在其中对消息做出反应并从中接收角色。当您单击??????时,您将获得“蓝色”角色。如果您然后单击????,例如,您的????反应被移除,您将获得“绿色”角色。

问题在于添加新角色并不能始终如一地工作。即使确认添加的角色在已删除角色的集合中,添加的角色有时也会添加给用户,然后立即删除。

我认为导致问题的具体行:

const addRole = guildRoles.find(role => role.name === colorRoles[emojiName])
// addRole: Role (ex. with name 'GREEN')
guildMember.roles.add(addRole)

const removeRoles = guildRoles.filter(role => Object.values(colorRoles).filter(color => color !== colorRoles[emojiName]).includes(role.name))
// removeRoles: Collection of Roles (ex. with names 'BLUE', 'RED', 'YELLOW')
guildMember.roles.remove(removeRoles)

// At this point 'GREEN' is added and removed; all other color roles are removed

Full method with more context on Pastebin

我不明白为什么新添加的颜色角色有时会立即被删除,非常感谢一些建议。

【问题讨论】:

    标签: javascript discord discord.js


    【解决方案1】:

    这里的问题是guildMember.roles.remove(removeRoles) 返回一个Promise。这意味着它不会同步执行,所以我们需要等到执行完成。 我们可以通过await调用函数来做到这一点:

    const removeRoles = guildRoles.filter(role => Object.values(colorRoles).filter(color => color !== colorRoles[emojiName]).includes(role.name));
    await guildMember.roles.remove(removeRoles);
    
    // Find that color's Role name, then add it to the GuildMember
    const addRole = guildRoles.find(role => role.name === colorRoles[emojiName]);
    await guildMember.roles.add(addRole);
    

    我还切换了删除并以相反的方式添加。

    【讨论】:

    • 这修复了它,但我不明白为什么。如果验证removeRoles 集合不包含addRole 角色,为什么需要等待remove(removeRoles)add(addRole)?感谢您的帮助!
    • @Matt 我看了一下official discord.js code,发现roles.add 函数实际上调用了roles.set 函数。添加 add 和 remove 函数都是异步的这一事实,可能会在 add 函数将角色设置为以前的角色减去要删除的角色之后调用 remove 函数。这就是为什么你有奇怪的行为,需要用 await 调用这些函数。
    • 我现在看到,在添加/删除函数中内部调用 set() 是这种情况下的问题,remove() 不等待添加 BLUE 然后设置角色它:add():将角色设置为以前的(例如管理员)+(蓝色)。 remove():将角色设置为以前的(例如管理员)-(绿色、红色、黄色)。感谢您检查代码和所有帮助,我很感激。
    猜你喜欢
    • 2021-08-22
    • 2015-07-21
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 2015-07-29
    • 2021-09-10
    相关资源
    最近更新 更多