«Telegram» is a cross platform messenger that allows to exchange messages and media files of many formats. Besides a standard message exchange in dialogues and groups, it is possible to store the unlimited amount of files, to channel (to microblog), create and use bots in a messenger. Bots are third-party utilities that are launched inside the application «Telegram». In fact, these are accounts controlled by software, not people. It is possible to use programmed buttons of a virtual keyboard for work, using which a bot is turned into a mini-application with intuitively clear interface. Using a bot allows receiving actual information from sensors connected to NetPing server room environmental monitoring units and power distribution units for monitoring and remote control of a power supply in any time and any location.
In this article, we will examine the process of configuration of receiving notifications from sensors in Telegram.
Receiving Information about Triggering Sensors, Connected to UniPing server solution v3 or UniPing server solution v4/SMS on a Request
Required equipment, software and preparing for the development:
- UniPing server solution v3 or UniPing server solution v4/SMS server room monitoring unit (it is possible to use any model of a NetPing server room environmental monitoring unit and power distribution unit with certain details) – 1 pc.;
- PC or server with a preinstalled operational system Linux or Windows – 1 pc.;
- A local network for connecting a monitoring device and a PC, on which a script of a bot is executed – 1 pc.;
- «Telegram» messenger on a PC or a smartphone with the access to the Internet – 1 pc.;
- Python 3 and a packet manager – 1 pc.
UniPing server solution v3 server room monitoring unit is used in this part of the article that is configured for the work with temperature and humidity sensors, and dry contact sensors, that are connected to IO lines of a device. It is possible to learn more about the configurations of a device here.
A virtual machine with the installed OS Ubuntu 16.04.4 LTS is used as a server on which a script of our bot is run. The interpreter of a programming language Python 3.5.2 is installed in the system on default. Let's install a pip packet manager using a command sudo apt install python3-pip:
Registering a new bot
It is suggested that you already have an installed messenger «Telegram» with an active account.
There is a specific Telegram bot, @BotFather to create new bots. It is relatively simple to add this bot to a messenger. Choose @BotFather in the search of the application, afterwards a window of actions with a biot will open. In a window, there is a button "Start". There is a need to click this button, and then a dialogue mode will be activated. The entire process of creating a new bot will be implemented through communication with @BotFather.
Initiate a dialogue with @BotFather and request a list of available commands by a command «/start»:
Create a bot using a command «/newbot». Afterwards, @BotFather will ask you to choose a name:
Make up a name, type it and send it. If a name is not taken, then a bot will be created, and a user for a bot will be offered to create. A user can be with any name, but it must end in "bot", for example, NetPingBot or NetPing_bot. In our example, a name of a bot and a user is UniPingSSv3_bot:
After entering the name, a main part of creating a bot is finished. In this message, there will be a token (1) to access API «Telegram» that will be necessary later.
In addition, it is possible to indicate a list of supported functions that will be displayed in a dialogue window when entering the symbol «/». To do that, in a dialogue with @BotFather, there is a need to execute the next command «/setcommands» and follow the hints of the bot:
Programming a bot
Now there is a need to program a bot for necessary actions. We will execute this through the represented «Telegram» API using a script on a programming language Python 3. All operations are performed in a server console with the installed OS Ubuntu 16.04.4 LTS.
First, let's install necessary packages «pyTelegramBotAPI» and «requests» using commands «pip3 install pyTelegramBotAPI» and «pip3 install requests»:
Then, let's create a bot configuration file «conf_bot.py» using a command «nano conf_bot.py»:
With the next content:
# The token that the bot @ BotFather issued when registering a new bot
TOKEN = '565036931:AAEoKiDwA-GbNNGkE-KWYz4yRcKf8zwZtvM'# Login and password for UniPing Server Solution v3 / UniPing Server Solution v4/SMS
auth = ('visor', 'ping')# IP address of UniPing Server Solution v3 / UniPing Server Solution v4/SMS
url = 'http://192.168.1.200/'
Then, let's create a main file of our bot «bot.py» using a command «nano bot.py»:
The contents of the file is as follows:
import telebot import requests from telebot import types import conf_bot auth = conf_bot.auth url = conf_bot.url bot = telebot.TeleBot(conf_bot.TOKEN) # Command processing "/start" и "/help" @bot.message_handler(commands=['start', 'help']) def start(message): sent = bot.send_message(message.chat.id, '''*Test bot NetPing * This bot can request the actual data with sensors and IO lines of the NetPing device. To continue, use the command / npstatus''') # Processing of the command /npstatus, creation of the menu @bot.message_handler(commands=['npstatus']) def status(m): keyboard = types.InlineKeyboardMarkup() keyboard.add(*[types.InlineKeyboardButton(text=name, callback_data=name) for name in ['Temperature', 'Humidity', 'Status of the IO line' ]]) msg = bot.send_message(m.chat.id, ' Choose an option:', reply_markup=keyboard) # Processing of the command of pressing the button of the menu "Temperature" @bot.callback_query_handler(func=lambda c: True) def inline(c): if c.data =='Temperature': bot.edit_message_text( chat_id=c.message.chat.id, message_id=c.message.message_id, text='Current readings of the Thermal Sensors UniPing Server Solution v3', parse_mode='Markdown') i=1 while i <=8: def termo (): r = requests.get(url+'thermo.cgi?t'+str(i), auth=auth) t = r.text[20:22] s = r.text[-3] if s == '0': t = ('Sensor #' +str(i) + ' not connected or malfunctioning.') return t else: t= ('Current temperature on the temperature sensor #' + str(i) +': '+ t + ' degrees С' ) return t term = termo() sent = bot.send_message(c.message.chat.id, term ) i=i+1 # Processing the command to press the "Humidity" menu button elif c.data =='Humidity': bot.edit_message_text( chat_id=c.message.chat.id, message_id=c.message.message_id, text='Current readings of humidity sensors UniPing Server Solution v3', parse_mode='Markdown') i=1 while i <=4: def rel_hum (): r = requests.get(url+'relhum.cgi?h'+str(i), auth=auth) h = r.text[20:22] s = r.text[-3] if s == '0': h = ('Sensor #' +str(i) + ' not connected or malfunctioning.') return h else: h= ('Current relative humidity at the sensor #' + str(i) +': '+ h + ' %' ) return h hum = rel_hum() sent = bot.send_message(c.message.chat.id, hum ) i=i+1 # Processing of pressing the menu button "IO line status" elif c.data =='IO line status': bot.edit_message_text( chat_id=c.message.chat.id, message_id=c.message.message_id, text='''Current status of IO lines of UniPing Server Solution v3 (0 - off 1 - on)''', parse_mode='Markdown') i=1 while i <=8: def IO_line (): r = requests.get(url+'io.cgi?io'+str(i), auth=auth) io = r.text[20:21] if io == '0': io = ('The current state of the IO line #' + str(i) + ': ' + io + ' Off') return io else: io= ('The current state of the IO line #' + str(i) + ': ' + io + ' On') return io io_stat = IO_line() sent = bot.send_message(c.message.chat.id, io_stat ) i=i+1 bot.polling()
Now, let's execute a created file using a command : «python3 ./bot.py».
If there is nothing displayed in a console, and a terminal looks frozen, it means that we did everything correctly and our bot operates.
Source files of a bot can be downloaded here. To use them with another bot, specify your data in the file «conf_bot.py».
Working with a Bot
Do not close a terminal (leave it as it is), and open our bot in «Telegram» (using a login - in our example @UniPingSSv3_bot, or using a link from the message from @BotFather). Start a bot using a button «Start»:
And, get a greeting message with a description of a bot and possible commands:
Then, write a command «/npstatus» to a bot, and get an invitation to choose the interesting parameter:
Click a necessary button and get data from sensors or IO lines from UniPing server solution v3 server room monitoring unit. For the first example, a button «Humidity» was clicked:
To invoke a menu of selecting a parameter again, there is a need to send a command «/npstatus» to a bot one more time:
On the screenshots below are the results of requesting temperatures and IO lines statuses:
As a result of the actions described above, we will get a bot for a messenger «Telegram» that can request a NetPing device and receive the data on the status of sensors in any time and any location (if there is an access to the Internet network).
Automatic Receiving of the Information about Triggering Sensors that Are Connected to UniPing server solution v3 or UniPing server solution v4/SMS
In the example above, we examined receiving information about a status of sensors and IO lines per request. Then, we will consider an example of receiving information in «Telegram» from sensors and IO lines, connected to UniPing server solution v3 or UniPing server solution v4/SMS server room monitoring unit in the automatic mode with the use of a service «Zapier».
Required Equipment and Software
- UniPing server solution v3 or UniPing server solution v4/SMS server room monitoring unit (it is possible to use other models of NetPing server room environmental monitoring units and power distribution units as well, with certain slight differences) – 1 pc.;
- A PC with a preinstalled operating system Linux or Windows and an installed browser with the Internet access – 1 pc.;
- A local network – 1 pc.;
- A Telegram messenger on a PC or a smartphone with the Internet access – 1 pc.
Registration and Configuration of a New Bot
The first configuration step is about creating a new bot «Telegram». A procedure is alike the one described above in the section «Registering a new bot». A name of a new bot is UniPingSSv3_send_bot. A token for accessing the «Telegram» API will be necessary later:
Then, there is a need to add a service bot @ChatFuel to «Telegram», using which we will add advanced features to our new bot that allows @UniPingSSv3_send_bot receive messages from the «Zapier» service. In a search box, type @Chatfuel, select @chatfuel_bot from the offered variants and start a dialogue by clicking the button «Start»:
Then, follow the link from a message sent by a bot @Chatfuel for installing @UniPingSSv3_send_bot the add-on «Chatfuel»:
After following the link, click the button «Start»:
And click the button «New bot» in a window that appears:
Then, in the field for entering a message, indicate a token that we received earlier from @BotFather when creating our bot @UniPingSSv3_send_bot.
After entering a token, we get a notification about a successful installation of the add-on for our bot. Add a bot to a contact list (if it is not added yet) by clicking the link:
And start it by the button «Start»:
Then, follow to the section of controlling out bot, with the aim to create a unique key that is necessary to link a bot to the system «Zapier». Send commands «/chatfuel» and «/botkey» to a bot:
Configuring Zapier
Then, go to the system «Zapier». To do this, in any convenient browser, open the website «https://zapier.com/». When using it for the first time, there is a need to register a new account (if you have the account, then you can skip this step). To register a new account, click the button «Sign Up»:
It is possible to get authorized using a Google account or indicate data for a manual registration:
After registration and authorization, we can create an automatic action, so-called «Zap» that will send a message to our Telegram-bot when registering events on UniPing server solution v3 or UniPing server solution v4/SMS server room monitoring unit. To do this, click the button «Make a Zap!»:
Then, select a trigger application (when triggered «Zap» will be executed). We will need to receive Webhook notification from UniPing server solution v3 or UniPing server solution v4/SMS server room monitoring unit about triggering sensors and changing statuses of IO lines.
Then, select a type of a Webhook, as on the screenshot, and click the button «Save +Continue» to continue to the next configuration step:
On the next step, we leave everything on default and click the button «Continue» to continue the configuration:
On the next step, a unique link will be created that will be used for transferring Webhook to «Zap». Click the button «Copy» in the field with a link:
Now, we will put aside «Zapier» for some time and follow to a web interface of our monitoring device, for example, UniPing server solution v4/SMS. Here, we need to configure the adjusted notification. To create the adjusted notification, there is a need to go to the page «NOTIFICATION» of a device web interface and click the line «click here to add new record»:
On this step, create a notification about exceeding the upper threshold of a normal temperature on a temperature sensor 1:
To do this, let's specify the next parameters:
Enable Notification – activate a checkbox;
Sensor – let's choose from the list «Termo» and «1»;
Event – activate a checkbox «Above Safe»;
Notification Method – choose «HTTP GET» from the list;
URL – in this field, specify a unique link to «Zap» that we copied earlier, and write a message after a space. The text of a notification can include the information from the MIB branch that is related to a sensor, an IO line or a relay that caused the event. Format: {N}, where N - is a component of SNMP OID that stands before the index of a sensor (more detailed information can be read here and here). In our message, {2} is used – OID .1.3.6.1.4.1.25728.8800.1.1.2.n - Current temperature on a temperature sensor, where n – is a sensor number. Unfortunately, Cyrillic letters are not supported by the system «Zapier».
Click «Apply changes». Then, follow to the page «TEMPERATURE» and artificially cause triggering the event «Temperature is above safe», by setting the upper threshold smaller than the current values of the temperature on the sensor:
Click the button «Apply changes», and go back to «Zapier», and click the button «Ok, I did this»:
If the parameters of out UniPing server solution v4/SMS server room monitoring unit are configured properly, then on the next step, we will receive the incoming Webhook notification. At this point, the configuration of a trigger is completed. To go to the parameters «Actions», click the button «Continue»:
On the next screen, select the Application-Action for our «Zap». Enter «Chatfuel for Telegram» in a search box and select it from the list of variants:
Then, select the action type that will be performed by the application «Chatfuel for Telegram» when a trigger operates, and click the button «Save +Continue»:
The next step requires linking the account of our Telegram bot to the «Zapier» system. Click the button «Connect an Account», and in a pop-up window that opens, specify a unique key that was previously obtained from our bot @UniPingSSv3_send_bot using a command «/botkey»:
Confirm the change by clicking the buttons «Yes, Continue» and «Save+Continue».
Then. the system will offer to specify the text of a message that will be sent to our Telegram bot. Click the button in the right upper corner of the field «Message», and select «Full Webhook Message» from the list. To follow to the next step of the configuration, click the button «Continue».
During the next step, the work of our «Zap» will be tested. Click the button «Send Test to Chatfuel for Telegram»:
And, if the test is completed successfully, we will receive the message about it in the «Zapier» system and a telegram message. Finish the process of creating a «Zap» by clicking the button «Finish».
Afterwards, we will be offered to name our «Zap» and launch it for execution. We will write the name of the «Zap» in a text box (we have NetPing Message), and move the execution switch in the position «ON»:
Afterwards, we will get a message that our «Zap» works.
At this point, the configuration of the system «Zapier» for sending the message from UniPing server solution v4/SMS server room monitoring unit to «Telegram» can be considered completed.
Configuring UniPing server solution v4/SMS
Let's go back to a web interface of UniPing server solution v4/SMS server room monitoring unit, and add important notifications for monitoring sensors. Parameters are configured the same as the parameters for a temperature sensor that have been described in the section of the «Zapier» configuration. After creating new customizable notifications on UniPing server solution v4/SMS server room monitoring unit, there is no need to change the configurations of the «Zapier» service. New messages will be automatically "picked up".
As a result of all configurations described above, in the moment of changing statuses of sensors connected to our monitoring device, the next notifications will be sent to «Telegram»: