OokamiPupV2/modules/permissions.py

76 lines
2.7 KiB
Python

import json
import os
PERMISSIONS_FILE = "permissions.json"
# Load permission settings
def load_permissions():
"""Loads the permissions from JSON."""
if not os.path.exists(PERMISSIONS_FILE):
return {}
with open(PERMISSIONS_FILE, "r", encoding="utf-8") as file:
return json.load(file)
def map_roles(platform: str, user_roles: list) -> list:
"""
Maps platform-specific roles to a unified role system.
:param platform: "discord" or "twitch"
:param user_roles: A list of raw roles/badges from the platform
:return: A list of mapped roles based on the JSON role mapping
"""
permissions = load_permissions()
role_mappings = permissions.get("role_mappings", {}).get(platform, {})
mapped_roles = []
for role in user_roles:
normalized_role = role.lower()
mapped_role = role_mappings.get(normalized_role, None)
if mapped_role:
mapped_roles.append(mapped_role)
return mapped_roles if mapped_roles else ["everyone"]
def has_permission(command_name: str, user_id: str, user_roles: list, platform: str) -> bool:
"""
Checks if a user has permission to run a command.
:param command_name: The name of the command being checked.
:param user_id: The ID of the user requesting the command.
:param user_roles: A list of roles/badges the user has (platform-specific).
:param platform: "discord" or "twitch"
:return: True if the user has permission, otherwise False.
"""
permissions = load_permissions()
command_perms = permissions.get("commands", {}).get(command_name, {})
# Extract settings
min_role = command_perms.get("min_role", "")
allowed_roles = command_perms.get("allowed_roles", [])
allowed_users = command_perms.get("allowed_users", [])
# If no min_role and no allowed_roles/users, it's open to everyone
if not min_role and not allowed_roles and not allowed_users:
return True
# Check if user is explicitly allowed
if user_id in allowed_users:
return True # Bypass role check
# Convert platform-specific roles to mapped roles
mapped_roles = map_roles(platform, user_roles)
# If a min_role is set, check against it
if min_role:
role_hierarchy = ["everyone", "follower", "subscriber", "vip", "moderator", "admin", "owner"]
user_role_level = max([role_hierarchy.index(role) for role in mapped_roles if role in role_hierarchy], default=0)
min_role_level = role_hierarchy.index(min_role) if min_role in role_hierarchy else 0
if user_role_level >= min_role_level:
return True
# Check if the user has any explicitly allowed roles
if any(role in allowed_roles for role in mapped_roles):
return True
return False