I’ve created a Discord bot that responds to various commands. Right now I have a command called !stream that makes the bot announce when I go live by posting a message to the channel.
The problem is that anyone in the server can trigger this command, but I only want certain people (like moderators or admins) to be able to use it. How can I add permission checking to prevent regular members from using restricted commands?
Here’s my current setup:
if user_input == "!stream":
return "Going live now - check out my stream!"
What’s the best way to verify if a user has the right permissions before the bot executes the command?
I ran into this exact issue when building my moderation bot last year. What worked best for me was creating a decorator function that handles permission checking before any command execution. You can set up a simple function that takes the user object and checks against a predefined list of authorized user IDs stored in your config file. This method gives you complete control without relying on role names or Discord permissions that server owners might change. Just add the user IDs of trusted members to your whitelist and check if user.id in authorized_users: before processing the command. It’s bulletproof and you can easily add or remove users without touching the main code.
You can implement permission checking by verifying the user has specific Discord permissions before executing the command. Instead of checking role names which can change, use Discord’s built-in permission system. Check if the user has administrator or manage_messages permissions with something like if user.guild_permissions.administrator or user.guild_permissions.manage_messages: then execute your command logic. This approach is more reliable than role name checking since permissions are standardized across Discord servers. You could also maintain a whitelist of user IDs in your bot’s configuration file for more granular control over who can access certain commands.
check the user’s roles b4 running the command. somthing like if 'moderator' in [role.name for role in user.roles]: works good to let only those users execute restricted commands. keep it simple, it’ll do the trick!