-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotifier.py
More file actions
34 lines (24 loc) · 1022 Bytes
/
notifier.py
File metadata and controls
34 lines (24 loc) · 1022 Bytes
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
"""Lightweight Telegram notifier used by StockBot."""
from __future__ import annotations
import logging
import os
from urllib.error import URLError
from urllib.parse import urlencode
from urllib.request import urlopen
from dotenv import load_dotenv
load_dotenv()
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
LOGGER = logging.getLogger(__name__)
def send_telegram_message(text: str) -> None:
"""Send a message via the configured Telegram bot."""
if not BOT_TOKEN or not CHAT_ID:
LOGGER.warning("Telegram credentials not configured; message not sent.")
return
try:
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
data = urlencode({"chat_id": CHAT_ID, "text": text}).encode()
with urlopen(url, data=data, timeout=10):
LOGGER.debug("Telegram message dispatched")
except URLError as error: # pragma: no cover - network failure
LOGGER.warning("Unable to send Telegram message: %s", error)