'How to convert guild.permissions number into an array of persmissions discord.js oauth2

I need to verify if a user logging into the website has sufficient permissions to modify my bot's behavior on a guild. I used passport-discord to get information on the user, and this is what I got:

{
  ...
  guilds: [
    {
      id: 'guild id',
      name: 'guild name',
      icon: 'guild icon',
      owner: false,
      permissions: 104189504,
      features: [Array],
      permissions_new: '1037338791488'
    }
    ...
  ]
}

For confidentiality purposes, I replaced the guild information above "owner". Now my question: How to convert the "permissions" section into an array of the user's permissions ?



Solution 1:[1]

I don't know if there is an API where you can do it (probably not), but it's not that complicated to implement this. Discord provides two community-created calculators for permissions, which do the opposite thing - you select which permissions you need and you get a calculated permissions result:

You could quite easily create a function that will do the reverse - convert the decimal permissions number into a hex number, then map the hexes to named permissions.

E.g. your permission from example 104189504 is 635CE40 in hex representation. Permissions are mapped to 1, 2, 4, or 8, so if you encounter any other hex, it means there is a sum. Thus, your permission int contains the following permissions:

  • 4000000
  • 2000000
  • 200000
  • 100000
  • 40000
  • 10000
  • 8000
  • 4000
  • 800
  • 400
  • 200
  • 40

Which you can then map to names, e.g. 4000000 is "Change nickname", and so on.

Solution 2:[2]

If you want to keep your bot's permission checks simple, you might find it sufficient to check if the member executing the command has a specific role.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michal Trojanowski
Solution 2 behabtu Getnet