Coverage for notifications/telegram_client.py: 100%
33 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Thin, injectable Telegram Bot API client (V2-19).
3Fire-and-forget, mirroring experience/redis_queue.py's ExperienceQueue: any
4failure (missing credentials, network error, non-2xx response) is caught
5and logged at WARNING, send_message() never raises. The `requests` import is
6deferred inside send_message() so importing this module doesn't hard-require
7`requests` when a _send_fn is injected (tests only).
8"""
10from __future__ import annotations
12import logging
13from collections.abc import Callable
15from execution.secrets import redact
16from execution.secrets_io import secret_env
18logger = logging.getLogger(__name__)
20_SEND_MESSAGE_URL = "https://api.telegram.org/bot{token}/sendMessage"
21_REQUEST_TIMEOUT_SECONDS = 10
24class TelegramClient:
25 """Sends plain-text messages to a single Telegram chat.
27 Parameters
28 ----------
29 bot_token : Telegram bot token; overridden by AETHER_TELEGRAM_BOT_TOKEN env
30 chat_id : Telegram chat id; overridden by AETHER_TELEGRAM_CHAT_ID env
31 _send_fn : injected callable(text) -> bool for test injection — when
32 provided, send_message() never imports/calls `requests`.
33 """
35 def __init__(
36 self,
37 *,
38 bot_token: str = "",
39 chat_id: str = "",
40 _send_fn: Callable[[str], bool] | None = None,
41 ) -> None:
42 self.bot_token = secret_env("TELEGRAM_BOT_TOKEN", bot_token)
43 self.chat_id = secret_env("TELEGRAM_CHAT_ID", chat_id)
44 self._send_fn = _send_fn
46 def send_message(self, text: str) -> bool:
47 """Send `text` to the configured chat. Never raises.
49 Returns True on success, False on any failure (missing
50 token/chat_id, network error, non-2xx response).
51 """
52 if self._send_fn is not None:
53 try:
54 return bool(self._send_fn(text))
55 except Exception as exc:
56 logger.warning("TelegramClient._send_fn failed: %s", redact(str(exc), [self.bot_token]))
57 return False
59 if not self.bot_token or not self.chat_id:
60 logger.warning("TelegramClient: missing bot_token/chat_id — message not sent.")
61 return False
63 try:
64 import requests # deferred — not always installed outside the telegram worker
66 response = requests.post(
67 _SEND_MESSAGE_URL.format(token=self.bot_token),
68 json={"chat_id": self.chat_id, "text": text},
69 timeout=_REQUEST_TIMEOUT_SECONDS,
70 )
71 if response.status_code >= 300:
72 logger.warning(
73 "TelegramClient.send_message: non-2xx response %d: %s",
74 response.status_code,
75 redact(response.text[:200], [self.bot_token]),
76 )
77 return False
78 return True
79 except Exception as exc:
80 # a requests error quotes the URL, and the URL holds the bot token
81 logger.warning("TelegramClient.send_message failed: %s", redact(str(exc), [self.bot_token]))
82 return False