I am in the process of making a discord bot using discord.py and asyncio. The bot has commands like kick
and ban
which obviously should not be available to normal users.
I want to make a simple system which will detect what permissions the user's role has using ctx.message.author
to get the user who sent the command.
I do not want the bot to detect a specific role name as these vary across servers. I also prefer not to have multiple files for the bot to keep it simple.
I have seen the discord.py documentation and various other sources but none contain examples of how to implement the various methods they talk about.
As an example, here is a single command from my bot:
async def kick(ctx, userName: discord.User):
if True: #ctx.message.author.Permissions.administrator
await BSL.kick(userName)
else:
permission_error = str('Sorry ' + ctx.message.author + ' you do not have permissions to do that!')
await BSL.send_message(ctx.message.channel, permission_error)
Where the if else
statement is my attempt of doing this on my own. The #ctx.message.author.Permissions.administrator
is commented out as it does not work and replaced with True
for testing purposes.
Thank you for any help and suggestions in advance.
Permissions
is the name of the class. To get the message authors permissions, you should access theserver_permissions
property of the author.Update:
A better way to validate the permissions of the person invoking the commands is by using the check feature of the
commands
extension, specifically thehas_permissions
check. For example, if you wanted to open your command only to people who had either themanage_roles
permission or theban_members
permission, you could write your command like this:The tips found the accepted answer may not work:
There may be compatibility issues with the rewrite version of the discord.py library and the pre-rewrite versions, which remain non-obsolete, non-deprecated, and still in use.
The bot should also check it's own permissions, to rule out one reason for the error.
If there is an error, or permissions for the bot itself are invalid, the bot should say something, correct?
Something needs to be implemented to prevent the bot from attempting to work this command in a DM or group context. It will almost always error.
I propose the following solution (assuming you use the command extension):