As home servers, media nodes, self-hosted AI services, and remote home labs become essential infrastructure for tech enthusiasts and developers in 2026, real-time visibility into network health and ISP performance is critical. While complex enterprise monitoring suites like Zabbix or Prometheus offer extensive metrics, they often require heavy configuration and dedicated dashboards that aren't convenient to check on mobile devices. Enter Netmon Telegram Bot: a lightweight, self-hosted Python solution that delivers network uptime alerts, periodic speed tests, and latency trend charts directly to your phone via Telegram.
In this step-by-step guide, you will learn how to build, configure, and deploy a self-hosted Network Monitor & Speedtest Telegram bot using Python 3.11, Docker, python-telegram-bot v20+, speedtest-cli, and matplotlib. Whether you want to catch ISP throttling, detect Wi-Fi drops, or get instant alerts when your homelab goes offline, this tutorial has you covered.
You can deploy the Telegram Network Monitor bot in under 5 minutes using Docker Compose. Set your TELEGRAM_BOT_TOKEN and CHAT_ID in a .env file, then run docker compose up -d. To find curated bots and Telegram tools, check Telekit's Tech & AI Directory.
Why Self-Host a Telegram Network Monitor Bot in 2026?
Modern remote work and automated homelab setups rely heavily on stable internet connectivity. Having a push notification system on Telegram provides several distinct advantages over traditional email or web dashboards:
- Instant Offline Alerts: Get push notifications on your phone within seconds if your gateway ping drops or packet loss spikes.
- On-Demand Diagnostics: Execute
/speedtestor/pingdirectly inside Telegram chat to run instant bandwidth and latency tests anywhere in the world. - ISP Throttling Proof: Automatically generate weekly and monthly bandwidth charts using
matplotlibto hold your ISP accountable during service degradation. - Zero Port Forwarding Needed: Because Telegram bots use long-polling via HTTPS websockets to outbound Telegram servers, your bot runs securely behind CGNAT and firewalls without opening incoming router ports.
Prerequisites & System Requirements
Before proceeding with the installation, ensure your environment meets the following basic requirements:
- Host Machine: Raspberry Pi (3B+/4/5), any Linux VPS (Ubuntu/Debian), mini PC, or local Docker host.
- Docker & Docker Compose: Installed and running on the host system.
- Telegram Account: To register a bot via
@BotFatherand obtain your personal Chat ID. - Python 3.11+: (Required only if running directly without Docker).
System Architecture & Feature Specifications
The network monitoring bot operates as an asynchronous daemon process with two core engines:
Step 1: Create Your Telegram Bot via @BotFather
First, create a new bot token on Telegram:
- Open your Telegram app and search for
@BotFather. - Send the command
/newbot. - Provide a display name (e.g.,
My Homelab Netmon) and a unique username ending in_bot(e.g.,homelab_netmon_bot). - Copy the API token provided by BotFather (formatted as
123456789:ABCdefGHIjklmnOPQRstUVwxYZ). - Start a chat with your new bot and send any message (e.g.,
/start). - Retrieve your personal numeric Telegram
CHAT_IDusing@userinfobotor by visitinghttps://api.telegram.org/bot<YOUR_TOKEN>/getUpdates.
Step 2: Project Structure Setup
Create a dedicated workspace directory on your host machine:
mkdir -p ~/netmon-bot && cd ~/netmon-bot
touch main.py requirements.txt Dockerfile docker-compose.yml .env
Your project tree will look as follows:
netmon-bot/
├── main.py
├── requirements.txt
├── Dockerfile
├── docker-compose.yml
├── .env
└── netmon.db (generated at runtime)
Step 3: Configuration & Dependencies
Create the requirements.txt file to specify all required Python libraries:
python-telegram-bot>=20.0
speedtest-cli>=2.1.3
ping3>=4.0.4
matplotlib>=3.7.0
python-dotenv>=1.0.0
Next, populate your .env configuration file with your bot credentials and thresholds:
TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklmnOPQRstUVwxYZ
ALLOWED_CHAT_ID=987654321
TARGET_HOST=1.1.1.1
PING_INTERVAL_SECONDS=60
LATENCY_THRESHOLD_MS=150
SPEEDTEST_INTERVAL_HOURS=6
Step 4: Writing the Complete Python Application (main.py)
Below is the complete, fully production-ready Python code for main.py. It includes database initialization with SQLite, background task loops, command handlers, and graph generation with Matplotlib:
import os
import sys
import asyncio
import sqlite3
import datetime
import logging
from dotenv import load_dotenv
from ping3 import ping
import speedtest
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from telegram import Update
from telegram.ext import (
ApplicationBuilder,
CommandHandler,
ContextTypes,
)
# Load Environment Variables
load_dotenv()
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
ALLOWED_CHAT_ID = int(os.getenv("ALLOWED_CHAT_ID", "0"))
TARGET_HOST = os.getenv("TARGET_HOST", "1.1.1.1")
PING_INTERVAL = int(os.getenv("PING_INTERVAL_SECONDS", "60"))
LATENCY_THRESHOLD = float(os.getenv("LATENCY_THRESHOLD_MS", "150"))
SPEEDTEST_INTERVAL = int(os.getenv("SPEEDTEST_INTERVAL_HOURS", "6"))
DB_FILE = "netmon.db"
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO
)
logger = logging.getLogger(__name__)
# --- Database Initialization ---
def init_db():
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS speed_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
ping_ms REAL,
download_mbps REAL,
upload_mbps REAL
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS ping_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
latency_ms REAL,
status TEXT
)
''')
conn.commit()
conn.close()
def record_speed_test(ping_ms, download_mbps, upload_mbps):
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute(
"INSERT INTO speed_logs (ping_ms, download_mbps, upload_mbps) VALUES (?, ?, ?)",
(ping_ms, download_mbps, upload_mbps)
)
conn.commit()
conn.close()
def record_ping(latency_ms, status):
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute(
"INSERT INTO ping_logs (latency_ms, status) VALUES (?, ?)",
(latency_ms, status)
)
conn.commit()
conn.close()
# --- Helper: Generate Trend Graph ---
def generate_trend_chart():
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("SELECT timestamp, download_mbps, upload_mbps FROM speed_logs ORDER BY id DESC LIMIT 20")
rows = cursor.fetchall()
conn.close()
if not rows:
return None
rows.reverse()
timestamps = [r[0][11:16] for r in rows]
downloads = [r[1] for r in rows]
uploads = [r[2] for r in rows]
plt.figure(figsize=(9, 4.5), dpi=120)
plt.style.use('dark_background')
plt.plot(timestamps, downloads, marker='o', color='#38bdf8', label='Download (Mbps)', linewidth=2)
plt.plot(timestamps, uploads, marker='s', color='#a855f7', label='Upload (Mbps)', linewidth=2)
plt.title('Homelab Internet Bandwidth Trend (Last 20 Runs)', fontsize=12, color='#f8fafc', pad=12)
plt.xlabel('Time', fontsize=10, color='#94a3b8')
plt.ylabel('Speed (Mbps)', fontsize=10, color='#94a3b8')
plt.grid(True, linestyle='--', alpha=0.3)
plt.legend(loc='upper left')
plt.tight_layout()
chart_path = "bandwidth_trend.png"
plt.savefig(chart_path, dpi=120)
plt.close()
return chart_path
# --- Run Speed Test Logic ---
def execute_speedtest():
st = speedtest.Speedtest()
st.get_best_server()
download_bps = st.download()
upload_bps = st.upload()
results = st.results.dict()
download_mbps = round(download_bps / 1_000_000, 2)
upload_mbps = round(upload_bps / 1_000_000, 2)
ping_ms = round(results.get("ping", 0), 1)
record_speed_test(ping_ms, download_mbps, upload_mbps)
return ping_ms, download_mbps, upload_mbps
# --- Command Handlers ---
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.effective_chat.id != ALLOWED_CHAT_ID:
return
welcome_text = (
"⚡ Netmon Telegram Bot Operational
"
"Available Commands:
"
"• /status - Show live latency and last speedtest log
"
"• /speedtest - Run an on-demand speed test now
"
"• /graph - Generate and send bandwidth trend chart
"
"• /ping - Ping target host instantly"
)
await update.message.reply_html(welcome_text)
async def status_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.effective_chat.id != ALLOWED_CHAT_ID:
return
# Check live ping
response_time = ping(TARGET_HOST, timeout=2)
latency_str = f"{round(response_time * 1000, 1)} ms" if response_time else "OFFLINE ❌"
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("SELECT timestamp, download_mbps, upload_mbps, ping_ms FROM speed_logs ORDER BY id DESC LIMIT 1")
last_log = cursor.fetchone()
conn.close()
speed_info = "No test logged yet."
if last_log:
speed_info = (
f"📅 {last_log[0]}
"
f"⬇️ Download: {last_log[1]} Mbps
"
f"⬆️ Upload: {last_log[2]} Mbps
"
f"📶 Ping: {last_log[3]} ms"
)
msg = (
f"🌐 Network Health Status
"
f"• Target Host ({TARGET_HOST}): {latency_str}
"
f"📊 Latest Speed Test Result:
{speed_info}"
)
await update.message.reply_html(msg)
async def speedtest_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.effective_chat.id != ALLOWED_CHAT_ID:
return
status_msg = await update.message.reply_html("⏳ Running internet speed test... This takes ~30 seconds.")
loop = asyncio.get_event_loop()
try:
ping_ms, dl_mbps, ul_mbps = await loop.run_in_executor(None, execute_speedtest)
reply = (
f"✅ Speed Test Completed
"
f"⬇️ Download: {dl_mbps} Mbps
"
f"⬆️ Upload: {ul_mbps} Mbps
"
f"📶 Latency: {ping_ms} ms"
)
await status_msg.edit_text(reply, parse_mode="HTML")
except Exception as e:
await status_msg.edit_text(f"❌ Speed test failed: {e}")
async def graph_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.effective_chat.id != ALLOWED_CHAT_ID:
return
chart_path = generate_trend_chart()
if chart_path and os.path.exists(chart_path):
with open(chart_path, 'rb') as photo:
await update.message.reply_photo(photo=photo, caption="📈 Homelab Bandwidth Trend Chart", parse_mode="HTML")
else:
await update.message.reply_text("⚠️ Not enough data logged to generate a trend chart.")
# --- Background Monitoring Loop ---
async def background_latency_checker(app):
await asyncio.sleep(5)
while True:
try:
res = ping(TARGET_HOST, timeout=3)
if res is None:
record_ping(-1, "OFFLINE")
await app.bot.send_message(
chat_id=ALLOWED_CHAT_ID,
text=f"🚨 ALERT: Network Gateway Unreachable!
Target {TARGET_HOST} dropped ping packet.",
parse_mode="HTML"
)
else:
latency_ms = round(res * 1000, 1)
record_ping(latency_ms, "ONLINE")
if latency_ms > LATENCY_THRESHOLD:
await app.bot.send_message(
chat_id=ALLOWED_CHAT_ID,
text=f"⚠️ WARNING: High Latency Detected!
Ping to {TARGET_HOST} is {latency_ms} ms (Threshold: {LATENCY_THRESHOLD} ms).",
parse_mode="HTML"
)
except Exception as e:
logger.error(f"Error in ping monitor loop: {e}")
await asyncio.sleep(PING_INTERVAL)
def main():
init_db()
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(CommandHandler("start", start_command))
app.add_handler(CommandHandler("status", status_command))
app.add_handler(CommandHandler("speedtest", speedtest_command))
app.add_handler(CommandHandler("graph", graph_command))
loop = asyncio.get_event_loop()
loop.create_task(background_latency_checker(app))
logger.info("Netmon Telegram Bot started successfully.")
app.run_polling()
if __name__ == "__main__":
main()
Step 5: Containerizing with Docker & Docker Compose
Containerizing your bot ensures it restarts automatically on host reboots and isolates dependencies cleanly. Create the Dockerfile:
FROM python:3.11-slim
# Install system utilities for network diagnostic
RUN apt-get update && apt-get install -y --no-install-recommends iputils-ping curl && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py .
CMD ["python", "-u", "main.py"]
Now write the docker-compose.yml file:
version: '3.8'
services:
netmon-bot:
build: .
container_name: netmon-telegram-bot
restart: unless-stopped
env_file:
- .env
volumes:
- ./netmon.db:/app/netmon.db
- /etc/localtime:/etc/localtime:ro
network_mode: "host"
Step 6: Building and Launching the Service
With all configuration files in place, deploy your container using Docker Compose:
# Build and start container in detached background mode
docker compose up -d --build
# Check container running status
docker compose ps
# View live application logs
docker compose logs -f netmon-bot
Once started, test your bot inside Telegram by executing the /status and /speedtest commands. You will receive real-time latency responses and interactive bandwidth charts!
Security & E-E-A-T Best Practices for Homelab Bots
When connecting automated Python bots to your private home network, keep these security guidelines top of mind:
- Restrict Chat Access: Always enforce strict
ALLOWED_CHAT_IDchecks at the top of every command handler. Never allow open access to unknown Telegram accounts. - Avoid Arbitrary Shell Execution: Never hook
os.system()orsubprocessdirectly to user inputs in Telegram to prevent remote code execution vulnerabilities. - Use Environment Files: Never hardcode bot tokens in public Git repositories. Add
.envand*.dbto your.gitignore.
Frequently Asked Questions (FAQ)
Does running speed tests consume significant data?
Yes, running an internet speed test consumes between 50 MB to 200 MB of data per test, depending on your ISP speed. On capped internet connections, adjust SPEEDTEST_INTERVAL_HOURS to 12 or 24 hours to reduce data consumption.
Can I run this Telegram bot on a Raspberry Pi Zero?
Absolutely. The Python runtime and SQLite database overhead is minimal (~35 MB RAM). Ensure you use a fast MicroSD card or USB SSD for smooth SQLite database write operations.
Why is network_mode: "host" required in Docker?
Using host networking allows the ping module to send raw ICMP socket packets directly through your physical network interface without Docker NAT layer latency interference.
Where can I find more self-hosted Telegram tools?
You can explore curated developer tools, admin bots, and self-hosted agents on the Telekit Tech & AI Directory.
Conclusion
Setting up a self-hosted Network Monitor & Speedtest Telegram bot provides instant peace of mind for your homelab infrastructure. With simple Python code and Docker deployment, you get mobile-first network visibility, visual bandwidth trend analysis, and immediate outage alerts. Ready to discover more powerful Telegram tools and active tech channels? Explore Telekit's main directory today!