Skip to content

Commit

Permalink
some fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
luwqz1 committed Jul 11, 2024
1 parent 7dd0e1d commit e0c56c6
Show file tree
Hide file tree
Showing 11 changed files with 981 additions and 978 deletions.
14 changes: 7 additions & 7 deletions .github/ISSUE_TEMPLATE/bug.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,19 @@ assignees: "luwqz1"
* [ ] 🟢 I have the **latest** version of the **framework** installed 🟢

### ✏️ Description ✏️
<!-- Describe the bug -->
`When I..., it...`
<!-- Describe the bug. -->
```
When I..., it...
```

### 🪄 Code example 🪄
<!-- Provide a minimal example -->
<!-- Provide a minimal example. -->
```python
from telegrinder import API, Telegrinder, Token

...
from telegrinder import ...
```

### 📝 Logs 📝
<!-- Provide logs/errors to review the issue -->
<!-- Provide logs/errors to review the issue. -->
```
Traceback (most recent call last):
File "main.py", line 1, in <module>
Expand Down
7 changes: 6 additions & 1 deletion .github/ISSUE_TEMPLATE/new_feat.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,19 @@ assignees: "luwqz1"
## 🚀 Feature Request 🚀

**✏️ New feature description ✏️**
<!-- A clear and concise description. Ex. -->
<!-- A clear and concise description. -->
```
No response
```

**🪄 Provide a minimal example 🪄**
<!-- A small code sample that will demonstrate your feature. -->
```python
from telegrinder import ...
```

**✨ Teachability, Documentation, Adoption ✨**
<!-- If you can, explain how users will be able to use this and possibly write out a version the docs. -->
```
No response
```
2 changes: 1 addition & 1 deletion .github/workflows/lint-and-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:
- name: Lint code with ruff
run: >
poetry run ruff check .
poetry run ruff check . --fix
- name: Check types with basedpyright
run: >
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -82,5 +82,5 @@ asyncio_mode = "auto"
[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"

[tool.basedpyright]
[tool.pyright]
typeCheckingMode = "basic"
21 changes: 10 additions & 11 deletions telegrinder/bot/dispatch/handler/func.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,22 @@
"F",
bound=typing.Callable[typing.Concatenate[typing.Any, ...], typing.Awaitable[typing.Any]],
)
AdaptTo = typing.TypeVar("AdaptTo", default=UpdateCute)
EventType = typing.TypeVar("EventType", bound=BaseCute)
Event = typing.TypeVar("Event", bound=BaseCute)
ErrorHandlerT = typing.TypeVar("ErrorHandlerT", bound=ABCErrorHandler, default=ErrorHandler)


@dataclasses.dataclass(repr=False)
class FuncHandler(ABCHandler[EventType], typing.Generic[EventType, F, ErrorHandlerT]):
class FuncHandler(ABCHandler[Event], typing.Generic[Event, F, ErrorHandlerT]):
func: F
rules: list["ABCRule[EventType] | ABCRule[tuple[Node, ...]]"]
_: dataclasses.KW_ONLY
is_blocking: bool = dataclasses.field(default=True)
dataclass: type[typing.Any] | None = dataclasses.field(default=dict)
rules: list["ABCRule"]
is_blocking: bool = dataclasses.field(default=True, kw_only=True)
dataclass: type[typing.Any] | None = dataclasses.field(default=dict, kw_only=True)
error_handler: ErrorHandlerT = dataclasses.field(
default_factory=lambda: typing.cast(ErrorHandlerT, ErrorHandler()),
kw_only=True,
)
preset_context: Context = dataclasses.field(default_factory=lambda: Context())
update_type: UpdateType | None = dataclasses.field(default=None)
preset_context: Context = dataclasses.field(default_factory=lambda: Context(), kw_only=True)
update_type: UpdateType | None = dataclasses.field(default=None, kw_only=True)

def __repr__(self) -> str:
return "<{}: {}={!r} with rules={!r}, dataclass={!r}, error_handler={!r}>".format(
Expand Down Expand Up @@ -79,7 +78,7 @@ async def check(self, api: ABCAPI, event: Update, ctx: Context | None = None) ->
ctx |= temp_ctx
return True

async def run(self, event: EventType, ctx: Context) -> typing.Any:
async def run(self, event: Event, ctx: Context) -> typing.Any:
api = event.api

if self.dataclass is not None:
Expand All @@ -94,7 +93,7 @@ async def run(self, event: EventType, ctx: Context) -> typing.Any:
event = self.dataclass(**event.to_dict())

result = (await self.error_handler.run(self.func, event, api, ctx)).unwrap()
if node_col := ctx["node_col"]:
if node_col := ctx.node_col:
await node_col.close_all()
return result

Expand Down
2 changes: 1 addition & 1 deletion telegrinder/bot/dispatch/handler/message_reply.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class MessageReplyHandler(ABCHandler[MessageCute]):
def __init__(
self,
text: str,
*rules: ABCRule[MessageCute],
*rules: ABCRule,
is_blocking: bool = True,
as_reply: bool = False,
preset_context: Context | None = None,
Expand Down
19 changes: 9 additions & 10 deletions telegrinder/bot/dispatch/view/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
from telegrinder.bot.rules.abc import ABCRule
from telegrinder.model import Model
from telegrinder.msgspec_utils import Option
from telegrinder.node.base import Node
from telegrinder.tools.error_handler.error_handler import ABCErrorHandler, ErrorHandler
from telegrinder.types.objects import Update

Expand Down Expand Up @@ -54,7 +53,7 @@ def get_state_key(self, event: Event) -> int | None:


class BaseView(ABCView, typing.Generic[Event]):
auto_rules: list[ABCRule[Event] | ABCRule[tuple[Node, ...]]]
auto_rules: list[ABCRule]
handlers: list[ABCHandler[Event]]
middlewares: list[ABCMiddleware[Event]]
return_manager: ABCReturnManager[Event] | None = None
Expand All @@ -76,7 +75,7 @@ def get_event_type(cls) -> Option[type[Event]]:
@classmethod
def to_handler(
cls,
*rules: ABCRule[Event] | ABCRule[tuple[Node, ...]],
*rules: ABCRule,
) -> typing.Callable[
[FuncType[Event]],
FuncHandler[Event, FuncType[Event], ErrorHandler[Event]],
Expand All @@ -86,7 +85,7 @@ def to_handler(
@classmethod
def to_handler(
cls,
*rules: ABCRule[Event] | ABCRule[tuple[Node, ...]],
*rules: ABCRule,
error_handler: ErrorHandlerT,
is_blocking: bool = True,
) -> typing.Callable[[FuncType[Event]], FuncHandler[Event, FuncType[Event], ErrorHandlerT]]: ...
Expand All @@ -95,7 +94,7 @@ def to_handler(
@classmethod
def to_handler(
cls,
*rules: ABCRule[Event] | ABCRule[tuple[Node, ...]],
*rules: ABCRule,
error_handler: typing.Literal[None] = None,
is_blocking: bool = True,
) -> typing.Callable[
Expand All @@ -106,7 +105,7 @@ def to_handler(
@classmethod
def to_handler( # type: ignore
cls,
*rules: ABCRule[Event] | ABCRule[tuple[Node, ...]],
*rules: ABCRule,
error_handler: ABCErrorHandler | None = None,
is_blocking: bool = True,
):
Expand All @@ -124,7 +123,7 @@ def wrapper(func: FuncType[Event]):
@typing.overload
def __call__(
self,
*rules: ABCRule[Event] | ABCRule[tuple[Node, ...]],
*rules: ABCRule,
) -> typing.Callable[
[FuncType[Event]],
FuncHandler[Event, FuncType[Event], ErrorHandler[Event]],
Expand All @@ -133,15 +132,15 @@ def __call__(
@typing.overload
def __call__( # type: ignore
self,
*rules: ABCRule[Event] | ABCRule[tuple[Node, ...]],
*rules: ABCRule,
error_handler: ErrorHandlerT,
is_blocking: bool = True,
) -> typing.Callable[[FuncType[Event]], FuncHandler[Event, FuncType[Event], ErrorHandlerT]]: ...

@typing.overload
def __call__(
self,
*rules: ABCRule[Event] | ABCRule[tuple[Node, ...]],
*rules: ABCRule,
error_handler: typing.Literal[None] = None,
is_blocking: bool = True,
) -> typing.Callable[
Expand All @@ -151,7 +150,7 @@ def __call__(

def __call__( # type: ignore
self,
*rules: ABCRule[Event] | ABCRule[tuple[Node, ...]],
*rules: ABCRule,
error_handler: ABCErrorHandler | None = None,
is_blocking: bool = True,
):
Expand Down
24 changes: 12 additions & 12 deletions telegrinder/bot/rules/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
from telegrinder.tools.magic import cache_translation, get_annotations, get_cached_translation
from telegrinder.types.objects import Update as UpdateObject

Ts = typing.TypeVarTuple("Ts")
AdaptTo = typing.TypeVar("AdaptTo", default=typing.Any)

Message: typing.TypeAlias = MessageCute
Expand All @@ -35,7 +34,7 @@ async def wrapper(self: "ABCRule", translator: ABCTranslator):

class ABCRule(ABC, typing.Generic[AdaptTo]):
adapter: ABCAdapter[UpdateObject, AdaptTo] = RawUpdateAdapter() # type: ignore
requires: list["ABCRule[AdaptTo]"] = []
requires: list["ABCRule"] = []

@abstractmethod
async def check(self, event: AdaptTo, *, ctx: Context) -> bool:
Expand All @@ -54,7 +53,8 @@ async def bounding_check(
node_col_values = node_col.values() if node_col is not None else {}

for k, v in get_annotations(self.check).items():
if isinstance(v, Event) or isinstance(adapted_value, typing.get_origin(v)):
v = typing.get_origin(v) or v # Function typing.get_origin may return the origin type or None
if isinstance(v, Event) or (isinstance(v, type) and isinstance(adapted_value, v)):
kw[k] = adapted_value
elif is_node(v):
assert k in node_col_values, "Node is undefined, error while bounding."
Expand All @@ -70,7 +70,7 @@ async def bounding_check(

return await self.check(**kw)

def __init_subclass__(cls, requires: list["ABCRule[AdaptTo]"] | None = None) -> None:
def __init_subclass__(cls, requires: list["ABCRule"] | None = None) -> None:
"""Merges requirements from inherited classes and rule-specific requirements."""

requirements = []
Expand All @@ -81,7 +81,7 @@ def __init_subclass__(cls, requires: list["ABCRule[AdaptTo]"] | None = None) ->
requirements.extend(requires or ())
cls.requires = list(dict.fromkeys(requirements))

def __and__(self, other: "ABCRule[AdaptTo]") -> "AndRule[AdaptTo]":
def __and__(self, other: "ABCRule") -> "AndRule":
"""And Rule.
```python
Expand All @@ -92,7 +92,7 @@ def __and__(self, other: "ABCRule[AdaptTo]") -> "AndRule[AdaptTo]":

return AndRule(self, other)

def __or__(self, other: "ABCRule[AdaptTo]") -> "OrRule[AdaptTo]":
def __or__(self, other: "ABCRule") -> "OrRule":
"""Or Rule.
```python
Expand All @@ -103,7 +103,7 @@ def __or__(self, other: "ABCRule[AdaptTo]") -> "OrRule[AdaptTo]":

return OrRule(self, other)

def __invert__(self) -> "NotRule[AdaptTo]":
def __invert__(self) -> "NotRule":
"""Not Rule.
```python
Expand All @@ -124,7 +124,7 @@ async def translate(self, translator: ABCTranslator) -> typing.Self:
return self


class AndRule(ABCRule[AdaptTo]):
class AndRule(ABCRule):
def __init__(self, *rules: ABCRule[AdaptTo]) -> None:
self.rules = rules

Expand All @@ -137,8 +137,8 @@ async def check(self, event: Update, ctx: Context) -> bool:
return True


class OrRule(ABCRule[AdaptTo]):
def __init__(self, *rules: ABCRule[AdaptTo]) -> None:
class OrRule(ABCRule):
def __init__(self, *rules: ABCRule) -> None:
self.rules = rules

async def check(self, event: Update, ctx: Context) -> bool:
Expand All @@ -150,8 +150,8 @@ async def check(self, event: Update, ctx: Context) -> bool:
return False


class NotRule(ABCRule[AdaptTo]):
def __init__(self, rule: ABCRule[AdaptTo]) -> None:
class NotRule(ABCRule):
def __init__(self, rule: ABCRule) -> None:
self.rule = rule

async def check(self, event: Update, ctx: Context) -> bool:
Expand Down
Loading

0 comments on commit e0c56c6

Please sign in to comment.