Building a Server Monitoring Telegram Bot Using Python and psutil

• 3 mnt baca

 

Building a Server Monitoring Telegram Bot Using Python and psutil

Maintaining the health of a server is a critical responsibility for any system administrator or developer. When a server's CPU maxes out or its memory overflows, the hosted applications inevitably crash, leading to downtime and frustrated users. Traditionally, server monitoring required logging into the terminal via SSH or setting up complex, resource-heavy dashboard software.

Today, there is a much more efficient and accessible approach: receiving real-time server health metrics directly on your smartphone. By combining the versatility of Python, the system-level access of the psutil library, and the instant messaging capabilities of Telegram, you can build a lightweight, automated monitoring bot in just a few minutes.

Telegram Bot Interface for Server Monitoring. Sumber: SOPA Images / SOPA Images/LightRocket via Getty Images

Why Choose Python and Telegram for Monitoring?

Building your own monitoring tool might sound complicated, but leveraging these specific technologies simplifies the process drastically while providing enterprise-level utility.

ComponentTechnical RoleKey Advantage
Telegram APINotification InterfaceExtremely fast delivery, requires no custom app development, and works seamlessly across mobile and desktop.
PythonLogic and ExecutionHighly readable syntax, allowing you to write the entire monitoring logic in under 50 lines of code.
psutil LibraryData ExtractionA cross-platform library that effortlessly reads real-time hardware data (CPU, RAM, Disk, Network) directly from the operating system kernel.

Step-by-Step Technical Implementation

Follow this structured guide to create, configure, and deploy your very own server monitoring bot. This guide assumes you have Python 3 installed on your Linux or Windows server.

1.Acquire the Bot Token from BotFather:Registering your application with Telegram.

Open your Telegram app and search for @BotFather (the official bot creation tool). Send the command /newbot and follow the prompts to choose a name and username for your bot. Once completed, BotFather will provide an HTTP API Token (a long string of characters). Copy this token and keep it secure; it is the unique key that allows your Python script to send messages through your bot.

2.Install Required Libraries:Preparing the Python environment.

Connect to your server's terminal. You need to install two external Python libraries: pyTelegramBotAPI (for interacting with Telegram) and psutil (for reading server hardware metrics).

Bash
pip install pyTelegramBotAPI psutil
3.Create the Python Script:Writing the extraction and messaging logic.

Create a new file named monitor_bot.py. This script will listen for a specific command (like /status) and respond with the current CPU, RAM, and Disk usage. Replace YOUR_BOT_TOKEN_HERE with the token you received from BotFather.

Python
import telebot
import psutil

# Initialize the bot
BOT_TOKEN = 'YOUR_BOT_TOKEN_HERE'
bot = telebot.TeleBot(BOT_TOKEN)

# Define the command handler
@bot.message_handler(commands=['status'])
def send_server_status(message):
    # Fetch hardware metrics
    cpu_usage = psutil.cpu_percent(interval=1)
    ram_info = psutil.virtual_memory()
    disk_info = psutil.disk_usage('/')

    # Format the response message
    status_text = (
        f"🖥️ **Server Health Status**\n\n"
        f"⚙️ **CPU Usage:** {cpu_usage}%\n"
        f"🧠 **RAM Usage:** {ram_info.percent}% ({ram_info.used // (1024**2)}MB / {ram_info.total // (1024**2)}MB)\n"
        f"💽 **Disk Usage:** {disk_info.percent}%"
    )
    
    # Send the message back to the user
    bot.reply_to(message, status_text)

# Start listening for messages
print("Bot is running...")
bot.polling()
4.Run the Script in the Background:Ensuring the bot remains active after you disconnect.

If you run the script normally, it will stop working as soon as you close your SSH terminal. To keep the bot running permanently in the background, use a process manager like PM2 or the built-in nohup command in Linux:

Bash
nohup python3 monitor_bot.py &

Now, open Telegram, find your bot, and type /status. The bot will instantly reply with the exact hardware utilization of your server.

Conclusion

Building a server monitoring Telegram bot using Python and psutil is an incredibly practical and cost-effective way to keep a watchful eye on your digital infrastructure. By routing hardware metrics directly to a messaging app you already use daily, you eliminate the need to constantly log into a server dashboard. This automated, instant-feedback loop empowers administrators to detect resource spikes early, perform necessary maintenance swiftly, and ensure that their web applications remain stable and highly available at all times.