DEV Community

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

Posted on

17

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (4)

Collapse
 
fyodorio profile image
Fyodor

Interesting… A couple of questions (if you will of course — sorry in advance if that’s inappropriate):

  1. What kind of identifier this chat id is here?
  2. Is it specific to a chat instance?
  3. Will it be the same if I open my Telegram acc from mobile and desktop?
  4. Is there a way to provide some authorization mechanism with this simple approach? Like if I want to give access to my server’s bot to my peer? Do I need to get the chat id from them as well?
Collapse
 
climentea profile image
Alin Climente • Edited

No worries.

  1. After you create the bot you need to "chat" with it -> a chat_id number will be created between you and the bot;
  2. yes, only between you and the bot -> others who will connect to the bot can't see what the bot sends (tested on 2 phones/accounts);
  3. Yes, same on desktop and mobile on same account;
  4. Yes, the bot token is recommended to be hidden under an apikey you can control (this is what I created for my sites: github.com/ClimenteA/telegram-push...). Not sure about multiple users for the same bot chat conversation. I didn't worked a lot on telegram bots - just enough to create what I needed. Checkout Telegram Channels.

Checkout this project: ntfy.sh/ (can do the same thing better and easier - I have not played with it yet.)

Good luck!

Collapse
 
intel89 profile image
Intel inside

I had a similar script running and since last week isn't working.. getting a connection error coming from the request module.. my guess is something changed on Telegram side (URL maybe..), by any chance are you having the same issue and/or do you know what changed?

Collapse
 
climentea profile image
Alin Climente

My script has now about 2 months since is running, no issues yet. I don't think something changed. Maybe your script was more complex than mine. Feel free to use it if it fits your needs: github.com/ClimenteA/telegram-push...

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay