KeiruaProd

Sending yourself a notification with a Telegram bot

TL;DR: it’s easy to create a Telegram bot that can send yourself messages.

The context

I’ve been playing around the idea of automating a couple things recently, and one of the question was: how can I send myself notifications. When something happens (eg an ISS satellite will be visible, or more generally event x for which I have metrics is triggered), it may be interesting to have a notification on my smartphone.

Some options I considered:

The solution

We will:

Our small Telegram API client

In this minimalistic implementation we only need 2 endpoints. Yes it could be shorter, better or have better error handling, but that’s enough for a start.

# telegram_lib.py
import urllib.parse
import requests
import json

class TelegramBot:
    def __init__(self, bot_token, chat_id=None):
        self.bot_token = bot_token
        self.chat_id = chat_id

    def get_updates(self):
        url = f"https://api.telegram.org/bot{self.bot_token}/getUpdates"
        return json.loads(requests.get(url).content)

    def send_message(self, message):
        encoded_message = urllib.parse.quote_plus(message)
        url = f"https://api.telegram.org/bot{self.bot_token}/sendMessage?chat_id={self.chat_id}&parse_mode=Markdown&text={encoded_message}"
        return requests.get(url).status_code == 200

Creation of our bot

It will ask for a bot name and a username, and will reply with an access token that you should keep, and the telegram address of your bot.

{
    "ok": true,
    "result": [
        {
            "update_id": 1234,
            "message": {
                "message_id": 2,
                "from": {
                    "id": 123456,
                    "is_bot": false,
                    "first_name": "some first_name",
                    "language_code": "fr"
                },
                "chat": {
                    "id": 123456,
                    "first_name": "some first_name",
                    "type": "private"
                },
                "date": 1624625831,
                "text": "/start",
                "entities": [
                    {
                        "offset": 0,
                        "length": 6,
                        "type": "bot_command"
                    }
                ]
            }
        }
    ]
} 

You need the chat.id attribute. We can overengineer a program to extract this and test our API client:

# get_updates.py
from telegram_lib import TelegramBot
import json

bot = TelegramBot("your_token")

print(json.dumps(bot.get_updates()))

Lets run it and extract the message id with jq:

python get_updates.py | jq .result[0].message.chat.id
123456

Ok so 123456 is our chat id.

Sending messages to ourself through our bot

With the same logic it is possible to send a message:

# send_message.py
bot = TelegramBot("your_token", "your_conversation_id (eg 123456 we just found)")
bot.send_message("test !")

Now on my phone…

Going further

See a typo ? You can suggest a modification on Github.