Skip to content

Commit

Permalink
fixiks
Browse files Browse the repository at this point in the history
  • Loading branch information
luwqz1 committed Jun 5, 2024
1 parent 041651b commit 8f3846f
Show file tree
Hide file tree
Showing 6 changed files with 19 additions and 31 deletions.
10 changes: 4 additions & 6 deletions examples/webhook_bot/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,8 @@

HOST = typing.cast(str, env.str("HOST")) # > host, for example: https://site.com
PORT = typing.cast(int, env.int("PORT")) # > port, can be either 443, 80, 88, or 8443.
WEBHOOK_PATH = typing.cast(
str, env.str("WEBHOOK_PATH") + token
) # > webhook path: /bot/ + bot token: 123:ABC...
WEBHOOK_URL = HOST + WEBHOOK_PATH # > host: https://site.com + webhook path: /bot/123:ABC...
WEBHOOK_PATH = typing.cast(str, env.str("WEBHOOK_PATH") + token) # > webhook path, for example: /bot/ + bot token: 123:ABC...
WEBHOOK_URL = HOST + WEBHOOK_PATH # > host + webhook path
SECRET_TOKEN = secrets.token_urlsafe(64) # > random secret token


Expand All @@ -39,11 +37,11 @@ async def lifespan(_):
@app.post(WEBHOOK_PATH, response_class=Response) # type: ignore
async def webhook_bot(request: Request) -> Response: # type: ignore
if request.headers.get("X-Telegram-Bot-Api-Secret-Token") != SECRET_TOKEN: # type: ignore
return Response(status_code=404)
return Response(status_code=404) # type: ignore
update = Update.from_bytes(await request.body()) # type: ignore
logger.debug("Webhook received update (update_id={})", update.update_id)
asyncio.get_running_loop().create_task(dp.feed(update, api))
return Response(status_code=200)
return Response(status_code=200) # type: ignore


if __name__ == "__main__":
Expand Down
2 changes: 2 additions & 0 deletions telegrinder/bot/dispatch/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,12 @@ async def check(self, event: T, ctx: Context) -> bool:
def __init__(self, **kwargs: AnyValue) -> None:
cls_vars = vars(self.__class__)
defaults = {}

for k in self.__class__.__annotations__:
if k in cls_vars:
defaults[k] = cls_vars[k]
delattr(self.__class__, k)

dict.__init__(self, **defaults | kwargs)

@recursive_repr()
Expand Down
12 changes: 6 additions & 6 deletions telegrinder/bot/dispatch/waiter_machine/machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@


class WaiterMachine:
def __init__(self, *, max_limit_storage: int = 1000) -> None:
self.max_limit_storage = max_limit_storage
def __init__(self, *, max_storage_size: int = 1000) -> None:
self.max_storage_size = max_storage_size
self.storage: Storage = {}

def __repr__(self) -> str:
return "<{}: max_limit_storage={}, storage={!r}>".format(
return "<{}: max_storage_size={}, storage={!r}>".format(
self.__class__.__name__,
self.max_limit_storage,
self.max_storage_size,
self.storage,
)

Expand Down Expand Up @@ -96,7 +96,7 @@ async def wait(

if view_name not in self.storage:
state_view.middlewares.insert(0, WaiterMiddleware(self, state_view))
self.storage[view_name] = LimitedDict(maxlimit=self.max_limit_storage)
self.storage[view_name] = LimitedDict(maxlimit=self.max_storage_size)

if (deleted_short_state := self.storage[view_name].set(key, short_state)) is not None:
deleted_short_state.cancel()
Expand All @@ -114,7 +114,7 @@ async def call_behaviour(
behaviour: Behaviour[EventModel] | None = None,
**context: typing.Any,
) -> None:
# TODO: support param view as a behaviour
# TODO: support view as a behaviour

if behaviour is None:
return
Expand Down
2 changes: 1 addition & 1 deletion telegrinder/bot/dispatch/waiter_machine/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async def pre(self, event: EventType, ctx: Context) -> bool:
if not self.view or not hasattr(self.view, "get_state_key"):
raise RuntimeError(
"WaiterMiddleware cannot be used inside a view which doesn't "
"provide get_state_key (ABCStateView Protocol)."
"provide get_state_key (ABCStateView interface)."
)

view_name = self.view.__class__.__name__
Expand Down
2 changes: 1 addition & 1 deletion telegrinder/bot/dispatch/waiter_machine/short_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class ShortState(typing.Generic[EventModel]):
context: ShortStateContext[EventModel] | None = dataclasses.field(default=None, init=False)

def __post_init__(self, expiration: datetime.timedelta | None = None) -> None:
self.expiration_date = (datetime.datetime.now() - expiration) if expiration is not None else None
self.expiration_date = (datetime.datetime.now() + expiration) if expiration is not None else None

def cancel(self) -> None:
"""Cancel schedule waiters."""
Expand Down
22 changes: 5 additions & 17 deletions telegrinder/tools/global_context/global_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,14 +315,10 @@ def pop(
var_value_type: type[T],
) -> Option[GlobalCtxVar[T]]: ...

def pop(
self,
var_name: str,
var_value_type: type[T] = typing.Any # type: ignore
) -> Option[GlobalCtxVar[typing.Any]]:
def pop(self, var_name, var_value_type=typing.Any):
"""Pop context variable by name."""

val = self.get(var_name, var_value_type)
val = self.get(var_name, var_value_type) # type: ignore
if val:
del self[var_name]
return val
Expand All @@ -338,11 +334,7 @@ def get(
var_value_type: type[T],
) -> Option[GlobalCtxVar[T]]: ...

def get(
self,
var_name: str,
var_value_type: type[T] = typing.Any, # type: ignore
) -> Option[GlobalCtxVar[typing.Any]]:
def get(self, var_name, var_value_type=typing.Any):
"""Get context variable by name."""

generic_types = typing.get_args(get_orig_class(self))
Expand Down Expand Up @@ -373,14 +365,10 @@ def get_value(
var_value_type: type[T],
) -> Option[T]: ...

def get_value(
self,
var_name: str,
var_value_type: type[T] = typing.Any, # type: ignore
) -> Option[typing.Any]:
def get_value(self, var_name, var_value_type=typing.Any):
"""Get context variable value by name."""

return self.get(var_name, var_value_type).map(lambda var: var.value)
return self.get(var_name, var_value_type).map(lambda var: var.value) # type: ignore

def rename(self, old_var_name: str, new_var_name: str) -> Result[_, str]:
"""Rename context variable."""
Expand Down

0 comments on commit 8f3846f

Please sign in to comment.