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…


This content originally appeared on DEV Community and was authored by Alin Climente

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'

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"
          }
        ]
      }
    }
  ]
}

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()

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.


This content originally appeared on DEV Community and was authored by Alin Climente


Print Share Comment Cite Upload Translate Updates
APA

Alin Climente | Sciencx (2024-06-16T12:54:29+00:00) Push notifications from server with Telegram Bot API. Retrieved from https://www.scien.cx/2024/06/16/push-notifications-from-server-with-telegram-bot-api/

MLA
" » Push notifications from server with Telegram Bot API." Alin Climente | Sciencx - Sunday June 16, 2024, https://www.scien.cx/2024/06/16/push-notifications-from-server-with-telegram-bot-api/
HARVARD
Alin Climente | Sciencx Sunday June 16, 2024 » Push notifications from server with Telegram Bot API., viewed ,<https://www.scien.cx/2024/06/16/push-notifications-from-server-with-telegram-bot-api/>
VANCOUVER
Alin Climente | Sciencx - » Push notifications from server with Telegram Bot API. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/16/push-notifications-from-server-with-telegram-bot-api/
CHICAGO
" » Push notifications from server with Telegram Bot API." Alin Climente | Sciencx - Accessed . https://www.scien.cx/2024/06/16/push-notifications-from-server-with-telegram-bot-api/
IEEE
" » Push notifications from server with Telegram Bot API." Alin Climente | Sciencx [Online]. Available: https://www.scien.cx/2024/06/16/push-notifications-from-server-with-telegram-bot-api/. [Accessed: ]
rf:citation
» Push notifications from server with Telegram Bot API | Alin Climente | Sciencx | https://www.scien.cx/2024/06/16/push-notifications-from-server-with-telegram-bot-api/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.