首页 > 解决方案 > 如何在 discord.py 中设置禁止命令而不禁止管理员?

问题描述

我的 discord.py 机器人中有一个禁止命令。权限有效,因此如果您不是管理员,则无法禁止某人。但是,当管理员试图禁止其他管理员或高于他的角色时,它会起作用。我该怎么做才能让管理员只能禁止他们下面的角色?

@commands.command(description = 'Bans a specified member with an optional reason')
@commands.has_permissions(ban_members = True)
async def ban(self,ctx, member:discord.Member, *, reason = "unspecified reason"):
    if member.id == ctx.author.id:
        await ctx.send("You cannot ban yourself, sorry! :)")
        return
    else: 
        await member.ban(reason = reason)
        reasonEmbed = discord.Embed(
            description = f'‍♂️Succesfully banned {member.mention} for {reason}\n \n ',
            colour = 0xFF0000
        )
        reasonEmbed.set_author(name=f"{member.name}" + "#"+ f"{member.discriminator}", icon_url='{}'.format(member.avatar_url))
        reasonEmbed.set_footer(text=f"Banned by {ctx.author.name}", icon_url = '{}'.format(ctx.author.avatar_url))
        await ctx.send(embed=reasonEmbed)

标签: pythondiscorddiscord.py

解决方案


您可以使用属性来比较用户>=top_role您尝试禁止的成员的角色,如果您的权限低于您尝试禁止的成员,它将阻止其余代码运行。这是一个简单的方法,

if member.top_role >= ctx.author.top_role:
    await ctx.send(f"You can only moderate members below your role")         
    return

这是应用于您的代码的示例,

@commands.command(description = 'Bans a specified member with an optional reason')
@commands.has_permissions(ban_members = True)
async def ban(self,ctx, member:discord.Member, *, reason = "unspecified reason"):
    if member.id == ctx.author.id:
        await ctx.send("You cannot ban yourself, sorry! :)")
        return
    
    if member.top_role >= ctx.author.top_role:
        await ctx.send(f"You can only moderate members below your role")         
        return

    else: 
        await member.ban(reason = reason)
        reasonEmbed = discord.Embed(
            description = f'‍♂️Succesfully banned {member.mention} for {reason}\n \n ',
            colour = 0xFF0000
        )
        reasonEmbed.set_author(name=f"{member.name}" + "#"+ f"{member.discriminator}", icon_url='{}'.format(member.avatar_url))
        reasonEmbed.set_footer(text=f"Banned by {ctx.author.name}", icon_url = '{}'.format(ctx.author.avatar_url))
        await ctx.send(embed=reasonEmbed)

推荐阅读