Skip to main content

A production-ready Python CLI tool to download videos from Telegram channels

Project description

telegram-dl

PyPI Version Python Versions License Tests Code Quality

Download videos from your own Telegram channels and groups easily.

This tool uses Telegram's official API - the same way the Telegram app works. It's 100% legal according to Telegram's Terms of Service.

Installation

pip install telegram-dl

Quick Start (3 Steps)

Step 1: Get Telegram API Credentials (Free)

  1. Go to my.telegram.org
  2. Login with your phone number
  3. Click "API development tools"
  4. Click "Create application"
  5. Copy your API ID and API Hash

Step 2: Find Your Channel ID

# Run this command with your credentials
telegram-dl --api-id YOUR_API_ID --api-hash YOUR_API_HASH --phone +1234567890 --list-channels

You'll see a list like:

Available channels and groups:

  [Channel] -1001234567890 | My Learning Videos
  [Channel] -1009876543210 | Course Materials
  [Group]   -1001112223334 | Study Group

Step 3: Download Videos

# Download all videos from a channel
telegram-dl --api-id 12345 --api-hash abc123 --phone +1234567890 --channel -1001234567890

Is This Legal?

Yes, absolutely!

This tool uses Telegram's Official API, which is the same API used by:

  • The official Telegram app
  • Telegram Desktop
  • Telegram Web
  • Many other Telegram clients

What this means:

  • ✅ Downloads videos from channels you are a member of
  • ✅ Uses MTProto protocol (Telegram's official protocol)
  • ✅ Your credentials stay on your device
  • ✅ No data is sent to third parties

What you can do:

  • ✅ Download your own content
  • ✅ Download content from channels you joined
  • ✅ Backup your purchased courses

What you cannot do:

  • ❌ Download from private channels you're not a member of
  • ❌ Redistribute copyrighted content
  • ❌ Violate channel/group rules

Read more: Telegram API Terms

Features

For Users

  • Easy to use - Just 3 commands to get started
  • Progress tracking - See download progress with progress bars
  • Skip existing - Don't re-download files you already have
  • Multiple retry - Automatically retries failed downloads
  • Custom output - Save to any folder you want

For Developers (Interview Ready!)

  • Production-Ready Code - Clean architecture with SOLID principles
  • Design Patterns - Builder, Factory, Observer, Repository, Strategy
  • Type Safety - Full Pydantic validation
  • Well Tested - 27 unit tests
  • Documented - Comprehensive docstrings
  • Extensible - Easy to add new features

How It Works

Architecture Overview

┌─────────────────────────────────────────────────────────────┐
│                        You (User)                          │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    CLI Interface                            │
│            (Commands: --list-channels, --download)          │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                  TelegramDownloader                        │
│    - Manages connection                                    │
│    - Handles downloads                                     │
│    - Notifies progress                                     │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│              Telethon Library (Official API)                │
│    - MTProto Protocol                                      │
│    - Encryption                                             │
│    - Session Management                                    │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                  Telegram Servers                          │
└─────────────────────────────────────────────────────────────┘

Data Flow

1. You provide credentials
         ↓
2. Tool connects to Telegram (using MTProto)
         ↓
3. Tool authenticates you (same as Telegram app)
         ↓
4. Tool fetches your channel list
         ↓
5. You select channel to download
         ↓
6. Tool iterates through messages
         ↓
7. For each video:
   - Check if already downloaded
   - Download video file
   - Update progress
         ↓
8. Done! Videos saved to your computer

Code Examples

Simple Usage

from telegram_dl import TelegramDownloader, TelegramCredentials
import asyncio

async def main():
    # Your credentials
    credentials = TelegramCredentials(
        api_id=12345,
        api_hash="abc123def456",
        phone="+1234567890"
    )
    
    # Download videos
    async with TelegramDownloader(credentials) as dl:
        results = await dl.download_all_videos(-1001234567890)
        
    print(f"Downloaded {len(results)} videos!")

asyncio.run(main())

With Progress Bar

from telegram_dl import TelegramDownloader
from telegram_dl.patterns import ProgressBarObserver

downloader = TelegramDownloader(credentials)
downloader.attach_observer(ProgressBarObserver())

async with downloader as dl:
    await dl.download_all_videos(-1001234567890)

Using Builder Pattern

from telegram_dl import DownloaderBuilder

downloader = (
    DownloaderBuilder()
    .with_credentials(api_id, api_hash, phone)
    .with_output_dir("./my_videos")
    .with_retry_strategy("exponential", max_attempts=5)
    .with_progress_bar()
    .with_logging()
    .build()
)

Design Patterns Used

Pattern Where Used Why
Builder DownloaderBuilder Flexible configuration
Factory RetryStrategyFactory Create retry strategies
Observer ProgressBarObserver Notify progress updates
Repository VideoRepository Manage video data
Strategy Retry strategies Swap algorithms easily

SOLID Principles

Principle Implementation
Single Responsibility Each class has one job
Open/Closed Add features without modifying existing code
Liskov Substitution Swap implementations easily
Interface Segregation Small, focused interfaces
Dependency Inversion Depend on abstractions

Project Structure

telegram-dl/
├── telegram_dl/
│   ├── __init__.py          # Package exports
│   ├── cli.py               # Command-line interface
│   ├── client.py            # Main downloader class
│   ├── exceptions.py        # Custom exceptions
│   ├── models.py            # Pydantic data models
│   └── patterns.py          # Design patterns
├── tests/
│   ├── conftest.py          # Test fixtures
│   └── test_telegram_dl.py  # Unit tests (27 tests)
├── pyproject.toml           # Package configuration
└── README.md                # This file

Building From Source

# Clone the repository
git clone https://github.com/kuldeep27396/telegram-dl
cd telegram-dl

# Install dependencies
pip install -e .

# Run tests
pytest tests/ -v

# Build package
rm -rf dist/
python -m build

# Publish to PyPI
twine upload dist/*

Requirements

  • Python 3.10 or higher
  • Telegram API credentials (free from my.telegram.org)

Dependencies

Package Purpose
telethon Telegram API client
pydantic Data validation
tenacity Retry logic
tqdm Progress bars

CLI Options

# Required
--api-id          Your Telegram API ID
--api-hash        Your Telegram API Hash
--phone           Your phone number (+1234567890)

# Optional
--channel         Channel ID to download from
--output          Output directory (default: ./telegram_videos)
--session         Session name (default: telegram_dl_session)
--list-channels   Show all your channels
--with-progress   Show progress bars
--log-level       Logging level (DEBUG, INFO, WARNING, ERROR)

Error Handling

The tool handles these errors gracefully:

Error What Happens
Wrong credentials Prompts to check API ID/Hash
2FA enabled Prompts for password
Channel not found Shows available channels
Network error Auto-retries with backoff
Download failed Logs error, continues with next

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Run tests: pytest tests/ -v
  4. Submit a pull request

License

MIT License - free to use, modify, and distribute.

Links


Made with ❤️ for developers who want to learn from Telegram courses

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

telegram_dl-2.0.1.tar.gz (20.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

telegram_dl-2.0.1-py3-none-any.whl (18.0 kB view details)

Uploaded Python 3

File details

Details for the file telegram_dl-2.0.1.tar.gz.

File metadata

  • Download URL: telegram_dl-2.0.1.tar.gz
  • Upload date:
  • Size: 20.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for telegram_dl-2.0.1.tar.gz
Algorithm Hash digest
SHA256 89a82ddf969fff59f175649b55794205c9b5cb48d747f100fd3b2b923c34681b
MD5 7ac7271e5c5a5a3a93517a22340f0180
BLAKE2b-256 01620079218e7fab989cf1a77a2fe48e1495423f00a24edf6a01b856016a9366

See more details on using hashes here.

File details

Details for the file telegram_dl-2.0.1-py3-none-any.whl.

File metadata

  • Download URL: telegram_dl-2.0.1-py3-none-any.whl
  • Upload date:
  • Size: 18.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for telegram_dl-2.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 0c4142628f9bdd79df209cd2aef3244259912c0a86eadaf3f078968fe857d483
MD5 fa19180df2c5f0687c4544c112e57a98
BLAKE2b-256 81a35746bb9bdc7035b858ba44dcd6be6ea492cd584d05c16a48e6ad2c664dc5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page