📜 ⬆️ ⬇️

Monitoring the status of your resource using Telegram-bot

Hi, Habr! I have been watching you for a long time, but I still can’t decide to take my first step. Now it seemed to me that I was ready. I'll tell you about my experience of working with a telegram bot - recently this topic has been quite popular in the open spaces of the network, and I have already seen quite a few articles on Habré itself. But for the most part they tell about the principles of creating bots, and there is not a word about the practical benefits you can get from these same bots.

I had experience in creating systems for monitoring the status of servers, with the ability to set up testing strategies and sending short sms messages in order to inform about problems on one of the monitored servers, but all this is not quite convenient, as well as a fee - each message costs money.

What is a condition monitoring system? According to its architecture, it should be a small module that is responsible for checking the state and for informing about deviations from the normal state.

There are many ready-made integrated solutions that include such a monitoring system. This is the famous zabbix and nagios , yandex metric and a huge pile of similar beautiful tools.
')

Analytics


At the stage of creating a site, any developer using my local development server. But as soon as the project comes to a working condition, I immediately want to put it on the production server. And often this becomes a big mistake, because as soon as your site becomes available for Internet users, you will find yourself in the wonderful world of adventure and instead of developing you will start setting up. And here, perforce, again, the state control system is remembered. It is very convenient when you learn about any difficulties or problems immediately from your informant.

At first, any fresh site is of little interest to users. However, with sufficient effort or financial investment (usually both) traffic appears on the resource.

We have already placed the google analytics script in our code and can observe the dynamics of changes in our audience. But this is not always enough. Sometimes you want to know more - you want to control the whole process of finding a user on the site, to lead him, to direct. Analyzing the headers of requests and responses, you can get comprehensive information about what each user did, when and why. For this, sooner or later, you start reading the logs of your web server - sometimes there is a bug that will help you fix a serious bug, and sometimes it’s just interesting to know: who is spamming your guestbook?

Bot


Python and django are ideal for working with a telegram bot. What is a bot? In this context, a bot is an interaction interface between your application and a telegram client. This interface allows you to send messages depending on the business logic of your application.
I will not write here the whole process of creating and configuring a web application on django - whether I’d be able to do it better than the creators of the official documentation. I can only say that it should not take you more than ten minutes if you have already worked with this framework.

I would like to say thanks to Pavel Durov and his team - thanks to the ability to install webHook, it has become as easy and convenient to work with a bot. All that is needed is:


Then it all comes down to a simple scheme. As soon as your bot receives a message, a request with information about this message comes to the url set in webHook. In particular, there is information about the date of the message, about the sender's chat id, about the sender himself. It is better to save this information in the database in order not to accidentally lose it - you need to work with it. We program the bot in such a way that if it receives a message that is a command, it performs an action. Let's say I want the bot to send me a telegram message with information about each request that comes to my site. To do this, you need to ask him only two teams, for example

/ requests and / stop_requests . The first team will add a subscription to the database to send information about the requests to the site, the second team will remove this subscription. Next, you need to create your own context processor - this can be done in most modern MVC frameworks . In its code, it is necessary to process subscriptions to the newsletter and then send messages to the chat with the specified id, which we previously saved in the database, when we received a request to our webHook url . We can also subscribe to absolutely any events on our site: user registration (conveniently realized through signals), comments, errors. The scope for creativity is just bottomless. On my born2fish resource, where you can edit information about the rivers and lakes of the World, I used a bot to get information about when someone changed the nature of the reservoir. This helps to quickly receive messages about reservoirs that need to be checked by a moderator.

The sending of the message itself depends on the implementation. In python, it looks like this:

def _send_msg(bot, chat_id, message): bot.sendMessage(chat_id=chat_id, text=message) 

This is how the function of processing subscriptions and sending information about a request might look like:

 def send_requests_subscriptions(request, city): """ send Telegram messages to subscribed users """ bot_message = request.META['HTTP_USER_AGENT'] + " request from " + get_client_ip( request) + " (" + str(city['city']) + ") url = [" + request.path_info + "]" subscriptions = RequestsSubscription.objects.all() for subscr in subscriptions: _send_msg(bot=bot, chat_id=subscr.chat_id, message=bot_message) 

This method allows the user to display help, which is read from the help.md file:

 def _display_help(): return render_to_string('help.md') 

Instead of conclusion


In words, everything seems very simple, but I note that these bots are difficult to test. The optimal solution will be Unit Test, in which you will simulate a request from a telegram and check the operation of the bot's business logic.

What else might come in handy? The information in the telegram user profile is not always full, so you should check the values ​​for None before saving to the database in order not to get an IndexError .

You can add your bot to the group. This will help not to send information to each user, but to send it to a single place from where it will already be available to everyone. This can be done through the client interface of the telegram, in the settings of your bot and your group.
As an example, I want to share a link to my test bot: @ born2fishBot , Write to him / help to get a list of possible commands.

Telegram is a great application that opens up new horizons for programmers, administrators and even simple users. Using innovations, you can get a tangible benefit from the use of telegram bots, with very little time spent on development. Get all the latest information about the status of your web resource first. And let this news be only pleasant.

Source: https://habr.com/ru/post/316148/


All Articles