File size: 1,089 Bytes
851f3c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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}"