【问题标题】:Discord.js Bot Roles Cache Out Out Of SyncDiscord.js 机器人角色缓存不同步
【发布时间】:2021-11-07 20:59:55
【问题描述】:

我的 discord.js 角色管理机器人刚开始出现问题。机器人将在反应事件时成功添加角色。如果用户随后删除了该反应,则该角色应该消失。

我有一个辅助方法,如果用户没有角色,它会提前返回(以避免不必要的工作,并保持日志记录干净)。此方法可防止角色在第一个反应删除事件中被删除。顺序如下:

  1. 用户添加反应,机器人为用户提供新角色
  2. 用户删除反应,机器人提前返回,因为 guild.members.cache.get(user.id).roles.cache.has(role.id) 返回 false。
  3. 用户再次添加反应,机器人提前返回,但现在角色出现在用户的角色缓存中。
  4. 用户再次删除反应,机器人从用户中删除角色。

角色第一次正确出现在不和谐中,但是我做了一些调查,并将以下代码添加到机器人中:

 guild.members.cache.get(member.id).roles.add(role.id)
    .then(() => guild.members.cache.get(author.id))
    .then(user => console.log(user._roles));

输出不包括新角色,尽管用户在客户端被提升,所以缓存似乎没有立即更新。如何确保获取最新信息?

编辑:我最终通过创建自己的缓存来存储角色来解决这个问题,但是为了后代,这里有一些额外的代码来尝试找出原因:

let guild;
const messageId = //some value
const roleId = //some value
const channelId = //some value
const emojiName = //some value

client.on('messageReactionAdd', async (reaction, user) => {
  handleReactionAdded(reaction, user)
});

client.on('messageReactionRemove', async (reaction, user) => {
  handleReactionRemoval(reaction, user)
});

const handleReactionAdded = async (reaction, user) => {
  if (reaction.message.partial) await reaction.message.fetch();
  if (reaction.partial) await reaction.fetch();
  if (user.bot || !reaction.message.guild) return;
  if (reaction.message.id == messageId && reaction.message.channel.id == channelId && reaction.emoji.name === emojiName) {

    guild = reaction.message.guild
    if (_hasRole(user)) return;
    guild.members.cache
        .get(user.id)
        .roles
        .add(roleId)
}

const handleReactionAdded = async (reaction, user) => {
  if (reaction.message.partial) await reaction.message.fetch();
  if (reaction.partial) await reaction.fetch();
  if (user.bot || !reaction.message.guild) return;
  if (reaction.message.id == messageId && reaction.message.channel.id == channelId && reaction.emoji.name === emojiName) {

    guild = reaction.message.guild
    if (!_hasRole(user)) return;
    guild.members.cache
        .get(user.id)
        .roles
        .remove(roleId)
}

const _hasRole = user => {
  return guild.members.cache.get(user.id).roles.has(roleId);
}

【问题讨论】:

  • 您提供的代码行数不够。您需要展示以下内容: 如何删除角色;您如何添加角色;可能使函数提前返回的事件和条件
  • 基本问题完全封装在我提供的 sn-p 中:在调用 member.roles.add(role.id) 之后,member._roles 应该包含该角色,但它没有(至少,不是马上) .我将其结构化为承诺,以尝试确保它异步执行。

标签: javascript node.js discord discord.js


【解决方案1】:

如果这是缓存过期的问题,在添加角色后强制从 API 获取成员可能会解决它,因为角色管理器似乎没有自己的 fetch 方法,但我不确定。

await guild.members.fetch({user, force: true})

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2021-05-10
    • 2021-10-07
    • 2020-12-21
    • 2021-03-14
    • 2021-09-03
    相关资源
    最近更新 更多