Bot API client (apps/integration/telegram.py):
- sendMessage, getMe, getUpdates over requests, no extra dependencies
- Telegram API errors are surfaced with the provider description
("chat not found", "bot was blocked") instead of a bare HTTP status
- messages longer than the Bot API limit are truncated with a marker
Notifications:
- notifications.py now goes through the client; failures are logged and
never break the exchange
Setup helpers:
- telegram_check: verifies the token, prints the bot name, sends a test
message, and suggests chats when chat_id is missing
- telegram_chats: lists chats that wrote to the bot, --apply saves the
chat_id when exactly one chat is known
- admin action "Detect chat_id from bot messages" does the same in the UI,
with explicit messages for no chats, many chats and API errors
- admin help text explains the BotFather -> /start -> test flow
Docs: Telegram setup section, command reference and limitations
(4096-char limit, negative chat_id for groups/channels, no internet =
no Telegram).
Tests: 12 new cases for the client, both commands and the admin action;
the suite is 45 passing.
107 lines
3.4 KiB
Python
107 lines
3.4 KiB
Python
"""Minimal Telegram Bot API client used for administrator alerts.
|
|
|
|
Only three Bot API methods are needed:
|
|
|
|
* ``sendMessage`` — deliver an alert;
|
|
* ``getMe`` — verify the token and show the bot name;
|
|
* ``getUpdates`` — find the ``chat_id`` of a chat that wrote to the bot.
|
|
|
|
The client is intentionally tiny: no polling loop, no webhook, no dependencies
|
|
beyond ``requests``.
|
|
"""
|
|
|
|
import logging
|
|
|
|
import requests
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
API_ROOT = "https://api.telegram.org"
|
|
TIMEOUT = 10
|
|
MAX_MESSAGE_LENGTH = 4096
|
|
TRUNCATION_SUFFIX = "\n… (сообщение обрезано)"
|
|
|
|
|
|
class TelegramError(Exception):
|
|
"""Raised when the Bot API rejects a call or is unreachable."""
|
|
|
|
|
|
def _call(method: str, token: str, payload: dict, timeout: int = TIMEOUT) -> object:
|
|
"""Calls a Bot API method and returns its ``result`` field."""
|
|
if not token:
|
|
raise TelegramError("не задан токен Telegram-бота")
|
|
|
|
url = f"{API_ROOT}/bot{token}/{method}"
|
|
try:
|
|
response = requests.post(url, json=payload, timeout=timeout)
|
|
except requests.RequestException as exc:
|
|
raise TelegramError(f"Telegram недоступен: {exc}") from exc
|
|
|
|
try:
|
|
data = response.json()
|
|
except ValueError:
|
|
data = {}
|
|
|
|
if response.status_code != 200 or not data.get("ok"):
|
|
description = data.get("description") or f"HTTP {response.status_code}"
|
|
raise TelegramError(f"Telegram API: {description}")
|
|
return data.get("result")
|
|
|
|
|
|
def get_me(token: str) -> dict:
|
|
"""Returns the bot description: id, username, first_name."""
|
|
return _call("getMe", token, {}) or {}
|
|
|
|
|
|
def send_message(token: str, chat_id: str, text: str) -> dict:
|
|
"""Sends a plain-text message. Long messages are truncated to 4096 chars."""
|
|
if len(text) > MAX_MESSAGE_LENGTH:
|
|
cut = MAX_MESSAGE_LENGTH - len(TRUNCATION_SUFFIX)
|
|
text = text[:cut] + TRUNCATION_SUFFIX
|
|
return _call(
|
|
"sendMessage",
|
|
token,
|
|
{
|
|
"chat_id": str(chat_id),
|
|
"text": text,
|
|
"disable_web_page_preview": True,
|
|
},
|
|
) or {}
|
|
|
|
|
|
def get_updates(token: str, limit: int = 50, offset: int | None = None) -> list:
|
|
"""Returns recent updates — used to discover chat ids."""
|
|
payload: dict = {"limit": limit, "timeout": 0, "allowed_updates": ["message"]}
|
|
if offset is not None:
|
|
payload["offset"] = offset
|
|
return _call("getUpdates", token, payload) or []
|
|
|
|
|
|
def recent_chats(token: str, limit: int = 50) -> list[dict]:
|
|
"""Returns chats that wrote to the bot, newest first, without duplicates."""
|
|
seen: dict[str, dict] = {}
|
|
for update in get_updates(token, limit=limit):
|
|
message = update.get("message") or update.get("edited_message") or {}
|
|
chat = message.get("chat")
|
|
if not chat:
|
|
continue
|
|
chat_id = str(chat.get("id"))
|
|
if chat_id in seen:
|
|
continue
|
|
seen[chat_id] = {
|
|
"id": chat_id,
|
|
"type": chat.get("type", ""),
|
|
"title": (
|
|
chat.get("title")
|
|
or " ".join(
|
|
part
|
|
for part in [chat.get("first_name"), chat.get("last_name")]
|
|
if part
|
|
)
|
|
or chat.get("username")
|
|
or chat_id
|
|
),
|
|
"username": chat.get("username", ""),
|
|
}
|
|
return list(seen.values())
|