Process monitoring with Python and Telegram
Keeping Watch

© Photo by David Taffet on Unsplash
A simple Python script checks to see if a process is running and, if not, notifies the user via Telegram.
Reliability is a crucial aspect of a computer system, especially for servers. Because continuous active monitoring isn't feasible, implementing mechanisms to alert the system administrator in case of a malfunction can be very useful. This article explores how to develop a simple tool that monitors the status of a process and sends a Telegram message in the event of a crash.
Prerequisites
To follow the development of this project, you'll need an integrated development environment enabled for Python programming and some basic knowledge of the Python language. On Ubuntu, it is possible to download VS Code from the App Center by simply finding the VS Code page in the App Center and clicking the Install button. If you prefer to proceed with the installation via the command line, the VS Code documentation provides all the necessary details for completing the procedure on various distributions [1]. I recommend installing the Pylance, Python, and Python Debugger extensions to make development easier. Simply click on the extensions button (on the left side), select the extension, and proceed with the installation.
In addition, you will need a Telegram account and the Telegram messaging application [2] installed on a smartphone or PC. For Ubuntu users, the application is available on the Snapstore. From the command line, you can install it with apt using the command
sudo apt install telegram-desktop
See the box entitled "Why Telegram?" for more on why I chose it for this task.
Why Telegram?
The choice to use Telegram for notifications comes from considering the available options, each with its strengths and disadvantages. The desirable characteristics of a notification system include freedom from third-party constraints, especially when it comes to for-profit companies; ease of use and implementation; and flexibility, meaning the ability to send notifications to both smartphones and desktop environments. A simple system involves sending a text string to a listening port on a device using an application such as Ncat [3], which is also available on smartphones. However, mobile devices often have dynamic IP addresses, which is inconvenient for this kind of implementation. Additionally, receiving a string does not automatically notify the user. Finally, for security reasons, you should set up a firewall to accept connections only from trusted sources, increasing the complexity of this approach. The Slack [4] platform is effective and quite easy to use. However, Slack requires registration for its various usage plans, only one of which is free. Additionally, with a tool like Slack, I would face the risk of future changes in the company's plans regarding service pricing and feature availability.
Email is widely supported by all kinds of devices and is free from third-party interference. However, to send emails requires a complex initial setup to support various formats and the different security standards adopted by servers. Alternatively, I could install an SMTP server on my own PC. A good candidate is Postfix [5], which is relatively simple to configure, free, and open source. However, installing an SMTP server for sending notifications seems inappropriate and too resource-intensive. The best compromise is therefore provided by Telegram, an application managed by a private company but currently free. A scenario in which Telegram becomes a paid service seems unlikely. Its configuration for our purpose requires just two instructions and a few lines of Python code. Moreover, Telegram works on various platforms, including Android and iPhone smartphones, as well as desktop environments.
Setting up a Telegram Bot
The first step is to create a Telegram bot, which you can control using a Python script to send notifications. After launching Telegram, access the search function by clicking on the appropriate icon at the top of the main screen. Search for the string BotFather
and select the corresponding entry. Then type the following commands:
/start /new bot
BotFather will guide you through the process of creating a new bot, prompting you to choose a name and a username for your bot. You will receive a token that you can use to interact with the bot via a script. At this point, I need to retrieve the user ID of the person to whom I will send the messages. I can use the Get Chat ID bot for this purpose. Just click on the User button and select the desired contact from the list. Make a note of the token and the user ID, which you will need to specify as parameters when running the script from the console.
Developing the Script
The monitoring script will check whether a process is running at user-defined intervals. If the application is running, the script prints a log string on the screen; otherwise, a warning message is sent to a specified user on Telegram.
The first step is to handle the application arguments, which include the token provided by Telegram, the user ID, the name of the process to monitor, and the time interval expressed in minutes (Listing 1).
Listing 1
Arguments
01 import requests 02 import time 03 from datetime import datetime 04 import psutil 05 import argparse 06 07 try: 08 parser=argparse.ArgumentParser() 09 parser.add_argument("token", help="Token assigned by Telegram when creating your Bot", type=str) 10 parser.add_argument("user_id",help="User ID on Telegram", type=str) 11 parser.add_argument("process_name",help="Name of the process to check for",type=str) 12 parser.add_argument("interval",help="Minutes of interval between checks",type=int) 13 args=parser.parse_args()
The essential part of the script consists of a loop that repeats as long as the process under examination is running (Listing 2). The boolean variable found
is set to False
at the beginning of the iteration. Then the script retrieves the list of active processes. If the process specified by the args.process_name
parameter is present in this list, the script prints an informative note to the screen with the current date and time. It then sets the variable found
to True
. At the end of each iteration, if the process is not active, the script outputs an alert string then sends the same message to the user specified by the args_user_id
parameter using the Telegram REST API. The application is then closed. The main function is enclosed in a try-except
block, and in case of an error, an informative message is displayed (Figure 1).
Listing 2
The Loop
01 while True: 02 found=False 03 for process in psutil.process_iter(): 04 if(process.name()==args.process_name): 05 print(args.process_name +" up and running at " +str(datetime.now())) 06 found=True 07 08 if(found==False): 09 message = "Process " +args.process_name + " is currently down" 10 print(message) 11 url = f"https://api.telegram.org/bot{args.token}/sendMessage?chat_id={args.user_id}&text={message}" 12 requests.get(url).json() 13 quit() 14 15 time.sleep(args.interval * 60) 16 17 except Exception as e: 18 print(f"Error {type(e)}")
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters
Support Our Work
Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.

News
-
Go-Based Botnet Attacking IoT Devices
Using an SSH credential brute-force attack, the Go-based PumaBot is exploiting IoT devices everywhere.
-
Plasma 6.5 Promises Better Memory Optimization
With the stable Plasma 6.4 on the horizon, KDE has a few new tricks up its sleeve for Plasma 6.5.
-
KaOS 2025.05 Officially Qt5 Free
If you're a fan of independent Linux distributions, the team behind KaOS is proud to announce the latest iteration that includes kernel 6.14 and KDE's Plasma 6.3.5.
-
Linux Kernel 6.15 Now Available
The latest Linux kernel is now available with several new features/improvements and the usual bug fixes.
-
Microsoft Makes Surprising WSL Announcement
In a move that might surprise some users, Microsoft has made Windows Subsystem for Linux open source.
-
Red Hat Releases RHEL 10 Early
Red Hat quietly rolled out the official release of RHEL 10.0 a bit early.
-
openSUSE Joins End of 10
openSUSE has decided to not only join the End of 10 movement but it also will no longer support the Deepin Desktop Environment.
-
New Version of Flatpak Released
Flatpak 1.16.1 is now available as the latest, stable version with various improvements.
-
IBM Announces Powerhouse Linux Server
IBM has unleashed a seriously powerful Linux server with the LinuxONE Emperor 5.
-
Plasma Ends LTS Releases
The KDE Plasma development team is doing away with the LTS releases for a good reason.