Implemented basic guild config, improved PycordUser and PycordGuild, fixed PycordBut, added stubs for events

This commit is contained in:
2025-04-18 18:17:35 +02:00
parent 691dd1c958
commit f7fd81f299
5 changed files with 297 additions and 19 deletions

View File

@@ -1,4 +1,3 @@
import logging
from dataclasses import dataclass
from logging import Logger
from typing import Any, Dict, Optional
@@ -9,8 +8,9 @@ from pymongo.results import InsertOneResult
from classes.errors.pycord_user import UserNotFoundError
from modules.database import col_users
from modules.logging_utils import get_logger
logger: Logger = logging.getLogger(__name__)
logger: Logger = get_logger(__name__)
@dataclass
@@ -18,6 +18,8 @@ class PycordUser:
"""Dataclass of DB entry of a user"""
__slots__ = ("_id", "id")
__short_name__ = "user"
__collection__ = col_users
_id: ObjectId
id: int
@@ -40,12 +42,12 @@ class PycordUser:
UserNotFoundError: User was not found and creation was not allowed
"""
if cache is not None:
cached_entry: Dict[str, Any] | None = cache.get_json(f"user_{user_id}")
cached_entry: Dict[str, Any] | None = cache.get_json(f"{cls.__short_name__}_{user_id}")
if cached_entry is not None:
return cls(**cached_entry)
db_entry = await col_users.find_one({"id": user_id})
db_entry = await cls.__collection__.find_one({"id": user_id})
if db_entry is None:
if not allow_creation:
@@ -53,12 +55,12 @@ class PycordUser:
db_entry = PycordUser.get_defaults(user_id)
insert_result: InsertOneResult = await col_users.insert_one(db_entry)
insert_result: InsertOneResult = await cls.__collection__.insert_one(db_entry)
db_entry["_id"] = insert_result.inserted_id
if cache is not None:
cache.set_json(f"user_{user_id}", db_entry)
cache.set_json(f"{cls.__short_name__}_{user_id}", db_entry)
return cls(**db_entry)
@@ -89,7 +91,7 @@ class PycordUser:
setattr(self, key, value)
await col_users.update_one({"_id": self._id}, {"$set": {key: value}}, upsert=True)
await self.__collection__.update_one({"_id": self._id}, {"$set": {key: value}}, upsert=True)
self._update_cache(cache)
@@ -109,14 +111,14 @@ class PycordUser:
setattr(self, key, default_value)
await col_users.update_one({"_id": self._id}, {"$set": {key: default_value}}, upsert=True)
await self.__collection__.update_one({"_id": self._id}, {"$set": {key: default_value}}, upsert=True)
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}"
return f"{self.__short_name__}_{self.id}"
def _update_cache(self, cache: Optional[Cache] = None) -> None:
if cache is None:
@@ -154,5 +156,5 @@ class PycordUser:
Args:
cache (:obj:`Cache`, optional): Cache engine to write the update into
"""
await col_users.delete_one({"_id": self._id})
await self.__collection__.delete_one({"_id": self._id})
self._delete_cache(cache)