I want to check if the bot has certain permissions in a server. So, I would like to make it return something like: "I am lacking the permission: MANAGE_GUILD". However, I only have the PermissionsBitField.Flags.ManageGuild. So, is there a way to return the name of the permission using the PermissionsBitField.Flags?
Thank you in advance! (Also, yes it is supposed to be for discordjs v.14)
CodePudding user response:
You can find out the name of the field which permissions this PermissionBitField holds using Object.keys(PermissionBitField.Flags)
. The code snippet below uses this to create an array of the human readable names from the PermissionBitField object:
import {PermissionsBitField} from 'discord.js';
function permissionsNames(permissions: PermissionsBitField) : string[] {
const result = [];
for (const perm of Object.keys(PermissionsBitField.Flags)) {
if (permissions.has(PermissionsBitField.Flags[perm])) {
result.push(perm);
}
}
return result;
}
console.log(permissionsNames( new PermissionsBitField(268550160n)));
This will result in
[
'ManageChannels',
'EmbedLinks',
'AttachFiles',
'ReadMessageHistory',
'ManageRoles'
]
You can also use this to get the name of exactly one field:
import {PermissionsBitField} from 'discord.js';
function getPermissionName(permission: bigint) : string {
for (const perm of Object.keys(PermissionsBitField.Flags)) {
if (PermissionsBitField.Flags[perm] === permission) {
return perm;
}
}
return 'UnknownPermission';
}
console.log(getPermissionName(PermissionsBitField.Flags.ManageGuild));
This will then result in ManageGuild
, which is what you are looking for!
Hope this helps!
CodePudding user response:
You can do that:
const { PermissionsBitField } = require('discord.js');
if (!message.guild.me.permissions.has(PermissionsBitField.Flags.ManageGuild)) return message.reply({content: "I am lacking the permission: MANAGE_GUILD"})