"""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())