Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code: Skills Get Started
FAQ’s Sections
Linux Security Virtual Servers

Build Your Own Telegram Bot to Monitor IPv4 Blacklists on a VPS

Keeping your IP address off spam blacklists is critical for email deliverability, service reputation, and uninterrupted operations. Whether you run a mail server, a SaaS platform, or a web application, a single blacklist entry can silently block your outbound emails and erode customer trust overnight. In this comprehensive guide, you will learn how to build and deploy a fully functional Telegram bot that automatically checks any IPv4 address against major spam databases — all running on a reliable VPS.

Why Automate IPv4 Blacklist Monitoring?

Manual blacklist checks are tedious and easy to forget. By automating the process through a Telegram bot, you get:

  • Instant on-demand checks — query any IP directly from your phone or desktop
  • Real-time feedback — results delivered inside Telegram within seconds
  • Zero infrastructure overhead — the bot runs persistently on your server in the background
  • Scalability — extend the bot later with scheduled alerts, webhook integrations, or multi-IP batch checks

An IP listed on databases such as Spamhaus, SpamCop, StopForumSpam, or Blocklist.de can cause email delivery failures, service suspensions, and reputational damage. Proactive monitoring is far cheaper than reactive damage control.

Why Deploy on an AlexHost VPS?

Running a Telegram bot requires a server that stays online 24/7, responds quickly, and provides full root access for installing custom dependencies. AlexHost VPS Hosting delivers exactly that — NVMe SSD storage for fast I/O, enterprise-grade DDoS protection, and full root access so you can install Python, Selenium, browser drivers, and any other tooling without restrictions.

Unlike shared environments where resource limits can throttle your bot's performance, a dedicated VPS gives your application consistent CPU and RAM allocation. If you prefer a managed control panel experience, VPS with cPanel is also available, making server management accessible even for those less comfortable with the command line.

Prerequisites

Before writing a single line of code, ensure the following are in place on your server:

System Requirements

RequirementMinimum Version
Python3.7 or higher
pipLatest stable
Google ChromeLatest stable
ChromeDriverMatching Chrome version
OSUbuntu 20.04+ / Debian 11+

Install Python Libraries

Connect to your VPS via SSH and run the following commands to install the required Python packages:

pip install selenium
pip install aiogram==3.4.1
  • Selenium — automates browser interactions to scrape blacklist check results from MXToolbox
  • aiogram 3.4.1 — a modern, async-first Python framework for the Telegram Bot API

Install Google Chrome and ChromeDriver (Headless)

Selenium requires a real browser to render JavaScript-heavy pages. Install Chrome in headless mode on your Linux server:

# Install dependencies
sudo apt update
sudo apt install -y wget curl unzip fonts-liberation libappindicator3-1 libasound2 
  libatk-bridge2.0-0 libatk1.0-0 libcups2 libdbus-1-3 libgdk-pixbuf2.0-0 
  libnspr4 libnss3 libx11-xcb1 libxcomposite1 libxdamage1 libxrandr2 
  xdg-utils libgbm1

# Download and install Chrome
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome-stable_current_amd64.deb
sudo apt --fix-broken install -y

# Verify installation
google-chrome --version

Then install the matching ChromeDriver:

# Get your Chrome version number first
CHROME_VERSION=$(google-chrome --version | grep -oP 'd+.d+.d+.d+')
CHROME_MAJOR=$(echo $CHROME_VERSION | cut -d. -f1)

# Download matching ChromeDriver
wget "https://chromedriver.storage.googleapis.com/LATEST_RELEASE_${CHROME_MAJOR}" -O latest_release
DRIVER_VERSION=$(cat latest_release)
wget "https://chromedriver.storage.googleapis.com/${DRIVER_VERSION}/chromedriver_linux64.zip"
unzip chromedriver_linux64.zip
sudo mv chromedriver /usr/local/bin/
sudo chmod +x /usr/local/bin/chromedriver

Step 1 — Create Your Telegram Bot with BotFather

Every Telegram bot starts with BotFather — the official Telegram bot for registering and managing bots.

1.1 Open Telegram and search for @BotFather (look for the verified blue checkmark).

1.2 Start a conversation and send the command:

/newbot

1.3 Follow the prompts:

  • Enter a display name for your bot (e.g., IP Blacklist Monitor)
  • Enter a unique username ending in bot (e.g., ip_blacklist_monitor_bot)

1.4 BotFather will respond with a confirmation message similar to:

Done! Congratulations on your new bot.
You will find it at t.me/ip_blacklist_monitor_bot.

Use this token to access the HTTP API:
7123456789:AAFxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Keep your token secure and store it safely — it can be used by anyone to control your bot.

Copy and save this API token securely. You will need it in the next step. Never commit it to a public repository.

Step 2 — Write the Bot Code

On your VPS, create a new Python file:

nano ~/my_bot.py

Paste the following complete, production-ready code:

import asyncio
import time
from aiogram import Bot, Dispatcher, F
from aiogram.filters import CommandStart
from aiogram.types import Message
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

# ─── Configuration ────────────────────────────────────────────────────────────
BOT_TOKEN = 'YOUR_BOT_TOKEN_HERE'  # Replace with your BotFather token
# ──────────────────────────────────────────────────────────────────────────────

bot = Bot(BOT_TOKEN)
dp = Dispatcher()

def get_chrome_driver():
    """Initialize a headless Chrome driver for server environments."""
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--window-size=1920,1080')
    return webdriver.Chrome(options=chrome_options)

def get_results(ip: str) -> list:
    """
    Use Selenium to check an IPv4 address against blacklists via MXToolbox.
    Returns a list of [status, blacklist_name] pairs.
    """
    results = []
    driver = get_chrome_driver()

    try:
        # Navigate to MXToolbox blacklist checker
        url = f"https://mxtoolbox.com/SuperTool.aspx?action=blacklist%3a{ip}&run=toolpage"
        driver.get(url)
        time.sleep(6)  # Allow the page and results to fully load

        # Locate the IP input field and submit the query
        input_field = driver.find_element(By.NAME, 'ctl00$ContentPlaceHolder1$txtInput2')
        input_field.clear()
        input_field.send_keys(ip)
        time.sleep(3)

        search_button = driver.find_element(By.ID, 'btnAction3')
        search_button.click()
        time.sleep(6)  # Wait for results to render

        # Scrape up to 60 status and name columns
        status_results = driver.find_elements(By.CLASS_NAME, 'table-column-Status')[:60]
        name_results = driver.find_elements(By.CLASS_NAME, 'table-column-Name')[:60]

        if len(status_results) == len(name_results):
            for status, name in zip(status_results, name_results):
                results.append([status.text, name.text])
        else:
            print(f"[WARNING] Status/name count mismatch for IP: {ip}")

    except Exception as e:
        print(f"[ERROR] Failed to retrieve results for {ip}: {e}")
    finally:
        driver.quit()

    return results

@dp.message(CommandStart())
async def handle_start(message: Message):
    """Handle the /start command — greet the user and explain usage."""
    await message.answer(
        f"👋 Hello, {message.from_user.first_name}!nn"
        f"Send me any IPv4 address and I will check it against major spam blacklists.nn"
        f"Example: <code>192.168.1.1</code>",
        parse_mode="HTML"
    )

@dp.message(F.text)
async def handle_ip_check(message: Message):
    """Receive an IP address, run the blacklist check, and return formatted results."""
    ip = message.text.strip()
    await message.answer(f"🔍 Checking <code>{ip}</code> against blacklists. Please wait...", parse_mode="HTML")

    loop = asyncio.get_event_loop()
    # Run the blocking Selenium call in a thread pool to avoid blocking the event loop
    raw_results = await loop.run_in_executor(None, get_results, ip)

    if not raw_results:
        await message.answer("⚠️ No results returned. Please verify the IP address and try again.")
        return

    output_lines = []
    blacklisted_count = 0

    for status, name in raw_results:
        if status.strip().upper() == 'OK':
            output_lines.append(f"✅ {name}")
        else:
            output_lines.append(f"❌ {name}")
            blacklisted_count += 1

    summary = f"📊 <b>Results for {ip}</b>n"
    summary += f"🚫 Listed on {blacklisted_count} blacklist(s)nn"
    summary += "n".join(output_lines)

    # Telegram messages have a 4096-character limit — split if necessary
    if len(summary) > 4096:
        for i in range(0, len(summary), 4096):
            await message.answer(summary[i:i+4096], parse_mode="HTML")
    else:
        await message.answer(summary, parse_mode="HTML")

async def main():
    print("✅ Bot is running. Listening for messages...")
    await dp.start_polling(bot)

if __name__ == '__main__':
    asyncio.run(main())

Save and exit (Ctrl+O, Enter, Ctrl+X in nano).

Step 3 — Configure the Bot Token Securely

Replace YOUR_BOT_TOKEN_HERE in the script with the token you received from BotFather. For production deployments, it is strongly recommended to use an environment variable instead of hardcoding the token:

export TELEGRAM_BOT_TOKEN="7123456789:AAFxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

Then update the code line to:

import os
BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN')

This prevents accidental token exposure if your code is ever shared or version-controlled.

Step 4 — Run the Bot as a Background Service

To keep the bot running persistently after you close your SSH session, set it up as a systemd service:

sudo nano /etc/systemd/system/ipblacklist-bot.service

Paste the following configuration:

[Unit]
Description=IPv4 Blacklist Monitor Telegram Bot
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/root
ExecStart=/usr/bin/python3 /root/my_bot.py
Restart=on-failure
RestartSec=10
Environment="TELEGRAM_BOT_TOKEN=YOUR_BOT_TOKEN_HERE"

[Install]
WantedBy=multi-user.target

Enable and start the service:

sudo systemctl daemon-reload
sudo systemctl enable ipblacklist-bot
sudo systemctl start ipblacklist-bot

# Verify it is running
sudo systemctl status ipblacklist-bot

Your bot will now automatically restart if it crashes and will start on every server reboot.

Step 5 — Test the Bot

  1. Open Telegram and search for your bot by its username
  2. Send /start — you should receive the welcome message
  3. Send any IPv4 address (e.g., 8.8.8.8)
  4. Within 15–20 seconds, you will receive a formatted list showing which blacklists the IP is listed on (❌) and which it passed (✅)

Code Architecture Overview

ComponentRole
aiogramAsync Telegram Bot API framework — handles message routing and polling
Selenium + ChromeHeadless browser that renders and scrapes MXToolbox results
get_chrome_driver()Configures Chrome for headless server operation
get_results(ip)Core scraping function — navigates MXToolbox and extracts status data
handle_start()Responds to /start with usage instructions
handle_ip_check()Receives IP input, runs the check asynchronously, returns formatted output
run_in_executor()Offloads the blocking Selenium call to a thread pool, keeping the async loop responsive
systemd serviceEnsures the bot runs persistently and restarts automatically on failure

Security and Compliance Considerations

Running a bot that interacts with external services from a VPS comes with responsibilities:

  • Protect your bot token — treat it like a password. Rotate it immediately via BotFather if compromised.
  • Validate user input — add IP address format validation before passing user input to Selenium to prevent unexpected behavior.
  • Rate limiting — consider adding per-user rate limits to prevent abuse of your bot and your server's resources.
  • Keep dependencies updated — regularly update aiogram, selenium, and Chrome to patch security vulnerabilities.
  • Firewall your VPS — restrict inbound ports to only what is necessary (SSH, and your bot's outbound connections).

If your infrastructure also handles email, pairing this bot with a properly secured mail environment is essential. AlexHost Email Hosting provides a managed, spam-policy-compliant environment that reduces the risk of your sending IPs appearing on blacklists in the first place.

For projects that require an SSL-secured domain alongside your bot infrastructure, AlexHost SSL Certificates and Domain Registration make it straightforward to establish a fully trusted web presence.

AlexHost's Spam and Blacklist Policy

AlexHost enforces a strict no-spam policy across its entire network. Any activity that results in IP blacklisting — including bulk unsolicited email, forum spam, or abuse flagged by Spamhaus, SpamCop, StopForumSpam, Blocklist.de, or similar databases — is strictly prohibited. Services found in violation are promptly suspended to protect the integrity of the shared network infrastructure and the reputation of all customers.

This makes proactive monitoring with a tool like the bot described in this guide not just useful, but essential for responsible server operation.

Extending the Bot — Ideas for Future Development

Once your basic bot is running, consider these enhancements:

  • Scheduled monitoring — use apscheduler to automatically check your server IPs every 6 or 24 hours and alert you only when a new listing is detected
  • Multi-IP batch checks — accept a comma-separated list of IPs in a single message
  • Persistent logging — store check results in a SQLite or PostgreSQL database for historical trend analysis
  • Webhook mode — switch from long polling to webhooks for lower latency and reduced server load
  • Additional data sources — integrate APIs from AbuseIPDB or Spamhaus directly for more authoritative results without browser automation

Conclusion

Building a Telegram bot to monitor IPv4 blacklists is a practical, high-value automation project that any systems administrator or developer can complete in an afternoon. With Python, aiogram, and Selenium running on an AlexHost VPS, you get a persistent, responsive monitoring tool that delivers results directly to your Telegram client — no dashboards to check, no manual lookups required.

Proactive IP reputation management protects your email deliverability, your customers' trust, and your service's uptime. Deploy this bot today, keep your dependencies updated, and extend it over time as your monitoring needs grow.