A robust Telegram client designed to run on Raspberry Pi that forwards incoming messages as JSON to a webhook URL. Features include local caching, auto-recovery, comprehensive logging, and easy installation.
- Message Forwarding: Receives Telegram messages and forwards them as JSON to a configurable webhook URL
- Local Caching: Uses SQLite or Redis to cache messages when webhook is unavailable
- Auto Recovery: Automatically retries failed messages and recovers after power outages
- Comprehensive Logging: Detailed logging with configurable levels
- Systemd Service: Runs as a system service with auto-start on boot
- Easy Installation: Interactive installation script that configures all environment variables
- Multiple Message Types: Supports text, photos, documents, voice messages, and videos
- Chat Filtering:
Only forwards messages from specified chat namesDISABLED - All messages are forwarded - Dynamic Chat Management: Add/remove allowed chats while the service is running
- Raspberry Pi (or any Linux system)
- Python 3.8 or higher
- Internet connection
- Telegram account with API credentials (from https://my.telegram.org/apps)
- Webhook URL to receive forwarded messages
-
Get Telegram API Credentials:
- Go to https://my.telegram.org/apps
- Log in with your phone number
- Create a new application
- Note down your
api_idandapi_hash
-
Clone the repository:
git clone https://github.com/Factory55/telegram-client.git cd telegram-client -
Run the installation script:
chmod +x install.sh ./install.sh
-
The script will prompt you for:
- Telegram API ID and Hash (from https://my.telegram.org/apps)
- Your phone number
- 2FA password (if enabled)
- Webhook URL
- Database preferences (SQLite/Redis)
- Logging configuration
- Performance settings
-
First Authentication (required before starting the service):
python auth_setup.py
- This will prompt you for the verification code that Telegram sends
- Enter the code when prompted
- If you have 2FA enabled, you'll be prompted for your password
- After successful authentication, a session file will be created
-
Start the service:
sudo systemctl start telegram-client.service
-
Check status:
./status.sh
To use this client with your real Telegram account, you need to get API credentials:
- Visit Telegram API: Go to https://my.telegram.org/apps
- Login: Use your phone number to log in
- Create App: Fill in the form with any app name and description
- Get Credentials: Note down your
api_idandapi_hash - Security: Keep these credentials secure and don't share them
Note: This uses your real Telegram account, not a bot. The client will log in as you and forward messages from your chats.
First Login: When you start the client for the first time, Telegram will send you a login code via Telegram message. Enter this code in the terminal when prompted. A session file will be created to remember your login for future starts.
The application uses a .env file for configuration. Key variables include:
TELEGRAM_API_ID: Your Telegram API ID from https://my.telegram.org/appsTELEGRAM_API_HASH: Your Telegram API Hash from https://my.telegram.org/appsTELEGRAM_PHONE: Your phone number (include country code)WEBHOOK_URL: The URL where messages will be forwarded as JSON
TELEGRAM_PASSWORD: 2FA password (provide for automatic login, or leave empty to enter manually)DATABASE_TYPE:sqlite(default) orredisWEBHOOK_TIMEOUT: Request timeout in seconds (default: 30)WEBHOOK_RETRY_ATTEMPTS: Number of retry attempts (default: 3)LOG_LEVEL: Logging level (default: INFO)MESSAGE_BATCH_SIZE: Messages to process in batch (default: 10)RECOVERY_CHECK_INTERVAL: Recovery check interval in seconds (default: 60)
- Lightweight, no additional setup required
- Stored in
telegram_client.dbfile - Suitable for most use cases
- Better performance for high message volumes
- Requires Redis server installation
- Configure with
REDIS_HOST,REDIS_PORT,REDIS_DB,REDIS_PASSWORD
# Start the service
sudo systemctl start telegram-client.service
# Stop the service
sudo systemctl stop telegram-client.service
# Restart the service
sudo systemctl restart telegram-client.service
# Check service status
sudo systemctl status telegram-client.service
# Enable auto-start on boot
sudo systemctl enable telegram-client.service# Manual start
./start.sh
# Check status and logs
./status.sh
# Stop service
./stop.sh
# Restart and show status
./restart.sh
# Manage allowed chats
./manage_chats.py list # List all allowed chats
./manage_chats.py add "My Chat Name" # Add a chat to allowed list
./manage_chats.py remove "My Chat Name" # Remove a chat from allowed list
./manage_chats.py test "My Chat Name" # Test if a chat is allowed# View real-time logs
tail -f telegram_client.log
# View recent logs
tail -n 50 telegram_client.log
# View service logs
sudo journalctl -u telegram-client.service -fMessages are forwarded to the webhook URL as JSON with the following structure:
{
"message_id": "12345",
"chat_id": "67890",
"user_id": "11111",
"username": "user123",
"text": "Hello world!",
"timestamp": "2024-01-01T12:00:00",
"message_type": "text",
"raw_message": {
// Complete Telegram message object
}
}- text: Plain text messages
- photo: Image messages (includes file_id array)
- document: File attachments (includes file_id)
- voice: Voice messages (includes file_id)
- video: Video messages (includes file_id)
The chat filtering feature has been temporarily disabled. Previously, the client only forwarded messages from chats listed in allowed_chats.txt.
To re-enable chat filtering:
- Uncomment the chat filter import in
telegram_client.py(line 12) - Uncomment the chat filter initialization (line 30)
- Uncomment the chat filtering logic in the
handle_messagemethod (lines 87-90)
Previous File Format:
# Add allowed chat names here (one per line)
# Lines starting with # are comments
The Beard Chat
Citadel to the beard
CFB Bets
Test Beard Telegram Client
Previous Management Commands:
# List all allowed chats
./manage_chats.py list
# Add a new chat
./manage_chats.py add "New Chat Name"
# Remove a chat
./manage_chats.py remove "Chat Name"
# Test if a chat is allowed
./manage_chats.py test "Chat Name"- TelegramClient: Main application that handles Telegram bot interactions
- DatabaseManager: Manages message storage in SQLite or Redis
- WebhookClient: Handles HTTP requests to the webhook URL
- Config: Manages environment variables and configuration
- ChatFilter:
Filters messages based on allowed chat namesDISABLED
- Telegram message received
Check if chat is in allowed listChat filtering disabledIf not allowed: Ignore messageAll messages processed- Convert message to JSON format
- Attempt to send to webhook URL
- If successful: Store as sent message
- If failed: Store as pending message
- Background thread processes pending messages
- Recovery monitor checks system health
- Automatic Retry: Failed messages are retried with exponential backoff
- Power Outage Recovery: Service automatically restarts and processes pending messages
- Network Recovery: Detects when webhook becomes available again
- Database Persistence: Messages survive system restarts
-
Service won't start:
sudo systemctl status telegram-client.service tail -f telegram_client.log
-
Authentication errors (EOF when reading a line):
- This happens when the service tries to authenticate without a session file
- Run the authentication setup first:
python auth_setup.py
- After successful authentication, restart the service:
sudo systemctl restart telegram-client.service
-
Messages not being forwarded:
- Check webhook URL is accessible
- Verify API credentials and phone number
- Check if 2FA password is correct (if you have 2FA enabled)
- Check network connectivity
-
Database errors:
- For SQLite: Check file permissions
- For Redis: Verify Redis server is running
-
High memory usage:
- Reduce
MESSAGE_BATCH_SIZE - Increase
MESSAGE_PROCESSING_INTERVAL - Consider using Redis instead of SQLite
- Reduce
Enable debug logging by setting LOG_LEVEL=DEBUG in your .env file:
# Edit .env file
nano .env
# Change LOG_LEVEL to DEBUG
LOG_LEVEL=DEBUG
# Restart service
sudo systemctl restart telegram-client.servicetelegram-client/
├── telegram_client.py # Main application
├── config.py # Configuration management
├── database.py # Database operations
├── webhook_client.py # HTTP client for webhooks
├── chat_filter.py # Chat filtering logic
├── manage_chats.py # Chat management script
├── allowed_chats.txt # Allowed chat names
├── requirements.txt # Python dependencies
├── install.sh # Installation script
├── start.sh # Manual start script
├── stop.sh # Stop script
├── restart.sh # Restart script
├── status.sh # Status and monitoring script
├── .env # Environment variables (created by install.sh)
├── telegram_client.db # SQLite database (if using SQLite)
└── telegram_client.log # Application logs
To support new message types, modify the handle_message method in telegram_client.py:
# Add new message type handling
elif message.new_message_type:
message_data['message_type'] = 'new_message_type'
message_data['new_message_type'] = message.new_message_type.file_id- Keep your
.envfile secure (chmod 600) - Use HTTPS for webhook URLs
- Regularly update dependencies
- Monitor logs for suspicious activity
- Consider using a firewall to restrict access
This project is open source. Please check the license file for details.
For issues and questions:
- Check the troubleshooting section
- Review the logs:
tail -f telegram_client.log - Check service status:
./status.sh - Create an issue in the repository
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request