Discord bot 有时不会向用户添加角色

时间:2021-03-12 14:12:07

标签: javascript node.js discord discord.js

  • 我在使用 Discord.js V12.5.1 向用户添加角色时遇到问题。以下代码在 80% 的情况下都能正常工作,但有时它只是不添加角色。

  • 查看审核日志时,显示bot为用户添加了角色,但用户看不到私聊,如果我查看用户的角色,则缺少角色。< /p>

我做错了吗?

AddRoleUser: (guid, msg, userId, roleName, reason) => {
        let role = msg.guild.roles.cache.find(r => r.name == roleName);
        let member = msg.guild.members.cache.get(userId);

        if (role && member && !member.roles.cache.has(role.id)) {
            try {
                member.roles.add(role, reason).catch((error) => logger.error(`UUID: ${guid}, Error: ${error.message}, StackTrace: ${error.stack}`));
                msg.react(reactions.RoleAdd);
                logger.info(`UUID: ${guid}, Role ${roleName} added to member: ${member.displayName}`);
            } catch (error) {
                logger.error(`UUID: ${guid}, Could not add role, Member: ${member.displayName}, Role: ${roleName}, Error: ${error.message}, StackTrace: ${error.stack}`);
            }
        } else {
            logger.warn(`UUID: ${guid}, Could not add role, Member: ${member.displayName}, Role: ${roleName}`);
        }
    },

1 个答案:

答案 0 :(得分:1)

member.roles.add 返回一个 promise,但是即使这个 promise 没有实现,你也会做出反应并记录结果。

你可以添加一个 then() 方法,只在里面记录和反应,你甚至可以检查返回的成员现在是否有角色:

try {
  member.roles
    .add(role, reason)
    .then((updatedMember) => {
      // you can check if the member has the role now
      msg.react(reactions.RoleAdd);
      logger.info(`UUID: ${guid}, Role ${roleName} added to member: ${updatedMember.displayName}`);
    })
    .catch((error) => logger.error(`UUID: ${guid}, Error: ${error.message}, StackTrace: ${error.stack}`));

// do you need try-catch? will this ever throw?
} catch (error) {
  logger.error(`UUID: ${guid}, Could not add role, Member: ${member.displayName}, Role: ${roleName}, Error: ${error.message}, StackTrace: ${error.stack}`);
}