Skip to content

Commit

Permalink
customize types (#30)
Browse files Browse the repository at this point in the history
* custom parser for types

* avoid error for manually parsing

* force parse

* fix parsing property/bound methods

* customize types example
  • Loading branch information
z44d authored Jul 20, 2024
1 parent 209016a commit 430902d
Show file tree
Hide file tree
Showing 3 changed files with 1,732 additions and 426 deletions.
24 changes: 24 additions & 0 deletions examples/custom_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import logging

from tgram import TgBot, filters
from tgram.types import Message

bot = TgBot("API_TOKEN_HERE")
logging.basicConfig(level=logging.INFO)


class CustomizedMessage(Message):
@property
def hello(self) -> str:
return f"Hello {self.from_user.full_name} !"


bot.customize(Message, CustomizedMessage)


@bot.on_message(filters.private & filters.command("start"))
async def say_hello(_, m: CustomizedMessage) -> CustomizedMessage:
return await m.reply_text(m.hello)


bot.run_for_updates()
10 changes: 10 additions & 0 deletions tgram/tgbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import io
import ssl
import certifi
import inspect

from .methods import TelegramBotMethods
from .decorators import Decorators
Expand Down Expand Up @@ -122,6 +123,7 @@ class TgBot(TelegramBotMethods, Decorators, Dispatcher):
me: "tgram.types.User" = None
_session: "aiohttp.ClientSession" = None
_api_url: str = None
_custom_types: dict = {}

def __init__(
self,
Expand Down Expand Up @@ -262,6 +264,14 @@ def load_plugins(self) -> None:
if isinstance(handler, tgram.handlers.Handler):
self.add_handler(handler)

def customize(self, old: type, new: type) -> Literal[True]:
if tgram.types.Type_ not in inspect.getmro(old):
raise ValueError("You can't customize this type, it's not tgram type.")

self._custom_types.update({old.__name__: new})

return True


wrap(Dispatcher)
wrap(TelegramBotMethods)
Loading

0 comments on commit 430902d

Please sign in to comment.