opened image

How to create a Telegram bot for monitoring remote hosts

There are many software solutions for monitoring servers or network devices, many of which require server resources for deployment and knowledge of configuration. However, if you have one or more servers or a router with a public* IP, there is no need to deploy a complex monitoring structure just to check if the server or router is available. It is sufficient to create a simple Telegram bot that will send you a notification in Telegram if the checked IP is unavailable (down) and when it is available again (up). The bot will run 24/7 on a virtual server under the management of the Linux operating system, with minimal resource load.
* A public IP address is a unique IP address assigned to a device or server and accessible from the internet. Such an IP is public.

What needs to be done:
1. Create a bot and a private channel in Telegram, adding the bot to the channel. You can invite others to the channel who can also monitor the monitoring.
2. Install python3 on the server. In this article, we will consider deploying the bot on a virtual server with Ubuntu 20.04 (it can be deployed on any OS where the python3 package can be installed).
3. Create a script file, specify the IPs of the hosts (servers or routers), set the monitoring period, and run the script in 24/7 mode.

Let's get started.

1. To register a new Telegram bot, you need to find the bot service @BotFather in the Telegram app and send it the command to register a new bot
/newbot
Next, @BotFather will ask for a name for our bot. There are no restrictions on the name, let's enter, for example:
IP monitoring

Now you need to enter a unique name for the bot in the Telegram system. The bot's name must end with _bot. Let's name it, for example
ip_monitoring_super_bot

After that, @BotFather will provide us with a TOKEN, which can be used to manage the bot. The TOKEN must be saved, as we will need it later.

The Telegram bot is registered.

Now let's create a private channel where our new bot named @ip_monitoring_super_bot will send messages.

To do this, in the chat window of the Telegram app, click on the icon to create a new message and select New channel - Create channel - come up with a name for the channel (for example, IP monitoring channel) - choose the channel type Private and add the bot @ip_monitoring_super_bot.


As a result, we get a private channel where the bot @ip_monitoring_super_bot will send messages about the status of the equipment we are monitoring. You can also invite any Telegram user to this channel via a special link.
It is important to check the properties of the channel IP monitoring channel to see if the bot @ip_monitoring_super_bot has been added as an administrator of the channel. To go to the channel properties, simply click on the channel name.

We will also need the value of chat_id. To do this, you need to:
 - go to the bot chat @ip_monitoring_super_bot and send the message /start (this will start the bot)
 - send a test message (any) in the channel IP monitoring channel
 - go to the browser at the link https://api.telegram.org/botTOKEN/getUpdates
In our example, the link will look like this:
https://api.telegram.org/bot5921115541:AAHltzyZpC_MBZzydhrOD_Brn8lnKNf7XXX/getUpdates
The result on the screen will look like this:
So, let's remember 2 important values for managing the bot:
token= 5921115541:AAHltzyZpC_MBZzydhrOD_Brn8lnKNf7XXX
chat_id = -100185915XXX

2. Connect to the server via SSH (how to do this)

Check if python3 is installed:
python3 --version

If python3 is not installed (error: -bash: python3: command not found), it needs to be installed with the command
- for Ubuntu:
apt install python3 -y
- for CentOS
yum install python3 -y
Additionally, install the requests module:
pip3 install requests

After installation, you can check the version again. It may look approximately like this:

For more details on installing python3: How to install Python 3.10 on Ubuntu 20.04

3. Create a folder where the monitoring script will be placed. To do this, execute the command:
cd && mkdir pingmonitor && cd pingmonitor

Create and open the file
vim main.py

and place the script in it:

#----------------------------------------------------
import os
import requests
import time
#-------------------------
hostname = ['8.8.8.8','1.1.1.1']
time_pause = 30
#-------------------------
def SendMsgToTelegramChanel(msg):
    token="TOKEN"
    chat_id = 'CHAT_ID'
    params = {'chat_id': chat_id,'text': msg}
    response = requests.get('https://api.telegram.org/bot'+token+'/sendMessage', params=params)
def IsHostAlive(host):
    ret = os.system('ping -c 2 {} > /dev/null'.format(host))
    if ret == 0:
        return True
    return False
while True:
    for i in range(len(hostname)):
        file_signal = hostname[i] +'_down'
        if IsHostAlive(hostname[i]):
            if os.path.isfile(file_signal):
               os.remove(file_signal)
               SendMsgToTelegramChanel(hostname[i] + ' is up')
               #print(hostname + ' is up!')
        else:
            if not os.path.isfile(file_signal):
                open(file_signal,'tw').close()
                SendMsgToTelegramChanel(hostname[i] + ' is down')
                #print(hostname + ' is down!')
    time.sleep(time_pause)
#------------------------------------------------

- In the script, you should replace TOKEN and CHAT_ID with the previously saved values of token and chat_id.
- In the line hostname = ['8.8.8.8','1.1.1.1'], instead of IP 8.8.8.8 and 1.1.1.1, specify the IP (or hostname) of your server or router that needs to be monitored*. IP addresses of devices should be specified in single quotes and separated by commas (if there are more than one IP).
- The value of the variable time_pause = 30 indicates the check period (in seconds). It is not recommended to set it to less than 10-15 seconds, especially if the list of checked IPs is large.
- Do not remove the indentation of lines in the script. This may lead to a syntax error.

(*) The script uses the method of checking by sending ICMP packets (ping), for this reason, make sure that ping requests are not blocked on the server or router being monitored.

Now everything is ready to run the script.
Since the script should run 24/7, to prevent its operation from being displayed on the main console screen, we will run it in a separate "window" using the screen utility (if it is not installed, install it. More details: Basics of working with the screen utility).
To do this, execute the command:
screen -S pingmonitor

and go to the folder with the script file:
cd && cd pingmonitor

Run the script with the command:
python3 main.py

To exit the session and leave our script running, press Ctrl+a+d. Now the SSH console can be closed.
To reconnect to the session with the running script, connect to the server via SSH and execute the command:
screen -r pingmonitor

In case the server or router becomes unavailable and then becomes available again, you will receive a message in the channel IP monitoring channel.