Improved docs and typing

This commit is contained in:
Profitroll 2023-08-17 23:04:38 +02:00
parent 4cbb51ca61
commit 32260e95a7
Signed by: profitroll
GPG Key ID: FA35CAB49DACD3B2
5 changed files with 38 additions and 9 deletions

View File

@ -9,7 +9,20 @@ class CallbackLanguage:
@classmethod @classmethod
def from_callback(cls, callback: CallbackQuery): def from_callback(cls, callback: CallbackQuery):
"""Parse callback query and extract language data from it.
### Args:
* callback (`CallbackQuery`): Callback query got from user interaction.
### Raises:
* `ValueError`: Raised when callback provided is not a language one.
### Returns:
* `CallbackLanguage`: Parsed callback query.
"""
action, language = str(callback.data).split(":") action, language = str(callback.data).split(":")
if action.lower() != "language": if action.lower() != "language":
raise ValueError("Callback provided is not a language callback") raise ValueError("Callback provided is not a language callback")
return cls(language) return cls(language)

View File

@ -11,10 +11,10 @@ class PyroClient(LibPyroClient):
"""Find User by it's ID or User object. """Find User by it's ID or User object.
### Args: ### Args:
* user (`Union[int, User]`): ID or User object to extract ID from * user (`Union[int, User]`): ID or User object to extract ID from.
### Returns: ### Returns:
* `PyroUser`: PyroUser object * `PyroUser`: User in database representation.
""" """
return ( return (

View File

@ -21,6 +21,18 @@ class PyroUser:
@classmethod @classmethod
async def find(cls, id: int, locale: Union[str, None] = None): async def find(cls, id: int, locale: Union[str, None] = None):
"""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.
"""
db_entry = await col_users.find_one({"id": id}) db_entry = await col_users.find_one({"id": id})
if db_entry is None: if db_entry is None:
@ -33,10 +45,10 @@ class PyroUser:
return cls(**db_entry) return cls(**db_entry)
async def update_locale(self, locale: Union[str, None]) -> None: async def update_locale(self, locale: Union[str, None]) -> None:
"""Change user's locale stored in the database """Change user's locale stored in the database.
### Args: ### Args:
* locale (`Union[str, None]`): New locale to be set * locale (`Union[str, None]`): New locale to be set.
""" """
logger.debug("%s's locale has been set to %s", self.id, locale) logger.debug("%s's locale has been set to %s", self.id, locale)
await col_users.update_one({"_id": self._id}, {"$set": {"locale": locale}}) await col_users.update_one({"_id": self._id}, {"$set": {"locale": locale}})

View File

@ -1,9 +1,11 @@
"""Module that provides all database collections""" """Module that provides all database collections"""
from async_pymongo import AsyncClient from typing import Any, Mapping
from async_pymongo import AsyncClient, AsyncCollection, AsyncDatabase
from libbot.sync import config_get from libbot.sync import config_get
db_config = config_get("database") db_config: Mapping[str, Any] = config_get("database")
if db_config["user"] is not None and db_config["password"] is not None: if db_config["user"] is not None and db_config["password"] is not None:
con_string = "mongodb://{0}:{1}@{2}:{3}/{4}".format( con_string = "mongodb://{0}:{1}@{2}:{3}/{4}".format(
@ -19,6 +21,6 @@ else:
) )
db_client = AsyncClient(con_string) db_client = AsyncClient(con_string)
db = db_client.get_database(name=db_config["name"]) db: AsyncDatabase = db_client.get_database(name=db_config["name"])
col_users = db.get_collection("users") col_users: AsyncCollection = db.get_collection("users")

View File

@ -1,3 +1,5 @@
from typing import List
from pykeyboard import InlineButton, InlineKeyboard from pykeyboard import InlineButton, InlineKeyboard
from pyrogram import filters from pyrogram import filters
from pyrogram.types import CallbackQuery, Message from pyrogram.types import CallbackQuery, Message
@ -13,7 +15,7 @@ async def command_language(app: PyroClient, message: Message):
user = await app.find_user(message.from_user) user = await app.find_user(message.from_user)
keyboard = InlineKeyboard(row_width=2) keyboard = InlineKeyboard(row_width=2)
buttons = [] buttons: List[InlineButton] = []
for locale, data in app.in_every_locale("metadata").items(): for locale, data in app.in_every_locale("metadata").items():
buttons.append( buttons.append(