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
ng_bot_api/__init__.py ADDED
@@ -0,0 +1,56 @@
1
+ """Official Python client for the NetGram Bot API (a 1:1 Telegram Bot API implementation)."""
2
+
3
+ from . import types
4
+ from .api_version import api_release_date, api_version
5
+ from .async_bot import AsyncBot
6
+ from .core import (
7
+ BadRequestError,
8
+ BotApiError,
9
+ BotObject,
10
+ ConflictError,
11
+ ForbiddenError,
12
+ InputFile,
13
+ NetworkError,
14
+ NgBotApiError,
15
+ NotFoundError,
16
+ ServerError,
17
+ TooManyRequestsError,
18
+ UnauthorizedError,
19
+ defaultApiUrl,
20
+ )
21
+ from .dispatcher import CallbackData, ChatType, Command, CommandObject, Dispatcher, Filter, Regexp, Router, Text
22
+ from .sync_bot import Bot
23
+ from .webhook import WebhookHandler
24
+
25
+ __version__ = "0.1.0"
26
+
27
+ __all__ = [
28
+ "AsyncBot",
29
+ "BadRequestError",
30
+ "Bot",
31
+ "BotApiError",
32
+ "BotObject",
33
+ "CallbackData",
34
+ "ChatType",
35
+ "Command",
36
+ "CommandObject",
37
+ "ConflictError",
38
+ "Dispatcher",
39
+ "Filter",
40
+ "ForbiddenError",
41
+ "InputFile",
42
+ "NetworkError",
43
+ "NgBotApiError",
44
+ "NotFoundError",
45
+ "Regexp",
46
+ "Router",
47
+ "ServerError",
48
+ "Text",
49
+ "TooManyRequestsError",
50
+ "UnauthorizedError",
51
+ "WebhookHandler",
52
+ "api_release_date",
53
+ "api_version",
54
+ "defaultApiUrl",
55
+ "types",
56
+ ]
@@ -0,0 +1,2 @@
1
+ api_version = '10.5'
2
+ api_release_date = 'November 22, 2026'
@@ -0,0 +1,97 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import os
5
+ import pathlib
6
+ from typing import Any, AsyncIterator, Sequence
7
+
8
+ import httpx
9
+
10
+ from .core.errors import NetworkError
11
+ from .core.polling import PollingState
12
+ from .core.request import defaultApiUrl, file_url, method_url, parse_response, prepare
13
+ from .methods import AsyncMethods
14
+ from .types import File, Update
15
+
16
+
17
+ class AsyncBot(AsyncMethods):
18
+ """Asynchronous (asyncio) Bot API client.
19
+
20
+ Use as ``async with AsyncBot(token) as bot: ...``. The default server is
21
+ ``https://api.netgram.su``; pass ``api_url`` to use another Bot API compatible server.
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ token: str,
27
+ *,
28
+ api_url: str = defaultApiUrl,
29
+ timeout: float = 30.0,
30
+ client: httpx.AsyncClient | None = None,
31
+ ) -> None:
32
+ self.token = token
33
+ self.api_url = api_url
34
+ self.timeout = timeout
35
+ self._owns_client = client is None
36
+ self._client = client or httpx.AsyncClient(timeout=timeout)
37
+
38
+ async def _call(self, method: str, params: dict[str, Any], returns: str) -> Any:
39
+ prepared = prepare(method, params)
40
+ timeout = self.timeout + prepared.poll_timeout if prepared.poll_timeout else self.timeout
41
+ try:
42
+ url = method_url(self.api_url, self.token, method)
43
+ response = await self._client.post(url, timeout=timeout, **prepared.httpx_arguments())
44
+ payload = response.json()
45
+ except httpx.HTTPError as error:
46
+ raise NetworkError(str(error)) from error
47
+ except ValueError as error:
48
+ raise NetworkError("Invalid JSON in response: " + str(error)) from error
49
+ return parse_response(method, response.status_code, payload, returns)
50
+
51
+ def file_url(self, file: File | str) -> str:
52
+ """Return the download URL of a file obtained with ``get_file``."""
53
+ path = file.file_path if isinstance(file, File) else file
54
+ if not path:
55
+ raise ValueError("The file has no file_path, call get_file first")
56
+ return file_url(self.api_url, self.token, path)
57
+
58
+ async def download_file(self, file: File | str, destination: str | os.PathLike[str] | None = None) -> bytes:
59
+ """Download a file by ``File`` object or ``file_path``; optionally save it to ``destination``."""
60
+ try:
61
+ response = await self._client.get(self.file_url(file), timeout=self.timeout)
62
+ response.raise_for_status()
63
+ except httpx.HTTPError as error:
64
+ raise NetworkError(str(error)) from error
65
+ if destination is not None:
66
+ pathlib.Path(destination).write_bytes(response.content)
67
+ return response.content
68
+
69
+ async def iter_updates(
70
+ self,
71
+ *,
72
+ timeout: int = 30,
73
+ limit: int | None = None,
74
+ allowed_updates: Sequence[str] | None = None,
75
+ offset: int | None = None,
76
+ ) -> AsyncIterator[Update]:
77
+ """Yield incoming updates forever using long polling (``getUpdates``)."""
78
+ state = PollingState(timeout=timeout, limit=limit, allowed_updates=allowed_updates, offset=offset)
79
+ while True:
80
+ try:
81
+ updates = state.accept(await self.get_updates(**state.request()))
82
+ except Exception as error:
83
+ await asyncio.sleep(state.delay_after(error))
84
+ continue
85
+ for update in updates:
86
+ yield update
87
+
88
+ async def shutdown(self) -> None:
89
+ """Close the underlying HTTP client (does not call the ``close`` Bot API method)."""
90
+ if self._owns_client:
91
+ await self._client.aclose()
92
+
93
+ async def __aenter__(self) -> AsyncBot:
94
+ return self
95
+
96
+ async def __aexit__(self, *exc_info: object) -> None:
97
+ await self.shutdown()
@@ -0,0 +1,31 @@
1
+ from .base import BotObject
2
+ from .errors import (
3
+ BadRequestError,
4
+ BotApiError,
5
+ ConflictError,
6
+ ForbiddenError,
7
+ NetworkError,
8
+ NgBotApiError,
9
+ NotFoundError,
10
+ ServerError,
11
+ TooManyRequestsError,
12
+ UnauthorizedError,
13
+ )
14
+ from .input_file import InputFile
15
+ from .request import defaultApiUrl
16
+
17
+ __all__ = [
18
+ "BadRequestError",
19
+ "BotApiError",
20
+ "BotObject",
21
+ "ConflictError",
22
+ "ForbiddenError",
23
+ "InputFile",
24
+ "NetworkError",
25
+ "NgBotApiError",
26
+ "NotFoundError",
27
+ "ServerError",
28
+ "TooManyRequestsError",
29
+ "UnauthorizedError",
30
+ "defaultApiUrl",
31
+ ]
@@ -0,0 +1,36 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import Any, TypeVar
5
+
6
+ from . import registry
7
+
8
+ ObjectType = TypeVar("ObjectType", bound="BotObject")
9
+
10
+
11
+ class BotObject:
12
+ """Base class of all Bot API objects."""
13
+
14
+ __slots__ = ()
15
+
16
+ def __init_subclass__(cls, **kwargs: Any) -> None:
17
+ super().__init_subclass__(**kwargs)
18
+ if cls.__module__.startswith("ng_bot_api.types."):
19
+ registry.register_object(cls)
20
+
21
+ @classmethod
22
+ def from_dict(cls: type[ObjectType], data: dict[str, Any]) -> ObjectType:
23
+ """Build the object from a decoded JSON dictionary (wire field names)."""
24
+ from .decoding import decode_object
25
+
26
+ return decode_object(cls, data)
27
+
28
+ def to_dict(self) -> dict[str, Any]:
29
+ """Convert the object to a JSON-compatible dictionary with wire field names."""
30
+ from .encoding import encode_value
31
+
32
+ return encode_value(self, None)
33
+
34
+ def to_json(self) -> str:
35
+ """Serialize the object to a JSON string."""
36
+ return json.dumps(self.to_dict(), ensure_ascii=False)
@@ -0,0 +1,17 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+
6
+ class SyncCaller:
7
+ __slots__ = ()
8
+
9
+ def _call(self, method: str, params: dict[str, Any], returns: str) -> Any:
10
+ raise NotImplementedError
11
+
12
+
13
+ class AsyncCaller:
14
+ __slots__ = ()
15
+
16
+ async def _call(self, method: str, params: dict[str, Any], returns: str) -> Any:
17
+ raise NotImplementedError
@@ -0,0 +1,85 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from . import registry
6
+ from .typespec import Node, parse, without_none
7
+
8
+
9
+ def decode(spec: str, value: Any) -> Any:
10
+ return decode_node(without_none(parse(spec)), value)
11
+
12
+
13
+ def decode_node(node: Node, value: Any) -> Any:
14
+ if value is None:
15
+ return None
16
+ kind = node[0]
17
+ if kind == "prim":
18
+ return float(value) if node[1] == "float" and isinstance(value, int) and not isinstance(value, bool) else value
19
+ if kind == "list":
20
+ return [decode_node(node[1], item) for item in value] if isinstance(value, list) else value
21
+ if kind == "ref":
22
+ return decode_named(node[1], value)
23
+ if kind == "union":
24
+ return _decode_union_node(node[1], value)
25
+ return value
26
+
27
+
28
+ def decode_named(name: str, value: Any) -> Any:
29
+ if name in registry.objects:
30
+ return decode_object(registry.objects[name], value)
31
+ if name in registry.unions:
32
+ return decode_union(registry.unions[name], value)
33
+ return value
34
+
35
+
36
+ def decode_object(cls: type, value: Any) -> Any:
37
+ if not isinstance(value, dict):
38
+ return value
39
+ arguments = {}
40
+ for info in registry.field_infos(cls):
41
+ if info.wire in value:
42
+ arguments[info.name] = decode(info.spec, value[info.wire])
43
+ elif info.required:
44
+ arguments[info.name] = None
45
+ return cls(**arguments)
46
+
47
+
48
+ def decode_union(info: registry.UnionInfo, value: Any) -> Any:
49
+ if not isinstance(value, dict):
50
+ for extra in info.extras:
51
+ node = parse(extra)
52
+ if (node[0] == "list") == isinstance(value, list):
53
+ return decode_node(node, value)
54
+ return value
55
+ target: Any = None
56
+ if info.field is not None and info.field in value:
57
+ target = info.mapping.get(value[info.field])
58
+ if target is None and info.field is not None and info.default is not None:
59
+ target = info.default
60
+ if isinstance(target, tuple):
61
+ cls = registry.best_match(target, value)
62
+ elif target is not None:
63
+ cls = registry.objects.get(target)
64
+ else:
65
+ cls = registry.best_match(info.members, value)
66
+ return decode_object(cls, value) if cls is not None else value
67
+
68
+
69
+ def _decode_union_node(options: tuple[Node, ...], value: Any) -> Any:
70
+ if isinstance(value, bool):
71
+ return value
72
+ if isinstance(value, list):
73
+ lists = [option for option in options if option[0] == "list"]
74
+ return decode_node(lists[0], value) if lists else value
75
+ if isinstance(value, dict):
76
+ named = [option[1] for option in options if option[0] == "ref"]
77
+ if len(named) == 1:
78
+ return decode_named(named[0], value)
79
+ object_names = [name for name in named if name in registry.objects]
80
+ for name in named:
81
+ if name in registry.unions:
82
+ object_names.extend(registry.unions[name].members)
83
+ cls = registry.best_match(object_names, value)
84
+ return decode_object(cls, value) if cls is not None else value
85
+ return value
@@ -0,0 +1,42 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from . import registry
6
+ from .input_file import InputFile
7
+
8
+
9
+ class FileCollector:
10
+ """Collects files found inside request parameters for a multipart upload."""
11
+
12
+ def __init__(self) -> None:
13
+ self.parts: dict[str, InputFile] = {}
14
+
15
+ def attach(self, file: InputFile) -> str:
16
+ name = "file" + str(len(self.parts))
17
+ self.parts[name] = file
18
+ return "attach://" + name
19
+
20
+ def add(self, name: str, file: InputFile) -> None:
21
+ self.parts[name] = file
22
+
23
+
24
+ def encode_value(value: Any, files: FileCollector | None) -> Any:
25
+ from .base import BotObject
26
+
27
+ if isinstance(value, BotObject):
28
+ result = {}
29
+ for info in registry.field_infos(type(value)):
30
+ item = getattr(value, info.name)
31
+ if item is not None:
32
+ result[info.wire] = encode_value(item, files)
33
+ return result
34
+ if isinstance(value, InputFile):
35
+ if files is None:
36
+ raise TypeError("InputFile can only be sent as a request parameter")
37
+ return files.attach(value)
38
+ if isinstance(value, (list, tuple)):
39
+ return [encode_value(item, files) for item in value]
40
+ if isinstance(value, dict):
41
+ return {key: encode_value(item, files) for key, item in value.items() if item is not None}
42
+ return value
@@ -0,0 +1,75 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+
6
+ class NgBotApiError(Exception):
7
+ """Base class of all errors raised by ng_bot_api."""
8
+
9
+
10
+ class NetworkError(NgBotApiError):
11
+ """The request could not be completed because of a transport problem."""
12
+
13
+
14
+ class BotApiError(NgBotApiError):
15
+ """The Bot API returned ``"ok": false``."""
16
+
17
+ def __init__(self, error_code: int, description: str, parameters: Any = None, method: str | None = None) -> None:
18
+ super().__init__(str(error_code) + ": " + description)
19
+ self.error_code = error_code
20
+ self.description = description
21
+ self.parameters = parameters
22
+ self.method = method
23
+
24
+ @property
25
+ def retry_after(self) -> int | None:
26
+ """Seconds to wait before repeating the request (flood control)."""
27
+ return getattr(self.parameters, "retry_after", None)
28
+
29
+ @property
30
+ def migrate_to_chat_id(self) -> int | None:
31
+ """New identifier of a group that was migrated to a supergroup."""
32
+ return getattr(self.parameters, "migrate_to_chat_id", None)
33
+
34
+
35
+ class BadRequestError(BotApiError):
36
+ """HTTP 400: the request is malformed or its parameters are invalid."""
37
+
38
+
39
+ class UnauthorizedError(BotApiError):
40
+ """HTTP 401: the bot token is invalid."""
41
+
42
+
43
+ class ForbiddenError(BotApiError):
44
+ """HTTP 403: the bot has no rights for the action (e.g. it was blocked by the user)."""
45
+
46
+
47
+ class NotFoundError(BotApiError):
48
+ """HTTP 404: the method or the object was not found."""
49
+
50
+
51
+ class ConflictError(BotApiError):
52
+ """HTTP 409: another getUpdates request or webhook is active."""
53
+
54
+
55
+ class TooManyRequestsError(BotApiError):
56
+ """HTTP 429: flood control exceeded, see ``retry_after``."""
57
+
58
+
59
+ class ServerError(BotApiError):
60
+ """HTTP 5xx: the server failed to process the request."""
61
+
62
+
63
+ errorClasses: dict[int, type[BotApiError]] = {
64
+ 400: BadRequestError,
65
+ 401: UnauthorizedError,
66
+ 403: ForbiddenError,
67
+ 404: NotFoundError,
68
+ 409: ConflictError,
69
+ 429: TooManyRequestsError,
70
+ }
71
+
72
+
73
+ def error_for(error_code: int, description: str, parameters: Any, method: str | None) -> BotApiError:
74
+ cls = errorClasses.get(error_code) or (ServerError if error_code >= 500 else BotApiError)
75
+ return cls(error_code, description, parameters, method)
@@ -0,0 +1,56 @@
1
+ from __future__ import annotations
2
+
3
+ import mimetypes
4
+ import os
5
+ import pathlib
6
+ from typing import IO, Union
7
+
8
+ FileSource = Union[bytes, bytearray, IO[bytes], str, "os.PathLike[str]"]
9
+
10
+
11
+ class InputFile:
12
+ """A file to be uploaded with multipart/form-data.
13
+
14
+ Pass a filesystem path, raw bytes or a binary file object. To send a file that is already
15
+ stored on the server, pass its ``file_id`` (or an HTTP URL) as a plain ``str`` instead.
16
+ """
17
+
18
+ __slots__ = ("source", "filename", "content_type")
19
+
20
+ def __init__(self, source: FileSource, filename: str | None = None, content_type: str | None = None) -> None:
21
+ self.source = source
22
+ self.filename = filename or self._guess_name(source)
23
+ self.content_type = content_type or mimetypes.guess_type(self.filename)[0] or "application/octet-stream"
24
+
25
+ @classmethod
26
+ def from_path(cls, path: str | os.PathLike[str], filename: str | None = None) -> InputFile:
27
+ """Create an upload from a file on disk."""
28
+ return cls(pathlib.Path(path), filename)
29
+
30
+ @classmethod
31
+ def from_bytes(cls, data: bytes, filename: str, content_type: str | None = None) -> InputFile:
32
+ """Create an upload from in-memory bytes."""
33
+ return cls(data, filename, content_type)
34
+
35
+ @staticmethod
36
+ def _guess_name(source: FileSource) -> str:
37
+ if isinstance(source, (str, os.PathLike)):
38
+ return pathlib.Path(source).name
39
+ name = getattr(source, "name", None)
40
+ if isinstance(name, str):
41
+ return pathlib.Path(name).name
42
+ return "file"
43
+
44
+ def read(self) -> bytes:
45
+ """Return the file content as bytes."""
46
+ if isinstance(self.source, (bytes, bytearray)):
47
+ return bytes(self.source)
48
+ if isinstance(self.source, (str, os.PathLike)):
49
+ return pathlib.Path(self.source).read_bytes()
50
+ return self.source.read()
51
+
52
+ def as_multipart(self) -> tuple[str, bytes, str]:
53
+ return self.filename, self.read(), self.content_type
54
+
55
+ def __repr__(self) -> str:
56
+ return "InputFile(filename=" + repr(self.filename) + ")"
@@ -0,0 +1,39 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any, Sequence
5
+
6
+ from .errors import BotApiError, TooManyRequestsError, UnauthorizedError
7
+
8
+
9
+ @dataclass
10
+ class PollingState:
11
+ """Offset tracking and error backoff for long polling."""
12
+
13
+ timeout: int = 30
14
+ limit: int | None = None
15
+ allowed_updates: Sequence[str] | None = None
16
+ offset: int | None = None
17
+ min_delay: float = 1.0
18
+ max_delay: float = 30.0
19
+ failures: int = field(default=0)
20
+
21
+ def request(self) -> dict[str, Any]:
22
+ allowed = list(self.allowed_updates) if self.allowed_updates is not None else None
23
+ return {"offset": self.offset, "limit": self.limit, "timeout": self.timeout, "allowed_updates": allowed}
24
+
25
+ def accept(self, updates: list[Any]) -> list[Any]:
26
+ self.failures = 0
27
+ if updates:
28
+ self.offset = max(update.update_id for update in updates) + 1
29
+ return updates
30
+
31
+ def delay_after(self, error: Exception) -> float:
32
+ if isinstance(error, UnauthorizedError):
33
+ raise error
34
+ if isinstance(error, TooManyRequestsError) and error.retry_after:
35
+ return float(error.retry_after)
36
+ if isinstance(error, BotApiError) and error.error_code == 400:
37
+ raise error
38
+ self.failures += 1
39
+ return min(self.max_delay, self.min_delay * (2 ** (self.failures - 1)))
@@ -0,0 +1,72 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import MISSING, dataclass, fields
4
+ from typing import Any
5
+
6
+ objects: dict[str, type] = {}
7
+ unions: dict[str, UnionInfo] = {}
8
+ fieldCache: dict[Any, tuple[FieldInfo, ...]] = {}
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class UnionInfo:
13
+ name: str
14
+ members: tuple[str, ...]
15
+ field: str | None
16
+ mapping: dict[Any, Any]
17
+ default: str | None
18
+ extras: tuple[str, ...]
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class FieldInfo:
23
+ name: str
24
+ wire: str
25
+ spec: str
26
+ required: bool
27
+
28
+
29
+ def register_object(cls: type) -> None:
30
+ objects[cls.__name__] = cls
31
+ fieldCache.clear()
32
+
33
+
34
+ def register_union(
35
+ name: str,
36
+ members: tuple[str, ...],
37
+ field: str | None,
38
+ mapping: dict[Any, Any],
39
+ default: str | None,
40
+ extras: tuple[str, ...],
41
+ ) -> None:
42
+ unions[name] = UnionInfo(name, members, field, mapping, default, extras)
43
+
44
+
45
+ def field_infos(cls: Any) -> tuple[FieldInfo, ...]:
46
+ cached = fieldCache.get(cls)
47
+ if cached is not None:
48
+ return cached
49
+ result = []
50
+ for item in fields(cls):
51
+ required = item.default is MISSING and item.default_factory is MISSING
52
+ wire = item.metadata.get("wire", item.name)
53
+ result.append(FieldInfo(item.name, wire, str(item.type), required))
54
+ fieldCache[cls] = tuple(result)
55
+ return fieldCache[cls]
56
+
57
+
58
+ def match_score(cls: type, data: dict[str, Any]) -> int:
59
+ score = 0
60
+ for info in field_infos(cls):
61
+ if info.wire in data:
62
+ score += 2
63
+ elif info.required:
64
+ score -= 3
65
+ return score
66
+
67
+
68
+ def best_match(names: tuple[str, ...] | list[str], data: dict[str, Any]) -> type | None:
69
+ candidates = [objects[name] for name in names if name in objects]
70
+ if not candidates:
71
+ return None
72
+ return max(candidates, key=lambda cls: match_score(cls, data))
@@ -0,0 +1,67 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import dataclass, field
5
+ from typing import Any
6
+
7
+ from .decoding import decode, decode_named
8
+ from .encoding import FileCollector, encode_value
9
+ from .errors import BotApiError, error_for
10
+ from .input_file import InputFile
11
+
12
+ defaultApiUrl = "https://api.netgram.su"
13
+
14
+
15
+ @dataclass
16
+ class PreparedRequest:
17
+ method: str
18
+ json_body: dict[str, Any] | None = None
19
+ form: dict[str, str] = field(default_factory=dict)
20
+ files: dict[str, tuple[str, bytes, str]] = field(default_factory=dict)
21
+ poll_timeout: float | None = None
22
+
23
+ def httpx_arguments(self) -> dict[str, Any]:
24
+ if self.files:
25
+ return {"data": self.form, "files": self.files}
26
+ return {"json": self.json_body or {}}
27
+
28
+
29
+ def _form_value(value: Any) -> str:
30
+ return value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)
31
+
32
+
33
+ def prepare(method: str, params: dict[str, Any]) -> PreparedRequest:
34
+ collector = FileCollector()
35
+ body: dict[str, Any] = {}
36
+ for name, value in params.items():
37
+ if name == "self" or value is None:
38
+ continue
39
+ if isinstance(value, InputFile):
40
+ collector.add(name, value)
41
+ continue
42
+ body[name] = encode_value(value, collector)
43
+ timeout = params.get("timeout") if method == "getUpdates" else None
44
+ prepared = PreparedRequest(method, poll_timeout=float(timeout) if timeout else None)
45
+ if not collector.parts:
46
+ prepared.json_body = body
47
+ return prepared
48
+ prepared.form = {name: _form_value(value) for name, value in body.items()}
49
+ prepared.files = {name: file.as_multipart() for name, file in collector.parts.items()}
50
+ return prepared
51
+
52
+
53
+ def parse_response(method: str, status_code: int, payload: Any, returns: str) -> Any:
54
+ if not isinstance(payload, dict) or "ok" not in payload:
55
+ raise BotApiError(status_code, "Unexpected response from the Bot API server", None, method)
56
+ if payload["ok"]:
57
+ return decode(returns, payload.get("result"))
58
+ parameters = decode_named("ResponseParameters", payload["parameters"]) if payload.get("parameters") else None
59
+ raise error_for(int(payload.get("error_code", status_code)), str(payload.get("description", "")), parameters, method)
60
+
61
+
62
+ def method_url(api_url: str, token: str, method: str) -> str:
63
+ return api_url.rstrip("/") + "/bot" + token + "/" + method
64
+
65
+
66
+ def file_url(api_url: str, token: str, file_path: str) -> str:
67
+ return api_url.rstrip("/") + "/file/bot" + token + "/" + file_path.lstrip("/")