Creating my own notification system with Telegram

5 min
Creating my own notification system with Telegram

COVID Vaccines Twitter bot

Twitter bot that reports daily on the status of vaccination against COVID-19 in Spain.

PythonTwitter API

Every time I developed a new application, every time I launched a new bot, every time I deployed a system, the same thing always came to mind. How can I get feedback on what’s going on? Not just what people are thinking, but how it’s working or if there are any issues with the application that requires manual intervention.

Researching about this, I discovered several platforms that partially solved this, although it was not as flexible as I wanted. In addition, many of these services require monthly fees designed for big companies.

As with many other things in life, the solution is much further from the original focus than we expect. Complex problems sometimes require simple solutions.

This is one of those cases where having range, as David Epstein calls it in his book, allows you to apply knowledge from other areas to solve problems you had in mind. In this case, I have used Telegram bots to develop a system that allows me to update in real-time the status of many of my applications with notifications that push me directly on my phone. Totally free, easy to implement and as flexible as you want it to be.

Let’s start

The idea is…

  • Create a new bot via @botfather.
  • Get the bot token
  • Open a conversation with the bot (by default, if you haven’t started a conversation with a bot, it can’t write to you. This avoids spam)
  • Get the chat ID
  • Make requests from our system, application or script

The idea is simple and this process will not take more than 10 minutes, but it’s important to follow this tutorial step by step. One wrong step and you will spend hours looking for what the hell went wrong.

Create the bot and get the token

To start creating it we will have to go to the bots father bot, never better said. There is a bot in Telegram where we can manage all our bots. You can find it as @botfather on Telegram. Once we start the conversation, we must send the command /newbot and add the name and username that will allow us to differentiate it from the rest (this username must end in bot).

create-bot-token.png

Once this is done, the bot will be created and a message will appear with all the information we need about it. Among this information, we have the token, which you should store and not share with anyone.

Start a conversation and get the chat ID

If you want to send a notification from a bot, you need two things: the bot token and the chat ID we want to send a notification. The first one we already have, so let’s see what is the ID of our conversation.

We start a conversation with our bot. We can do this by using the link that appears in the creation confirmation message or by searching our boy in Telegram by the username we have assigned to it.

Once this is done, we will access the page with all the updates that our bot has received. We open any browser and access the following page:

https://api.telegram.org/bot[token]/getUpdates

You will have to change [token] for your bot token. In my case, the URL will look like this: https://api.telegram.org/bot1725563685:AAGQNBsLvzA-ssf0QsqNQ9K3BUIB1NVnbJ8/getUpdates

getting-chat-id-min.png

Once you access this address, you will see a JSON file with an array of a single object (if you have sent only one message, of course). Inside this object, there is another object called chat. If you open the chat object, you will see the id property. Save it!

Order in the room!

Flexibility is a double-edged sword. Telegram bots offer a wide range of possibilities, therefore, it’s necessary to design guidelines and rules.

In this case, we are not going to need an ISO standard to mark the rules of this notification system. Let’s be honest, it’s just a notification system. But keeping order in doing things will avoid future complications (avoiding chaos).

In this case, I have decided that the notifications are composed of three elements:

  • Emoji to indicate the type of notification.
  • Title in bold indicating the system or application from which it has been sent.
  • Details

Not all notifications are the same, let’s think for a moment what happens when we pick up our cell phone in the morning. Our brain categorizes the notifications. Some are critical and require immediate action, others warn of a potential problem and others are just informative.

For that same reason, I have divided the notifications into four categories, which with the correct formatting, the messages would look like this:

Info notification

ℹ️ **App 1**

It has been three days since you last updated the DB data.

Success notification

✅ **App 2**

The scheduled tweet has been successfully published

Warning notification

⚠️ **App 3**

No new data to be obtained.

Error notification

❌ **App 4**

Could not get the CSV file from the server. Invalid URL format.

Now, you can start implementing your notification system in applications. If you are curious and have already started looking for how to make the bot work, you will realize that it’s quite simple. Let’s see some practical examples in the next section.

Implement our notification system

Now, with the bot token and the chat id, we can implement the notification system. We have to make a GET request to the following address:

https://api.telegram.org/bot[token]/sendMessage?chat_id[chatId]&parse_mode=Markdown&text=[msg]

Where [token] is the bot token, [chatId] is the chat identifier and [msg] is the message we want to send.

To check that everything works, we can run a curl from our terminal:

curl 'https://api.telegram.org/bot1725563685:AAGQNBsLvzA-ssf0QsqNQ9K3BUIB1NVnbJ8/sendMessage?chat_id=123456789&parse_mode=Markdown&text=helloWorld'

If everything is well, we will receive a notification from our Telegram bot. But we are not interested in executing this kind of commands from the terminal. Unless you are programming a bash script, you will most likely want to execute that request using some programming language. On Python, for example, you can use the following function:

def sendNotification(notification, emoji):
 bot_token = '1725563685:AAGQNBsLvzA-ssf0QsqNQ9K3BUIB1NVnbJ8'
 bot_chatID = '123456789'
 msg = emoji + ' *Vaccines COVID Twitter bot*'+notification
 send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + msg
 response = requests.get(send_text)
 return response.json()

sendNotification('Message sent successfully', '✅')

Many programming languages have HTTP request libraries. JavaScript, for example, have API fetch natively. However, if you want to make it easier, there are modules developed by the community to send request, although due to the simplicity of the API offered by Telegram, I do not see much sense.

Messages can be sent in both Markdown and HTML format. I think Markdown is much faster and simpler, although I recommend take a look at the documentation of this format. If you choose HTML, you will have to change the parse_mode attribute of the HTTP request.