ubits-bot 0.1.0b2__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.
ubits_bot/__init__.py
ADDED
ubits_bot/client.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
from contextlib import asynccontextmanager
|
|
2
|
+
import asyncio
|
|
3
|
+
import random
|
|
4
|
+
import json
|
|
5
|
+
import mimetypes
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Awaitable, Callable
|
|
9
|
+
from urllib.parse import urlsplit
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class BotAPIError(Exception):
|
|
14
|
+
def __init__(self, status: int, message: str):
|
|
15
|
+
self.status = status
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Bot:
|
|
20
|
+
def __init__(self, token: str, base_url: str = "https://ubits.org/bot/v1", *, transport=None):
|
|
21
|
+
url = urlsplit(base_url)
|
|
22
|
+
if url.scheme != "https" or not url.hostname or url.username or url.password or url.query or url.fragment:
|
|
23
|
+
raise ValueError("base_url must be an HTTPS URL without credentials, query or fragment")
|
|
24
|
+
if not token or any(c.isspace() for c in token):
|
|
25
|
+
raise ValueError("Invalid bot token")
|
|
26
|
+
self._transport = transport
|
|
27
|
+
self._client = httpx.AsyncClient(base_url=base_url.rstrip("/") + "/",
|
|
28
|
+
headers={"Authorization": "Bot " + token}, timeout=40,
|
|
29
|
+
follow_redirects=False, trust_env=False, transport=transport)
|
|
30
|
+
|
|
31
|
+
async def __aenter__(self):
|
|
32
|
+
return self
|
|
33
|
+
|
|
34
|
+
async def __aexit__(self, *args):
|
|
35
|
+
await self.close()
|
|
36
|
+
|
|
37
|
+
async def close(self):
|
|
38
|
+
await self._client.aclose()
|
|
39
|
+
|
|
40
|
+
async def _result(self, response):
|
|
41
|
+
try:
|
|
42
|
+
value = response.json()
|
|
43
|
+
except ValueError:
|
|
44
|
+
raise BotAPIError(response.status_code, "Invalid Bot API response") from None
|
|
45
|
+
if not response.is_success or not value.get("ok"):
|
|
46
|
+
raise BotAPIError(response.status_code, value.get("error", {}).get("message", "Bot API request failed"))
|
|
47
|
+
return value["result"]
|
|
48
|
+
|
|
49
|
+
async def call(self, method: str, **params) -> Any:
|
|
50
|
+
# Restrict method names so callers cannot route credentials to another URL.
|
|
51
|
+
if not method.isascii() or not method.isalpha():
|
|
52
|
+
raise ValueError("Invalid method")
|
|
53
|
+
return await self._result(await self._client.post(method, json=params))
|
|
54
|
+
|
|
55
|
+
async def get_me(self):
|
|
56
|
+
return await self.call("getMe")
|
|
57
|
+
|
|
58
|
+
async def get_user(self, user_id: str):
|
|
59
|
+
return await self.call("getUser", userId=user_id)
|
|
60
|
+
|
|
61
|
+
async def get_chat(self, chat_id: str):
|
|
62
|
+
return await self.call("getChat", chatId=chat_id)
|
|
63
|
+
|
|
64
|
+
async def get_message(self, chat_id: str, message_id: str):
|
|
65
|
+
return await self.call("getMessage", chatId=chat_id, messageId=message_id)
|
|
66
|
+
|
|
67
|
+
async def get_updates(self, offset="0", limit=50, timeout=25):
|
|
68
|
+
return await self.call("getUpdates", offset=str(offset), limit=limit, timeout=timeout)
|
|
69
|
+
|
|
70
|
+
async def send_message(self, chat_id: str, content: str, *, message_id=None, reply_to_id=None):
|
|
71
|
+
from uuid import uuid4
|
|
72
|
+
data = {"chatId": chat_id, "content": content, "messageId": message_id or str(uuid4())}
|
|
73
|
+
if reply_to_id:
|
|
74
|
+
data["replyToId"] = reply_to_id
|
|
75
|
+
return await self.call("sendMessage", **data)
|
|
76
|
+
|
|
77
|
+
async def edit_message(self, chat_id, message_id, content):
|
|
78
|
+
return await self.call("editMessage", chatId=chat_id, messageId=message_id, content=content)
|
|
79
|
+
|
|
80
|
+
async def delete_message(self, chat_id, message_id):
|
|
81
|
+
return await self.call("deleteMessage", chatId=chat_id, messageId=message_id)
|
|
82
|
+
|
|
83
|
+
async def _upload(self, method, chat_id, path, *, message_id=None, caption=None, kind=None):
|
|
84
|
+
path = Path(path)
|
|
85
|
+
if path.stat().st_size > 25 * 1024 * 1024:
|
|
86
|
+
raise ValueError("Media is limited to 25 MiB")
|
|
87
|
+
params = {"chatId": chat_id}
|
|
88
|
+
if message_id:
|
|
89
|
+
params["messageId"] = message_id
|
|
90
|
+
if caption is not None:
|
|
91
|
+
params["caption"] = caption
|
|
92
|
+
if kind:
|
|
93
|
+
params["kind"] = kind
|
|
94
|
+
with path.open("rb") as stream:
|
|
95
|
+
response = await self._client.post(method, params=params,
|
|
96
|
+
files={"file": (path.name, stream, mimetypes.guess_type(path.name)[0] or "application/octet-stream")}, timeout=180)
|
|
97
|
+
return await self._result(response)
|
|
98
|
+
|
|
99
|
+
async def send_media(self, chat_id, path, *, caption=None, kind=None):
|
|
100
|
+
return await self._upload("sendMedia", chat_id, path, caption=caption, kind=kind)
|
|
101
|
+
|
|
102
|
+
async def edit_media(self, chat_id, message_id, path, *, caption=None, kind=None):
|
|
103
|
+
return await self._upload("editMedia", chat_id, path, message_id=message_id, caption=caption, kind=kind)
|
|
104
|
+
|
|
105
|
+
@asynccontextmanager
|
|
106
|
+
async def _file_response(self, method, params):
|
|
107
|
+
async with self._client.stream("GET", method, params=params, timeout=180) as response:
|
|
108
|
+
if response.status_code not in (302, 303, 307, 308):
|
|
109
|
+
yield response
|
|
110
|
+
return
|
|
111
|
+
target = response.headers.get("location", "")
|
|
112
|
+
url = urlsplit(target)
|
|
113
|
+
if url.scheme != "https" or not url.hostname or url.username or url.password:
|
|
114
|
+
raise BotAPIError(502, "Unsafe media redirect")
|
|
115
|
+
# The API issues a short-lived signed CDN grant. Never forward the bot
|
|
116
|
+
# token, cookies, environment proxy credentials, or further redirects.
|
|
117
|
+
async with httpx.AsyncClient(timeout=180, follow_redirects=False,
|
|
118
|
+
trust_env=False, transport=self._transport) as delivery:
|
|
119
|
+
async with delivery.stream("GET", target) as response:
|
|
120
|
+
yield response
|
|
121
|
+
|
|
122
|
+
async def _download(self, method, params, destination):
|
|
123
|
+
path = Path(destination)
|
|
124
|
+
import tempfile
|
|
125
|
+
descriptor, name = tempfile.mkstemp(prefix=path.name + ".", suffix=".part", dir=path.parent)
|
|
126
|
+
temporary = Path(name)
|
|
127
|
+
try:
|
|
128
|
+
with os.fdopen(descriptor, "wb") as stream:
|
|
129
|
+
async with self._file_response(method, params) as response:
|
|
130
|
+
if not response.is_success:
|
|
131
|
+
await response.aread()
|
|
132
|
+
await self._result(response)
|
|
133
|
+
async for block in response.aiter_bytes():
|
|
134
|
+
stream.write(block)
|
|
135
|
+
os.replace(temporary, path)
|
|
136
|
+
finally:
|
|
137
|
+
temporary.unlink(missing_ok=True)
|
|
138
|
+
return path
|
|
139
|
+
|
|
140
|
+
async def download_file(self, chat_id, message_id, destination, *, index=None):
|
|
141
|
+
params = {"chatId": chat_id, "messageId": message_id}
|
|
142
|
+
if index is not None:
|
|
143
|
+
params["index"] = index
|
|
144
|
+
return await self._download("getFile", params, destination)
|
|
145
|
+
|
|
146
|
+
async def download_user_photo(self, user_id, destination):
|
|
147
|
+
return await self._download("getUserPhoto", {"userId": user_id}, destination)
|
|
148
|
+
|
|
149
|
+
async def run_polling(self, handler: Callable[[dict], Awaitable[None]], *, checkpoint="ubits-offset.json"):
|
|
150
|
+
"""Persist the cursor after the complete batch succeeds. Handlers must deduplicate updateId."""
|
|
151
|
+
path = Path(checkpoint)
|
|
152
|
+
offset = json.loads(path.read_text())["offset"] if path.exists() else "0"
|
|
153
|
+
failures = 0
|
|
154
|
+
while True:
|
|
155
|
+
try:
|
|
156
|
+
batch = await self.get_updates(offset)
|
|
157
|
+
except (httpx.TransportError, BotAPIError) as error:
|
|
158
|
+
if isinstance(error, BotAPIError) and error.status < 500 and error.status != 429:
|
|
159
|
+
raise
|
|
160
|
+
failures += 1
|
|
161
|
+
await asyncio.sleep(min(30, 2 ** min(failures, 5)) + random.random())
|
|
162
|
+
continue
|
|
163
|
+
failures = 0
|
|
164
|
+
for update in batch["updates"]:
|
|
165
|
+
await handler(update)
|
|
166
|
+
offset = batch["nextOffset"]
|
|
167
|
+
temporary = path.with_name(path.name + ".tmp")
|
|
168
|
+
temporary.write_text(json.dumps({"offset": offset}), encoding="utf-8")
|
|
169
|
+
os.replace(temporary, path)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ubits-bot
|
|
3
|
+
Version: 0.1.0b2
|
|
4
|
+
Summary: Async Python client for the Ubits Bot API beta
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Documentation, https://ubits.org/assets/bots/bot-api-v1-beta-2.md
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: httpx<1,>=0.27
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
# ubits-bot
|
|
14
|
+
|
|
15
|
+
Асинхронная Python-библиотека для Ubits Bot API. Python 3.10+.
|
|
16
|
+
|
|
17
|
+
**Bot API пока не включён на ubits.org.** SDK и пример готовы; запросы начнут
|
|
18
|
+
работать после активации API на сервере.
|
|
19
|
+
|
|
20
|
+
## Установка
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
python -m pip install --pre ubits-bot
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Для установки бета-версии нужен флаг `--pre`.
|
|
27
|
+
|
|
28
|
+
## Пример
|
|
29
|
+
|
|
30
|
+
Создайте бота через @CreateBot: `/newbot`. Сохраните выданный токен в переменную
|
|
31
|
+
окружения `UBITS_BOT_TOKEN`.
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
import asyncio
|
|
35
|
+
import os
|
|
36
|
+
from ubits_bot import Bot
|
|
37
|
+
|
|
38
|
+
async def main():
|
|
39
|
+
async with Bot(os.environ["UBITS_BOT_TOKEN"]) as bot:
|
|
40
|
+
async def handle(update):
|
|
41
|
+
message = update.get("message")
|
|
42
|
+
if update["type"] == "message" and message and message["kind"] == "text":
|
|
43
|
+
await bot.send_message(message["chatId"], "Привет!")
|
|
44
|
+
await bot.run_polling(handle)
|
|
45
|
+
|
|
46
|
+
asyncio.run(main())
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Программа должна оставаться запущенной. Один процесс polling на токен.
|
|
50
|
+
Пользователь сначала сам открывает диалог с ботом в Ubits.
|
|
51
|
+
|
|
52
|
+
## Методы
|
|
53
|
+
|
|
54
|
+
- `get_me`, `get_user`, `get_chat`, `get_message`
|
|
55
|
+
- `send_message`, `edit_message`, `delete_message`
|
|
56
|
+
- `send_media`, `edit_media`
|
|
57
|
+
- `download_file`, `download_user_photo`
|
|
58
|
+
- `get_updates`, `run_polling`
|
|
59
|
+
|
|
60
|
+
[Документация API](docs/API.md) · [OpenAPI](docs/openapi.json) ·
|
|
61
|
+
[Игровой бот](examples/game_bot/README.md)
|
|
62
|
+
|
|
63
|
+
run_polling сохраняет offset после обработки всей пачки событий.
|
|
64
|
+
Повторная обработка события возможна: учитывайте updateId в своём коде.
|
|
65
|
+
SDK автоматически повторяет чтение при транспортных ошибках, 429 и 5xx.
|
|
66
|
+
Отправка и загрузка файлов автоматически не повторяются. Для повторной отправки
|
|
67
|
+
текста используйте заранее сохранённый message_id.
|
|
68
|
+
|
|
69
|
+
## Разработка
|
|
70
|
+
|
|
71
|
+
```sh
|
|
72
|
+
python -m pip install -e .
|
|
73
|
+
python -m unittest discover -s tests -v
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Лицензия MIT.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
ubits_bot/__init__.py,sha256=YYn8jf7s2BX8-kbrFEF-s0YYB0FwPC9_R81Pw6Sez1c,148
|
|
2
|
+
ubits_bot/client.py,sha256=iRNBh7jE-Y3iNJM-vJCkFt_l42ayZbKNn8j9YRSJgSY,7797
|
|
3
|
+
ubits_bot-0.1.0b2.dist-info/licenses/LICENSE,sha256=ETSyDOsjKoSQOxWKEklshUSCvJWP01IXBNWZNhqWMqE,1096
|
|
4
|
+
ubits_bot-0.1.0b2.dist-info/METADATA,sha256=kF2iKbxWZqBl0OQA34nAsR0nIHIImKKGzz8JMhDQVsY,2794
|
|
5
|
+
ubits_bot-0.1.0b2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
ubits_bot-0.1.0b2.dist-info/top_level.txt,sha256=x8WyifBP0lC3ZPBFXbS1PfXk87Ypm8k5xB5ismFSI84,10
|
|
7
|
+
ubits_bot-0.1.0b2.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ubits contributors
|
|
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 @@
|
|
|
1
|
+
ubits_bot
|