Discord/classes/holo_user.py

228 lines
7.0 KiB
Python
Raw Normal View History

2023-05-06 17:08:52 +02:00
import logging
from logging import Logger
from typing import Any, Dict
from bson import ObjectId
from discord import User, Member
2024-12-26 19:12:50 +01:00
from libbot.utils import config_get
2024-12-27 22:43:40 +01:00
from pymongo.results import InsertOneResult
2023-05-04 16:09:47 +02:00
2025-02-09 23:00:18 +01:00
from classes.cache import HoloCache
from errors import UserNotFoundError
2025-02-10 12:50:56 +01:00
from modules.database import col_users
2023-05-04 16:09:47 +02:00
logger: Logger = logging.getLogger(__name__)
2023-05-06 17:08:52 +02:00
2023-05-04 16:14:23 +02:00
class HoloUser:
2024-12-27 22:43:40 +01:00
def __init__(
self,
_id: ObjectId,
id: int,
custom_role: int | None,
custom_channel: int | None,
) -> None:
self._id: ObjectId = _id
self.id: int = id
self.custom_role: int | None = custom_role
self.custom_channel: int | None = custom_channel
@classmethod
async def from_user(
2025-02-09 23:00:18 +01:00
cls,
user: User | Member,
allow_creation: bool = True,
cache: HoloCache | None = None,
2024-12-27 22:43:40 +01:00
) -> "HoloUser":
2023-05-04 16:09:47 +02:00
"""Get an object that has a proper binding between Discord ID and database
### Args:
2024-12-27 22:43:40 +01:00
* `user` (User | Member): Object from which an ID can be extracted
2025-02-09 23:00:18 +01:00
* `allow_creation` (bool, optional): Whether to allow creation of a new user record if none found. Defaults to True.
* `cache` (HoloCache | None, optional): Cache engine to get the cache from
2023-05-04 16:09:47 +02:00
### Raises:
* `UserNotFoundError`: User with such ID does not seem to exist in database
2023-05-04 16:14:23 +02:00
"""
2025-02-09 23:00:18 +01:00
if cache is not None:
cached_entry: Dict[str, Any] | None = cache.get_json(f"user_{user.id}")
if cached_entry is not None:
return cls(**cached_entry)
db_entry: Dict[str, Any] | None = await col_users.find_one({"id": user.id})
2023-05-04 16:09:47 +02:00
2024-12-27 22:43:40 +01:00
if db_entry is None:
if not allow_creation:
raise UserNotFoundError(user=user, user_id=user.id)
2023-05-04 16:09:47 +02:00
2025-02-09 23:00:18 +01:00
db_entry = HoloUser.get_defaults(user.id)
2023-05-04 16:09:47 +02:00
2024-12-27 22:43:40 +01:00
insert_result: InsertOneResult = await col_users.insert_one(db_entry)
2023-05-04 16:09:47 +02:00
2025-02-09 23:00:18 +01:00
db_entry["_id"] = insert_result.inserted_id
2023-05-04 16:09:47 +02:00
2025-02-09 23:00:18 +01:00
if cache is not None:
cache.set_json(f"user_{user.id}", db_entry)
2023-05-04 16:09:47 +02:00
2024-12-27 22:43:40 +01:00
return cls(**db_entry)
@classmethod
async def from_id(cls, user_id: int) -> "HoloUser":
2025-02-10 12:50:56 +01:00
raise NotImplementedError()
2023-05-04 16:09:47 +02:00
2025-02-09 23:00:18 +01:00
async def _set(self, key: str, value: Any, cache: HoloCache | None = None) -> None:
2024-12-27 22:43:40 +01:00
"""Set attribute data and save it into the database
2023-05-04 16:09:47 +02:00
### Args:
* `key` (str): Attribute to be changed
* `value` (Any): Value to set
2025-02-09 23:00:18 +01:00
* `cache` (HoloCache | None, optional): Cache engine to write the update into
2023-05-04 16:14:23 +02:00
"""
2023-05-04 16:09:47 +02:00
if not hasattr(self, key):
raise AttributeError()
2024-12-15 23:36:48 +01:00
2023-05-04 16:09:47 +02:00
setattr(self, key, value)
2024-12-16 16:25:35 +01:00
await col_users.update_one(
2024-12-27 22:43:40 +01:00
{"_id": self._id}, {"$set": {key: value}}, upsert=True
2023-05-04 16:14:23 +02:00
)
2024-12-15 23:36:48 +01:00
2025-02-09 23:00:18 +01:00
self._update_cache(cache)
logger.info("Set attribute '%s' of user %s to '%s'", key, self.id, value)
2023-05-04 16:09:47 +02:00
2025-02-09 23:00:18 +01:00
async def _remove(self, key: str, cache: HoloCache | None = None) -> None:
2024-12-27 22:43:40 +01:00
"""Remove attribute data and save it into the database
### Args:
* `key` (str): Attribute to be removed
2025-02-09 23:00:18 +01:00
* `cache` (HoloCache | None, optional): Cache engine to write the update into
2024-12-27 22:43:40 +01:00
"""
if not hasattr(self, key):
raise AttributeError()
2025-02-09 23:00:18 +01:00
default_value: Any = HoloUser.get_default_value(key)
setattr(self, key, default_value)
2024-12-27 22:43:40 +01:00
await col_users.update_one(
2025-02-09 23:00:18 +01:00
{"_id": self._id}, {"$set": {key: default_value}}, upsert=True
2024-12-27 22:43:40 +01:00
)
2025-02-09 23:00:18 +01:00
self._update_cache(cache)
logger.info("Removed attribute '%s' of user %s", key, self.id)
def _get_cache_key(self) -> str:
return f"user_{self.id}"
def _update_cache(self, cache: HoloCache | None = None) -> None:
if cache is None:
return
user_dict: Dict[str, Any] = self._to_dict()
if user_dict is not None:
cache.set_json(self._get_cache_key(), user_dict)
else:
self._delete_cache(cache)
def _delete_cache(self, cache: HoloCache | None = None) -> None:
if cache is None:
return
cache.delete(self._get_cache_key())
@staticmethod
def get_defaults(user_id: int | None = None) -> Dict[str, Any]:
return {
"id": user_id,
"custom_role": None,
"custom_channel": None,
}
@staticmethod
def get_default_value(key: str) -> Any:
if key not in HoloUser.get_defaults():
raise KeyError(f"There's no default value for key '{key}' in HoloUser")
return HoloUser.get_defaults()[key]
def _to_dict(self) -> Dict[str, Any]:
return {
"_id": self._id,
"id": self.id,
"custom_role": self.custom_role,
"custom_channel": self.custom_channel,
}
async def set_custom_channel(
self, channel_id: int, cache: HoloCache | None = None
) -> None:
await self._set("custom_channel", channel_id, cache=cache)
2024-12-27 22:43:40 +01:00
2025-02-09 23:00:18 +01:00
async def set_custom_role(
self, role_id: int, cache: HoloCache | None = None
) -> None:
await self._set("custom_role", role_id, cache=cache)
2024-12-27 22:43:40 +01:00
2025-02-09 23:00:18 +01:00
async def remove_custom_channel(self, cache: HoloCache | None = None) -> None:
await self._remove("custom_channel", cache=cache)
2024-12-27 22:43:40 +01:00
2025-02-09 23:00:18 +01:00
async def remove_custom_role(self, cache: HoloCache | None = None) -> None:
await self._remove("custom_role", cache=cache)
2024-12-27 22:43:40 +01:00
2025-02-09 23:00:18 +01:00
async def purge(self, cache: HoloCache | None = None) -> None:
2025-02-10 12:50:56 +01:00
"""Completely remove user data from database. Only removes the user record from users collection.
2024-12-27 22:43:40 +01:00
2025-02-09 23:00:18 +01:00
### Args:
* `cache` (HoloCache | None, optional): Cache engine to write the update into
"""
2024-12-27 22:43:40 +01:00
await col_users.delete_one({"_id": self._id})
2025-02-09 23:00:18 +01:00
self._delete_cache(cache)
2024-12-27 22:43:40 +01:00
2024-12-16 16:25:35 +01:00
@staticmethod
async def is_moderator(member: User | Member) -> bool:
2023-05-08 15:45:00 +02:00
"""Check if user is moderator or council member
### Args:
* `member` (User | Member): Member object
2023-05-08 15:45:00 +02:00
### Returns:
`bool`: `True` if member is a moderator or member of council and `False` if not
"""
if isinstance(member, User):
2023-05-08 15:45:00 +02:00
return False
2024-12-15 23:36:48 +01:00
moderator_role: int | None = await config_get("moderators", "roles")
council_role: int | None = await config_get("council", "roles")
2024-12-15 23:36:48 +01:00
2023-05-08 15:45:00 +02:00
for role in member.roles:
if role.id in (moderator_role, council_role):
2023-05-08 15:45:00 +02:00
return True
2024-12-15 23:36:48 +01:00
2023-05-08 15:45:00 +02:00
return False
2024-12-16 16:25:35 +01:00
@staticmethod
async def is_council(member: User | Member) -> bool:
2023-05-08 15:45:00 +02:00
"""Check if user is a member of council
### Args:
* `member` (User | Member): Member object
2023-05-08 15:45:00 +02:00
### Returns:
`bool`: `True` if member is a member of council and `False` if not
"""
if isinstance(member, User):
2023-05-08 15:45:00 +02:00
return False
2024-12-15 23:36:48 +01:00
2023-05-08 15:45:00 +02:00
council_role = await config_get("council", "roles")
2024-12-15 23:36:48 +01:00
2023-05-08 15:45:00 +02:00
for role in member.roles:
if role.id == council_role:
return True
2024-12-15 23:36:48 +01:00
2023-05-08 15:45:00 +02:00
return False