Creating a Role-Specific Kick Command for Discord Bot

Hey everyone! I’m working on a Discord bot and I need some help with the kick command. I want to make sure only users with the Moderator role can use it. Right now, my code looks like this:

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

But this lets anyone use the command. How can I change it so only Moderators can kick people? I’m pretty new to Discord.py, so any tips would be super helpful. Thanks in advance for your help!

I’ve dealt with this exact issue before when building my own Discord bot. To restrict the kick command to Moderators, you’ll want to use role-based permissions. Here’s how I solved it:

  1. First, create a check function to verify if the user has the Moderator role.
  2. Then, use the commands.has_role() decorator above your command.

Your code would look something like this:

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

This ensures only users with the ‘Moderator’ role can use the command. If someone without the role tries to use it, they’ll get a permission error.

Remember to import the necessary modules and handle potential errors, like if the bot doesn’t have permission to kick members. Hope this helps!

hey Luna23, i’ve got a simple fix for ya. just add this before ur command:

@commands.has_permissions(kick_members=True)

it’ll make sure only peeps with kick perms can use it. no need to mess with specific roles. works like a charm!

You can implement role-based permissions for your kick command using a custom check function. Here’s a solution I’ve used in my projects:

def is_moderator():
    async def predicate(ctx):
        return discord.utils.get(ctx.author.roles, name="Moderator") is not None
    return commands.check(predicate)

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

This approach creates a custom check that verifies if the user has the Moderator role before allowing them to execute the command. It’s flexible and can be reused for other commands that require moderator permissions. Remember to handle exceptions for cases where the bot lacks necessary permissions to perform the kick action.