Python Python Free

Python: Send a Message with a Telegram Bot

Send yourself a Telegram message from Python — free alerts for scripts, servers and price trackers.

16 lines · Updated Nov 26, 2026

Preview of Python: Send a Message with a Telegram Bot
python-telegram-bot-message.py
import os
import requests

def send_telegram(message):
    token = os.environ["TELEGRAM_BOT_TOKEN"]
    chat_id = os.environ["TELEGRAM_CHAT_ID"]
    url = f"https://api.telegram.org/bot{token}/sendMessage"
    response = requests.post(url, json={
        "chat_id": chat_id,
        "text": message,
    }, timeout=15)
    response.raise_for_status()
    return response.json()

if __name__ == "__main__":
    send_telegram("Price alert: the laptop dropped to Rs 145,000!")

About this snippet

Telegram bots are the easiest way to get instant notifications on your phone from any script: a backup finished, a price dropped, a server went down, a new order arrived. This snippet sends a message through the Telegram Bot API with a single HTTP request in Python — no special library needed.

How it works

  1. Every bot has a secret token issued by Telegram's @BotFather.
  2. Every chat (you, a group or a channel) has a chat ID.
  3. The script sends a POST request to the Bot API's sendMessage method with the chat ID and the text, and checks the response.

Setup in 3 minutes

  1. Open Telegram, message @BotFather, send /newbot and follow the steps to get your token.
  2. Send any message to your new bot, then open https://api.telegram.org/bot<TOKEN>/getUpdates in a browser and copy the chat.id value.
  3. Save the token and chat ID as environment variables and run the script.

Ideas

  • Add it to the end of a backup script, a cron job or a scraper.
  • Use parse_mode HTML or Markdown for bold text and links.
  • Send to a group to notify a whole team; add the bot to the group first.

Common problems

  • "chat not found": you have not started a conversation with the bot yet, or the chat ID is wrong. Group IDs usually start with a minus sign.
  • 401 Unauthorized: the token is wrong or was revoked.
  • Messages stop under heavy use: Telegram rate-limits bots; batch notifications instead of sending hundreds per minute.

Security

Anyone with the token controls your bot. Never commit it to GitHub — keep it in an environment variable, and revoke it in BotFather if it leaks.

Related: Website change monitor · Retry with backoff

How to install

Create a bot with @BotFather on Telegram, start a chat with it, and get your chat id. Set TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID as environment variables — never hard-code the token.

Share this snippet

See all
Chat with us