Tech & AI Verified Editorial

How to Build a Self-Hosted Telegram Auto-Forwarder & Channel Filter Bot with Python (2026)

In 2026, Telegram has solidified its position as the world's leading real-time news, crypto, and developer messaging hub. However, for community managers, crypto signal traders, news aggregators, and developers, keeping track of dozens of high-velocity public and private Telegram channels presents a major information overload challenge. Manually reading, filtering, and copying relevant updates from multiple source channels into a centralized destination group is inefficient and prone to latency.

Building a self-hosted Telegram auto-forwarder and channel filter bot is the ultimate technical solution. By leveraging Python and the official Telegram Client API (via the Telethon framework), you can create an automated, low-latency pipeline that monitors multiple source channels, filters incoming messages by custom regex rules or keywords, strips unwanted spam signatures, and forwards the cleaned content to your destination channel in milliseconds.

Quick Answer & Key Takeaways:

A Telegram auto-forwarder bot operates as either a standard Bot API bot or an MTProto Userbot. Userbots allow you to read and forward content from channels where standard bots are restricted. To ensure maximum uptime, host your script using Docker Compose or Systemd on a lightweight VPS. Explore pre-screened bot and developer channels in Telekit's Tech & AI Catalog.

Architecture Comparison: Bot API vs. MTProto Userbot

Before writing code, it is critical to select the correct architectural approach based on your access permissions and requirements. Telegram provides two distinct interfaces for interacting with messages:

Feature Standard Bot API (BotFather) MTProto Userbot (Telethon / Pyrogram)
Channel Access Requires Admin access in source channel Works on any channel you join as a member
Authentication Simple Bot Token API ID, API Hash + Phone Session
Private Group Support Restricted unless invited as admin Full support for private invite links
Message Modification Can format text & add buttons Full raw payload editing & signature removal

For auto-forwarding setups across public and private channels, the MTProto Userbot approach using Telethon is recommended because it does not require administrator access in source channels.

Show count:

Prerequisites & Initial Environment Setup

To follow this guide, ensure you have the following prerequisites ready:

  • Python 3.10+ installed on your local machine or Linux server.
  • Telegram API ID & API Hash: Obtain these by signing into your account at my.telegram.org under "API development tools".
  • Source & Destination Chat IDs: The numerical IDs or public usernames of the source channels (e.g., @source_channel) and destination channel (e.g., -100123456789).

Step 1: Installing Required Dependencies

Create a dedicated working directory and virtual environment, then install Telethon and PyYAML for configuration management:

# Create directory and enter it
mkdir telegram-auto-forwarder && cd telegram-auto-forwarder

# Create and activate Python virtual environment
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scriptsctivate

# Install Telethon and PyYAML
pip install telethon pyyaml python-dotenv

Configuring the Forwarder Script

We will separate configuration parameters from executable code to maintain security best practices. Create a config.yaml file to define your API keys, channel mappings, keyword filters, and replacement rules.

Step 2: Creating config.yaml

# Telegram API Credentials (from my.telegram.org)
api_id: 1234567
api_hash: "0123456789abcdef0123456789abcdef"
session_name: "forwarder_session"

# Channel Routing Rules
forward_rules:
  - name: "Tech News Forwarder"
    source_chats:
      - "@techcrunch_news"
      - "@hackernews_feed"
    destination_chat: "@my_tech_digest"
    
    # Filtering logic
    whitelist_keywords:
      - "AI"
      - "Python"
      - "Telegram"
      - "OpenSource"
    blacklist_keywords:
      - "SPAM"
      - "Airdrop"
      - "Promo"
      
    # Content cleaning
    strip_forward_header: true
    replace_words:
      "Join channel": "Read on Telekit"
      "t.me/spammer": "telekit.link"
    custom_footer: "

⚡ Forwarded via Telekit Automated Digest"

Building the Python Auto-Forwarder Engine

Now create forwarder.py. This script loads the configuration, initializes the Telethon client, listens for incoming channel messages in real-time using event listeners, filters text content based on rules, and sends the processed messages to the destination.

Step 3: Creating forwarder.py

import sys
import logging
import yaml
import re
from telethon import TelegramClient, events
from telethon.errors import FloodWaitError

# Setup logging
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.INFO
)
logger = logging.getLogger("TGForwarder")

# Load Configuration
try:
    with open("config.yaml", "r", encoding="utf-8") as f:
        config = yaml.safe_load(f)
except FileNotFoundError:
    logger.error("config.yaml file not found!")
    sys.exit(1)

api_id = config.get("api_id")
api_hash = config.get("api_hash")
session_name = config.get("session_name", "forwarder_session")
rules = config.get("forward_rules", [])

client = TelegramClient(session_name, api_id, api_hash)

def should_process_message(text, whitelist, blacklist):
    if not text:
        return len(whitelist) == 0  # Process media without text if no mandatory whitelist
    
    text_lower = text.lower()
    
    # Check Blacklist
    for word in blacklist:
        if word.lower() in text_lower:
            logger.info(f"Message blocked by blacklist keyword: '{word}'")
            return False
            
    # Check Whitelist
    if whitelist:
        match_found = any(word.lower() in text_lower for word in whitelist)
        if not match_found:
            logger.info("Message skipped: No whitelist keywords matched.")
            return False
            
    return True

def clean_text(text, replace_dict, footer):
    if not text:
        return text or ""
    
    # Apply word replacements
    for original, replacement in replace_dict.items():
        text = re.sub(re.escape(original), replacement, text, flags=re.IGNORECASE)
        
    if footer:
        text = text + footer
        
    return text

@client.on(events.NewMessage)
async def message_handler(event):
    for rule in rules:
        source_chats = rule.get("source_chats", [])
        destination_chat = rule.get("destination_chat")
        
        # Check if event comes from one of the target source chats
        chat = await event.get_chat()
        chat_username = f"@{chat.username}" if getattr(chat, 'username', None) else str(event.chat_id)
        
        if chat_username in source_chats or event.chat_id in source_chats:
            logger.info(f"Incoming message from {chat_username} (ID: {event.chat_id})")
            
            raw_text = event.raw_text or ""
            whitelist = rule.get("whitelist_keywords", [])
            blacklist = rule.get("blacklist_keywords", [])
            
            if not should_process_message(raw_text, whitelist, blacklist):
                continue
                
            replace_dict = rule.get("replace_words", {})
            footer = rule.get("custom_footer", "")
            cleaned_text = clean_text(raw_text, replace_dict, footer)
            
            strip_header = rule.get("strip_forward_header", True)
            
            try:
                if strip_header:
                    # Send new message with cleaned text and media copy
                    if event.media:
                        await client.send_file(destination_chat, file=event.media, caption=cleaned_text)
                    else:
                        await client.send_message(destination_chat, cleaned_text)
                    logger.info(f"Successfully cleaned & forwarded message to {destination_chat}")
                else:
                    # Native Telegram forward (retains "Forwarded from" header)
                    await event.forward_to(destination_chat)
                    logger.info(f"Successfully forwarded native message to {destination_chat}")
                    
            except FloodWaitError as e:
                logger.warning(f"Telegram FloodWait triggered! Must sleep for {e.seconds} seconds.")
                await asyncio.sleep(e.seconds)
            except Exception as e:
                logger.error(f"Failed to forward message: {e}")

async def main():
    logger.info("Starting Telegram Auto-Forwarder Bot...")
    await client.start()
    logger.info("Bot authenticated and listening for channel messages...")
    await client.run_until_disconnected()

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())
Show count:

Deploying for 24/7 Uptime with Docker Compose

To ensure your auto-forwarder operates continuously without interruption from system restarts, it should be containerized using Docker. Below is the setup for containerizing the application.

Step 4: Creating the Dockerfile

FROM python:3.11-slim

WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends     gcc     && rm -rf /var/lib/apt/lists/*

# Copy configuration and code
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

# Run script
CMD ["python", "forwarder.py"]

Step 5: Creating docker-compose.yml

version: '3.8'

services:
  tg-forwarder:
    build: .
    container_name: telegram_auto_forwarder
    restart: always
    volumes:
      - ./config.yaml:/app/config.yaml
      - ./forwarder_session.session:/app/forwarder_session.session
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"

Step 6: Launching the Container

# Authenticate locally first to create forwarder_session.session
python forwarder.py

# Launch background container via Docker Compose
docker compose up -d --build

# View container logs
docker compose logs -f

Security & Rate Limit Best Practices (E-E-A-T)

Operating a Telegram MTProto userbot requires strict adherence to Telegram's terms of service and security guidelines:

  • Handle FloodWait Errors: Always enclose API calls in try-except FloodWaitError blocks as demonstrated in Step 3. Telegram restricts accounts that ignore wait times when rate-limited.
  • Protect Session Files: The .session file generated by Telethon acts as an active login token. Never commit session files or api_hash keys to public GitHub repositories. Add *.session to your .gitignore file.
  • Use Moderated Delay Intervals: When forwarding bulk posts or historical archives, implement a randomized sleep delay between messages (e.g., await asyncio.sleep(random.uniform(2, 5))) to mimic natural human behavior.
  • Verify Public Directory Channels: Before subscribing your bot to new channels, verify channel credentials and quality on trusted directories such as Telekit's Tech & AI Section.

Frequently Asked Questions (FAQ)

Can I auto-forward messages from private Telegram channels?

Yes! As long as your Telegram account has joined the private channel via an invite link, the Telethon userbot can access incoming messages and forward them to your target destination.

Will my Telegram account get banned for using an auto-forwarder script?

Account bans usually happen due to excessive rate limit violations or forwarding illegal content. As long as your script handles FloodWaitError gracefully, uses moderate request rates, and only forwards clean content, your account will remain safe.

How do I strip telegram usernames and external links from forwarded posts?

You can use regular expression patterns inside the clean_text() helper function in forwarder.py. For instance, applying re.sub(r'https?://\S+|@\w+', '', text) removes all HTTP URLs and @username mentions prior to forwarding.

Can I host this auto-forwarder on a cheap $5/month VPS?

Absolutely. Telethon userbots use minimal system resources (under 50MB RAM and negligible CPU). A basic Linux VPS running Debian or Ubuntu with Docker installed is more than sufficient for continuous operation.

Conclusion

Automating content curation across Telegram channels saves time and keeps your audience informed with targeted news. By combining Python, Telethon, regex cleaning rules, and Docker containerization, you can build a resilient, 24/7 self-hosted auto-forwarding system. Stay updated with the latest developer tools, Telegram bots, and tech communities by exploring our verified listings on Telekit today!

Telekit Technical Editorial Desk

Verified Author

Authored and reviewed by Telekit's community research and bot engineering team. All code snippets, webhook payloads, and MTProto recommendations are tested in production environments against current Telegram API standards.

Found this guide helpful? Share it with fellow creators!