Post alerts on Telegram

Post alerts on Telegram#

To create a Telegram channel:

  1. Open Telegram and tap the menu icon.

  2. Select “New Channel”.

  3. Enter a name, description, and set the channel type (public/private).

  4. Invite members if desired.

To create a Telegram bot:

  1. Search for “BotFather” in Telegram.

  2. Start a chat and send /newbot.

  3. Follow the instructions to set a name and username for your bot.

  4. 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#

  1. Make the bot admin, adding it as @NAME_BOT

  2. send a random message in the channel

  3. 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.')