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
|
|
|
|
|
2023-08-23 16:45:15 +03:00
|
|
|
from modules.database_sqlite import cursor
|
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-23 16:45:15 +03:00
|
|
|
__slots__ = ("id", "locale")
|
2023-08-14 16:16:30 +03:00
|
|
|
|
2023-08-03 22:29:47 +03:00
|
|
|
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-23 16:45:15 +03:00
|
|
|
db_entry = cursor.execute(
|
|
|
|
"SELECT id, locale FROM users WHERE id = ?", (id,)
|
|
|
|
).fetchone()
|
2023-08-17 16:01:35 +03:00
|
|
|
|
|
|
|
if db_entry is None:
|
2023-08-23 16:45:15 +03:00
|
|
|
cursor.execute("INSERT INTO users VALUES (?, ?)", (id, locale))
|
|
|
|
cursor.connection.commit()
|
|
|
|
db_entry = cursor.execute(
|
|
|
|
"SELECT id, locale FROM users WHERE id = ?", (id,)
|
|
|
|
).fetchone()
|
2023-08-17 16:01:35 +03:00
|
|
|
|
|
|
|
if db_entry is None:
|
|
|
|
raise RuntimeError("Could not find inserted user entry.")
|
|
|
|
|
2023-08-23 16:45:15 +03:00
|
|
|
return cls(*db_entry)
|
2023-08-17 16:01:35 +03:00
|
|
|
|
|
|
|
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-23 16:45:15 +03:00
|
|
|
cursor.execute(
|
|
|
|
"UPDATE users SET locale = ? WHERE id = ?",
|
|
|
|
(locale, self.id),
|
|
|
|
)
|
|
|
|
cursor.connection.commit()
|