Skip to content

Commit

Permalink
feat: add default_params & proxies
Browse files Browse the repository at this point in the history
  • Loading branch information
timoniq committed Jul 8, 2024
1 parent cabe112 commit 64ec2b3
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 23 deletions.
5 changes: 2 additions & 3 deletions examples/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
from telegrinder.tools import HTMLFormatter, bold, italic, mention

api = API(token=Token.from_env())
api.default_params["parse_mode"] = HTMLFormatter.PARSE_MODE

bot = Telegrinder(api)
logger.set_level("INFO")

Expand All @@ -12,18 +14,15 @@
async def formatting(m: Message):
await m.answer(
HTMLFormatter(bold(italic("bold italic text!"))),
parse_mode=HTMLFormatter.PARSE_MODE,
)
await m.answer(
"python library 'telegrinder' - "
+ HTMLFormatter(
"{:bold} for effective and reliable telegram {:bold+italic} {:underline}!"
).format("Framework", "bot", "building"),
parse_mode=HTMLFormatter.PARSE_MODE,
)
await m.answer(
"this is " + mention(m.from_user.first_name, m.from_user.id),
parse_mode=HTMLFormatter.PARSE_MODE,
)


Expand Down
52 changes: 44 additions & 8 deletions telegrinder/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

T = typing.TypeVar("T")


MODEL_CONFIG: typing.Final[dict[str, typing.Any]] = {
"omit_defaults": True,
"dict": True,
Expand Down Expand Up @@ -44,14 +45,17 @@ def full_result(


def get_params(params: dict[str, typing.Any]) -> dict[str, typing.Any]:
return {
k: v.unwrap() if isinstance(v, Some) else v
for k, v in (
*params.pop("other", {}).items(),
*params.items(),
)
if k != "self" and type(v) not in (NoneType, Nothing)
}
validated_params = {}
for k, v in (
*params.pop("other", {}).items(),
*params.items(),
):
if isinstance(v, Proxy):
v = v.get()
if k == "self" or type(v) in (NoneType, Nothing):
continue
validated_params[k] = v.unwrap() if isinstance(v, Some) else v
return validated_params


class Model(msgspec.Struct, **MODEL_CONFIG):
Expand Down Expand Up @@ -154,6 +158,38 @@ def convert_tpl(
return data


class Proxy:
def __init__(self, cfg: "_ProxiedDict", key: str):
self.key = key
self.cfg = cfg

def get(self):
return self.cfg._defaults.get(self.key)


class _ProxiedDict(typing.Generic[T]):
def __init__(self, tp: type[T]) -> None:
self._type = tp
self._defaults = {}

def __getitem__(self, key: str) -> None:
return Proxy(self, key) # type: ignore

def __setattribute__(self, name: str, value) -> None:
self._defaults[name] = value

def __setitem__(self, key: str, value: typing.Any) -> None:
self._defaults[key] = value


if typing.TYPE_CHECKING:
def ProxiedDict(typed_dct: type[T]) -> T | _ProxiedDict: # noqa: N802
...

else:
ProxiedDict = _ProxiedDict


__all__ = (
"DataConverter",
"MODEL_CONFIG",
Expand Down
29 changes: 17 additions & 12 deletions telegrinder/types/methods.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import dataclasses
import typing
from datetime import datetime

from fntypes.co import Result, Variative

from telegrinder.api.error import APIError
from telegrinder.model import full_result, get_params
from telegrinder.model import ProxiedDict, full_result, get_params
from telegrinder.types.enums import * # noqa: F403
from telegrinder.types.objects import * # noqa: F403

Expand All @@ -15,6 +16,10 @@
class APIMethods:
"""Telegram Bot API 7.7 methods, released `July 7, 2024`."""

default_params = ProxiedDict(
typing.TypedDict("DefaultParams", {"parse_mode": str})
)

def __init__(self, api: "ABCAPI") -> None:
self.api = api

Expand Down Expand Up @@ -206,7 +211,7 @@ async def send_message(
text: str,
business_connection_id: str | None = None,
message_thread_id: int | None = None,
parse_mode: str | None = None,
parse_mode: str | None = default_params["parse_mode"],
entities: list[MessageEntity] | None = None,
link_preview_options: LinkPreviewOptions | None = None,
disable_notification: bool | None = None,
Expand Down Expand Up @@ -351,7 +356,7 @@ async def copy_message(
message_id: int,
message_thread_id: int | None = None,
caption: str | None = None,
parse_mode: str | None = None,
parse_mode: str | None = default_params["parse_mode"],
caption_entities: list[MessageEntity] | None = None,
show_caption_above_media: bool | None = None,
disable_notification: bool | None = None,
Expand Down Expand Up @@ -468,7 +473,7 @@ async def send_photo(
business_connection_id: str | None = None,
message_thread_id: int | None = None,
caption: str | None = None,
parse_mode: str | None = None,
parse_mode: str | None = default_params["parse_mode"],
caption_entities: list[MessageEntity] | None = None,
show_caption_above_media: bool | None = None,
has_spoiler: bool | None = None,
Expand Down Expand Up @@ -543,7 +548,7 @@ async def send_audio(
business_connection_id: str | None = None,
message_thread_id: int | None = None,
caption: str | None = None,
parse_mode: str | None = None,
parse_mode: str | None = default_params["parse_mode"],
caption_entities: list[MessageEntity] | None = None,
duration: int | None = None,
performer: str | None = None,
Expand Down Expand Up @@ -632,7 +637,7 @@ async def send_document(
message_thread_id: int | None = None,
thumbnail: InputFile | str | None = None,
caption: str | None = None,
parse_mode: str | None = None,
parse_mode: str | None = default_params["parse_mode"],
caption_entities: list[MessageEntity] | None = None,
disable_content_type_detection: bool | None = None,
disable_notification: bool | None = None,
Expand Down Expand Up @@ -717,7 +722,7 @@ async def send_video(
height: int | None = None,
thumbnail: InputFile | str | None = None,
caption: str | None = None,
parse_mode: str | None = None,
parse_mode: str | None = default_params["parse_mode"],
caption_entities: list[MessageEntity] | None = None,
show_caption_above_media: bool | None = None,
has_spoiler: bool | None = None,
Expand Down Expand Up @@ -814,7 +819,7 @@ async def send_animation(
height: int | None = None,
thumbnail: InputFile | str | None = None,
caption: str | None = None,
parse_mode: str | None = None,
parse_mode: str | None = default_params["parse_mode"],
caption_entities: list[MessageEntity] | None = None,
show_caption_above_media: bool | None = None,
has_spoiler: bool | None = None,
Expand Down Expand Up @@ -903,7 +908,7 @@ async def send_voice(
business_connection_id: str | None = None,
message_thread_id: int | None = None,
caption: str | None = None,
parse_mode: str | None = None,
parse_mode: str | None = default_params["parse_mode"],
caption_entities: list[MessageEntity] | None = None,
duration: int | None = None,
disable_notification: bool | None = None,
Expand Down Expand Up @@ -1048,7 +1053,7 @@ async def send_paid_media(
star_count: int,
media: list[InputPaidMedia],
caption: str | None = None,
parse_mode: str | None = None,
parse_mode: str | None = default_params["parse_mode"],
caption_entities: list[MessageEntity] | None = None,
show_caption_above_media: bool | None = None,
disable_notification: bool | None = None,
Expand Down Expand Up @@ -3177,7 +3182,7 @@ async def edit_message_text(
chat_id: int | str | None = None,
message_id: int | None = None,
inline_message_id: str | None = None,
parse_mode: str | None = None,
parse_mode: str | None = default_params["parse_mode"],
entities: list[MessageEntity] | None = None,
link_preview_options: LinkPreviewOptions | None = None,
reply_markup: InlineKeyboardMarkup | None = None,
Expand Down Expand Up @@ -3229,7 +3234,7 @@ async def edit_message_caption(
message_id: int | None = None,
inline_message_id: str | None = None,
caption: str | None = None,
parse_mode: str | None = None,
parse_mode: str | None = default_params["parse_mode"],
caption_entities: list[MessageEntity] | None = None,
show_caption_above_media: bool | None = None,
reply_markup: InlineKeyboardMarkup | None = None,
Expand Down

0 comments on commit 64ec2b3

Please sign in to comment.