DEV Community

ScottsTechX
ScottsTechX

Posted on

How I Built a Telegram Bot That Monitors My Server in Real-Time

How I Built a Telegram Bot That Monitors My Server in Real-Time

Ever wished you could get instant alerts when your server goes down — straight to your phone? In this guide, I'll walk you through how I built a production-ready server monitoring Telegram bot that keeps you notified 24/7.

The Problem

When your server goes down, you need to know — immediately. Email alerts are too slow. Third-party monitoring services are expensive and overkill for small projects.

The Solution

A lightweight Telegram bot that pings your server every 30 seconds and alerts you the moment something goes wrong.

Tech Stack

  • Python 3.10+
  • python-telegram-bot library
  • psutil for system metrics
  • SQLite for logging

Key Features

  1. CPU/RAM Monitoring — Get alerts when resource usage exceeds thresholds
  2. Disk Space Warnings — Never run out of storage unexpectedly
  3. Service Health Checks — Monitor HTTP endpoints and custom ports
  4. Alert Routing — Different severity levels to different chat IDs
  5. Incident Logging — All events stored in SQLite for review

The Code

import telegram
import psutil
import time
from datetime import datetime

class ServerMonitor:
    def __init__(self, token, chat_id):
        self.bot = telegram.Bot(token=token)
        self.chat_id = chat_id
        self.thresholds = {
            "cpu": 80,
            "ram": 85,
            "disk": 90
        }

    async def check_system(self):
        cpu = psutil.cpu_percent(interval=1)
        ram = psutil.virtual_memory().percent
        disk = psutil.disk_usage("/").percent

        if cpu > self.thresholds["cpu"]:
            await self.send_alert(f"CPU alert: {cpu}%")
        if ram > self.thresholds["ram"]:
            await self.send_alert(f"RAM alert: {ram}%")
        if disk > self.thresholds["disk"]:
            await self.send_alert(f"Disk alert: {disk}%")

    async def send_alert(self, message):
        await self.bot.send_message(
            chat_id=self.chat_id,
            text=f"[{datetime.now()}] {message}"
        )

    def run(self, interval=30):
        while True:
            asyncio.run(self.check_system())
            time.sleep(interval)
Enter fullscreen mode Exit fullscreen mode

Setup Instructions

  1. Create a bot via @botfather on Telegram
  2. Get your chat ID using @userinfobot
  3. Install dependencies: pip install python-telegram-bot psutil
  4. Configure thresholds in the script
  5. Run with: python monitor.py &

Result

Instant alerts, zero monthly cost, full control over your infrastructure.

GitHub: github.com/fredscottsbulls
Website: scottechx.com

Top comments (0)