Setting up a role-specific kick command for Discord bot

Hey everyone! I’m trying to create a kick command for my Discord bot that only Moderators can use. I’ve got a basic kick command working, but I’m not sure how to restrict it to a specific role. Here’s what I have so far:

@bot.command()
async def remove_user(ctx, target: discord.Member):
    await target.kick()
    await ctx.send('User has been removed from the server.')

This works, but anyone can use it. How can I modify this so only users with the Moderator role can execute the command? I’ve looked into role checks, but I’m not sure how to implement them correctly. Any help would be awesome! Thanks in advance!

I’ve implemented a similar feature in my Discord bot. Here’s a method that’s worked well for me:

from discord.ext import commands

def is_moderator():
    async def predicate(ctx):
        return ctx.author.guild_permissions.kick_members
    return commands.check(predicate)

@bot.command()
@is_moderator()
async def remove_user(ctx, target: discord.Member):
    await target.kick()
    await ctx.send(f'{target.mention} has been removed from the server.')

This approach checks the user’s actual permissions rather than relying on a specific role name. It’s more secure and adaptable, as it works even if you change role names or add new moderator roles. The command will only execute if the user has the ‘kick_members’ permission, which is typically assigned to moderator roles.

hey dancingfox, i can help with that! you’ll wanna use a decorator to check for the mod role. try adding this above ur command:

@commands.has_role(‘Moderator’)

that should restrict it to only mods. lmk if u need more help!

I’ve dealt with this exact issue before. The decorator approach works, but it can be a bit inflexible if your role names change. Here’s a more robust solution I’ve used:

def is_mod(ctx):
    return any(role.name.lower() == 'moderator' for role in ctx.author.roles)

@bot.command()
async def remove_user(ctx, target: discord.Member):
    if not is_mod(ctx):
        await ctx.send('You do not have permission to use this command.')
        return
    await target.kick()
    await ctx.send(f'{target.name} has been removed from the server.')

This checks if the user has any role with ‘moderator’ in the name (case-insensitive). It’s more flexible and allows for multiple moderator roles. Plus, it gives a clear message if someone without permission tries to use it.