简体   繁体   中英

How can i make the ban command in discord.py not ban admins?

I have a ban command in my discord.py bot. The permissions work, so if you are not admin you cannot ban someone. But when an admin tries to ban another admin or a role above him, it works. How can i do so admins can only ban roles below them?

@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)

You can use >= and the top_role attribute which would compare the roles that the user compared to the member you are attempting to ban, if your permissions are lower than the member you are attempting to ban, it will prevent the rest of the code running. Here is a simple way of doing this,

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

Here is the example applied to your code,

@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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM