Implemented #3 and made some improvements for #8 and #1

This commit is contained in:
2025-04-26 13:29:16 +02:00
parent f969f7d3f1
commit a17b1cd768
8 changed files with 87 additions and 25 deletions

View File

@@ -51,12 +51,13 @@ class PycordUser:
@classmethod
async def from_id(
cls, user_id: int, allow_creation: bool = True, cache: Optional[Cache] = None
cls, user_id: int, guild_id: int, allow_creation: bool = True, cache: Optional[Cache] = None
) -> "PycordUser":
"""Find user in database and create new record if user does not exist.
Args:
user_id (int): User's Discord ID
guild_id (int): User's guild Discord ID
allow_creation (:obj:`bool`, optional): Create new user record if none found in the database
cache (:obj:`Cache`, optional): Cache engine to get the cache from
@@ -66,25 +67,27 @@ class PycordUser:
Raises:
UserNotFoundError: User was not found and creation was not allowed
"""
cached_entry: Dict[str, Any] | None = restore_from_cache(cls.__short_name__, user_id, cache=cache)
cached_entry: Dict[str, Any] | None = restore_from_cache(
cls.__short_name__, f"{user_id}_{guild_id}", cache=cache
)
if cached_entry is not None:
return cls(**cached_entry)
db_entry = await cls.__collection__.find_one({"id": user_id})
db_entry = await cls.__collection__.find_one({"id": user_id, "guild_id": guild_id})
if db_entry is None:
if not allow_creation:
raise UserNotFoundError(user_id)
raise UserNotFoundError(user_id, guild_id)
db_entry = PycordUser.get_defaults(user_id)
db_entry = PycordUser.get_defaults(user_id, guild_id)
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"{cls.__short_name__}_{user_id}", db_entry)
cache.set_json(f"{cls.__short_name__}_{user_id}_{guild_id}", db_entry)
return cls(**db_entry)
@@ -367,3 +370,9 @@ class PycordUser:
await self._set(
cache, current_stage_id=stage_id if isinstance(stage_id, str) else ObjectId(stage_id)
)
async def jail(self, cache: Optional[Cache] = None) -> None:
await self._set(cache, is_jailed=True)
async def unjail(self, cache: Optional[Cache] = None) -> None:
await self._set(cache, is_jailed=False)