Permissions API¶
This page assumes you’ve completed Creating a Simple Hello World Module. If not, check the previous pages.
Let’s make the !hello
command only accessible to certain people and certain roles.
Permission File¶
Permission files live under the DATA_PATH
’s
perms
subdirectory (/data/perms/<server id>.conf
by default). Instead of having
multiple permission files per module, we instead have a single file for each server,
and modules can put their permissions under their own namespace.
Permission Syntax¶
The permission syntax is quite flexible. The file uses the HOCON syntax, and the content will be similar to this psuedocode:
"permission": [
"role name 1",
"role name 2",
"user:name#1234", # Give permission to specific user
"perm:other.permission", # Include another permission
]
Note
Since the file uses HOCON, dotted permissions will be nested inside each other
Adding The Permission¶
Before doing anything, you’ll want to add the permission to the permission files. For
that, we use add_permission
:
async def on_ready(self):
for server in self.client.servers:
# self.client.get_permissions(server.id) is used to receive the permissions
# object for server
self.client.get_permissions(server.id).add_permission(
"helloworld.command", [] # List of roles, see Permission Syntax
)
Checking For Permissions¶
To check for permissions, you can use
has_permission
:
async def run(self, message: discord.Message, **kwargs):
if not self.client.get_permissions(message.server.id).has_permission(
message.author,
"helloworld.command"
):
await self.client.send_message(message.channel, "You can't use this command.")
return
await self.client.send_message(message.channel, "Hello, World!")
Warning
If you’re using permissions as user markers, be careful as by default the server owner has all permissions
You can disable this in check-by-check basis by adding ignore_owner=True
to
your has_permission calls.
And that’s about it for permissions.