ng-bot-api 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. ng_bot_api/__init__.py +56 -0
  2. ng_bot_api/api_version.py +2 -0
  3. ng_bot_api/async_bot.py +97 -0
  4. ng_bot_api/core/__init__.py +31 -0
  5. ng_bot_api/core/base.py +36 -0
  6. ng_bot_api/core/caller.py +17 -0
  7. ng_bot_api/core/decoding.py +85 -0
  8. ng_bot_api/core/encoding.py +42 -0
  9. ng_bot_api/core/errors.py +75 -0
  10. ng_bot_api/core/input_file.py +56 -0
  11. ng_bot_api/core/polling.py +39 -0
  12. ng_bot_api/core/registry.py +72 -0
  13. ng_bot_api/core/request.py +67 -0
  14. ng_bot_api/core/typespec.py +57 -0
  15. ng_bot_api/dispatcher/__init__.py +17 -0
  16. ng_bot_api/dispatcher/dispatcher.py +95 -0
  17. ng_bot_api/dispatcher/filter_base.py +78 -0
  18. ng_bot_api/dispatcher/filters.py +124 -0
  19. ng_bot_api/dispatcher/handler.py +34 -0
  20. ng_bot_api/dispatcher/router.py +69 -0
  21. ng_bot_api/methods/__init__.py +115 -0
  22. ng_bot_api/methods/async_01.py +99 -0
  23. ng_bot_api/methods/async_02.py +114 -0
  24. ng_bot_api/methods/async_03.py +85 -0
  25. ng_bot_api/methods/async_04.py +110 -0
  26. ng_bot_api/methods/async_05.py +114 -0
  27. ng_bot_api/methods/async_06.py +74 -0
  28. ng_bot_api/methods/async_07.py +114 -0
  29. ng_bot_api/methods/async_08.py +106 -0
  30. ng_bot_api/methods/async_09.py +97 -0
  31. ng_bot_api/methods/async_10.py +92 -0
  32. ng_bot_api/methods/async_11.py +107 -0
  33. ng_bot_api/methods/async_12.py +119 -0
  34. ng_bot_api/methods/async_13.py +119 -0
  35. ng_bot_api/methods/async_14.py +113 -0
  36. ng_bot_api/methods/async_15.py +117 -0
  37. ng_bot_api/methods/async_16.py +115 -0
  38. ng_bot_api/methods/async_17.py +121 -0
  39. ng_bot_api/methods/async_18.py +118 -0
  40. ng_bot_api/methods/async_19.py +128 -0
  41. ng_bot_api/methods/async_20.py +115 -0
  42. ng_bot_api/methods/async_21.py +127 -0
  43. ng_bot_api/methods/async_22.py +110 -0
  44. ng_bot_api/methods/async_23.py +116 -0
  45. ng_bot_api/methods/async_24.py +118 -0
  46. ng_bot_api/methods/async_25.py +109 -0
  47. ng_bot_api/methods/async_26.py +124 -0
  48. ng_bot_api/methods/async_27.py +119 -0
  49. ng_bot_api/methods/async_28.py +119 -0
  50. ng_bot_api/methods/async_29.py +108 -0
  51. ng_bot_api/methods/async_30.py +115 -0
  52. ng_bot_api/methods/async_31.py +112 -0
  53. ng_bot_api/methods/async_32.py +126 -0
  54. ng_bot_api/methods/async_33.py +105 -0
  55. ng_bot_api/methods/async_34.py +117 -0
  56. ng_bot_api/methods/async_35.py +122 -0
  57. ng_bot_api/methods/async_36.py +121 -0
  58. ng_bot_api/methods/async_37.py +126 -0
  59. ng_bot_api/methods/async_38.py +112 -0
  60. ng_bot_api/methods/async_39.py +84 -0
  61. ng_bot_api/methods/async_40.py +125 -0
  62. ng_bot_api/methods/async_41.py +115 -0
  63. ng_bot_api/methods/async_42.py +30 -0
  64. ng_bot_api/methods/sync_01.py +99 -0
  65. ng_bot_api/methods/sync_02.py +114 -0
  66. ng_bot_api/methods/sync_03.py +85 -0
  67. ng_bot_api/methods/sync_04.py +110 -0
  68. ng_bot_api/methods/sync_05.py +114 -0
  69. ng_bot_api/methods/sync_06.py +74 -0
  70. ng_bot_api/methods/sync_07.py +114 -0
  71. ng_bot_api/methods/sync_08.py +106 -0
  72. ng_bot_api/methods/sync_09.py +97 -0
  73. ng_bot_api/methods/sync_10.py +92 -0
  74. ng_bot_api/methods/sync_11.py +107 -0
  75. ng_bot_api/methods/sync_12.py +119 -0
  76. ng_bot_api/methods/sync_13.py +119 -0
  77. ng_bot_api/methods/sync_14.py +113 -0
  78. ng_bot_api/methods/sync_15.py +117 -0
  79. ng_bot_api/methods/sync_16.py +115 -0
  80. ng_bot_api/methods/sync_17.py +121 -0
  81. ng_bot_api/methods/sync_18.py +118 -0
  82. ng_bot_api/methods/sync_19.py +128 -0
  83. ng_bot_api/methods/sync_20.py +115 -0
  84. ng_bot_api/methods/sync_21.py +127 -0
  85. ng_bot_api/methods/sync_22.py +110 -0
  86. ng_bot_api/methods/sync_23.py +116 -0
  87. ng_bot_api/methods/sync_24.py +118 -0
  88. ng_bot_api/methods/sync_25.py +109 -0
  89. ng_bot_api/methods/sync_26.py +124 -0
  90. ng_bot_api/methods/sync_27.py +119 -0
  91. ng_bot_api/methods/sync_28.py +119 -0
  92. ng_bot_api/methods/sync_29.py +108 -0
  93. ng_bot_api/methods/sync_30.py +115 -0
  94. ng_bot_api/methods/sync_31.py +112 -0
  95. ng_bot_api/methods/sync_32.py +126 -0
  96. ng_bot_api/methods/sync_33.py +105 -0
  97. ng_bot_api/methods/sync_34.py +117 -0
  98. ng_bot_api/methods/sync_35.py +122 -0
  99. ng_bot_api/methods/sync_36.py +121 -0
  100. ng_bot_api/methods/sync_37.py +126 -0
  101. ng_bot_api/methods/sync_38.py +112 -0
  102. ng_bot_api/methods/sync_39.py +84 -0
  103. ng_bot_api/methods/sync_40.py +125 -0
  104. ng_bot_api/methods/sync_41.py +115 -0
  105. ng_bot_api/methods/sync_42.py +30 -0
  106. ng_bot_api/py.typed +0 -0
  107. ng_bot_api/sync_bot.py +95 -0
  108. ng_bot_api/types/__init__.py +82 -0
  109. ng_bot_api/types/available_types_01.py +102 -0
  110. ng_bot_api/types/available_types_02.py +141 -0
  111. ng_bot_api/types/available_types_03.py +311 -0
  112. ng_bot_api/types/available_types_04.py +84 -0
  113. ng_bot_api/types/available_types_05.py +134 -0
  114. ng_bot_api/types/available_types_06.py +126 -0
  115. ng_bot_api/types/available_types_07.py +119 -0
  116. ng_bot_api/types/available_types_08.py +120 -0
  117. ng_bot_api/types/available_types_09.py +115 -0
  118. ng_bot_api/types/available_types_10.py +109 -0
  119. ng_bot_api/types/available_types_11.py +121 -0
  120. ng_bot_api/types/available_types_12.py +120 -0
  121. ng_bot_api/types/available_types_13.py +128 -0
  122. ng_bot_api/types/available_types_14.py +124 -0
  123. ng_bot_api/types/available_types_15.py +129 -0
  124. ng_bot_api/types/available_types_16.py +121 -0
  125. ng_bot_api/types/available_types_17.py +124 -0
  126. ng_bot_api/types/available_types_18.py +128 -0
  127. ng_bot_api/types/available_types_19.py +115 -0
  128. ng_bot_api/types/available_types_20.py +123 -0
  129. ng_bot_api/types/available_types_21.py +101 -0
  130. ng_bot_api/types/available_types_22.py +121 -0
  131. ng_bot_api/types/available_types_23.py +128 -0
  132. ng_bot_api/types/available_types_24.py +107 -0
  133. ng_bot_api/types/available_types_25.py +100 -0
  134. ng_bot_api/types/available_types_26.py +81 -0
  135. ng_bot_api/types/available_types_27.py +114 -0
  136. ng_bot_api/types/available_types_28.py +125 -0
  137. ng_bot_api/types/available_types_29.py +118 -0
  138. ng_bot_api/types/available_types_30.py +113 -0
  139. ng_bot_api/types/available_types_31.py +120 -0
  140. ng_bot_api/types/available_types_32.py +124 -0
  141. ng_bot_api/types/available_types_33.py +125 -0
  142. ng_bot_api/types/available_types_34.py +113 -0
  143. ng_bot_api/types/available_types_35.py +125 -0
  144. ng_bot_api/types/available_types_36.py +119 -0
  145. ng_bot_api/types/available_types_37.py +126 -0
  146. ng_bot_api/types/available_types_38.py +118 -0
  147. ng_bot_api/types/available_types_39.py +121 -0
  148. ng_bot_api/types/available_types_40.py +121 -0
  149. ng_bot_api/types/available_types_41.py +116 -0
  150. ng_bot_api/types/available_types_42.py +112 -0
  151. ng_bot_api/types/available_types_43.py +110 -0
  152. ng_bot_api/types/available_types_44.py +30 -0
  153. ng_bot_api/types/games_01.py +57 -0
  154. ng_bot_api/types/getting_updates_01.py +123 -0
  155. ng_bot_api/types/inline_mode_01.py +124 -0
  156. ng_bot_api/types/inline_mode_02.py +91 -0
  157. ng_bot_api/types/inline_mode_03.py +116 -0
  158. ng_bot_api/types/inline_mode_04.py +126 -0
  159. ng_bot_api/types/inline_mode_05.py +124 -0
  160. ng_bot_api/types/inline_mode_06.py +124 -0
  161. ng_bot_api/types/inline_mode_07.py +119 -0
  162. ng_bot_api/types/inline_mode_08.py +104 -0
  163. ng_bot_api/types/inline_mode_09.py +84 -0
  164. ng_bot_api/types/payments_01.py +124 -0
  165. ng_bot_api/types/payments_02.py +124 -0
  166. ng_bot_api/types/payments_03.py +119 -0
  167. ng_bot_api/types/payments_04.py +70 -0
  168. ng_bot_api/types/rich_messages_01.py +126 -0
  169. ng_bot_api/types/rich_messages_02.py +125 -0
  170. ng_bot_api/types/rich_messages_03.py +115 -0
  171. ng_bot_api/types/rich_messages_04.py +116 -0
  172. ng_bot_api/types/rich_messages_05.py +128 -0
  173. ng_bot_api/types/rich_messages_06.py +125 -0
  174. ng_bot_api/types/rich_messages_07.py +114 -0
  175. ng_bot_api/types/rich_messages_08.py +118 -0
  176. ng_bot_api/types/rich_messages_09.py +124 -0
  177. ng_bot_api/types/rich_messages_10.py +125 -0
  178. ng_bot_api/types/rich_messages_11.py +122 -0
  179. ng_bot_api/types/rich_messages_12.py +122 -0
  180. ng_bot_api/types/stickers_01.py +107 -0
  181. ng_bot_api/types/telegram_passport_01.py +120 -0
  182. ng_bot_api/types/telegram_passport_02.py +113 -0
  183. ng_bot_api/types/telegram_passport_03.py +24 -0
  184. ng_bot_api/types/unions_01.py +140 -0
  185. ng_bot_api/types/unions_02.py +132 -0
  186. ng_bot_api/types/unions_03.py +134 -0
  187. ng_bot_api/types/unions_04.py +149 -0
  188. ng_bot_api/types/unions_05.py +96 -0
  189. ng_bot_api/webhook.py +78 -0
  190. ng_bot_api-0.1.0.dist-info/METADATA +179 -0
  191. ng_bot_api-0.1.0.dist-info/RECORD +193 -0
  192. ng_bot_api-0.1.0.dist-info/WHEEL +4 -0
  193. ng_bot_api-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from functools import lru_cache
5
+ from typing import Any, Tuple
6
+
7
+ tokenPattern = re.compile(r'list\[|\]|\||[A-Za-z_][A-Za-z0-9_]*|"')
8
+ primitiveNames = frozenset({"int", "float", "str", "bool"})
9
+
10
+ Node = Tuple[Any, ...]
11
+
12
+
13
+ class _Reader:
14
+ def __init__(self, text: str) -> None:
15
+ self.tokens = [token for token in tokenPattern.findall(text) if token != '"']
16
+ self.position = 0
17
+
18
+ def peek(self) -> str | None:
19
+ return self.tokens[self.position] if self.position < len(self.tokens) else None
20
+
21
+ def take(self) -> str:
22
+ token = self.tokens[self.position]
23
+ self.position += 1
24
+ return token
25
+
26
+ def union(self) -> Node:
27
+ options = [self.single()]
28
+ while self.peek() == "|":
29
+ self.take()
30
+ options.append(self.single())
31
+ return options[0] if len(options) == 1 else ("union", tuple(options))
32
+
33
+ def single(self) -> Node:
34
+ token = self.take()
35
+ if token == "list[":
36
+ inner = self.union()
37
+ self.take()
38
+ return ("list", inner)
39
+ if token == "None":
40
+ return ("none",)
41
+ if token in primitiveNames:
42
+ return ("prim", token)
43
+ if token in ("InputFile", "file"):
44
+ return ("file",)
45
+ return ("ref", token)
46
+
47
+
48
+ @lru_cache(maxsize=None)
49
+ def parse(text: str) -> Node:
50
+ return _Reader(text).union()
51
+
52
+
53
+ def without_none(node: Node) -> Node:
54
+ if node[0] != "union":
55
+ return node
56
+ options = tuple(option for option in node[1] if option[0] != "none")
57
+ return options[0] if len(options) == 1 else ("union", options)
@@ -0,0 +1,17 @@
1
+ from .dispatcher import Dispatcher, update_type_of
2
+ from .filter_base import Filter
3
+ from .filters import CallbackData, ChatType, Command, CommandObject, Regexp, Text
4
+ from .router import Router
5
+
6
+ __all__ = [
7
+ "CallbackData",
8
+ "ChatType",
9
+ "Command",
10
+ "CommandObject",
11
+ "Dispatcher",
12
+ "Filter",
13
+ "Regexp",
14
+ "Router",
15
+ "Text",
16
+ "update_type_of",
17
+ ]
@@ -0,0 +1,95 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import logging
5
+ from dataclasses import fields
6
+ from typing import Any, Sequence
7
+
8
+ from ..async_bot import AsyncBot
9
+ from ..types import Update
10
+ from .router import Router
11
+
12
+ logger = logging.getLogger("ng_bot_api.dispatcher")
13
+
14
+
15
+ def update_type_of(update: Update) -> tuple[str, Any] | None:
16
+ """Return ``(update_type, event)`` for the single non-empty field of an ``Update``."""
17
+ for item in fields(update):
18
+ if item.name == "update_id":
19
+ continue
20
+ value = getattr(update, item.name)
21
+ if value is not None:
22
+ return item.name, value
23
+ return None
24
+
25
+
26
+ class Dispatcher(Router):
27
+ """Root router that receives updates from long polling or a webhook.
28
+
29
+ Handlers get the event as the first argument and may declare ``bot``, ``update``,
30
+ ``event_type`` and any filter-injected names (``command``, ``match``, ``callback_args``).
31
+ """
32
+
33
+ def __init__(self, **context: Any) -> None:
34
+ super().__init__("dispatcher")
35
+ self.context = context
36
+ self._bot_usernames: dict[str, str | None] = {}
37
+
38
+ async def _bot_username(self, bot: AsyncBot) -> str | None:
39
+ if bot.token not in self._bot_usernames:
40
+ try:
41
+ me = await bot.get_me()
42
+ self._bot_usernames[bot.token] = getattr(me, "username", None)
43
+ except Exception:
44
+ logger.exception("getMe failed")
45
+ return None
46
+ return self._bot_usernames[bot.token]
47
+
48
+ async def feed_update(self, bot: AsyncBot, update: Update) -> bool:
49
+ """Process a single update; returns ``True`` if a handler accepted it."""
50
+ found = update_type_of(update)
51
+ if found is None:
52
+ return False
53
+ update_type, event = found
54
+ context = dict(self.context, bot=bot, update=update, event_type=update_type)
55
+ context["bot_username"] = await self._bot_username(bot)
56
+ return await self.propagate(update_type, event, context)
57
+
58
+ async def _safe_feed(self, bot: AsyncBot, update: Update) -> None:
59
+ try:
60
+ await self.feed_update(bot, update)
61
+ except Exception:
62
+ logger.exception("Update %s handler failed", update.update_id)
63
+
64
+ async def start_polling(
65
+ self,
66
+ bot: AsyncBot,
67
+ *,
68
+ timeout: int = 30,
69
+ allowed_updates: Sequence[str] | None = None,
70
+ drop_pending_updates: bool = False,
71
+ ) -> None:
72
+ """Delete any webhook and process updates with long polling until cancelled."""
73
+ await bot.delete_webhook(drop_pending_updates=drop_pending_updates)
74
+ async for update in bot.iter_updates(timeout=timeout, allowed_updates=allowed_updates):
75
+ await self._safe_feed(bot, update)
76
+
77
+ def run_polling(self, bot: AsyncBot, **kwargs: Any) -> None:
78
+ """Blocking helper: ``asyncio.run(start_polling(...))`` that closes the bot on exit."""
79
+
80
+ async def runner() -> None:
81
+ async with bot:
82
+ await self.start_polling(bot, **kwargs)
83
+
84
+ try:
85
+ asyncio.run(runner())
86
+ except KeyboardInterrupt:
87
+ pass
88
+
89
+ def webhook_callback(self, bot: AsyncBot) -> Any:
90
+ """Return an ``on_update`` callback for ``WebhookHandler``."""
91
+
92
+ async def on_update(update: Update) -> None:
93
+ await self._safe_feed(bot, update)
94
+
95
+ return on_update
@@ -0,0 +1,78 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from typing import Any, Callable
5
+
6
+
7
+ class Filter:
8
+ """Base class for handler filters.
9
+
10
+ ``check`` returns ``False`` to skip the handler, ``True`` to accept, or a ``dict`` to accept
11
+ and inject extra keyword arguments into the handler. Filters combine with ``&``, ``|`` and ``~``.
12
+ """
13
+
14
+ async def check(self, event: Any, context: dict[str, Any]) -> bool | dict[str, Any]:
15
+ raise NotImplementedError
16
+
17
+ def __and__(self, other: Any) -> Filter:
18
+ return AllOf(self, as_filter(other))
19
+
20
+ def __or__(self, other: Any) -> Filter:
21
+ return AnyOf(self, as_filter(other))
22
+
23
+ def __invert__(self) -> Filter:
24
+ return Not(self)
25
+
26
+
27
+ class CallableFilter(Filter):
28
+ def __init__(self, function: Callable[..., Any]) -> None:
29
+ self.function = function
30
+
31
+ async def check(self, event: Any, context: dict[str, Any]) -> bool | dict[str, Any]:
32
+ result = self.function(event)
33
+ if inspect.isawaitable(result):
34
+ result = await result
35
+ return result if isinstance(result, dict) else bool(result)
36
+
37
+
38
+ class AllOf(Filter):
39
+ def __init__(self, *filters: Filter) -> None:
40
+ self.filters = filters
41
+
42
+ async def check(self, event: Any, context: dict[str, Any]) -> bool | dict[str, Any]:
43
+ injected: dict[str, Any] = {}
44
+ for item in self.filters:
45
+ result = await item.check(event, context)
46
+ if not result:
47
+ return False
48
+ if isinstance(result, dict):
49
+ injected.update(result)
50
+ return injected or True
51
+
52
+
53
+ class AnyOf(Filter):
54
+ def __init__(self, *filters: Filter) -> None:
55
+ self.filters = filters
56
+
57
+ async def check(self, event: Any, context: dict[str, Any]) -> bool | dict[str, Any]:
58
+ for item in self.filters:
59
+ result = await item.check(event, context)
60
+ if result:
61
+ return result
62
+ return False
63
+
64
+
65
+ class Not(Filter):
66
+ def __init__(self, inner: Filter) -> None:
67
+ self.inner = inner
68
+
69
+ async def check(self, event: Any, context: dict[str, Any]) -> bool | dict[str, Any]:
70
+ return not await self.inner.check(event, context)
71
+
72
+
73
+ def as_filter(value: Any) -> Filter:
74
+ if isinstance(value, Filter):
75
+ return value
76
+ if callable(value):
77
+ return CallableFilter(value)
78
+ raise TypeError("Filter must be a Filter instance or a callable")
@@ -0,0 +1,124 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from typing import Any, Iterable
6
+
7
+ from .filter_base import Filter
8
+
9
+
10
+ def _text_of(event: Any) -> str | None:
11
+ for name in ("text", "caption", "data", "query"):
12
+ value = getattr(event, name, None)
13
+ if isinstance(value, str):
14
+ return value
15
+ return None
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class CommandObject:
20
+ """A parsed bot command: ``/start@my_bot payload`` -> command ``start``, args ``payload``."""
21
+
22
+ prefix: str
23
+ command: str
24
+ mention: str | None
25
+ args: str | None
26
+
27
+
28
+ class Command(Filter):
29
+ """Matches messages starting with one of the given commands, injects ``command: CommandObject``."""
30
+
31
+ def __init__(self, *commands: str, prefixes: str = "/", ignore_case: bool = True) -> None:
32
+ self.commands = {command.lower() if ignore_case else command for command in commands}
33
+ self.prefixes = prefixes
34
+ self.ignore_case = ignore_case
35
+
36
+ async def check(self, event: Any, context: dict[str, Any]) -> bool | dict[str, Any]:
37
+ text = getattr(event, "text", None)
38
+ if not text or text[0] not in self.prefixes:
39
+ return False
40
+ head, _, args = text.partition(" ")
41
+ name, _, mention = head[1:].partition("@")
42
+ username = context.get("bot_username")
43
+ if mention and username and mention.lower() != username.lower():
44
+ return False
45
+ if (name.lower() if self.ignore_case else name) not in self.commands:
46
+ return False
47
+ return {"command": CommandObject(head[0], name, mention or None, args.strip() or None)}
48
+
49
+
50
+ class Text(Filter):
51
+ """Matches by the text (message text/caption, callback data or inline query)."""
52
+
53
+ def __init__(
54
+ self,
55
+ equals: str | Iterable[str] | None = None,
56
+ contains: str | None = None,
57
+ startswith: str | None = None,
58
+ ignore_case: bool = False,
59
+ ) -> None:
60
+ self.equals = {equals} if isinstance(equals, str) else set(equals) if equals is not None else None
61
+ self.contains = contains
62
+ self.startswith = startswith
63
+ self.ignore_case = ignore_case
64
+
65
+ def _norm(self, value: str) -> str:
66
+ return value.lower() if self.ignore_case else value
67
+
68
+ async def check(self, event: Any, context: dict[str, Any]) -> bool | dict[str, Any]:
69
+ text = _text_of(event)
70
+ if text is None:
71
+ return False
72
+ value = self._norm(text)
73
+ if self.equals is not None and value not in {self._norm(item) for item in self.equals}:
74
+ return False
75
+ if self.contains is not None and self._norm(self.contains) not in value:
76
+ return False
77
+ return self.startswith is None or value.startswith(self._norm(self.startswith))
78
+
79
+
80
+ class Regexp(Filter):
81
+ """Matches the text against a regular expression, injects ``match``."""
82
+
83
+ def __init__(self, pattern: str | re.Pattern[str]) -> None:
84
+ self.pattern = re.compile(pattern) if isinstance(pattern, str) else pattern
85
+
86
+ async def check(self, event: Any, context: dict[str, Any]) -> bool | dict[str, Any]:
87
+ text = _text_of(event)
88
+ match = self.pattern.search(text) if text is not None else None
89
+ return {"match": match} if match else False
90
+
91
+
92
+ class CallbackData(Filter):
93
+ """Matches callback queries whose data equals ``prefix`` or starts with ``prefix + separator``.
94
+
95
+ Injects ``callback_args``: the remaining parts split by ``separator``.
96
+ """
97
+
98
+ def __init__(self, prefix: str, separator: str = ":") -> None:
99
+ self.prefix = prefix
100
+ self.separator = separator
101
+
102
+ async def check(self, event: Any, context: dict[str, Any]) -> bool | dict[str, Any]:
103
+ data = getattr(event, "data", None)
104
+ if not isinstance(data, str):
105
+ return False
106
+ if data == self.prefix:
107
+ return {"callback_args": []}
108
+ if data.startswith(self.prefix + self.separator):
109
+ return {"callback_args": data[len(self.prefix) + len(self.separator):].split(self.separator)}
110
+ return False
111
+
112
+
113
+ class ChatType(Filter):
114
+ """Matches events in chats of the given types (``private``, ``group``, ``supergroup``, ``channel``)."""
115
+
116
+ def __init__(self, *chat_types: str) -> None:
117
+ self.chat_types = set(chat_types)
118
+
119
+ async def check(self, event: Any, context: dict[str, Any]) -> bool | dict[str, Any]:
120
+ chat = getattr(event, "chat", None)
121
+ if chat is None:
122
+ message = getattr(event, "message", None)
123
+ chat = getattr(message, "chat", None)
124
+ return chat is not None and chat.type in self.chat_types
@@ -0,0 +1,34 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from typing import Any, Callable
5
+
6
+ from .filter_base import Filter, as_filter
7
+
8
+
9
+ class Handler:
10
+ """A callback with its filters. Keyword arguments are injected by parameter name."""
11
+
12
+ def __init__(self, callback: Callable[..., Any], filters: tuple[Any, ...]) -> None:
13
+ self.callback = callback
14
+ self.filters: list[Filter] = [as_filter(item) for item in filters]
15
+ parameters = inspect.signature(callback).parameters.values()
16
+ self.accepts_any = any(item.kind is inspect.Parameter.VAR_KEYWORD for item in parameters)
17
+ self.names = {item.name for item in parameters}
18
+
19
+ async def match(self, event: Any, context: dict[str, Any]) -> dict[str, Any] | None:
20
+ injected: dict[str, Any] = {}
21
+ for item in self.filters:
22
+ result = await item.check(event, context)
23
+ if not result:
24
+ return None
25
+ if isinstance(result, dict):
26
+ injected.update(result)
27
+ return injected
28
+
29
+ async def call(self, event: Any, context: dict[str, Any]) -> Any:
30
+ arguments = context if self.accepts_any else {k: v for k, v in context.items() if k in self.names}
31
+ result = self.callback(event, **arguments)
32
+ if inspect.isawaitable(result):
33
+ result = await result
34
+ return result
@@ -0,0 +1,69 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Callable, TypeVar
4
+
5
+ from .handler import Handler
6
+
7
+ CallbackType = TypeVar("CallbackType", bound=Callable[..., Any])
8
+
9
+
10
+ def _observer(update_type: str) -> Callable[..., Callable[[CallbackType], CallbackType]]:
11
+ def register(self: Router, *filters: Any) -> Callable[[CallbackType], CallbackType]:
12
+ return self.on(update_type, *filters)
13
+
14
+ register.__name__ = update_type
15
+ register.__doc__ = "Register a handler for ``" + update_type + "`` updates."
16
+ return register
17
+
18
+
19
+ class Router:
20
+ """A group of handlers. The first matching handler processes an update."""
21
+
22
+ def __init__(self, name: str | None = None) -> None:
23
+ self.name = name
24
+ self.handlers: dict[str, list[Handler]] = {}
25
+ self.children: list[Router] = []
26
+
27
+ def on(self, update_type: str, *filters: Any) -> Callable[[CallbackType], CallbackType]:
28
+ """Register a handler for any update type, e.g. ``router.on("purchased_paid_media")``."""
29
+
30
+ def decorator(callback: CallbackType) -> CallbackType:
31
+ self.register(update_type, callback, *filters)
32
+ return callback
33
+
34
+ return decorator
35
+
36
+ def register(self, update_type: str, callback: Callable[..., Any], *filters: Any) -> None:
37
+ self.handlers.setdefault(update_type, []).append(Handler(callback, filters))
38
+
39
+ def include_router(self, router: Router) -> Router:
40
+ self.children.append(router)
41
+ return router
42
+
43
+ async def propagate(self, update_type: str, event: Any, context: dict[str, Any]) -> bool:
44
+ for handler in self.handlers.get(update_type, []):
45
+ injected = await handler.match(event, context)
46
+ if injected is not None:
47
+ await handler.call(event, {**context, **injected})
48
+ return True
49
+ for child in self.children:
50
+ if await child.propagate(update_type, event, context):
51
+ return True
52
+ return False
53
+
54
+ message = _observer("message")
55
+ edited_message = _observer("edited_message")
56
+ channel_post = _observer("channel_post")
57
+ edited_channel_post = _observer("edited_channel_post")
58
+ business_message = _observer("business_message")
59
+ callback_query = _observer("callback_query")
60
+ inline_query = _observer("inline_query")
61
+ chosen_inline_result = _observer("chosen_inline_result")
62
+ shipping_query = _observer("shipping_query")
63
+ pre_checkout_query = _observer("pre_checkout_query")
64
+ poll = _observer("poll")
65
+ poll_answer = _observer("poll_answer")
66
+ my_chat_member = _observer("my_chat_member")
67
+ chat_member = _observer("chat_member")
68
+ chat_join_request = _observer("chat_join_request")
69
+ message_reaction = _observer("message_reaction")
@@ -0,0 +1,115 @@
1
+ from __future__ import annotations
2
+
3
+ from .sync_01 import SyncMethods01
4
+ from .sync_02 import SyncMethods02
5
+ from .sync_03 import SyncMethods03
6
+ from .sync_04 import SyncMethods04
7
+ from .sync_05 import SyncMethods05
8
+ from .sync_06 import SyncMethods06
9
+ from .sync_07 import SyncMethods07
10
+ from .sync_08 import SyncMethods08
11
+ from .sync_09 import SyncMethods09
12
+ from .sync_10 import SyncMethods10
13
+ from .sync_11 import SyncMethods11
14
+ from .sync_12 import SyncMethods12
15
+ from .sync_13 import SyncMethods13
16
+ from .sync_14 import SyncMethods14
17
+ from .sync_15 import SyncMethods15
18
+ from .sync_16 import SyncMethods16
19
+ from .sync_17 import SyncMethods17
20
+ from .sync_18 import SyncMethods18
21
+ from .sync_19 import SyncMethods19
22
+ from .sync_20 import SyncMethods20
23
+ from .sync_21 import SyncMethods21
24
+ from .sync_22 import SyncMethods22
25
+ from .sync_23 import SyncMethods23
26
+ from .sync_24 import SyncMethods24
27
+ from .sync_25 import SyncMethods25
28
+ from .sync_26 import SyncMethods26
29
+ from .sync_27 import SyncMethods27
30
+ from .sync_28 import SyncMethods28
31
+ from .sync_29 import SyncMethods29
32
+ from .sync_30 import SyncMethods30
33
+ from .sync_31 import SyncMethods31
34
+ from .sync_32 import SyncMethods32
35
+ from .sync_33 import SyncMethods33
36
+ from .sync_34 import SyncMethods34
37
+ from .sync_35 import SyncMethods35
38
+ from .sync_36 import SyncMethods36
39
+ from .sync_37 import SyncMethods37
40
+ from .sync_38 import SyncMethods38
41
+ from .sync_39 import SyncMethods39
42
+ from .sync_40 import SyncMethods40
43
+ from .sync_41 import SyncMethods41
44
+ from .sync_42 import SyncMethods42
45
+ from .async_01 import AsyncMethods01
46
+ from .async_02 import AsyncMethods02
47
+ from .async_03 import AsyncMethods03
48
+ from .async_04 import AsyncMethods04
49
+ from .async_05 import AsyncMethods05
50
+ from .async_06 import AsyncMethods06
51
+ from .async_07 import AsyncMethods07
52
+ from .async_08 import AsyncMethods08
53
+ from .async_09 import AsyncMethods09
54
+ from .async_10 import AsyncMethods10
55
+ from .async_11 import AsyncMethods11
56
+ from .async_12 import AsyncMethods12
57
+ from .async_13 import AsyncMethods13
58
+ from .async_14 import AsyncMethods14
59
+ from .async_15 import AsyncMethods15
60
+ from .async_16 import AsyncMethods16
61
+ from .async_17 import AsyncMethods17
62
+ from .async_18 import AsyncMethods18
63
+ from .async_19 import AsyncMethods19
64
+ from .async_20 import AsyncMethods20
65
+ from .async_21 import AsyncMethods21
66
+ from .async_22 import AsyncMethods22
67
+ from .async_23 import AsyncMethods23
68
+ from .async_24 import AsyncMethods24
69
+ from .async_25 import AsyncMethods25
70
+ from .async_26 import AsyncMethods26
71
+ from .async_27 import AsyncMethods27
72
+ from .async_28 import AsyncMethods28
73
+ from .async_29 import AsyncMethods29
74
+ from .async_30 import AsyncMethods30
75
+ from .async_31 import AsyncMethods31
76
+ from .async_32 import AsyncMethods32
77
+ from .async_33 import AsyncMethods33
78
+ from .async_34 import AsyncMethods34
79
+ from .async_35 import AsyncMethods35
80
+ from .async_36 import AsyncMethods36
81
+ from .async_37 import AsyncMethods37
82
+ from .async_38 import AsyncMethods38
83
+ from .async_39 import AsyncMethods39
84
+ from .async_40 import AsyncMethods40
85
+ from .async_41 import AsyncMethods41
86
+ from .async_42 import AsyncMethods42
87
+
88
+
89
+ class SyncMethods(
90
+ SyncMethods01, SyncMethods02, SyncMethods03, SyncMethods04, SyncMethods05, SyncMethods06,
91
+ SyncMethods07, SyncMethods08, SyncMethods09, SyncMethods10, SyncMethods11, SyncMethods12,
92
+ SyncMethods13, SyncMethods14, SyncMethods15, SyncMethods16, SyncMethods17, SyncMethods18,
93
+ SyncMethods19, SyncMethods20, SyncMethods21, SyncMethods22, SyncMethods23, SyncMethods24,
94
+ SyncMethods25, SyncMethods26, SyncMethods27, SyncMethods28, SyncMethods29, SyncMethods30,
95
+ SyncMethods31, SyncMethods32, SyncMethods33, SyncMethods34, SyncMethods35, SyncMethods36,
96
+ SyncMethods37, SyncMethods38, SyncMethods39, SyncMethods40, SyncMethods41, SyncMethods42,
97
+ ):
98
+ __slots__ = ()
99
+
100
+
101
+ class AsyncMethods(
102
+ AsyncMethods01, AsyncMethods02, AsyncMethods03, AsyncMethods04, AsyncMethods05,
103
+ AsyncMethods06, AsyncMethods07, AsyncMethods08, AsyncMethods09, AsyncMethods10,
104
+ AsyncMethods11, AsyncMethods12, AsyncMethods13, AsyncMethods14, AsyncMethods15,
105
+ AsyncMethods16, AsyncMethods17, AsyncMethods18, AsyncMethods19, AsyncMethods20,
106
+ AsyncMethods21, AsyncMethods22, AsyncMethods23, AsyncMethods24, AsyncMethods25,
107
+ AsyncMethods26, AsyncMethods27, AsyncMethods28, AsyncMethods29, AsyncMethods30,
108
+ AsyncMethods31, AsyncMethods32, AsyncMethods33, AsyncMethods34, AsyncMethods35,
109
+ AsyncMethods36, AsyncMethods37, AsyncMethods38, AsyncMethods39, AsyncMethods40,
110
+ AsyncMethods41, AsyncMethods42,
111
+ ):
112
+ __slots__ = ()
113
+
114
+
115
+ __all__ = ["AsyncMethods", "SyncMethods"]