Tech & Coding Verified Editorial

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

In 2026, content distribution across Telegram has become a primary workflow for news syndicates, trading signal communities, educational platforms, and multi-channel media networks. Managing multiple Telegram channels manually—copying messages, re-uploading media, removing competitor branding, and updating links—is both inefficient and prone to human error. Building an automated, self-hosted Telegram channel mirror bot provides an instant, programmatic solution to sync messages in real-time across channels, groups, and private chats.

Quick Take:

Unlike traditional Telegram Bot API scripts that require administrator privileges in source channels, a Pyrogram MTProto userbot authenticates as a user account. This allows you to listen to any public or private channel you belong to, apply custom regular expression filters, modify captions, remove watermark links, and automatically mirror posts to target destinations 24/7. Explore developer tools and top channels in Telekit's Tech & Coding Directory.

Why Choose Pyrogram & MTProto Over Standard Telegram Bot API?

Developers often start building Telegram tools with the official Telegram Bot API via standard HTTP webhooks. However, when building channel forwarders and mirroring tools, the Bot API hits severe structural limitations:

  • Source Channel Access: Bot API bots can only read messages from channels where they have been explicitly added as Administrators. They cannot read updates from private channels or groups where administrator rights are restricted.
  • Forwarding Restrictions: Bots cannot view or read posts from channels that restrict content saving or forwarding unless authenticated via MTProto user session protocols.
  • Media & Batch Handling: Standard Bot API requests handle media groups (albums) as individual, disconnected update events. Pyrogram provides native asynchronous handling for multi-photo and document albums.

By leveraging Pyrogram, a modern, asynchronous Python MTProto framework, your script connects directly to Telegram's native client protocol. This allows your script to act as a hyper-fast, automated user client (commonly called a userbot), granting complete access to read, transform, and mirror content seamlessly.

Feature Comparison Standard Bot API Pyrogram MTProto Userbot
Source Channel Access Admin Privileges Required Any Joined Channel / Group
Content Modification Limited to Bot Output Full Regex Text / Link Rewriting
Media Group / Album Support Complex Webhook Batching Native Async Media Collectors
Rate Limiting Resilience 30 msgs/sec global limit Custom Async Queue & FloodWait Handlers
Show count:

Prerequisites & Telegram API Credentials

Before deploying the auto-forwarder script, ensure you have the following requirements ready:

  1. Python 3.10+ Installed: Verify by running python3 --version in your terminal.
  2. Telegram Account: An active account joined to the source channel(s) you wish to forward from.
  3. Telegram API Credentials (api_id & api_hash):
    • Visit the official Telegram core portal at my.telegram.org.
    • Log in with your phone number and enter the confirmation code sent to your Telegram app.
    • Navigate to API Development Tools.
    • Create a new application (e.g., AutoForwarderBot2026) and copy down your api_id (an integer) and api_hash (a 32-character string).
  4. Linux VPS or Docker Host: A basic $5/month cloud instance (Ubuntu 22.04/24.04 LTS on Hetzner, DigitalOcean, or AWS) for 24/7 background operation.

Step 1: Setting Up the Python Virtual Environment

Connect to your server terminal and create an isolated Python virtual environment to manage dependencies securely:

# Create project directory
mkdir -p ~/telegram-autoforwarder && cd ~/telegram-autoforwarder

# Initialize Python virtual environment
python3 -m venv venv
source venv/bin/activate

# Upgrade pip and install Pyrogram with TgCrypto (for high-speed C-based encryption)
pip install --upgrade pip
pip install pyrogram tgcrypto python-dotenv

Step 2: Writing the Production-Grade Auto-Forwarder Script

Create a file named forwarder.py inside your project directory. This production script includes multi-channel mapping, keyword filtering (blacklist/whitelist), link stripping, and automatic FloodWait exception handling.

import asyncio
import os
import re
import logging
from dotenv import load_dotenv
from pyrogram import Client, filters, enums
from pyrogram.types import Message
from pyrogram.errors import FloodWait

# Configure Logging
logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(message)s",
    level=logging.INFO
)

# Load environment variables
load_dotenv()

API_ID = int(os.getenv("API_ID", "1234567"))
API_HASH = os.getenv("API_HASH", "your_api_hash_here")

# Define Channel Mapping: { SOURCE_CHAT_ID: [TARGET_CHAT_ID_1, TARGET_CHAT_ID_2] }
# Tip: Use chat IDs (e.g. -1001234567890) or public usernames (e.g. "@my_target_channel")
CHANNEL_MAP = {
    -1001987654321: [-1001122334455],
    "@crypto_news_source": ["@my_crypto_mirror_channel"]
}

# Filtering Rules
BLACKLIST_WORDS = ["SPAM", "DISCOUNT", "PROMO", "CLICK HERE", "BUY NOW"]
REPLACE_LINKS = True
MY_BRANDING_FOOTER = "\n\n📢 Mirrored automatically via Telekit Tech Network"

app = Client("userbot_session", api_id=API_ID, api_hash=API_HASH)

def clean_text(text: str) -> str:
    # Applies regex filters to remove unwanted links and inject custom branding
    if not text:
        return ""
    
    # Check blacklist
    for word in BLACKLIST_WORDS:
        if word.lower() in text.lower():
            logging.info(f"Message skipped due to blacklisted keyword: {word}")
            return ""
            
    # Optional: Strip competitor t.me links
    if REPLACE_LINKS:
        text = re.sub(r'https?://t\.me/[a-zA-Z0-9_]+', '', text)
        
    return text.strip() + MY_BRANDING_FOOTER

@app.on_message(filters.chat(list(CHANNEL_MAP.keys())))
async def auto_forward_handler(client: Client, message: Message):
    source_id = message.chat.id if message.chat.id in CHANNEL_MAP else message.chat.username
    if not source_id:
        return
        
    target_destinations = CHANNEL_MAP.get(source_id) or CHANNEL_MAP.get(f"@{source_id}")
    if not target_destinations:
        return

    logging.info(f"New update received from source: {source_id}")

    for target in target_destinations:
        try:
            # Handle text messages
            if message.text:
                cleaned = clean_text(message.text)
                if cleaned:
                    await client.send_message(target, cleaned, parse_mode=enums.ParseMode.HTML)
                    
            # Handle media (Photos, Videos, Documents) with captions
            elif message.media:
                caption = clean_text(message.caption) if message.caption else ""
                await message.copy(target, caption=caption)
                
            logging.info(f"Successfully mirrored message to target: {target}")
            await asyncio.sleep(1.5)  # Rate limit prevention delay

        except FloodWait as e:
            logging.warning(f"FloodWait triggered! Sleeping for {e.value} seconds...")
            await asyncio.sleep(e.value)
        except Exception as e:
            logging.error(f"Failed to forward message to {target}: {e}")

if __name__ == "__main__":
    logging.info("Starting Pyrogram Auto-Forwarder Userbot...")
    app.run()

Step 3: Creating the Environment File & Authentication

Create a .env file in your project directory to keep credentials separate from your codebase:

# Save as .env
API_ID=YOUR_TELEGRAM_API_ID
API_HASH=YOUR_TELEGRAM_API_HASH

Now, run the script manually once in your terminal to complete the interactive authentication process:

python forwarder.py

Pyrogram will prompt you to enter your phone number (including international country code, e.g., +1234567890) and the login code sent to your Telegram app. If 2-Factor Authentication (2FA) is enabled, enter your password when prompted. Once authorized, Pyrogram generates a persistent userbot_session.session file in your directory.

Step 4: Deploying as a Persistent Systemd Background Service

To ensure your auto-forwarder stays online continuously and automatically restarts after server reboots, configure it as a systemd background service.

Create a service file at /etc/systemd/system/tg-forwarder.service using root privileges:

[Unit]
Description=Telegram Auto-Forwarder & Channel Mirror Bot
After=network.target

[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/telegram-autoforwarder
ExecStart=/home/ubuntu/telegram-autoforwarder/venv/bin/python forwarder.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Reload systemd, enable the service on boot, and start it immediately:

# Reload systemctl daemon
sudo systemctl daemon-reload

# Enable and start the forwarder daemon
sudo systemctl enable tg-forwarder
sudo systemctl start tg-forwarder

# Check live real-time status and logs
sudo systemctl status tg-forwarder
sudo journalctl -u tg-forwarder -f
Show count:

Alternative: Docker Container Deployment

If you deploy applications using Docker, you can package your Pyrogram forwarder into a lightweight container. Create a Dockerfile in your project directory:

FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["python", "forwarder.py"]

Launch with docker-compose.yml:

version: '3.8'

services:
  tg-forwarder:
    build: .
    container_name: tg_autoforwarder
    restart: always
    volumes:
      - ./.env:/app/.env
      - ./userbot_session.session:/app/userbot_session.session

Telegram Rate Limits & Anti-Spam Security Best Practices

Because MTProto userbots operate on personal accounts, adhering to Telegram's protocol guidelines is critical to avoid temporary account restrictions:

  • Implement Message Delays: Never forward dozens of messages simultaneously without sleep intervals. Always insert await asyncio.sleep(1.5) between post transfers.
  • Catch FloodWait Exceptions: Always wrap messaging calls in try...except FloodWait blocks. If Telegram requests a cool-down, respect e.value and sleep for the exact duration requested.
  • Secure Session Files: Your userbot_session.session file contains your active login tokens. Never commit session files or .env credentials to public GitHub repositories.
  • Use Telegram Accounts in Good Standing: Avoid using brand-new Telegram accounts registered minutes prior for heavy auto-forwarding tasks, as fresh accounts face stricter rate limits.

Frequently Asked Questions (FAQ)

Can Pyrogram forward messages from private channels?

Yes. As long as the authenticated Telegram account running the Pyrogram userbot has joined the private channel, it can read updates and copy or send the messages to any destination channel where it has posting rights.

Will my Telegram account get banned for auto-forwarding?

No, provided you adhere to reasonable rate limits. Adding asynchronous delays (1-2 seconds per post) and avoiding mass-spamming protects your account from automated detection algorithms.

How do I find the numeric Chat ID of a channel?

You can forward any message from the target channel to userbot helper tools like @userinfobot or print message.chat.id in your Pyrogram message handler during testing.

What is the difference between Pyrogram and Telethon?

Both are excellent Python MTProto libraries. Pyrogram features a modern, clean API inspired by standard bot frameworks with native asyncio support, making it widely favored for new project developments in 2026.

Conclusion

Building a self-hosted Telegram auto-forwarder with Pyrogram gives you total control over content aggregation, channel mirroring, and custom post transformation. By deploying this script on a lightweight VPS using systemd or Docker, you maintain a 24/7 automated publishing engine. Ready to explore more high-value Telegram developer scripts and verified coding channels? Browse Telekit's Tech & Coding Directory 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!