z230
This commit is contained in:
35
TelegramMessaging.py
Normal file
35
TelegramMessaging.py
Normal file
@@ -0,0 +1,35 @@
|
||||
# TelegramMessaging.py
|
||||
import os
|
||||
import requests
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
|
||||
TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
|
||||
|
||||
def send_message(text: str) -> bool:
|
||||
"""
|
||||
Send a plain text message to a Telegram chat using a bot.
|
||||
Returns True on success, False otherwise.
|
||||
"""
|
||||
if not TELEGRAM_TOKEN or not TELEGRAM_CHAT_ID:
|
||||
print("TelegramMessaging: Missing TELEGRAM_TOKEN or TELEGRAM_CHAT_ID in environment.")
|
||||
return False
|
||||
|
||||
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
|
||||
payload = {
|
||||
"chat_id": TELEGRAM_CHAT_ID,
|
||||
"text": text
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.post(url, json=payload, timeout=10)
|
||||
if response.status_code == 200:
|
||||
return True
|
||||
else:
|
||||
print(f"TelegramMessaging: Telegram API returned {response.status_code}: {response.text}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"TelegramMessaging: Error sending message: {e}")
|
||||
return False
|
||||
Reference in New Issue
Block a user