Creating a Role-Specific Kick Command for Discord Bot

Hey everyone! I’m working on a Discord bot and I want to set up a kick command that only users with the Moderator role can use. Right now, I have a basic kick command, but it doesn’t check for roles. Here’s what I’ve got so far:

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

Can anyone help me modify this code to check if the user has the Moderator role before allowing them to use the command? I’m not sure how to implement role checking in Discord.py. Any tips or examples would be super helpful! Thanks in advance!

hey pete, i’ve done this before. here’s a quick way:

@bot.command()
async def remove_user(ctx, member: discord.Member):
if ‘Moderator’ in [role.name for role in ctx.author.roles]:
await member.kick()
await ctx.send(f’{member.name} kicked.')
else:
await ctx.send(‘nope, mods only!’)

this checks if the user has the Moderator role. simple and works great!

I’ve implemented something similar in my Discord bot. Here’s how you can modify your code to check for the Moderator role:

@bot.command()
@commands.has_role('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 uses the @commands.has_role() decorator to check if the user has the ‘Moderator’ role. If they don’t, it’ll raise an error automatically.

You might also want to add error handling:

@remove_user.error
async def remove_user_error(ctx, error):
    if isinstance(error, commands.MissingRole):
        await ctx.send('You need the Moderator role to use this command.')

This will send a message if someone without the right role tries to use the command. Hope this helps!

Great question! I’ve tackled this issue before. Here’s a solution that should work for you:

@bot.command()
async def remove_user(ctx, member: discord.Member):
if discord.utils.get(ctx.author.roles, name=‘Moderator’):
await member.kick()
await ctx.send(f’{member.name} has been removed from the server.')
else:
await ctx.send(‘You do not have permission to use this command.’)

This checks if the user invoking the command has the ‘Moderator’ role. If they do, it proceeds with the kick. If not, it sends a message denying permission. Remember to replace ‘Moderator’ with the exact name of your moderator role in your server.

Also, consider adding error handling for cases where the bot lacks permissions to kick members.