| import os | |
| import requests | |
| def _get_env(): | |
| token = os.getenv("TELEGRAM_BOT_TOKEN", "").strip() | |
| chat_id = os.getenv("TELEGRAM_CHAT_ID", "").strip() | |
| enabled = bool(token and chat_id) | |
| return enabled, token, chat_id | |
| def send_telegram_message(text: str) -> tuple[bool, str]: | |
| """ | |
| Returns (ok, message) | |
| """ | |
| enabled, token, chat_id = _get_env() | |
| if not enabled: | |
| return False, "Telegram отключён: нет TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID в .env" | |
| url = f"https://api.telegram.org/bot{token}/sendMessage" | |
| payload = { | |
| "chat_id": chat_id, | |
| "text": text, | |
| "disable_web_page_preview": True | |
| } | |
| try: | |
| r = requests.post(url, json=payload, timeout=15) | |
| if r.status_code != 200: | |
| return False, f"Telegram error: HTTP {r.status_code} — {r.text}" | |
| data = r.json() | |
| if not data.get("ok"): | |
| return False, f"Telegram error: {data}" | |
| return True, "Отправлено в Telegram" | |
| except Exception as e: | |
| return False, f"Telegram exception: {e}" | |