【问题标题】:Check if User has a certain role检查用户是否具有特定角色
【发布时间】:2019-06-16 21:06:24
【问题描述】:

我有代码,您可以在其中输入-giverole <user> <rolename>,例如-giverole @Soup Board of Executives.
我现在需要的是一种方法来检查输入命令的用户是否具有特定的角色。

我有可以赋予某人角色的代码:

@client.command(pass_context=True)
async def giverole(ctx, member: discord.Member, *, role: discord.Role):
    await client.add_roles(member, role)
    await client.say("The role '" + str(role) + "' has been given to " + member.mention + " .")

如果用户有正确的排名,它应该是await client.say()。如果他们不这样做,则会引发错误消息。

【问题讨论】:

  • 欢迎来到 SO!遗憾的是,您的帖子中没有问题。

标签: python python-3.x discord discord.py


【解决方案1】:

你可以使用discord.Member.roles 来做类似的事情

from discord.utils import get

@client.command(pass_context=True)
async def giverole(ctx, member: discord.Member, *, role: discord.Role):
  check_role = get(ctx.message.server.roles, name='Board of Executives')
  if check_role not in member.roles:
    await client.say(f"You don't have the role '{str(role)}'")
  else:
    await client.add_roles(member, role)
    await client.say(f"The role '{str(role)}' has been given to {member.mention}.")

【讨论】:

    【解决方案2】:

    您可以使用commands.has_role 检查来确定调用命令的人是否具有特定角色:

    @client.command(pass_context=True)
    @has_role("Role Name")
    async def giverole(ctx, member: discord.Member, *, role: discord.Role):
        await client.add_roles(member, role)
        await client.say(f"The role '{role}' has been given to {member.mention}.")
    

    当没有角色的人尝试调用它时,commands.CheckFailure error will be raised。如果你想让机器人说点什么,你可以handle that error

    @giverole.error
    async def giverole_error(error, ctx):
        if isinstance(error, CheckFailure):
            await client.send_message(ctx.message.channel, "You are lacking a required role")
        else:
            raise error
    

    【讨论】:

    • 谢谢。我的代码引发错误。 “has_role 未定义”。我该如何解决这个问题?
    • 需要导入:from discord.ext.commands import has_role
    • 哦,谢谢。我想到了,但是我输入了from discord.ext import has_role。非常感谢。我是使用不和谐 API 使用 Python 编码机器人的初学者。这真的很有帮助:)
    • 您还知道如何为has_role 设置多个参数。例如,他们可以担任执行委员会的角色,也可以担任审核经理的角色。
    • 还有另一个名为 has_any_role 的检查可以做到这一点
    猜你喜欢
    • 2010-12-22
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    相关资源
    最近更新 更多