You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
1.8 KiB
Python
54 lines
1.8 KiB
Python
"""Telegram notification client — sends messages via Bot API."""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from typing import Optional
|
|
|
|
from loguru import logger
|
|
|
|
TELEGRAM_API_URL = "https://api.telegram.org/bot{token}/sendMessage"
|
|
MAX_TEXT_LENGTH = 4096 # Telegram message limit
|
|
|
|
|
|
class TelegramClient:
|
|
def __init__(
|
|
self,
|
|
bot_token: Optional[str] = None,
|
|
chat_id: Optional[str] = None,
|
|
):
|
|
self.bot_token = bot_token or os.environ.get("TELEGRAM_BOT_TOKEN", "")
|
|
self.chat_id = chat_id or os.environ.get("TELEGRAM_CHAT_ID", "")
|
|
|
|
def is_configured(self) -> bool:
|
|
return bool(self.bot_token and self.chat_id)
|
|
|
|
def send_message(self, text: str) -> bool:
|
|
"""Send a message to the configured chat. Returns True on success."""
|
|
if not self.is_configured():
|
|
logger.warning("Telegram not configured (missing BOT_TOKEN or CHAT_ID)")
|
|
return False
|
|
|
|
if len(text) > MAX_TEXT_LENGTH:
|
|
text = text[: MAX_TEXT_LENGTH - 20] + "\n\n[...truncated]"
|
|
|
|
try:
|
|
import httpx
|
|
response = httpx.post(
|
|
TELEGRAM_API_URL.format(token=self.bot_token),
|
|
json={
|
|
"chat_id": self.chat_id,
|
|
"text": text,
|
|
"parse_mode": "HTML",
|
|
},
|
|
timeout=15.0,
|
|
)
|
|
if response.status_code == 200 and response.json().get("ok"):
|
|
logger.info("Telegram message sent successfully")
|
|
return True
|
|
else:
|
|
logger.error(f"Telegram API error: {response.text[:200]}")
|
|
return False
|
|
except Exception as e:
|
|
logger.error(f"Telegram send failed: {e}")
|
|
return False
|