Removed the use of the context instance (Bot.get_current) from all placements that were used previously.

This commit is contained in:
Alex Root Junior 2023-07-28 22:04:27 +03:00
parent 479e302cba
commit 599f843268
No known key found for this signature in database
GPG key ID: 074C1D455EBEA4AC
7 changed files with 19 additions and 21 deletions

View file

@ -230,7 +230,7 @@ from .session.base import BaseSession
T = TypeVar("T")
class Bot(ContextInstanceMixin["Bot"]):
class Bot:
def __init__(
self,
token: str,
@ -284,16 +284,14 @@ class Bot(ContextInstanceMixin["Bot"]):
"""
Generate bot context
:param auto_close:
:param auto_close: close session on exit
:return:
"""
token = self.set_current(self)
try:
yield self
finally:
if auto_close:
await self.session.close()
self.reset_current(token)
async def me(self) -> User:
"""

View file

@ -13,13 +13,6 @@ class BotContextController(BaseModel):
def model_post_init(self, __context: Any) -> None:
self._bot = __context.get("bot") if __context else None
def get_mounted_bot(self) -> Optional["Bot"]:
# Properties are not supported in pydantic BaseModel
# @computed_field decorator is not a solution for this case in due to
# it produces an additional field in model with validation and serialization that
# we don't need here
return self._bot
def as_(self, bot: Optional["Bot"]) -> Self:
"""
Bind object to a bot instance.
@ -29,3 +22,12 @@ class BotContextController(BaseModel):
"""
self._bot = bot
return self
@property
def bot(self) -> Optional["Bot"]:
"""
Get bot instance.
:return: Bot instance
"""
return self._bot

View file

@ -143,7 +143,7 @@ class Dispatcher(Router):
handled = False
start_time = loop.time()
if update.get_mounted_bot() != bot:
if update.bot != bot:
# Re-mounting update to the current bot instance for making possible to
# use it in shortcuts.
# Here is update is re-created because we need to propagate context to
@ -184,7 +184,7 @@ class Dispatcher(Router):
:param update:
:param kwargs:
"""
parsed_update = Update(**update)
parsed_update = Update.model_validate(update, context={"bot": bot})
return await self.feed_update(bot=bot, update=parsed_update, **kwargs)
@classmethod
@ -558,7 +558,7 @@ class Dispatcher(Router):
polling_timeout: int = 10,
handle_as_tasks: bool = True,
backoff_config: BackoffConfig = DEFAULT_BACKOFF_CONFIG,
allowed_updates: Optional[List[str]] = None,
allowed_updates: Optional[Union[List[str], UNSET_TYPE]] = UNSET,
handle_signals: bool = True,
close_bot_session: bool = True,
**kwargs: Any,

View file

@ -27,7 +27,7 @@ class StateFilter(Filter):
)
async def __call__(
self, obj: Union[TelegramObject], raw_state: Optional[str] = None
self, obj: TelegramObject, raw_state: Optional[str] = None
) -> Union[bool, Dict[str, Any]]:
allowed_states = cast(Sequence[StateType], self.states)
for allowed_state in allowed_states:

View file

@ -32,7 +32,7 @@ class BaseHandler(BaseHandlerMixin[T], ABC):
if "bot" in self.data:
return cast(Bot, self.data["bot"])
return Bot.get_current(no_error=False)
raise RuntimeError("Bot instance not found in the context")
@property
def update(self) -> Update:

View file

@ -14,6 +14,7 @@ class TelegramObject(BotContextController, BaseModel):
frozen=True,
populate_by_name=True,
arbitrary_types_allowed=True,
defer_build=True,
)

View file

@ -31,22 +31,19 @@ class ChatActionSender:
def __init__(
self,
*,
bot: Bot,
chat_id: Union[str, int],
action: str = "typing",
interval: float = DEFAULT_INTERVAL,
initial_sleep: float = DEFAULT_INITIAL_SLEEP,
bot: Optional[Bot] = None,
) -> None:
"""
:param bot: instance of the bot
:param chat_id: target chat id
:param action: chat action type
:param interval: interval between iterations
:param initial_sleep: sleep before first iteration
:param bot: instance of the bot, can be omitted from the context
"""
if bot is None:
bot = Bot.get_current(False)
self.chat_id = chat_id
self.action = action
self.interval = interval