Skip to content

Instantly share code, notes, and snippets.

@limijs
Last active May 1, 2024 22:12
Show Gist options
  • Save limijs/48de2ce73d94cf1b022ebe234c484c76 to your computer and use it in GitHub Desktop.
Save limijs/48de2ce73d94cf1b022ebe234c484c76 to your computer and use it in GitHub Desktop.
Bitwise permission flags system that mimics Discord's
PERMISSIONS = {
"CREATE_INSTANT_INVITE": 1 << 0,
"KICK_MEMBERS": 1 << 1,
"BAN_MEMBERS": 1 << 2,
"ADMINISTRATOR": 1 << 3,
"MANAGE_CHANNELS": 1 << 4,
"MANAGE_GUILD": 1 << 5,
"ADD_REACTIONS": 1 << 6,
"VIEW_AUDIT_LOG": 1 << 7,
"PRIORITY_SPEAKER": 1 << 8,
"STREAM": 1 << 9,
"VIEW_CHANNEL": 1 << 10,
"SEND_MESSAGES": 1 << 11
}
def get_permission_bitmask(permission_name):
"""Retrieves the bitmask for a specific permission."""
if permission_name in PERMISSIONS:
return PERMISSIONS[permission_name]
else:
raise ValueError(f"Invalid permission: {permission_name}")
def calculate_total_permissions(permissions):
"""Calculates the total permissions by OR-ing individual permissions."""
total_permissions = 0
for permission in permissions:
permission_bitmask = get_permission_bitmask(permission)
total_permissions |= permission_bitmask # Bitwise OR to combine permissions
return total_permissions
def convert_to_binary_string(total_permissions, num_bits):
"""Converts the integer permission to a binary string with leading zeros."""
binary_string = format(total_permissions, f'0{num_bits}b') # Base-2 conversion with leading zeros
return binary_string
def has_permission(total_permissions, permission_name):
"""Checks if a permission flag is set using bitwise AND."""
permission_bitmask = get_permission_bitmask(permission_name)
return total_permissions & permission_bitmask != 0 # Bitwise AND and check non-zero
# Example usage
permissions_to_grant = ["ADD_REACTIONS", "SEND_MESSAGES"]
total_permissions = calculate_total_permissions(permissions_to_grant)
num_bits = 12 # Assuming 12 potential permissions
# Verify the decimal value
decimal_value = int(convert_to_binary_string(total_permissions, num_bits), 2)
print(f"Total permissions (decimal): {decimal_value}") # Outputs 2112
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment