首页 > 解决方案 > Discord.js - 是否有一种简单的方法来检查玩家是否有角色或以上

问题描述

我知道一种使用 if 语句和一大堆 elseif 来检查玩家是否有角色或更高角色的方法。必须有一种更快、更简单的方法来做到这一点。提前致谢!

标签: javascriptdiscord.js

解决方案


如果我理解正确,您正在尝试检查服务器成员是否具有某些角色或任何高于该给定角色的角色(例如 mod 或更高)。为此,假设您具有成员 ID 和角色 ID,以下可能会起作用:

async function yourFunction() {
  const guild = await client.guilds.fetch("your_guild_id"); //gets the guild
  const member = await guild.members.fetch("your_user_id"); //gets the member of the guild
  const role = guild.roles.cache.get("your_role_id"); //gets the specified role from the guild
  const role_position = role.position; //gets the position of the specified role (counted from the bottom of the roles list, the higher the role is placed on the roles list, the higher the role position)
  const highest_user_role_position = member.roles.highest.position; //gets the position of the highest role of the member
  if(highest_user_role_position >= role_position) { //comparison
    //the member has the specified role or any role above it
  } else {
    //the member does not have the specified role or any role above it
  };
};

它的工作原理基本上是它获取指定角色的位置(位置越高,角色放置的位置越高 - @everyone 的位置为 0,最高的角色(假设所有者)将具有最高的位置)和指定成员的最高角色的位置。如果成员具有指定的角色或在其之上的任何角色(mod 或管理员、所有者等) - 基于角色列表 - 比较将产生结果true,因此它将在if. 如果用户的最高角色低于指定角色(假设“member”低于“mod”),则比较结果falseelse运行代码。


推荐阅读