I'm trying to let my tool/script determine if a logged in user has the correct permission to use the tool. however Discord is responding with a permission int.
It seems that I have to check permission using a bitwise operator, But from everything that i've googled or searched almost everything I find seems completely irrelevant.
Example Permission: 2146958591
Permission references;
// General
generalCreateInstantInvite: 0x1,
generalKickMembers: 0x2,
generalBanMembers: 0x4,
generalAdministrator: 0x8,
generalManageChannels: 0x10,
generalManageServer: 0x20,
generalChangeNickname: 0x4000000,
generalManageNicknames: 0x8000000,
generalManageRoles: 0x10000000,
generalManageWebhooks: 0x20000000,
generalManageEmojis: 0x40000000,
generalViewAuditLog: 0x80,
// Text
textAddReactions: 0x40,
textReadMessages: 0x400,
textSendMessages: 0x800,
textSendTTSMessages: 0x1000,
textManageMessages: 0x2000,
textEmbedLinks: 0x4000,
textAttachFiles: 0x8000,
textReadMessageHistory: 0x10000,
textMentionEveryone: 0x20000,
textUseExternalEmojis: 0x40000,
// Voice
voiceViewChannel: 0x400,
voiceConnect: 0x100000,
voiceSpeak: 0x200000,
voiceMuteMembers: 0x400000,
voiceDeafenMembers: 0x800000,
voiceMoveMembers: 0x1000000,
voiceUseVAD: 0x2000000
Is there a tool or a sample script that I can study, to determine how this calculation is made?
Thank you in advance!
Imagine that you have 4
different actions you want to allow or disallow for each user:
Let's create a 4-characters string of 1
and 0
. The first character in the string represents the user's possibility to create post
action. The second character – update post
, third – read post
and the fourth – delete post
. For example, if a user has permissions 1001
then he can create posts and delete posts, but can't update and read.
What is the most efficient way to store these permissions? We have only 0
and 1
in every position of our string, so we can store this data not inside the string but inside the binary representation of the number. So, the user's permission will be some decimal number, and every bit of this number will represent permission for a specific action.
For example, our permission string 1001
will be just decimal number 9
(= 1*2^0 + 0*2^1 + 0*2^2 + 1*2^3
).
We can represent every permission as binary:
1000
0100
0010
0001
But how can we check that user has specific permission or has a group of permissions? It's easy, let's use bitwise operator &
:
If user permission equals 9
= 1001
b, then:
1001 & 1000 = 1000
, 1000 > 0
– user can create posts1001 & 0100 = 0000
, 0000 == 0
– user can't update posts1001 & 0010 = 0000
, 0000 == 0
– user can't read posts1001 & 0001 = 0001
, 0001 > 0
– user can delete posts