'How to overwrite channel permissions with bitfield

I tried to get my bot to save channel permissions but it only saves its bitfield. Can I somehow overwrite channel permissions for a specific role only using the bitfield?

I tried doing something like this:

channel.overwritePermissions(role, {
  permissions: perms
});

and then tried changing it to:

channel.overwritePermissions(role, {
  bitfield: perms
});

It just puts / for every permission.



Solution 1:[1]

According to the docs of the stable branch, the use of GuildChannel.overwritePermissions() is different from yours:

GuildChannel.overwritePermissions(your_role, {
  VIEW_CHANNEL: false,
  SEND_MESSAGES: null,
  PERMISSIONS_WRITTEN_IN_THIS_FORMAT: true
});

In order to convert the bitfield to a permission name, you can use Permissions.FLAGS, an object that contains all the bitfield values for every permission. Here's the current one:

{ CREATE_INSTANT_INVITE: 1,
KICK_MEMBERS: 2,
BAN_MEMBERS: 4,
ADMINISTRATOR: 8,
MANAGE_CHANNELS: 16,
MANAGE_GUILD: 32,
ADD_REACTIONS: 64,
VIEW_AUDIT_LOG: 128,
PRIORITY_SPEAKER: 256,
VIEW_CHANNEL: 1024,
READ_MESSAGES: 1024,
SEND_MESSAGES: 2048,
SEND_TTS_MESSAGES: 4096,
MANAGE_MESSAGES: 8192,
EMBED_LINKS: 16384,
ATTACH_FILES: 32768,
READ_MESSAGE_HISTORY: 65536,
MENTION_EVERYONE: 131072,
EXTERNAL_EMOJIS: 262144,
USE_EXTERNAL_EMOJIS: 262144,
CONNECT: 1048576,
SPEAK: 2097152,
MUTE_MEMBERS: 4194304,
DEAFEN_MEMBERS: 8388608,
MOVE_MEMBERS: 16777216,
USE_VAD: 33554432,
CHANGE_NICKNAME: 67108864,
MANAGE_NICKNAMES: 134217728,
MANAGE_ROLES: 268435456,
MANAGE_ROLES_OR_PERMISSIONS: 268435456,
MANAGE_WEBHOOKS: 536870912,
MANAGE_EMOJIS: 1073741824 }

To get the name of the permission, you can simply work backwards:

function getPermName(bitfield = 0) {
  for (let key in Discord.Permissions.FLAGS) 
    if (Discord.Permissions.FLAGS[key] == bitfield) return key;
  return null;
}

Once you got the name, you can use it as shown above.

Solution 2:[2]

To find the name of the permission returned by a simple bitfield.

const { Permissions } = require('discord.js');
const simpleBitfield = 2048n;
Object.entries(Permissions.FLAGS).find(p => p[1] == simpleBitfield);
// outpout: [ 'SEND_MESSAGES', 2048n ]

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
Solution 2 squarfiuz