Skip to content
Advertisement

discord.py – Get channel permissions of user

I am trying to create a command that lists the permissions that the user has in the current channel. I have tried using a function that adds permissions to a list and calling it in the command.

Unfortunately, this command sends all of the permissions that a member could possibly have, rather than the permissions that the member has currently. How could I edit my code into finding what permissions the member has currently?

@commands.command()
async def perms(self, ctx, user):
     def _perms(ctx):
          perms = []

         for p in user.permissions_in(ctx.channel):
              perms.append(p[0])
            
         return perms
     
     await ctx.send(" ".join(_perms(ctx)))

Advertisement

Answer

As described in the docs, a discord.Permissions object defines the __iter__-method by returning a list of tuples (permission_name, permission_value), where permission_value will be True if the member has the permission and False otherwise. You simply need to add a check if the value is true before appending the name to your list like so:

for p in user.permissions_in(ctx.channel):
    if p[1] is True:
        perms.append(p[0])

That said, your definition of _perms is entirely unnecessary and your code can be improved/shortened quite a bit. The following one-liner should also do what you want:

@commands.command()
async def perms(self, ctx, user):
     await ctx.send(" ".join(p[0] for p in user.permissions_in(ctx.channel) if p[1]))

On a general note, some precautions should be taken in case the user has no permissions on the channel (the bot can’t send an empty message and will throw an error)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement