Post alerts on Telegram#
To create a Telegram channel:
Open Telegram and tap the menu icon.
Select “New Channel”.
Enter a name, description, and set the channel type (public/private).
Invite members if desired.
To create a Telegram bot:
Search for “BotFather” in Telegram.
Start a chat and send
/newbot.Follow the instructions to set a name and username for your bot.
BotFather will give you a token to access the HTTP API.
You can use this token to interact with your bot programmatically.
Obtain the chat ID#
Make the bot admin, adding it as @NAME_BOT
send a random message in the channel
run the folloeing cell to obtain the chat ID of the channel
import requests
def get_chat_id_by_name(bot_token, chat_name):
url = f"https://api.telegram.org/bot{bot_token}/getUpdates"
resp = requests.get(url)
if resp.status_code == 200:
updates = resp.json()
for result in updates.get("result", []):
# Check for channel_post
channel_post = result.get("channel_post")
if channel_post:
chat = channel_post.get("chat", {})
if chat.get("type") == "channel" and chat.get("title") == chat_name:
return chat.get("id")
# Check for message (optional, if you want to support private/group chats)
message = result.get("message")
if message:
chat = message.get("chat", {})
if chat.get("type") == "channel" and chat.get("title") == chat_name:
return chat.get("id")
return None
Define here the name of the channel#
Change channhel name and BOT_token accordingly
from credentials import load_credentials, get_credential
# Load credentials from credentials.txt
load_credentials()
channel_name = "acme_alerts"
BOT_TOKEN = get_credential('TELEGRAM_BOT_TOKEN') # From credentials.txt
get_chat_id_by_name(BOT_TOKEN, "acme_alerts")
CHAT_ID = get_chat_id_by_name(BOT_TOKEN, channel_name)
def post_telegram(file, message):
try:
with open(file, 'rb') as f:
requests.post(
f'https://api.telegram.org/bot{BOT_TOKEN}/sendDocument',
data={
'chat_id': CHAT_ID,
'caption': message,
'parse_mode': 'Markdown'
},
files={'document': f}
)
except Exception as e:
print(f"Error posting to Telegram: {e}")
# Example usage
#post_telegram('skymap.fits', 'New skymap received!')
# empty file
post_telegram('./bayestar.multiorder.fits,1', 'This is a test message without a file.')