检测用户的角色是否高于/低于特定角色 (Discord.py)

时间:2021-06-18 00:22:19

标签: python discord.py

顾名思义,我想知道我的机器人是否可以检测用户是在层次结构中的特定角色之上还是之下。 (例如:if ctx.author.role < 'fabled'

我最近看到这个 article 根据目标角色对作者做出回应。

基于此,我写了这行代码:

@bot.command(pass_context=True)
async def test(ctx):
 intern = discord.utils.find(lambda r: r.name == 'intern', ctx.message.guild.roles)
 if ctx.author.top_role > intern:
   print("true")
 else:
   print("false")

无济于事。相反,我返回了错误:

Ignoring exception in on_command_error
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 229, in test
    if ctx.author.top_role > intern:
TypeError: '>' not supported between instances of 'Role' and 'NoneType'

也许我可以用另一个符号替换“>”?打电话给所有书呆子,请帮忙!

1 个答案:

答案 0 :(得分:0)

您可以使用 dict 来确定角色的位置。返回的 int 越高,位置就越高。

以您的示例为例:

role.position

https://discordpy.readthedocs.io/en/latest/api.html?highlight=role#discord.Role.position

编辑:
抱歉,我刚刚再次阅读了您的帖子,错误是由您的机器人无法找到您指定的角色引起的。而不是 if ctx.author.top_role.position > intern.position: print("true") else: print("false") 尝试这样的事情,名称需要准确(区分大小写!):

intern = discord.utils.find(lambda r: r.name == 'intern', ctx.message.guild.roles)

或者更好的是,使用角色 ID:

intern = discord.utils.get(ctx.guild.roles, name="Exact name of your role")