DEV Community

Cover image for Push notifications from server with Telegram Bot API
Alin Climente
Alin Climente

Posted on

Push notifications from server with Telegram Bot API

I needed a way to keep myself updated with what happens on the server (new user signup, daily stats with visitors, new user send a message to me thru contact form etc.).

You can do that with just email, but you can also do it with the help of Telegram Bot API.

Install telegram on your phone. Once installed, search for BotFather - click start and then type /newbot (follow the steps there, save safely the private bot token for the api). After the new bot is created search it and start a conversation with it (this will help you get chat_id which we will need later).

After your first conversation with the bot get the chat_id:

curl -X GET 'https://api.telegram.org/botTOKEN:FROM-BOTFATHER/getUpdates'
Enter fullscreen mode Exit fullscreen mode

The response will look similar to this:

{
  "ok": true,
  "result": [
    {
      "update_id": 123123123123,
      "message": {
        "message_id": 124,
        "from": {
          "id": CHAT_ID,
          "is_bot": false,
          "first_name": "NAME",
          "last_name": "NAME",
          "language_code": "en"
        },
        "chat": {
          "id": "HERE-IS-CHAT_ID-YOU-NEED",
          "first_name": "NAME",
          "last_name": "NAME",
          "type": "private"
        },
        "date": 1718539209,
        "text": "/start",
        "entities": [
          {
            "offset": 0,
            "length": 6,
            "type": "bot_command"
          }
        ]
      }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Take chat_id value from: HERE-IS-CHAT_ID-YOU-NEED (see up).

Nice, now save CHAT_ID and TELEGRAM_API_TOKEN in .env file (or somewhere else just don't push it to a public repo).

Here is the code to send push notifications (messages from the server to your phone) at each 10 seconds.


import time
import requests
from config import cfg


def server_push_notifications():
    try:
        while True:
            url = f"https://api.telegram.org/bot{cfg.TELEGRAM_API_TOKEN}/sendMessage"
            response = requests.post(
                url=url,
                params={'chat_id': cfg.CHAT_ID, 'text': 'All system are ok.', 'parse_mode': 'Markdown'}
            )
            print(url, response.json())
            time.sleep(10)
    except KeyboardInterrupt:
        return 


if __name__ == "__main__":
    server_push_notifications()

Enter fullscreen mode Exit fullscreen mode

As you can see the base is just a POST request to telegram api with chat_id and text as body. What you send as a message is up to you.

For something more serious I would recommend using scheduler, but I don't see why a barebones while loop with a time.sleep won't do the same thing.

Top comments (0)