Check if User has a certain role

后端 未结 2 618
灰色年华
灰色年华 2021-01-25 13:14

I have code in which you can type -giverole e.g. -giverole @Soup Board of Executives.
What I need now is a method tha

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 14:04

    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
    

提交回复
热议问题