-
Notifications
You must be signed in to change notification settings - Fork 0
Home
An asynchronous Telegram message forwarding bot with a modern Python architecture, built with Telethon and Rich.
This project is based on the original Telegram Forwarder Bot by Mohammad Shabib.
- Async/Await Architecture: Fully asynchronous for high performance
- Live Forwarding: Real-time message forwarding with event handlers
- History Forwarding: Bulk message forwarding with date filtering
- Progress Tracking: Real-time progress indicators
- Multi-Account Support: Switch between multiple Telegram accounts
- Rate Limiting: Built-in rate limiting to respect API limits
- Rich Console UI: Beautiful terminal interface
- Type-Safe: Full type hints with mypy support
# Clone and setup
git clone https://github.com/klept0/Telegram-Forwarder-Bot-v2.git
cd Telegram-Forwarder-Bot-v2
# Install dependencies
pip install -e ".[dev]"
# Configure environment
cp .env.example .env
# Edit .env with your credentials
# Run the bot
python main.py- Python 3.10 or higher
- A Telegram account with API credentials from my.telegram.org
- Docker & Docker Compose (optional, for containerized deployment)
-
Clone the repository:
git clone https://github.com/klept0/Telegram-Forwarder-Bot-v2.git cd Telegram-Forwarder-Bot-v2 -
Create virtual environment:
python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate
-
Install dependencies:
pip install -e ".[dev]" -
Set up environment variables:
cp .env.example .env # Edit .env with your Telegram API credentials -
Run the bot:
python main.py
-
Clone the repository:
git clone https://github.com/klept0/Telegram-Forwarder-Bot-v2.git cd Telegram-Forwarder-Bot-v2 -
Set up environment variables:
cp .env.example .env # Edit .env with your Telegram API credentials -
Run with Docker Compose:
docker-compose up --build
Or run in background:
docker-compose up -d --build
-
View logs:
docker-compose logs -f
- Go to my.telegram.org and log in
- Click on "API development tools"
- Create a new application
- Copy the
api_idandapi_hashvalues - Add them to your
.envfile
After installation, you should see the main menu with options for account management and forwarding configuration.
Create a .env file in the project root with the following variables:
# Telegram API Credentials
TELEGRAM_API_ID=your_api_id_here
TELEGRAM_API_HASH=your_api_hash_here
# Optional: Bot Token (for bot functionality)
BOT_TOKEN=your_bot_token_here
# Optional: Web Interface
WEB_HOST=0.0.0.0
WEB_PORT=8000- Visit my.telegram.org
- Log in with your Telegram account
- Navigate to "API development tools"
- Create a new application
- Copy the
api_idandapi_hash
The bot supports multiple Telegram accounts. Credentials are stored securely in resources/credentials.json.
- Run the bot:
python main.py - Select "Manage Accounts" from the main menu
- Choose "Add Account"
- Enter your phone number and API credentials
- Complete the Telegram authentication flow
- Select "Switch Account" from the main menu
- Choose the account you want to use
- The bot will reconnect with the selected account
Forwarding rules are stored in resources/forward_config.json. Each rule maps a source chat to one or more destination chats.
- Select "Configure Forwarding" from the main menu
- Choose "Add Forward Rule"
- Select source chat
- Select destination chat(s)
- Configure filtering options (optional)
[
{
"source_id": 123456789,
"source_name": "Source Chat",
"destination_id": 987654321,
"destination_name": "Destination Chat",
"enabled": true,
"filters": {
"date_from": "2024-01-01",
"date_to": "2024-12-31",
"keywords": ["important", "urgent"]
}
}
]The bot includes built-in rate limiting to respect Telegram's API limits:
- Messages: 30 messages per second
- Media: 10 media uploads per second
- Other operations: Appropriate limits per operation type
Rate limits are configurable in source/utils/RateLimiter.py.
After starting the bot, you'll see the main menu with the following options:
- Manage Accounts: Add, remove, or switch between Telegram accounts
- Configure Forwarding: Set up forwarding rules between chats
- Start Live Forwarding: Begin real-time message forwarding
- Forward History: Bulk forward messages from chat history
- View History: Check forwarding history and statistics
- Settings: Configure bot settings and preferences
Live forwarding monitors chats in real-time and forwards new messages according to your rules.
- Select "Start Live Forwarding" from the main menu
- Choose which forwarding rules to activate
- The bot will begin monitoring and forwarding messages
- Progress indicators show forwarding status
- Press
Ctrl+Cto stop gracefully - The bot will save current state and statistics
Forward messages from chat history with date filtering and progress tracking.
- Select "Forward History" from the main menu
- Choose source chat
- Select date range or specific months
- Choose destination chat
- Monitor progress as messages are forwarded
- Date Range: Specify start and end dates
- Months: Select specific months to forward
- Keywords: Filter messages containing specific words
- Media Only: Forward only messages with media attachments
- Select "Find Chats" from the main menu
- Search by name or browse your chat list
- View chat details and message counts
The bot provides statistics for each chat:
- Total messages
- Media count
- Last activity
- Chat type (private, group, channel)
- Console output shows real-time progress
- Logs are saved to
logs/bot_YYYY-MM-DD.log - Use
richformatting for better readability
During forwarding operations, you'll see:
Forwarding messages: 150/500 (30%)
Processing media: 45/100 (45%)
Rate limiting active: 2.1 seconds remaining
Problem: "Invalid API credentials" or "Phone number not registered"
Solutions:
- Verify your
api_idandapi_hashfrom my.telegram.org - Check that your phone number is correctly formatted (+country code)
- Ensure your Telegram account is not banned or restricted
Problem: "Connection failed" or "Network timeout"
Solutions:
- Check your internet connection
- Try switching networks (mobile data vs WiFi)
- Wait a few minutes and retry
- Check if Telegram is blocked in your region
Problem: "Too many requests" or slow forwarding
Solutions:
- The bot has built-in rate limiting - wait for it to complete
- Reduce the number of active forwarding rules
- Increase delays between operations in settings
Problem: "Access denied" or "Not authorized"
Solutions:
- Ensure you have access to the source chat
- Check that you can send messages to destination chats
- For channels, ensure you have admin/editor permissions
Problem: Docker container fails to start
Solutions:
- Check Docker and Docker Compose installation
- Verify
.envfile exists and has correct credentials - Check container logs:
docker-compose logs - Ensure ports 8000 (web) are not in use
Problem: File permission errors in container
Solutions:
- Check host file permissions
- Ensure Docker has access to project directory
- Try running with
--user $(id -u):$(id -g)
Causes:
- Large message volumes
- Media-heavy chats
- Network latency
- Rate limiting
Solutions:
- Reduce batch sizes
- Filter messages to reduce volume
- Use faster network connection
- Run during off-peak hours
Causes:
- Large chat histories
- Media downloads
- Multiple concurrent operations
Solutions:
- Process chats in smaller batches
- Disable media forwarding temporarily
- Restart the bot periodically
- Monitor with
docker stats
Set environment variable: LOG_LEVEL=DEBUG
- Console output: Real-time logs
- File logs:
logs/bot_YYYY-MM-DD.log - Docker logs:
docker-compose logs -f
If you can't resolve an issue:
- Check the FAQ page
- Review GitHub Issues
- Create a new issue with:
- Error messages
- Log excerpts
- Steps to reproduce
- Your environment details
Main Telegram client wrapper.
from source.core.Telegram import TelegramClient
client = TelegramClient(api_id, api_hash, phone)
await client.connect()Methods:
-
connect(): Establish connection -
disconnect(): Close connection -
get_chats(): Retrieve user's chats -
send_message(chat_id, text): Send text message
Handles message forwarding operations.
from source.service.Forward import ForwardService
service = ForwardService(client, console)
await service.forward_history(source_id, dest_id, date_from, date_to)Methods:
-
forward_history(): Bulk forward from history -
start_live_forwarding(): Begin real-time forwarding -
stop_live_forwarding(): Stop real-time forwarding
Manages message queuing and rate limiting.
from source.service.MessageQueue import MessageQueue
queue = MessageQueue(rate_limiter)
await queue.add_message(message)
await queue.process_queue()from source.model.ForwardConfig import ForwardConfig
config = ForwardConfig(
source_id=123,
source_name="Source",
destination_id=456,
destination_name="Destination",
enabled=True
)from source.model.Credentials import Credentials
creds = Credentials(
phone="+1234567890",
api_id=12345,
api_hash="abcdef123456"
)Handles API rate limiting.
from source.utils.RateLimiter import RateLimiter
limiter = RateLimiter()
await limiter.wait_if_needed() # Respects rate limitsRich console output wrapper.
from source.utils.Console import Terminal
Terminal.console.print("[green]Success![/]")
Terminal.console.print("[red]Error![/]")Located in source/utils/Constants.py:
RESOURCES_DIR = "resources"
SESSIONS_DIR = "sessions"
MEDIA_DIR = "media"
LOGS_DIR = "logs"Custom exceptions:
from source.core.Telegram import TelegramError
from source.service.Forward import ForwardError
try:
await client.connect()
except TelegramError as e:
console.print(f"[red]Connection failed: {e}[/]")Q: What is Telegram Forwarder Bot v2?
A: It's an asynchronous Python application that forwards messages between Telegram chats automatically, with support for live forwarding, history forwarding, and multi-account management.
Q: How is this different from the original version?
A: This version features modern Python async architecture, better error handling, progress indicators, Docker support, and improved user interface.
Q: Is it safe to use?
A: Yes, it only requires standard Telegram API access and doesn't store your messages. All credentials are stored locally and encrypted.
Q: Do I need programming knowledge to use this?
A: Basic command-line knowledge is helpful, but the installation guides are step-by-step. Docker installation requires even less technical knowledge.
Q: Can I run multiple instances?
A: Yes, each instance can run with different accounts or configurations. Use separate directories or Docker containers.
Q: What are the system requirements?
A: Python 3.10+ for local installation, or Docker for containerized deployment. Minimal RAM (512MB) and storage requirements.
Q: Can I forward from channels I'm not admin of?
A: No, you need to be a member of the source chat and have permission to read messages.
Q: How fast does forwarding work?
A: Speed depends on message volume and media content. Typically 30-50 messages per minute with rate limiting.
Q: Can I filter messages during forwarding?
A: Yes, you can filter by date range, keywords, and media type.
Q: What happens if the bot loses connection?
A: It will automatically attempt to reconnect. Live forwarding will resume when connection is restored.
Q: How does rate limiting work?
A: The bot respects Telegram's API limits (30 messages/second, 10 media uploads/second) and includes additional safety buffers.
Q: Where are my credentials stored?
A: Credentials are stored encrypted in resources/credentials.json. Never commit this file to version control.
Q: Can I use this with a bot token instead of user account?
A: Yes, set the BOT_TOKEN environment variable. Note that bots have different API limitations.
Q: How do I backup my configuration?
A: Backup the resources/ directory. It contains all your settings, credentials, and forwarding rules.
Q: The bot says "phone not registered"?
A: Ensure your phone number includes the country code (+1 for US, +44 for UK, etc.) and that you've completed Telegram verification.
Q: Forwarding is very slow?
A: This is normal due to rate limiting. The bot prioritizes reliability over speed to avoid being blocked.
Q: Can I run this on a server?
A: Yes, use Docker deployment for server environments. Ensure proper firewall and security configurations.
Q: How do I update the bot?
A: Pull the latest changes from Git (git pull) and reinstall dependencies (pip install -e ".[dev]").
Telegram-Forwarder-Bot-v2/
├── main.py # Entry point
├── source/
│ ├── core/ # Core functionality
│ │ ├── Bot.py # Main bot class
│ │ └── Telegram.py # Telegram client wrapper
│ ├── service/ # Business logic services
│ │ ├── Forward.py # Forwarding logic
│ │ ├── MessageQueue.py # Queue management
│ │ └── ...
│ ├── model/ # Data models
│ │ ├── ForwardConfig.py
│ │ ├── Credentials.py
│ │ └── ...
│ ├── dialog/ # User interaction dialogs
│ ├── menu/ # Menu systems
│ └── utils/ # Utilities
├── resources/ # Runtime data
├── sessions/ # Telegram sessions
├── media/ # Downloaded media
├── logs/ # Application logs
└── requirements.txt # Dependencies
-
Clone and setup:
git clone https://github.com/klept0/Telegram-Forwarder-Bot-v2.git cd Telegram-Forwarder-Bot-v2 python -m venv .venv source .venv/bin/activate pip install -e ".[dev]"
-
Install development tools:
pip install -e ".[dev]" # Includes pytest, black, ruff, mypy
-
Set up pre-commit hooks:
pre-commit install
# Format code
black source/
isort source/
# Lint code
ruff check source/
mypy source/
# Fix auto-fixable issues
ruff check --fix source/# Run all tests
pytest tests/ -v --cov=source --cov-report=html
# Run specific test
pytest tests/test_forward.py -v
# Run with coverage
pytest tests/ --cov=source --cov-report=term-missing# Run mypy
mypy source/
# Strict mode
mypy source/ --strict-
Create a feature branch:
git checkout -b feature/your-feature-name
-
Make changes and run tests:
# Make your changes pytest tests/ # Ensure tests pass black source/ && isort source/ # Format code ruff check source/ # Lint code
-
Commit changes:
git add . git commit -m "feat: add your feature description"
-
Create pull request
Use conventional commits:
feat: add new forwarding filter options
fix: resolve rate limiting issue
docs: update installation guide
refactor: simplify message queue logic
test: add unit tests for forward service
- Type Hints: Use comprehensive type hints for all functions
- Docstrings: Add docstrings to classes and public methods
- Async/Await: Use async patterns consistently
- Error Handling: Use custom exceptions and proper error propagation
-
Logging: Use structured logging with
loguru
- Unit Tests: Test individual functions and methods
- Integration Tests: Test service interactions
-
Async Tests: Use
pytest-asynciofor async functions -
Mocking: Use
pytest-mockfor external dependencies - Coverage: Aim for >80% code coverage
All I/O operations use async/await:
async def forward_message(self, message: Message) -> None:
await self.rate_limiter.wait_if_needed()
await self.client.send_message(self.dest_id, message)Business logic separated into services:
class ForwardService:
def __init__(self, client: TelegramClient, console: Console):
self.client = client
self.console = console
async def forward_history(self, config: ForwardConfig) -> None:
# ImplementationServices receive dependencies through constructor:
# Good
service = ForwardService(client, console, queue)
# Avoid
service = ForwardService()
service.client = client # Tight couplingGET /api/chats # List chats
POST /api/forward # Start forwarding
GET /api/status # Get bot status
POST /api/accounts # Add account
// Real-time progress updates
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'progress') {
updateProgress(data.current, data.total);
}
};# Build and run
docker-compose up --build
# Run tests in container
docker-compose exec app pytest tests/# Use production compose file
docker-compose -f docker-compose.prod.yml up -d
# Monitor logs
docker-compose logs -f appimport cProfile
cProfile.run('main()', 'profile.prof')import tracemalloc
tracemalloc.start()
# ... code ...
current, peak = tracemalloc.get_traced_memory()
print(f"Current memory usage: {current / 1024 / 1024:.1f} MB")- Use
asyncio.gather()for concurrent operations - Implement connection pooling for database operations
- Use streaming for large file transfers
- Never commit
.envfiles - Use environment variables for sensitive data
- Encrypt stored credentials
- Implement proper rate limiting
- Validate all user inputs
- Use HTTPS for web interface
- Run as non-root user
- Use minimal base images
- Regularly update dependencies
- Web-based management interface
- Message filtering and transformation
- Scheduled forwarding
- Multi-language support
- Plugin system for custom functionality
- GraphQL API
- Message queuing with Redis
- Distributed deployment support
- Real-time notifications
- Advanced analytics dashboard