Run automated Telegram backups
4.4K
Automated Telegram data backup system with Docker support. Performs incremental backups of your Telegram messages and media on a configurable schedule.
⨠Incremental Backups - Only downloads new messages since last backup
š
Scheduled Execution - Configurable cron schedule (hourly, daily, etc.)
š³ Docker Ready - Easy deployment with Docker and Docker Compose
š Secure - Uses official Telegram API, runs as non-root user
š Flexible Filtering - Choose private chats, groups, and/or channels
š¾ Point-in-time Recovery - Export data from any specific date range
š Media Support - Download photos, videos, documents with size limits
šļø SQLite Storage - Efficient database with full-text search capability
The system uses incremental backups to minimize storage and bandwidth usage:
Messages:
last_message_id for each chat in a SQLite databaseMedia Files:
MAX_MEDIA_SIZE_MB (configurable)Example:
First backup: 10,000 messages, 2 GB media ā Full download
Second backup: 50 new messages, 10 MB media ā Only downloads new data
Third backup: 30 new messages, 5 MB media ā Only downloads new data
You can export and recover messages from any specific date range:
Export Capabilities:
Use Cases:
Important Notes:
You need to obtain API credentials from Telegram:
API_ID and API_HASHClone or download this repository
Configure environment variables
You have two options for setting environment variables:
Option A: Using .env file (Recommended)
cp .env.example .env
Then edit .env with your credentials:
TELEGRAM_API_ID=your_api_id
TELEGRAM_API_HASH=your_api_hash
TELEGRAM_PHONE=+1234567890
SCHEDULE=0 */6 * * *
Option B: Directly in docker-compose.yml
You can also set environment variables directly in the docker-compose.yml file instead of using .env:
environment:
TELEGRAM_API_ID: 12345678
TELEGRAM_API_HASH: abcdef1234567890
TELEGRAM_PHONE: +1234567890
# ... other variables
Note: Using a
.envfile is recommended because:
- Keeps sensitive data out of version control (
.envis gitignored)- Easier to manage multiple configurations
- Cleaner
docker-compose.ymlfile
Run authentication setup (one-time only)
This step is required to generate the session file. It runs interactively to ask for your Telegram verification code (and 2FA password if enabled).
Windows:
init_auth.bat
Linux/Mac:
chmod +x init_auth.sh
./init_auth.sh
Manual Docker Command (if not using scripts):
docker-compose run --rm telegram-backup python -m src.setup_auth
Start the backup service
docker-compose up -d
Check logs
docker-compose logs -f
Install dependencies
pip install -r requirements.txt
Create and configure .env
cp .env.example .env
# Edit .env with your credentials
Run authentication setup
python -m src.setup_auth
Start scheduler
python -m src.scheduler
If you don't want to clone the repository and just want to run the container:
telegram-backup).env file inside it (see Configuration section)docker run --rm -it \
--env-file .env \
-v $(pwd)/data:/data \
drumsergio/telegram-backup-automation:latest \
python -m src.setup_auth
docker run -d \
--name telegram-backup \
--restart unless-stopped \
--env-file .env \
-v $(pwd)/data:/data \
drumsergio/telegram-backup-automation:latest
All configuration is done via environment variables in the .env file:
| Variable | Description | Example |
|---|---|---|
TELEGRAM_API_ID | API ID from my.telegram.org | 12345678 |
TELEGRAM_API_HASH | API Hash from my.telegram.org | abcdef1234567890 |
TELEGRAM_PHONE | Your phone number with country code | +1234567890 |
| Variable | Default | Description |
|---|---|---|
SCHEDULE | 0 */6 * * * | Cron schedule (every 6 hours) |
BACKUP_PATH | /data/backups | Backup storage path |
DOWNLOAD_MEDIA | true | Download media files |
MAX_MEDIA_SIZE_MB | 100 | Max media file size to download |
CHAT_TYPES | private,groups,channels | Chat types to backup |
LOG_LEVEL | INFO | Logging level (DEBUG, INFO, WARNING, ERROR) |
SESSION_NAME | telegram_backup | Session file name |
The SCHEDULE variable uses cron format: minute hour day month day_of_week
Examples:
0 */6 * * * - Every 6 hours0 0 * * * - Daily at midnight0 */1 * * * - Every hour0 2 * * * - Daily at 2 AM0 0 * * 0 - Weekly on Sunday at midnightSet CHAT_TYPES to control what gets backed up:
private - One-on-one conversationsgroups - Group chatschannels - Channels you're subscribed toExamples:
CHAT_TYPES=private - Only private chatsCHAT_TYPES=private,groups - Private chats and groupsCHAT_TYPES=private,groups,channels - Everything# Docker
docker-compose exec telegram-backup python -m src.export_backup stats
# Local
python -m src.export_backup stats
# Docker
docker-compose exec telegram-backup python -m src.export_backup list-chats
# Local
python -m src.export_backup list-chats
Export all messages:
python -m src.export_backup export -o backup.json
Export specific chat:
python -m src.export_backup export -o chat_backup.json -c 123456789
Export date range (point-in-time recovery):
python -m src.export_backup export -o recovery.json \
-s 2024-01-01 \
-e 2024-12-31
# Docker
docker-compose exec telegram-backup python -m src.telegram_backup
# Local
python -m src.telegram_backup
data/
āāā session/
ā āāā telegram_backup.session # Authentication session (stored separately)
āāā backups/
āāā telegram_backup.db # SQLite database
āāā media/ # Downloaded media files
āāā 123456/ # Chat ID
ā āāā 20240101_120000_1.jpg
ā āāā 20240101_120100_2.mp4
āāā 789012/
āāā ...
The SQLite database contains:
Example: 10,000 messages with 1,000 photos ā 20 MB text + 1-2 GB media
Export messages from desired date range:
python -m src.export_backup export -o recovery.json \
-s 2024-06-01 -e 2024-06-30
The JSON file contains all messages and metadata from that period
Media files are referenced by path in the JSON
The SQLite database can be queried directly:
sqlite3 data/backups/telegram_backup.db
# Example queries
SELECT COUNT(*) FROM messages;
SELECT * FROM chats;
SELECT * FROM messages WHERE date >= '2024-01-01' LIMIT 10;
Problem: "Failed to authorize"
setup_auth.py again to re-authenticate+1234567890)Problem: "Two-factor authentication required"
Problem: "No new messages"
Problem: "Media download failed"
MAX_MEDIA_SIZE_MB settingProblem: "Permission denied" errors
chmod -R 755 data/
Problem: Container keeps restarting
docker-compose logs.env file has correct credentialssetup_auth.py first)Problem: Backups don't run on schedule
docker-compose logs -fdocker-compose ps.env file secure and never commit it to version control.session file contains authentication tokens - protect it like a passwordTo backup multiple Telegram accounts:
Create separate .env files:
cp .env .env.account1
cp .env .env.account2
Use different session names:
# .env.account1
SESSION_NAME=account1
# .env.account2
SESSION_NAME=account2
Run separate containers or processes for each account
You can import the modules in your own scripts:
import asyncio
from src.config import Config, setup_logging
from src.telegram_backup import run_backup
async def custom_backup():
config = Config()
setup_logging(config)
await run_backup(config)
asyncio.run(custom_backup())
Access backup data programmatically:
from src.database import Database
from datetime import datetime
db = Database('data/backups/telegram_backup.db')
# Get all chats
chats = db.get_all_chats()
# Get messages in date range
messages = db.get_messages_by_date_range(
start_date=datetime(2024, 1, 1),
end_date=datetime(2024, 12, 31)
)
# Get statistics
stats = db.get_statistics()
print(f"Total messages: {stats['messages']}")
db.close()
MAX_MEDIA_SIZE_MB are skippedContributions are welcome! Please feel free to submit issues or pull requests.
This project is provided as-is for personal use. Make sure to comply with Telegram's Terms of Service when using the API.
For issues and questions:
Note: This tool uses the official Telegram API and operates as a regular Telegram client. It does not violate Telegram's Terms of Service when used responsibly for personal backups.
Content type
Image
Digest
sha256:674feac57ā¦
Size
137.8 MB
Last updated
9 months ago
docker pull drumsergio/telegram-backup-automation