paint-brush
From Python to Telegram: Build your own Notification Systemby@beranzor
15,778 reads
15,778 reads

From Python to Telegram: Build your own Notification System

by Anzor BerezgovJanuary 10th, 2022
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

Learn how to send messages from python script to Telegram chat.
featured image - From Python to Telegram: Build your own Notification System
Anzor Berezgov HackerNoon profile picture


Sometimes it is useful to make your python script able to send some kind of notifications directly to a user’s mobile phone or to a developer (maybe yourself). It can be a kind of logging, or notifying that some job was done, or an error report.


The most popular, free, stable, and flawless tool to add software notifications to your phone is Telegram messenger. At the moment of writing this article Telegram has more than 1 billion downloads and about 500 million active users per month.


In this tutorial, I will show step by step how to add Telegram notifications with 25 lines of code and no extra libraries for your project, except for two basic libraries: requests and json, which are almost standard for python.


If you already have a Telegram account - feel free to move to step 2.

Otherwise, you should have an account in Telegram Messenger. So let’s learn how to get that account.

Step 1. Creating a Telegram account

Telegram is available at all well-known platforms like iOS, Android, Linux, Windows, macOS.  It is better to have the telegram app on a mobile device because our goal is to receive notifications wherever we are.

Choose an appropriate version of telegram at https://telegram.org/  and install it on your mobile device.


Right after launching, Telegram will suggest you register an account using a mobile phone number. You should have one, or you can register an account without having your own number, but using a temporary number provided by a service. Maybe I will write a tutorial about it.

Next, we should register a bot. If you know how to do that, or already have a bot, just skip this step...


Step 2. Registering a Bot

Open the Telegram app, push the search icon on the top-right corner and enter BotFather.

You should see a screen like this:

Searching for BotFather


Notice an icon of a white checkmark in blue surroundings to the right of BotFather. It means that the account is not fake.


Select the BotFather account and push the START button to start chatting with BotFather.

Initial window before starting BotFather bot


Notice an icon of a white checkmark in blue surroundings to the right of BotFather. It means that the account is not fake.


Select the BotFather account and push the START button to start chatting with BotFather.

Interacting with BotFather


Congratulations on your new bot.

BotFather sends you a token to let you access the HTTP API. Copy it for further use. It is private information that allows full control of your Bot. Store it carefully.

Find your Bot using a search bar and open a chat with your Bot. Click start.



Step 3. Copy this function to your python code


import requests
import json

def send_telegram_message(message: str,
                          chat_id: str,
                          api_key: str,
                          proxy_username: str = None,
                          proxy_password: str = None,
		  proxy_url: str = None):
    responses = {}

    proxies = None
    if proxy_url is not None:
        proxies = {
            'https': f'http://{username}:{password}@{proxy_url}',
            'http': f'http://{username}:{password}@{proxy_url}'
        }
        headers = {'Content-Type': 'application/json',
                   'Proxy-Authorization': 'Basic base64'}
        data_dict = {'chat_id': chat_id,
                     'text': message,
                     'parse_mode': 'HTML',
                     'disable_notification': True}
        data = json.dumps(data_dict)
        url = f'https://api.telegram.org/bot{api_key}/sendMessage'
        response = requests.post(url,
                                 data=data,
                                 headers=headers,
                                 proxies=proxies,
                                 verify=False)
        return response


That is it.

Now you can send notifications to Telegram by calling the send_telegram_message  function.

Step 4. Using a Proxy

Proxy URL, username and password are usually not necessary, and if it is required these data can be provided by a system administrator of your network. Usually, proxy URLs for https and http are the same. If not - this function can be slightly modified to fit new requirements by adding a new set of parameters for HTTPS URL.

Step 5. How to get a chat_id

It can be tricky to find out how to get a chat_id for sending messages to.

But the solution is simple: just use @username_to_id_bot  or other similar bots (there are many bots in telegram ready to help you).

This bot will send you your ID which can be used as a parameter in the send_telegram_message function.


Finally, let’s test how it works.

Add these lines to your code:

chat_id = "<fill your chat id here>"
api_key = "<fill api key of your bot here>"

send_telegram_message("Hello world!!!", chat_id, api_key)


It’s done!