Check if User has a certain role

社会主义新天地 提交于 2019-12-13 02:17:59

问题


I have code in which you can type -giverole <user> <rolename> e.g. -giverole @Soup Board of Executives.
What I need now is a method that checks to see if the user typing the command has a certain role.

I have code that can give a role to someone:

@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 + " .")

It should do await client.say() if the user has the right rank. If they don't, then it raises an error message.


回答1:


You can use the commands.has_role check to determine whether or not the person invoking the command has a particular 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}.")

When someone without the role tries to invoke it, a commands.CheckFailure error will be raised. You can then handle that error if you want the bot to say something:

@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



回答2:


You can use discord.Member.roles to do something like

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}.")


来源:https://stackoverflow.com/questions/54324466/check-if-user-has-a-certain-role

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!