Hachther Blog > Open Source  > Get notify by Telegram in case of error on your Django application

Get notify by Telegram in case of error on your Django application

As you already know (or not ) I am a fan of Django and I built a lot of my projects with it. Between other things, they have in good logging mechanism which allow you handle different kind and level of log. One of my project required to be able to notify a group of people in case on error. Django already have the ability to notify by email but email was not good enough. So I decided to implement a module which can notify but by using Telegram. The aim of this article is to explian how you can be notify by Telegram when error on your Django application.

To implement this, the key is to have an Telegram bot.

Telegam Bot

Telegram is a messaging application for all platform desktop and mobile. It is cloud based, fast, secure… and the essential thing for us is the fact that it is open and it allow developer to interact with it using API. In our case we will create a chat bot and use api to interact with it.

You can learn about Telegram bots and how to create them by follow this link. In case of any issue just left a comment or contact us it can be the subject of another article.

Once your bot is created you should have the token of you bot: something like this: 345725234:AADFFN31nk5uQ99HncL… store this token it will be used in the next parts.

Now let us go on Django and implement the notification.

Configure Django to send a Telegram message

If you had read about bot on Telegram you should know that a bot cannot initiate a conversation with a human. Human must to start the conversation in order to allow bot to start send messages to him.

Get a chat ID

You need to obtain a chat ID which is the identification of the conversation between a user and the bot. Then this ID will be used by Django in to sent message to the user. In order to do that, user must first search the bot in his Telegram contacts and once done he must click to the button start to initiate the conversation.

To capture you chat ID, sent a message in the chat (“Test” for example) then call this link https://api.telegram.org/bot[BOT_TOKEN]/getUpdates in your browser and you will have a output like the one below:

{
  "ok": true,
  "result": [
    {
      "update_id": 58256111,
      "message": {
        "message_id": 167,
        "from": {
          "id": 209871203,
          "is_bot": false,
          "first_name": "Daniel",
          "last_name": "De Vigny",
          "username": "devigny",
          "language_code": "en"
        },
        "chat": {
          "id": 209871203,
          "first_name": "Daniel",
          "last_name": "De Vigny",
          "username": "devigny",
          "type": "private"
        },
        "date": 1513775515,
        "text": "Test"
      }
    }
  ]
}

In the output you can get the chat ID from the value of the property id in the object chat (209871203).

Now we have our chat ID we can start to send messages.

Send error with telegram

Telegram already provide a REST Api which can be used to interact with your bot. So you can directly used it (find it here) or you can use a python telegram library which is the option we have used here.

The library we have used is telepot. to install it it si very simple: pip install telepot.

Once you installed you need now to configure your logging system to send error through telegram. Find below a sample of code to use to add or edit your Django settings.

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    ...
    'handlers': {
        ...
        'hlogging': {
            'level': 'ERROR',
            'class': 'hlogging.handlers.HLoggingHandler',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        ...
        'django.request': {
            'handlers': ['hlogging'],
            'level': 'ERROR',
            'propagate': False,
        },
    },
}

You can follow this docto see how you can more customize logging for your needs.But the most important thing here is the class in the hlogging handler (hlogging.handlers.HLoggingHandler). Because it where the code to send Telegram messages will be write.

Find below the code of HLoggingHandler:

import logging

from django.utils.module_loading import import_string
from django.views.debug import ExceptionReporter

class HLoggingHandler(logging.Handler):
    def __init__(self):
        logging.Handler.__init__(self)

    def emit(self, record):
        try:
            request = record.request
        except Exception:
            request = None

        if record.exc_info:
            exc_info = record.exc_info
        else:
            exc_info = (None, record.getMessage(), None)

        text = self.format(record)
        levelname = record.levelname
        for type in self.types:
            message = LoggingMessage(level=levelname, text=text, html=html)
            bot = telepot.Bot([BOT_TOKEN])
            bot.sendMessage([chat_id], text[:4095])

As you can se in the code above, you need to have the chat Id and the bot token and depending of the level you set in your logging configuration (in this case level ERROR) each time the application with log an ERROR event, this event will be sent by Telegram. So you can be instantly aware in case of issue on your application.

This is just a sample to explain the principle but in case you are interested you can clone this repository which is a Django module I developed for this purpose. You can even participate in the development to integrate other channels why not.

Thanks you for reading

Comments:
  • hermest
    December 21, 2017 at 12:35 am

    Good…
    someting else in wordpress?

Leave a reply