shtab-sdk 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shtab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.4
2
+ Name: shtab-sdk
3
+ Version: 0.1.0
4
+ Summary: Typed SDK for the Shtab public API
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: jsonschema<5,>=4.18
10
+ Requires-Dist: typing_extensions>=4.4
11
+ Dynamic: license-file
12
+
13
+ # Python SDK Штаба
14
+
15
+ Поддерживается Python 3.10 и новее.
16
+
17
+ ```sh
18
+ pip install shtab-sdk
19
+ ```
20
+
21
+ Выпустите токен в Штабе и сохраните его в переменной окружения `SHTAB_TOKEN`. Для персонального токена используйте `token_type="personal"`, для токена команды — `"team"`, для токена бота — `"bot"`.
22
+
23
+ ```python
24
+ import os
25
+
26
+ from shtab_sdk import ApiError, ShtabClient
27
+
28
+ client = ShtabClient(os.environ["SHTAB_TOKEN"], token_type="personal")
29
+
30
+ try:
31
+ for page in client.iter_tasks_list_list_pages(path={"team_id": "123"}, query={"limit": 20}):
32
+ for task in page["results"]:
33
+ print(task["id"], task["name"])
34
+ except ApiError as error:
35
+ print(error.status, error.code, error.body)
36
+ if error.response.retry_after is not None:
37
+ print(f"Следующая попытка через {error.response.retry_after} с")
38
+ raise
39
+ ```
40
+
41
+ Имя метода и типы аргументов каждой операции приведены в справочнике API. Параметры пути передаются в `path`, параметры строки запроса — в `query`, тело — в `body`. Для multipart-загрузки один из полей `body` принимает `FileUpload(filename, content, content_type)`, где `content` — байты файла.
42
+
43
+ Методы с пагинацией принимают соответствующие параметры API и возвращают исходную страницу ответа. Методы `iter_…_pages` загружают страницы по запросу и сохраняют фильтры исходного вызова.
44
+
45
+ Для каждого HTTP-ответа вызов `on_response=callback` передаёт статус и заголовки, включая лимиты. Ошибка `ApiError` содержит статус, заголовки, исходные байты и разобранное тело при наличии. Например, при HTTP 429 время ожидания доступно в `error.response.retry_after`. SDK выполняет один HTTP-запрос на вызов метода. При сбое соединения или истечении таймаута у сервера мог сохраниться результат записи, поэтому перед повтором изменяющей операции проверьте результат или используйте предусмотренный этой операцией ключ идемпотентности.
@@ -0,0 +1,33 @@
1
+ # Python SDK Штаба
2
+
3
+ Поддерживается Python 3.10 и новее.
4
+
5
+ ```sh
6
+ pip install shtab-sdk
7
+ ```
8
+
9
+ Выпустите токен в Штабе и сохраните его в переменной окружения `SHTAB_TOKEN`. Для персонального токена используйте `token_type="personal"`, для токена команды — `"team"`, для токена бота — `"bot"`.
10
+
11
+ ```python
12
+ import os
13
+
14
+ from shtab_sdk import ApiError, ShtabClient
15
+
16
+ client = ShtabClient(os.environ["SHTAB_TOKEN"], token_type="personal")
17
+
18
+ try:
19
+ for page in client.iter_tasks_list_list_pages(path={"team_id": "123"}, query={"limit": 20}):
20
+ for task in page["results"]:
21
+ print(task["id"], task["name"])
22
+ except ApiError as error:
23
+ print(error.status, error.code, error.body)
24
+ if error.response.retry_after is not None:
25
+ print(f"Следующая попытка через {error.response.retry_after} с")
26
+ raise
27
+ ```
28
+
29
+ Имя метода и типы аргументов каждой операции приведены в справочнике API. Параметры пути передаются в `path`, параметры строки запроса — в `query`, тело — в `body`. Для multipart-загрузки один из полей `body` принимает `FileUpload(filename, content, content_type)`, где `content` — байты файла.
30
+
31
+ Методы с пагинацией принимают соответствующие параметры API и возвращают исходную страницу ответа. Методы `iter_…_pages` загружают страницы по запросу и сохраняют фильтры исходного вызова.
32
+
33
+ Для каждого HTTP-ответа вызов `on_response=callback` передаёт статус и заголовки, включая лимиты. Ошибка `ApiError` содержит статус, заголовки, исходные байты и разобранное тело при наличии. Например, при HTTP 429 время ожидания доступно в `error.response.retry_after`. SDK выполняет один HTTP-запрос на вызов метода. При сбое соединения или истечении таймаута у сервера мог сохраниться результат записи, поэтому перед повтором изменяющей операции проверьте результат или используйте предусмотренный этой операцией ключ идемпотентности.
@@ -0,0 +1,64 @@
1
+ """Run behind HTTPS with SHTAB_TEAM_ID, SHTAB_TOKEN and SHTAB_WEBHOOK_SECRET set.
2
+
3
+ Set SHTAB_API_BASE_URL to point the SDK at a local API when testing.
4
+ """
5
+
6
+ import os
7
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
8
+
9
+ from shtab_sdk import ApiError, ShtabClient
10
+ from shtab_sdk.events import WebhookEvent
11
+ from shtab_sdk.webhooks import PayloadError, SignatureError, WebhookRouter, parse_delivery
12
+
13
+ base_url = os.environ.get("SHTAB_API_BASE_URL")
14
+ client = ShtabClient(
15
+ os.environ["SHTAB_TOKEN"],
16
+ token_type="bot", # noqa: S106 -- public token type
17
+ **({"base_url": base_url} if base_url else {}),
18
+ )
19
+ secret = os.environ["SHTAB_WEBHOOK_SECRET"]
20
+ team_id = os.environ["SHTAB_TEAM_ID"]
21
+ router = WebhookRouter()
22
+
23
+
24
+ def reply(event: WebhookEvent) -> None:
25
+ if event["type"] != "messenger.message.created":
26
+ return
27
+ message = event["body"]
28
+ if message is None or message["text"].strip().lower() != "ping":
29
+ return
30
+ client.bots_chats_messages_replies_create(
31
+ path={
32
+ "team_id": team_id,
33
+ "chat_id": str(message["chat_id"]),
34
+ "message_id": str(message["thread_root_id"] or message["id"]),
35
+ },
36
+ body={"text": "pong", "client_message_id": event["event_id"]},
37
+ )
38
+
39
+
40
+ router.on("messenger.message.created", reply)
41
+
42
+
43
+ class Receiver(BaseHTTPRequestHandler):
44
+ def do_POST(self):
45
+ try:
46
+ length = int(self.headers.get("Content-Length", "0"))
47
+ if not 0 < length <= 8 * 1024 * 1024:
48
+ self.send_error(413)
49
+ return
50
+ delivery = parse_delivery(self.rfile.read(length), self.headers.get("X-Shtab-Signature", ""), secret)
51
+ router.dispatch(delivery)
52
+ except SignatureError:
53
+ self.send_error(401)
54
+ except (PayloadError, ValueError):
55
+ self.send_error(400)
56
+ except (ApiError, OSError):
57
+ self.send_error(503)
58
+ else:
59
+ self.send_response(204)
60
+ self.end_headers()
61
+
62
+
63
+ if __name__ == "__main__":
64
+ ThreadingHTTPServer(("127.0.0.1", int(os.environ.get("PORT", "8080"))), Receiver).serve_forever()
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "shtab-sdk"
7
+ version = "0.1.0"
8
+ description = "Typed SDK for the Shtab public API"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = ["jsonschema>=4.18,<5", "typing_extensions>=4.4"]
14
+
15
+ [tool.setuptools.packages.find]
16
+ where = ["src"]
17
+
18
+ [tool.setuptools.package-data]
19
+ shtab_sdk = ["py.typed", "event_schema.json"]
20
+
21
+ [tool.setuptools.data-files]
22
+ "share/shtab-sdk/examples" = ["examples/*.py"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,4 @@
1
+ from ._transport import ApiError, FileUpload, ResponseInfo, TokenType
2
+ from .client import ShtabClient
3
+
4
+ __all__ = ["ApiError", "FileUpload", "ResponseInfo", "ShtabClient", "TokenType"]
@@ -0,0 +1,197 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ from collections.abc import Callable, Iterator, Mapping
6
+ from dataclasses import dataclass
7
+ from email.message import Message
8
+ from email.policy import HTTP
9
+ from typing import Literal, TypeVar
10
+ from urllib.error import HTTPError
11
+ from urllib.parse import parse_qs, quote, urlencode, urlsplit
12
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
13
+ from uuid import uuid4
14
+
15
+ TokenType = Literal["personal", "team", "bot"]
16
+ T = TypeVar("T")
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class FileUpload:
21
+ filename: str
22
+ content: bytes
23
+ content_type: str = "application/octet-stream"
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class ResponseInfo:
28
+ status: int
29
+ headers: Mapping[str, str]
30
+
31
+ @property
32
+ def retry_after(self) -> int | None:
33
+ value = self.headers.get("retry-after", "")
34
+ return int(value) if value.isdecimal() else None
35
+
36
+
37
+ class ApiError(Exception):
38
+ def __init__(self, response: ResponseInfo, body: object, raw_body: bytes):
39
+ self.response = response
40
+ self.status = response.status
41
+ self.headers = response.headers
42
+ self.body = body
43
+ self.raw_body = raw_body
44
+ payload = body if isinstance(body, dict) else {}
45
+ error = payload.get("error")
46
+ details = error if isinstance(error, dict) else payload
47
+ self.code = details.get("code")
48
+ self.details = details.get("details")
49
+ message = details.get("message") or details.get("detail")
50
+ super().__init__(message or f"Shtab API returned HTTP {self.status}")
51
+
52
+
53
+ class _NoRedirect(HTTPRedirectHandler):
54
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: PLR0917
55
+ return None
56
+
57
+
58
+ class Transport:
59
+ def __init__(
60
+ self,
61
+ token: str,
62
+ *,
63
+ token_type: TokenType,
64
+ base_url: str,
65
+ timeout: float = 30,
66
+ on_response: Callable[[ResponseInfo], None] | None = None,
67
+ ):
68
+ origin = urlsplit(base_url)
69
+ if origin.scheme not in {"http", "https"} or not origin.netloc or origin.username is not None or origin.query or origin.fragment:
70
+ raise ValueError("base_url must be an absolute HTTP(S) URL without credentials, query parameters or fragments")
71
+ self.token_type = token_type
72
+ self._token = token
73
+ self._base_url = base_url.rstrip("/")
74
+ self._timeout = timeout
75
+ self._on_response = on_response
76
+ self._opener = build_opener(_NoRedirect)
77
+
78
+ def request(
79
+ self,
80
+ method: str,
81
+ route: str,
82
+ token_types: tuple[TokenType, ...],
83
+ *,
84
+ path: Mapping[str, object] | None = None,
85
+ query: Mapping[str, object] | None = None,
86
+ headers: Mapping[str, str] | None = None,
87
+ body: object = None,
88
+ multipart: bool = False,
89
+ ) -> object:
90
+ if self.token_type not in token_types:
91
+ raise ValueError(f"{method} {route} requires one of {', '.join(token_types)}")
92
+ route = re.sub(r"\{([^}]+)\}", lambda match: quote(str((path or {})[match[1]]), safe=""), route)
93
+ url = self._base_url + route
94
+ if query:
95
+ fields = [(key, _query_value(value)) for key, value in query.items() if value is not None]
96
+ if fields:
97
+ url += "?" + urlencode(fields, doseq=True)
98
+ request_headers = {
99
+ key: value for key, value in (headers or {}).items()
100
+ if key.lower() not in {"authorization", "authorization-team"}
101
+ }
102
+ request_headers.update({"Accept": "application/json", "Authorization": f"Bearer {self._token}"})
103
+ content = None
104
+ if multipart and isinstance(body, Mapping):
105
+ content, request_headers["Content-Type"] = _encode_multipart(body)
106
+ elif body is not None:
107
+ content = json.dumps(body, ensure_ascii=False, allow_nan=False).encode("utf-8")
108
+ request_headers["Content-Type"] = "application/json"
109
+ request = Request(url, data=content, headers=request_headers, method=method) # noqa: S310
110
+
111
+ try:
112
+ response = self._opener.open(request, timeout=self._timeout)
113
+ except HTTPError as error:
114
+ with error:
115
+ info, payload, raw = self._read(error)
116
+ raise ApiError(info, payload, raw) from None
117
+ with response:
118
+ _info, payload, _raw = self._read(response)
119
+ return payload
120
+
121
+ def _read(self, response):
122
+ info = ResponseInfo(response.code, {key.lower(): value for key, value in response.headers.items()})
123
+ if self._on_response is not None:
124
+ self._on_response(info)
125
+ raw = response.read()
126
+ if not raw:
127
+ return info, None, raw
128
+ content_type = info.headers.get("content-type", "").partition(";")[0]
129
+ if content_type == "application/json" or content_type.endswith("+json"):
130
+ try:
131
+ return info, json.loads(raw), raw
132
+ except (ValueError, UnicodeError):
133
+ pass
134
+ if content_type.startswith("text/") or content_type == "application/json":
135
+ return info, raw.decode("utf-8", errors="replace"), raw
136
+ return info, raw, raw
137
+
138
+
139
+ def _query_value(value):
140
+ if isinstance(value, bool):
141
+ return "true" if value else "false"
142
+ if isinstance(value, (list, tuple)):
143
+ return [_query_value(item) for item in value]
144
+ return str(value)
145
+
146
+
147
+ def _encode_multipart(fields):
148
+ boundary = uuid4().hex
149
+ parts = []
150
+ for key, value in fields.items():
151
+ if value is None:
152
+ continue
153
+ headers = Message(policy=HTTP)
154
+ params = {"name": key}
155
+ if isinstance(value, FileUpload):
156
+ params["filename"] = value.filename
157
+ headers["Content-Type"] = value.content_type
158
+ content = value.content
159
+ else:
160
+ content = _query_value(value).encode("utf-8")
161
+ headers.add_header("Content-Disposition", "form-data", **params)
162
+ parts.extend([f"--{boundary}\r\n".encode(), headers.as_bytes(policy=HTTP), content, b"\r\n"])
163
+ parts.append(f"--{boundary}--\r\n".encode())
164
+ return b"".join(parts), f"multipart/form-data; boundary={boundary}"
165
+
166
+
167
+ def iterate_pages(
168
+ fetch_page: Callable[[dict[str, object]], T],
169
+ query: Mapping[str, object] | None,
170
+ pagination: Literal["limit-offset", "page-number", "cursor"],
171
+ ) -> Iterator[T]:
172
+ params = dict(query or {})
173
+ while True:
174
+ page = fetch_page(params)
175
+ yield page
176
+ if not isinstance(page, dict):
177
+ return
178
+ if pagination == "limit-offset":
179
+ link = page.get("next")
180
+ if not link:
181
+ return
182
+ values = parse_qs(urlsplit(link).query)
183
+ updates = {key: int(values[key][0]) for key in ("limit", "offset") if key in values}
184
+ elif pagination == "page-number":
185
+ number = int(params.get("page", 1))
186
+ if number >= page["num_pages"]:
187
+ return
188
+ updates = {"page": number + 1}
189
+ else:
190
+ before = page.get("next_before")
191
+ if before is None:
192
+ return
193
+ updates = {"before": before}
194
+ # Continue the same operation even when the response contains an absolute link.
195
+ if not updates or all(params.get(key) == value for key, value in updates.items()):
196
+ return
197
+ params.update(updates)