shadivan 0.1.0__tar.gz

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.
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.5
2
+ Name: shadivan
3
+ Version: 0.1.0
4
+ Summary: A professional, modular, and extensible Python library for building bots on the Bale messenger.
5
+ Project-URL: Homepage, https://github.com/shadivan/shadivan
6
+ Project-URL: Repository, https://github.com/shadivan/shadivan
7
+ Project-URL: Issues, https://github.com/shadivan/shadivan/issues
8
+ Project-URL: Documentation, https://github.com/shadivan/shadivan#readme
9
+ Author: Shadivan Team
10
+ License: MIT
11
+ Keywords: api,async,bale,bot,messenger,shadivan
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: httpx<1.0,>=0.27
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
28
+ Requires-Dist: pytest>=8.0; extra == 'dev'
29
+ Requires-Dist: ruff>=0.6; extra == 'dev'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # Shadivan
33
+
34
+ **Bot Development Made Simple.**
35
+
36
+ Shadivan is a simple, modern and extensible Python library for developing bots on the Bale messenger.
37
+
38
+ ## Features
39
+
40
+ - Async HTTP Client
41
+ - Simple Bot Management
42
+ - Message Handling
43
+ - Long Polling
44
+ - Command Handlers
45
+ - Custom Error Handling
46
+
47
+ ## Installation
48
+
49
+ ```bash
50
+ pip install shadivan
51
+ ```
52
+
53
+ ## Quick Start
54
+
55
+ Shadivan is currently under development.
56
+
57
+ The first release is planned as version 0.1.0.
58
+
59
+ ## Requirements
60
+
61
+ - Python 3.10+
62
+ - httpx
63
+
64
+ ## License
65
+
66
+ MIT License
67
+
68
+ ---
69
+
70
+ Made with care by Shadivan Team.
@@ -0,0 +1,39 @@
1
+ # Shadivan
2
+
3
+ **Bot Development Made Simple.**
4
+
5
+ Shadivan is a simple, modern and extensible Python library for developing bots on the Bale messenger.
6
+
7
+ ## Features
8
+
9
+ - Async HTTP Client
10
+ - Simple Bot Management
11
+ - Message Handling
12
+ - Long Polling
13
+ - Command Handlers
14
+ - Custom Error Handling
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pip install shadivan
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ Shadivan is currently under development.
25
+
26
+ The first release is planned as version 0.1.0.
27
+
28
+ ## Requirements
29
+
30
+ - Python 3.10+
31
+ - httpx
32
+
33
+ ## License
34
+
35
+ MIT License
36
+
37
+ ---
38
+
39
+ Made with care by Shadivan Team.
@@ -0,0 +1,36 @@
1
+ import asyncio
2
+ import os
3
+
4
+ from shadivan.bot import Bot
5
+ from shadivan.dispatcher.router import Router
6
+ from shadivan.polling import start_polling
7
+
8
+
9
+ async def main():
10
+ token = os.environ["BALE_BOT_TOKEN"]
11
+
12
+ bot = Bot(token)
13
+ router = Router()
14
+
15
+ @router.message
16
+ async def echo(update):
17
+ message = update.message
18
+
19
+ if message.text:
20
+ await bot.request(
21
+ "sendMessage",
22
+ {
23
+ "chat_id": message.chat.id,
24
+ "text": message.text,
25
+ },
26
+ )
27
+
28
+ try:
29
+ print("Shadivan Echo Bot is running...")
30
+ await start_polling(bot, router)
31
+ finally:
32
+ await bot.close()
33
+
34
+
35
+ if __name__ == "__main__":
36
+ asyncio.run(main())
@@ -0,0 +1,78 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "shadivan"
7
+ version = "0.1.0"
8
+ description = "A professional, modular, and extensible Python library for building bots on the Bale messenger."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [
13
+ { name = "Shadivan Team" },
14
+ ]
15
+ keywords = ["bale", "bot", "messenger", "async", "shadivan", "api"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Framework :: AsyncIO",
27
+ "Topic :: Software Development :: Libraries :: Python Modules",
28
+ "Typing :: Typed",
29
+ ]
30
+ dependencies = [
31
+ "httpx>=0.27,<1.0",
32
+ ]
33
+
34
+ [project.optional-dependencies]
35
+ dev = [
36
+ "pytest>=8.0",
37
+ "pytest-asyncio>=0.23",
38
+ "ruff>=0.6",
39
+ ]
40
+
41
+ [project.urls]
42
+ Homepage = "https://github.com/shadivan/shadivan"
43
+ Repository = "https://github.com/shadivan/shadivan"
44
+ Issues = "https://github.com/shadivan/shadivan/issues"
45
+ Documentation = "https://github.com/shadivan/shadivan#readme"
46
+
47
+ [tool.hatch.build.targets.wheel]
48
+ packages = ["shadivan"]
49
+
50
+ [tool.hatch.build.targets.sdist]
51
+ include = [
52
+ "shadivan",
53
+ "tests",
54
+ "examples",
55
+ "README.md",
56
+ ]
57
+
58
+ [tool.pytest.ini_options]
59
+ minversion = "8.0"
60
+ asyncio_mode = "auto"
61
+ testpaths = ["tests"]
62
+
63
+ [tool.ruff]
64
+ line-length = 100
65
+ target-version = "py310"
66
+
67
+ [tool.ruff.lint]
68
+ select = [
69
+ "E", # pycodestyle errors
70
+ "W", # pycodestyle warnings
71
+ "F", # pyflakes
72
+ "I", # isort
73
+ "B", # flake8-bugbear
74
+ "UP", # pyupgrade
75
+ ]
76
+ ignore = [
77
+ "E501", # line-too-long (handled by line-length)
78
+ ]
@@ -0,0 +1,20 @@
1
+ """Shadivan - Async Python library for Bale Bot API."""
2
+
3
+ from shadivan.bot import Bot
4
+ from shadivan.client.async_client import AsyncClient
5
+ from shadivan.exceptions.errors import (
6
+ APIError,
7
+ NetworkError,
8
+ ShadivanError,
9
+ )
10
+
11
+ __version__ = "0.1.0"
12
+
13
+ __all__ = [
14
+ "Bot",
15
+ "AsyncClient",
16
+ "ShadivanError",
17
+ "NetworkError",
18
+ "APIError",
19
+ "__version__",
20
+ ]
@@ -0,0 +1,52 @@
1
+ """High-level Bot class for Shadivan."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Optional
6
+
7
+ from shadivan.client.async_client import AsyncClient
8
+ from shadivan.methods.send_message import send_message
9
+
10
+
11
+ class Bot:
12
+ """High-level interface for the Bale Bot API."""
13
+
14
+ def __init__(self, token: str) -> None:
15
+ self._client = AsyncClient(token)
16
+
17
+ async def request(
18
+ self,
19
+ method: str,
20
+ params: Optional[Dict[str, Any]] = None,
21
+ ) -> Any:
22
+ return await self._client.request(method, params)
23
+
24
+ async def get_me(self) -> Any:
25
+ return await self.request("getMe")
26
+
27
+ async def get_updates(
28
+ self,
29
+ limit: int = 100,
30
+ timeout: int = 30,
31
+ offset: Optional[int] = None,
32
+ ) -> Any:
33
+ params = {"limit": limit, "timeout": timeout}
34
+ if offset is not None:
35
+ params["offset"] = offset
36
+ return await self.request("getUpdates", params)
37
+
38
+ async def send_message(
39
+ self,
40
+ chat_id: str | int,
41
+ text: str,
42
+ ) -> Any:
43
+ return await send_message(self._client, chat_id, text)
44
+
45
+ async def close(self) -> None:
46
+ await self._client.close()
47
+
48
+ async def __aenter__(self) -> "Bot":
49
+ return self
50
+
51
+ async def __aexit__(self, *exc_info: Any) -> None:
52
+ await self.close()
File without changes
@@ -0,0 +1,166 @@
1
+ """Async HTTP client for the Shadivan library (Bale Bot API transport layer)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Optional
6
+ from urllib.parse import urlparse
7
+
8
+ import httpx
9
+
10
+ from shadivan.exceptions.errors import APIError, NetworkError, ShadivanError
11
+
12
+
13
+ class AsyncClient:
14
+ """Low-level async HTTP client for the Bale Bot API.
15
+
16
+ This class is responsible only for generic HTTP communication with the
17
+ Bale API. It does **not** implement any endpoint-specific methods; those
18
+ belong in higher-level modules.
19
+
20
+ Parameters
21
+ ----------
22
+ token:
23
+ The bot token issued by Bale.
24
+ base_url:
25
+ Full base URL of the Bale Bot API including the token, ending with a
26
+ trailing slash. Defaults to ``https://tapi.bale.ai/bot<token>/``.
27
+ timeout:
28
+ Request timeout in seconds. Defaults to ``30.0``.
29
+
30
+ Security
31
+ --------
32
+ The token is never included in exception messages or in ``__repr__``.
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ token: str,
38
+ base_url: Optional[str] = None,
39
+ timeout: float = 30.0,
40
+ ) -> None:
41
+ if not isinstance(token, str) or not token:
42
+ raise ValueError("token must be a non-empty string.")
43
+ if any(ch.isspace() for ch in token):
44
+ raise ValueError("token must not contain whitespace.")
45
+
46
+ self._token: str = token
47
+
48
+ if base_url is None:
49
+ self._base_url: str = f"https://tapi.bale.ai/bot{token}/"
50
+ else:
51
+ if not isinstance(base_url, str) or not base_url:
52
+ raise ValueError("base_url must be a non-empty string.")
53
+ parsed = urlparse(base_url)
54
+ if parsed.scheme != "https":
55
+ raise ValueError("base_url must use HTTPS.")
56
+ if not parsed.netloc:
57
+ raise ValueError("base_url must include a host.")
58
+ if not base_url.endswith("/"):
59
+ raise ValueError("base_url must end with a trailing '/'.")
60
+ self._base_url = base_url
61
+
62
+ parsed_full = urlparse(self._base_url)
63
+ self._safe_display: str = f"{parsed_full.scheme}://{parsed_full.netloc}/bot***/"
64
+
65
+ if (
66
+ not isinstance(timeout, (int, float))
67
+ or isinstance(timeout, bool)
68
+ or timeout <= 0
69
+ ):
70
+ raise ValueError("timeout must be a positive number.")
71
+
72
+ self._client: httpx.AsyncClient = httpx.AsyncClient(timeout=float(timeout))
73
+
74
+ async def request(
75
+ self,
76
+ method: str,
77
+ params: Optional[Dict[str, Any]] = None,
78
+ ) -> Any:
79
+ """Send a request to a Bale Bot API method and return the parsed result.
80
+
81
+ Parameters
82
+ ----------
83
+ method:
84
+ The API method name (e.g. ``"getMe"``, ``"getUpdates"``).
85
+ params:
86
+ Optional dictionary of parameters. Sent as a JSON request body.
87
+
88
+ Returns
89
+ -------
90
+ Any
91
+ The ``result`` field of the API response.
92
+
93
+ Raises
94
+ ------
95
+ NetworkError
96
+ On connection failures, timeouts, or other transport-level errors.
97
+ APIError
98
+ When the API responds with ``ok=false`` or a non-2xx HTTP status
99
+ that carries a non-JSON body.
100
+ ShadivanError
101
+ When the response body is not valid JSON, is not a JSON object,
102
+ or lacks the ``result`` field.
103
+ ValueError
104
+ When ``method`` or ``params`` are invalid.
105
+ """
106
+ if not isinstance(method, str) or not method:
107
+ raise ValueError("method must be a non-empty string.")
108
+ if any(ch.isspace() or ch == "/" for ch in method):
109
+ raise ValueError("method must not contain whitespace or '/'.")
110
+ if params is not None and not isinstance(params, dict):
111
+ raise ValueError("params must be a dict or None.")
112
+
113
+ url = f"{self._base_url}{method}"
114
+
115
+ try:
116
+ response = await self._client.post(url, json=params or {})
117
+ except httpx.TimeoutException:
118
+ raise NetworkError("Request timed out.") from None
119
+ except httpx.RequestError as exc:
120
+ # Only the exception class name is exposed; the original message
121
+ # (which may contain the full URL including the token) is suppressed.
122
+ raise NetworkError(f"Network error ({type(exc).__name__}).") from None
123
+
124
+ try:
125
+ data: Any = response.json()
126
+ except ValueError:
127
+ if response.status_code >= 400:
128
+ raise APIError(
129
+ error_code=int(response.status_code),
130
+ description=f"HTTP {response.status_code} with non-JSON body.",
131
+ ) from None
132
+ raise ShadivanError(
133
+ f"API returned a non-JSON response (status {response.status_code})."
134
+ ) from None
135
+
136
+ if not isinstance(data, dict):
137
+ raise ShadivanError("API returned an unexpected JSON structure.") from None
138
+
139
+ if not data.get("ok", False):
140
+ raw_code = data.get("error_code", response.status_code)
141
+ try:
142
+ error_code = int(raw_code)
143
+ except (TypeError, ValueError):
144
+ error_code = int(response.status_code)
145
+ description = data.get("description")
146
+ if not isinstance(description, str) or not description:
147
+ description = "Unknown API error."
148
+ raise APIError(error_code, description)
149
+
150
+ if "result" not in data:
151
+ raise ShadivanError("API response is missing the 'result' field.")
152
+
153
+ return data["result"]
154
+
155
+ async def close(self) -> None:
156
+ """Close the underlying HTTP connection pool."""
157
+ await self._client.aclose()
158
+
159
+ async def __aenter__(self) -> "AsyncClient":
160
+ return self
161
+
162
+ async def __aexit__(self, *exc_info: Any) -> None:
163
+ await self.close()
164
+
165
+ def __repr__(self) -> str:
166
+ return f"<AsyncClient base_url='{self._safe_display}'>"
@@ -0,0 +1,5 @@
1
+ """Public dispatcher API."""
2
+
3
+ from shadivan.dispatcher.router import Router
4
+
5
+ __all__ = ["Router"]
@@ -0,0 +1,30 @@
1
+ """Message router for the Shadivan library (MVP 0.1.0)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Awaitable, Callable, List
6
+
7
+ from shadivan.types.update import Update
8
+
9
+
10
+ Handler = Callable[[Update], Awaitable[Any]]
11
+
12
+
13
+ class Router:
14
+ """Routes incoming updates to registered handlers."""
15
+
16
+ def __init__(self) -> None:
17
+ self.handlers: List[Handler] = []
18
+
19
+ def message(self, handler: Handler) -> Handler:
20
+ """Register a handler for incoming messages."""
21
+ self.handlers.append(handler)
22
+ return handler
23
+
24
+ async def dispatch(self, update: Update) -> None:
25
+ """Run all registered handlers for an update."""
26
+ if update.message is None:
27
+ return
28
+
29
+ for handler in self.handlers:
30
+ await handler(update)
File without changes
@@ -0,0 +1,18 @@
1
+ """Exception classes for Shadivan."""
2
+
3
+
4
+ class ShadivanError(Exception):
5
+ """Base exception for Shadivan."""
6
+
7
+
8
+ class NetworkError(ShadivanError):
9
+ """Raised when a network error occurs."""
10
+
11
+
12
+ class APIError(ShadivanError):
13
+ """Raised when the Bale API returns an error."""
14
+
15
+ def __init__(self, error_code: int, description: str) -> None:
16
+ self.error_code = error_code
17
+ self.description = description
18
+ super().__init__(f"API error {error_code}: {description}")
@@ -0,0 +1,5 @@
1
+ """Public methods for the Shadivan library."""
2
+
3
+ from shadivan.methods.send_message import send_message
4
+
5
+ __all__ = ["send_message"]
@@ -0,0 +1,57 @@
1
+ """The ``sendMessage`` method for the Shadivan library (MVP 0.1.0)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from shadivan.client.async_client import AsyncClient
8
+
9
+
10
+ async def send_message(
11
+ client: AsyncClient,
12
+ chat_id: str | int,
13
+ text: str,
14
+ ) -> Any:
15
+ """Send a text message to a specific chat via the Bale Bot API.
16
+
17
+ This function is a thin wrapper around the ``sendMessage`` endpoint. It
18
+ only exposes the two parameters that are confirmed to be part of the
19
+ ``sendMessage`` API across multiple Bale Bot SDKs: ``chat_id`` and
20
+ ``text``. No optional parameters are accepted in this MVP.
21
+
22
+ Parameters
23
+ ----------
24
+ client:
25
+ An instance of :class:`~shadivan.client.async_client.AsyncClient`
26
+ used to perform the HTTP request.
27
+ chat_id:
28
+ Unique identifier for the target chat. Can be an integer or a string.
29
+ text:
30
+ The text of the message to be sent.
31
+
32
+ Returns
33
+ -------
34
+ Any
35
+ The ``result`` field of the API response, typically a ``Message``
36
+ object in the form of a dictionary.
37
+
38
+ Raises
39
+ ------
40
+ NetworkError
41
+ On connection failures, timeouts, or other transport-level errors.
42
+ APIError
43
+ When the Bale API returns ``ok=false``.
44
+ ShadivanError
45
+ When the response body is invalid or lacks expected fields.
46
+
47
+ Notes
48
+ -----
49
+ The ``chat_id`` and ``text`` parameters are documented in several Bale
50
+ Bot SDKs (e.g., ``juniora/bale-bot-sdk``, ``bale-bot-ts``, and
51
+ ``python-bale-bot``) and are treated as the minimal confirmed set for
52
+ this MVP.
53
+ """
54
+ return await client.request(
55
+ "sendMessage",
56
+ {"chat_id": chat_id, "text": text},
57
+ )
@@ -0,0 +1,59 @@
1
+ """Long polling implementation for Shadivan."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Optional
6
+
7
+ from shadivan.bot import Bot
8
+ from shadivan.dispatcher.router import Router
9
+ from shadivan.types.update import Update
10
+
11
+
12
+ class Polling:
13
+ """Receive Bale updates and dispatch them to a Router."""
14
+
15
+ def __init__(
16
+ self,
17
+ bot: Bot,
18
+ router: Router,
19
+ limit: int = 100,
20
+ timeout: int = 30,
21
+ ) -> None:
22
+ self.bot = bot
23
+ self.router = router
24
+ self.limit = limit
25
+ self.timeout = timeout
26
+ self.offset: Optional[int] = None
27
+ self._running = False
28
+
29
+ async def start(self) -> None:
30
+ self._running = True
31
+
32
+ while self._running:
33
+ params = {
34
+ "limit": self.limit,
35
+ "timeout": self.timeout,
36
+ }
37
+
38
+ if self.offset is not None:
39
+ params["offset"] = self.offset
40
+
41
+ updates = await self.bot.request("getUpdates", params)
42
+
43
+ for raw_update in updates:
44
+ update = Update.from_dict(raw_update)
45
+ self.offset = update.update_id + 1
46
+ await self.router.dispatch(update)
47
+
48
+ def stop(self) -> None:
49
+ self._running = False
50
+
51
+
52
+ async def start_polling(
53
+ bot: Bot,
54
+ router: Router,
55
+ limit: int = 100,
56
+ timeout: int = 30,
57
+ ) -> None:
58
+ polling = Polling(bot, router, limit, timeout)
59
+ await polling.start()
@@ -0,0 +1,13 @@
1
+ """Public data models for Shadivan."""
2
+
3
+ from shadivan.types.user import User
4
+ from shadivan.types.chat import Chat
5
+ from shadivan.types.message import Message
6
+ from shadivan.types.update import Update
7
+
8
+ __all__ = [
9
+ "User",
10
+ "Chat",
11
+ "Message",
12
+ "Update",
13
+ ]
@@ -0,0 +1,50 @@
1
+ """The ``Chat`` type for the Shadivan library (MVP 0.1.0)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any, Dict
7
+
8
+
9
+ @dataclass
10
+ class Chat:
11
+ """Represents a Bale chat.
12
+
13
+ This is a minimal model used in the MVP. It captures only the fields that
14
+ are most commonly needed when handling incoming updates.
15
+
16
+ Attributes
17
+ ----------
18
+ id:
19
+ Unique identifier for the chat.
20
+ type:
21
+ Type of the chat, such as ``"private"``, ``"group"``, or
22
+ ``"channel"``.
23
+ """
24
+
25
+ id: int
26
+ type: str
27
+
28
+ @classmethod
29
+ def from_dict(cls, data: Dict[str, Any]) -> "Chat":
30
+ """Build a :class:`Chat` instance from a raw API dictionary.
31
+
32
+ Parameters
33
+ ----------
34
+ data:
35
+ A dictionary as returned by the Bale Bot API for a chat object.
36
+
37
+ Returns
38
+ -------
39
+ Chat
40
+ A new :class:`Chat` instance.
41
+
42
+ Raises
43
+ ------
44
+ KeyError
45
+ If a required field (``id`` or ``type``) is missing.
46
+ """
47
+ return cls(
48
+ id=data["id"],
49
+ type=data["type"],
50
+ )
@@ -0,0 +1,75 @@
1
+ """The ``Message`` type for the Shadivan library (MVP 0.1.0)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any, Dict, Optional
7
+
8
+ from shadivan.types.chat import Chat
9
+ from shadivan.types.user import User
10
+
11
+
12
+ @dataclass
13
+ class Message:
14
+ """Represents a Bale message.
15
+
16
+ This is a minimal model used in the MVP. It captures only the fields that
17
+ are most commonly needed when handling incoming updates.
18
+
19
+ Attributes
20
+ ----------
21
+ message_id:
22
+ Unique identifier for the message within the chat.
23
+ date:
24
+ Date the message was sent, as a Unix timestamp (integer).
25
+ chat:
26
+ The chat to which the message belongs.
27
+ text:
28
+ Optional text content of the message.
29
+ from_user:
30
+ Optional sender of the message. In the raw Bale Bot API JSON this
31
+ field is named ``from``; it is exposed here as ``from_user`` to
32
+ avoid shadowing the Python keyword.
33
+ """
34
+
35
+ message_id: int
36
+ date: int
37
+ chat: Chat
38
+ text: Optional[str] = None
39
+ from_user: Optional[User] = None
40
+
41
+ @classmethod
42
+ def from_dict(cls, data: Dict[str, Any]) -> "Message":
43
+ """Build a :class:`Message` instance from a raw API dictionary.
44
+
45
+ Parameters
46
+ ----------
47
+ data:
48
+ A dictionary as returned by the Bale Bot API for a message
49
+ object.
50
+
51
+ Returns
52
+ -------
53
+ Message
54
+ A new :class:`Message` instance.
55
+
56
+ Raises
57
+ ------
58
+ KeyError
59
+ If a required field (``message_id``, ``date``, or ``chat``) is
60
+ missing.
61
+ """
62
+ chat = Chat.from_dict(data["chat"])
63
+
64
+ from_user: Optional[User] = None
65
+ raw_from = data.get("from")
66
+ if raw_from is not None:
67
+ from_user = User.from_dict(raw_from)
68
+
69
+ return cls(
70
+ message_id=data["message_id"],
71
+ date=data["date"],
72
+ chat=chat,
73
+ text=data.get("text"),
74
+ from_user=from_user,
75
+ )
@@ -0,0 +1,29 @@
1
+ """The Update type for the Shadivan library (MVP 0.1.0)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any, Dict, Optional
7
+
8
+ from shadivan.types.message import Message
9
+
10
+
11
+ @dataclass
12
+ class Update:
13
+ """Represents an incoming Bale update."""
14
+
15
+ update_id: int
16
+ message: Optional[Message] = None
17
+
18
+ @classmethod
19
+ def from_dict(cls, data: Dict[str, Any]) -> "Update":
20
+ raw_message = data.get("message")
21
+
22
+ message = None
23
+ if raw_message is not None:
24
+ message = Message.from_dict(raw_message)
25
+
26
+ return cls(
27
+ update_id=data["update_id"],
28
+ message=message,
29
+ )
@@ -0,0 +1,53 @@
1
+ """The ``User`` type for the Shadivan library (MVP 0.1.0)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any, Dict, Optional
7
+
8
+
9
+ @dataclass
10
+ class User:
11
+ """Represents a Bale user.
12
+
13
+ This is a minimal model used in the MVP. It captures only the fields that
14
+ are most commonly needed when handling incoming updates.
15
+
16
+ Attributes
17
+ ----------
18
+ id:
19
+ Unique identifier for the user.
20
+ first_name:
21
+ The user's first name.
22
+ username:
23
+ Optional username of the user. May be missing for some users.
24
+ """
25
+
26
+ id: int
27
+ first_name: str
28
+ username: Optional[str] = None
29
+
30
+ @classmethod
31
+ def from_dict(cls, data: Dict[str, Any]) -> "User":
32
+ """Build a :class:`User` instance from a raw API dictionary.
33
+
34
+ Parameters
35
+ ----------
36
+ data:
37
+ A dictionary as returned by the Bale Bot API for a user object.
38
+
39
+ Returns
40
+ -------
41
+ User
42
+ A new :class:`User` instance.
43
+
44
+ Raises
45
+ ------
46
+ KeyError
47
+ If a required field (``id`` or ``first_name``) is missing.
48
+ """
49
+ return cls(
50
+ id=data["id"],
51
+ first_name=data["first_name"],
52
+ username=data.get("username"),
53
+ )