This repository has been archived on 2024-10-15. You can view files and clone it, but cannot push or open issues or pull requests.
PyrogramBotBase/classes/pyrouser_mongo.py

55 lines
1.6 KiB
Python
Raw Normal View History

2023-08-17 16:01:35 +03:00
import logging
2023-08-14 16:16:30 +03:00
from dataclasses import dataclass
2023-08-03 22:29:47 +03:00
from typing import Union
from bson import ObjectId
2023-08-23 16:45:15 +03:00
from modules.database_mongo import col_users
2023-08-03 22:29:47 +03:00
2023-08-17 16:01:35 +03:00
logger = logging.getLogger(__name__)
2023-08-03 22:29:47 +03:00
2023-08-14 16:16:30 +03:00
@dataclass
2023-08-03 22:29:47 +03:00
class PyroUser:
"""Dataclass of DB entry of a user"""
2023-08-14 16:16:30 +03:00
__slots__ = ("_id", "id", "locale")
2023-08-03 22:29:47 +03:00
_id: ObjectId
id: int
locale: Union[str, None]
2023-08-17 16:01:35 +03:00
@classmethod
async def find(cls, id: int, locale: Union[str, None] = None):
2023-08-18 00:04:38 +03:00
"""Find user in database and create new record if user does not exist.
### Args:
* id (`int`): User's Telegram ID
* locale (`Union[str, None]`, *optional*): User's locale. Defaults to `None`.
### Raises:
* `RuntimeError`: Raised when user entry after insertion could not be found.
### Returns:
* `PyroUser`: User with its database data.
"""
2023-08-17 16:01:35 +03:00
db_entry = await col_users.find_one({"id": id})
if db_entry is None:
inserted = await col_users.insert_one({"id": id, "locale": locale})
db_entry = await col_users.find_one({"_id": inserted.inserted_id})
if db_entry is None:
raise RuntimeError("Could not find inserted user entry.")
return cls(**db_entry)
async def update_locale(self, locale: Union[str, None]) -> None:
2023-08-18 00:04:38 +03:00
"""Change user's locale stored in the database.
2023-08-03 22:29:47 +03:00
### Args:
2023-08-18 00:04:38 +03:00
* locale (`Union[str, None]`): New locale to be set.
2023-08-03 22:29:47 +03:00
"""
2023-08-17 16:01:35 +03:00
logger.debug("%s's locale has been set to %s", self.id, locale)
2023-08-14 16:16:30 +03:00
await col_users.update_one({"_id": self._id}, {"$set": {"locale": locale}})