I need help making my Discord bot’s kick feature only work for users who have a certain role. Right now anyone can use the kick command but I want to limit it so only people with Admin role can actually kick members.
Here’s what I have so far:
@bot.command()
async def remove_user(ctx, target: discord.Member):
"""Remove a member from the server"""
await target.kick()
await ctx.send("**Member has been removed successfully!**")
The problem is that any user can run this command. I want to add a check so only users with the Admin role can use it. How do I add role verification to this command? I’ve seen some examples but I’m not sure how to implement the role checking part properly.
You could check permissions instead of roles - way more flexible. Use ctx.author.guild_permissions.kick_members
to see if they can kick. Works with any role that has kick perms, not just “admin.” Saved my ass when the server restructured their roles
You need to add a role check before the kick happens. Here’s how I fixed the same issue in my bot:
@bot.command()
async def remove_user(ctx, target: discord.Member):
"""Remove a member from the server"""
admin_role = discord.utils.get(ctx.guild.roles, name="Admin")
if admin_role not in ctx.author.roles:
await ctx.send("You don't have permission to use this command.")
return
await target.kick()
await ctx.send("**Member has been removed successfully!**")
Use discord.utils.get()
to grab the role by name, then check if the user has it. Just make sure your role name matches exactly - capitalization matters. This works great for all my moderation commands.
You can also use Discord.py’s built-in decorators - they make the code way cleaner. Just add @commands.has_role('Admin')
above your command:
@bot.command()
@commands.has_role('Admin')
async def remove_user(ctx, target: discord.Member):
"""Remove a member from the server"""
await target.kick()
await ctx.send("**Member has been removed successfully!**")
The decorator handles permission checking automatically. If someone without the Admin role tries using the command, Discord.py throws a MissingRole
error. You can catch this error with an error handler to send your own message instead of the default. I like this method better - it keeps permission logic separate from the main command code and it’s easier to read.