Maintaining high server uptime and monitoring containerized applications are critical duties for system administrators, DevOps engineers, and self-hosting enthusiasts. In 2026, relying solely on heavy web-based monitoring dashboards like Grafana or complex enterprise suites can often introduce unnecessary overhead and security vectors for lightweight VPS instances. Instead, receiving immediate, actionable notifications on your mobile device through a secure messaging platform has become the standard for modern server infrastructure monitoring.
Telegram provides a robust, zero-latency delivery network with built-in end-to-end transport encryption, making it an ideal real-time alerting system. By combining Python 3, Aiogram 3 (an asynchronous Telegram Bot framework), psutil, and the official Docker SDK for Python, you can deploy a customized, lightweight monitoring bot that tracks system metrics (CPU, RAM, disk space, network I/O), inspects running Docker containers, sends automated alert notifications when thresholds are breached, and allows remote container restarts straight from your Telegram chat.
To build a self-hosted Telegram server monitoring bot, you need a Linux server (Ubuntu 22.04/24.04 recommended), Python 3.10+, Docker installed with socket permissions, and a Telegram Bot token from @BotFather. To browse top developer tools and bot templates, explore Telekit's Tech & Coding Directory.
Why Build a Custom Telegram Monitoring Bot in 2026?
While standalone solutions such as Uptime Kuma or netdata offer full web UIs, building a custom Python Telegram bot offers several distinct architectural advantages for self-hosted environments:
- Zero Inbound Firewall Exposure: Telegram bots use long-polling or secure outgoing webhook transport. Your server does not need to open public inbound HTTP ports or expose management UIs to the internet.
- Instant Push Alerts & Rich Media: Receive push notifications directly to your phone, smartwatch, or desktop client with real-time performance graphs generated using
matplotlib. - Interactive Remote Control: Execute secure administrative commands—such as restarting a failed Docker container or pulling log snippets—directly from your verified Telegram account.
- Minimal Resource Footprint: The Python daemon consumes under 40 MB of RAM and negligible CPU cycles, making it suitable for $4/month VPS instances.
Architecture Overview & Component Diagram
The monitoring architecture consists of a persistent background daemon running on your Linux host. The script listens for Telegram updates via asynchronous polling, communicates directly with the local Docker daemon via the UNIX socket (/var/run/docker.sock), and polls system statistics using Linux kernel APIs wrapped by psutil.
Step 1: Obtain Bot Token & Admin Chat ID
Before creating the Python application, you must register a new bot with Telegram's official BotFather and retrieve your personal Telegram user ID to restrict bot access exclusively to your account.
- Open Telegram and start a chat with
@BotFather. - Send the command
/newbotand follow the prompts to specify a name and username (e.g.,MyServerMonitorBot). - Copy the HTTP API Token provided by BotFather (formatted as
123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ). - To find your user ID, start a chat with
@userinfobot. Note the integer ID returned (e.g.,987654321).
Step 2: Server Environment & Dependency Setup
SSH into your Linux server and create a dedicated project directory. We will set up a isolated Python virtual environment and install aiogram 3, psutil, docker, and matplotlib.
# Create directory and enter it
mkdir -p /opt/tg-server-monitor && cd /opt/tg-server-monitor
# Create Python virtual environment
python3 -m venv venv
source venv/bin/activate
# Upgrade pip and install core dependencies
pip install --upgrade pip
pip install aiogram docker psutil matplotlib python-dotenv
Step 3: Write the Configuration File (.env)
Create a .env file to securely store your token, admin user ID, and monitoring thresholds:
# /opt/tg-server-monitor/.env
TELEGRAM_BOT_TOKEN=123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ
ADMIN_CHAT_ID=987654321
CPU_THRESHOLD=85
RAM_THRESHOLD=90
DISK_THRESHOLD=90
CHECK_INTERVAL_SECONDS=60
Step 4: Implementation of the Monitoring Bot (main.py)
Now create main.py. This complete script initializes the Aiogram 3 bot, registers admin-only filters, executes Docker status checks, generates metric graphs, and runs an asynchronous background loop for continuous threshold alerting.
import asyncio
import io
import logging
import os
import docker
import psutil
import matplotlib.pyplot as plt
from dotenv import load_dotenv
from aiogram import Bot, Dispatcher, types
from aiogram.filters import Command
from aiogram.types import BufferedInputFile
# Load environment configuration
load_dotenv()
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
ADMIN_CHAT_ID = int(os.getenv("ADMIN_CHAT_ID", "0"))
CPU_THRESHOLD = float(os.getenv("CPU_THRESHOLD", "85"))
RAM_THRESHOLD = float(os.getenv("RAM_THRESHOLD", "90"))
DISK_THRESHOLD = float(os.getenv("DISK_THRESHOLD", "90"))
CHECK_INTERVAL = int(os.getenv("CHECK_INTERVAL_SECONDS", "60"))
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
bot = Bot(token=BOT_TOKEN)
dp = Dispatcher()
# Initialize Docker client with error handling
try:
docker_client = docker.from_env()
except Exception as err:
logging.warning(f"Could not connect to Docker socket: {err}")
docker_client = None
def is_admin(user_id: int) -> bool:
return user_id == ADMIN_CHAT_ID
@dp.message(Command("start"))
async def cmd_start(message: types.Message):
if not is_admin(message.from_user.id):
await message.answer("⚠️ Unauthorized access denied.")
return
await message.answer(
"🖥️ Server & Docker Sentinel Bot
"
"Available Commands:
"
"• /stats - Live CPU, RAM, Disk & Network Usage
"
"• /chart - Generate system metric visualization
"
"• /containers - List Docker container status
"
"• /restart <name> - Restart a Docker container
"
"• /logs <name> - Tail container logs",
parse_mode="HTML"
)
@dp.message(Command("stats"))
async def cmd_stats(message: types.Message):
if not is_admin(message.from_user.id):
return
cpu = psutil.cpu_percent(interval=1)
ram = psutil.virtual_memory()
disk = psutil.disk_usage('/')
net = psutil.net_io_counters()
text = (
"📊 Current Server Metrics
"
f"CPU Usage: {cpu}%
"
f"RAM Usage: {ram.percent}% ({ram.used // (1024**2)} MB / {ram.total // (1024**2)} MB)
"
f"Disk Usage: {disk.percent}% ({disk.used // (1024**3)} GB / {disk.total // (1024**3)} GB)
"
f"Network Sent: {net.bytes_sent // (1024**2)} MB
"
f"Network Recv: {net.bytes_recv // (1024**2)} MB"
)
await message.answer(text, parse_mode="HTML")
@dp.message(Command("chart"))
async def cmd_chart(message: types.Message):
if not is_admin(message.from_user.id):
return
status_msg = await message.answer("⏳ Generating performance chart...")
cpu = psutil.cpu_percent(interval=1)
ram = psutil.virtual_memory().percent
disk = psutil.disk_usage('/').percent
swap = psutil.swap_memory().percent
categories = ['CPU', 'RAM', 'Disk', 'Swap']
values = [cpu, ram, disk, swap]
colors = ['#0284c7', '#10b981', '#f59e0b', '#ef4444']
fig, ax = plt.subplots(figsize=(6, 4))
bars = ax.bar(categories, values, color=colors)
ax.set_ylim(0, 100)
ax.set_ylabel('Usage (%)')
ax.set_title('Live System Metrics', fontsize=12, fontweight='bold')
for bar in bars:
height = bar.get_height()
ax.annotate(f'{height:.1f}%',
xy=(bar.get_x() + bar.get_width() / 2, height),
xytext=(0, 3), textcoords="offset points",
ha='center', va='bottom', fontweight='bold')
buf = io.BytesIO()
plt.tight_layout()
plt.savefig(buf, format='png', dpi=120)
buf.seek(0)
plt.close(fig)
await status_msg.delete()
photo = BufferedInputFile(buf.getvalue(), filename="metrics.png")
await message.answer_photo(photo, caption="📈 Live System Utilization Chart", parse_mode="HTML")
@dp.message(Command("containers"))
async def cmd_containers(message: types.Message):
if not is_admin(message.from_user.id):
return
if not docker_client:
await message.answer("❌ Docker client is not available on this host.")
return
try:
containers = docker_client.containers.list(all=True)
if not containers:
await message.answer("ℹ️ No containers found.")
return
lines = ["🐳 Docker Containers Overview:
"]
for c in containers:
status_icon = "🟢" if c.status == "running" else "🔴"
lines.append(f"{status_icon} {c.name} ({c.status}) - {c.short_id}")
await message.answer("
".join(lines), parse_mode="HTML")
except Exception as err:
await message.answer(f"❌ Error querying Docker: {err}")
@dp.message(Command("restart"))
async def cmd_restart(message: types.Message):
if not is_admin(message.from_user.id):
return
args = message.text.split(maxsplit=1)
if len(args) < 2:
await message.answer("⚠️ Usage: /restart <container_name>", parse_mode="HTML")
return
container_name = args[1].strip()
try:
container = docker_client.containers.get(container_name)
await message.answer(f"⏳ Restarting container {container_name}...", parse_mode="HTML")
container.restart()
await message.answer(f"✅ Container {container_name} restarted successfully!", parse_mode="HTML")
except Exception as err:
await message.answer(f"❌ Failed to restart {container_name}: {err}", parse_mode="HTML")
# Continuous Background Monitor Task
async def background_monitoring_loop():
while True:
try:
cpu = psutil.cpu_percent(interval=1)
ram = psutil.virtual_memory().percent
disk = psutil.disk_usage('/').percent
alerts = []
if cpu > CPU_THRESHOLD:
alerts.append(f"🚨 HIGH CPU ALERT: Current usage is {cpu}% (Threshold: {CPU_THRESHOLD}%)")
if ram > RAM_THRESHOLD:
alerts.append(f"🚨 HIGH RAM ALERT: Current usage is {ram}% (Threshold: {RAM_THRESHOLD}%)")
if disk > DISK_THRESHOLD:
alerts.append(f"🚨 HIGH DISK ALERT: Current usage is {disk}% (Threshold: {DISK_THRESHOLD}%)")
if alerts:
alert_text = "
".join(alerts)
await bot.send_message(chat_id=ADMIN_CHAT_ID, text=alert_text, parse_mode="HTML")
except Exception as err:
logging.error(f"Error in background monitor: {err}")
await asyncio.sleep(CHECK_INTERVAL)
async def main():
logging.info("Starting Telegram Server Monitor Bot...")
asyncio.create_task(background_monitoring_loop())
await dp.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())
Step 5: Run as a Production 24/7 Systemd Daemon
To ensure your monitoring script runs continuously, restarts automatically on server reboots, and recovers from unexpected exceptions, configure it as a Linux systemd service.
Create the service file /etc/systemd/system/tg-monitor.service:
[Unit]
Description=Telegram Server & Docker Monitor Bot
After=network.target docker.service
Requires=docker.service
[Service]
Type=simple
User=root
WorkingDirectory=/opt/tg-server-monitor
ExecStart=/opt/tg-server-monitor/venv/bin/python main.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
Reload systemd, enable the service, and verify its live execution status:
# Reload systemd configuration
sudo systemctl daemon-reload
# Enable service on boot and start immediately
sudo systemctl enable --now tg-monitor
# Check live service status and output logs
sudo systemctl status tg-monitor
sudo journalctl -u tg-monitor -f -n 50
Security & Hardening Best Practices
Because a Telegram monitoring bot possesses high-privilege access to server diagnostics and container execution controls, implementing strict security controls is essential:
- Enforce Admin ID Filtering: Never omit user validation checks. Ensure every command handler verifies
message.from_user.id == ADMIN_CHAT_IDbefore executing code. - Restrict Docker Socket Access: Avoid exposing the Docker TCP port (
2375) over the network. Access the Docker daemon strictly through the local UNIX socket (/var/run/docker.sock). - Store Tokens in Environment Variables: Never hardcode API keys or chat IDs directly inside source files. Keep your
.envfile permissions locked usingchmod 600 .env. - Set Up Rate Limits: Implement basic message throttling to prevent rapid command spamming from flooding your server's CPU or memory.
Frequently Asked Questions (FAQ)
Can I monitor multiple Linux servers with a single Telegram Bot?
Yes. You can deploy the monitoring daemon on multiple VPS nodes using the same Telegram Bot token. To distinguish notifications, add a SERVER_NAME environment variable to your .env file and prepend it to all alert messages (e.g., [VPS-US-East] HIGH CPU ALERT).
Why use Aiogram 3 instead of python-telegram-bot?
Aiogram 3 is built natively around Python's asyncio architecture. It delivers superior performance, lower RAM footprint, and cleaner asynchronous middleware integration, making it ideal for non-blocking I/O tasks like monitoring background services and Docker APIs simultaneously.
How do I fix Docker permission errors when running without root?
If running the service under a non-root user, add that user to the system docker group using sudo usermod -aG docker $USER, then restart the system session or service.
Does this monitoring bot consume heavy server resources?
No. The Python script runs as an asynchronous event loop that sleeps between check intervals. Total memory consumption is typically under 40 MB, and CPU utilization stays well below 0.5% during background checks.
Conclusion
Building your own self-hosted Telegram server and Docker monitoring bot gives you full visibility and administrative control over your cloud infrastructure without sacrificing privacy or opening inbound firewall vulnerabilities. With immediate push alerts, automated threshold monitoring, and direct container restart capability, you can catch service outages before your users notice. Ready to discover more advanced Telegram automation bots, scripts, and developer channels? Explore Telekit's Tech & Coding Directory today!