# telegram-dl

A Python CLI tool to download videos from Telegram channels.

## Installation

```bash
pip install telegram-dl
```

## Quick Start

### 1. Get Telegram API Credentials

1. Go to [my.telegram.org](https://my.telegram.org)
2. Log in with your phone number
3. Click **"API development tools"**
4. Create a new app
5. Copy your **API ID** and **API Hash**

### 2. Download Videos

```bash
# List your channels first
telegram-dl --api-id 12345 --api-hash abc123def456 --phone +1234567890 --list-channels

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

### 3. Use Custom Output Directory

```bash
telegram-dl --api-id 12345 --api-hash abc123def456 --phone +1234567890 --channel -1001234567890 --output ./my_videos
```

## Programmatic Usage

```python
from telegram_dl import TelegramDownloader

async def main():
    async with TelegramDownloader(
        api_id=12345,
        api_hash="abc123def456",
        phone="+1234567890"
    ) as dl:
        # List channels
        async for dialog in dl.client.iter_dialogs():
            if dialog.is_channel:
                print(f"{dialog.id} | {dialog.title}")
        
        # Download all videos
        await dl.download_all_videos(channel_id, "./videos")

asyncio.run(main())
```

## High Level Design (HLD)

> **Note:** For colorful Mermaid diagrams, see the [GitHub README](https://github.com/kuldeep27396/telegram-dl/blob/main/README.md)

### Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                      User Layer (👤)                         │
│  ┌─────────────────┐         ┌─────────────────────┐       │
│  │  CLI Interface  │         │    Python API        │       │
│  │   (telegram-dl) │         │ TelegramDownloader   │       │
│  └─────────────────┘         └─────────────────────┘       │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    Core Layer (⚙️)                           │
│  TelegramDownloader                                          │
│  ├─ connect() / disconnect()                                 │
│  ├─ get_channel_videos()                                     │
│  ├─ download_video()                                         │
│  └─ download_all_videos()                                    │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                  Protocol Layer (🔌)                        │
│  Telethon Library                                           │
│  ├─ MTProto Protocol                                       │
│  ├─ Session Management                                     │
│  └─ OTP/2FA Authentication                                 │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│              External Services (🌐)                         │
│            Telegram Servers (api.telegram.org)               │
└─────────────────────────────────────────────────────────────┘
```

### Data Flow

```
User ──► CLI/API ──► TelegramDownloader ──► Telethon ──► Telegram
           │               │                    │           │
           │               │                    │           │
        Credentials    Connect & Auth       MTProto    Server
           │               │                    │           │
           ▼               ▼                    ▼           ▼
         Input      Session Created       Protocol    Video Stream
```

### Class Structure

```
TelegramDownloader
├── api_id: int
├── api_hash: str  
├── phone: str
├── client: TelegramClient
│
├── connect() → TelegramClient
├── disconnect()
├── get_dialogs() → List[Dict]
├── get_channel_videos(channel_id) → List[Dict]
├── download_video(channel_id, video_id, output_dir, filename) → str
└── download_all_videos(channel_id, output_dir, progress_callback) → List[str]

Exceptions
├── TelegramDLError (base)
├── AuthenticationError
├── ChannelNotFoundError
└── VideoNotFoundError
```

### Session Management Flow

```
First Run ──► OTP Verification ──► Save Session ──► Ready
    │              │                     │
    │              │                     ▼
    │              └───────────────────► Done!
    │
    ▼
Next Run ──► Session Valid? ──► Yes ──► Ready
                │
                └── No ──► OTP Verification
```

### Error Handling

```
┌─────────────────────────────────────────┐
│           Telethon Errors               │
│  ConnectionError │ SessionPasswordError  │
└─────────────────┴───────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────┐
│          Custom Exceptions              │
│  TelegramDLError (base)                │
│  ├─ AuthenticationError                 │
│  ├─ ChannelNotFoundError                │
│  └─ VideoNotFoundError                  │
└─────────────────────────────────────────┘
                     │
                     ▼
          User fixes & retries
```

### Components

| Component | File | Responsibility |
|-----------|------|----------------|
| CLI | `cli.py` | Command-line interface |
| Client | `client.py` | Core download logic |
| Exceptions | `exceptions.py` | Error classes |

### Key Features

- **CLI Interface** - Simple commands, progress tracking, channel listing
- **Core Logic** - Async download, auto retry, skip existing files
- **Session Management** - Persistent login, OTP/2FA support
- **File Handling** - Named preservation, custom output, progress callbacks

## Features

- Download all videos from Telegram channels
- Automatic session management (login once, use many times)
- Progress tracking
- Named file preservation from Telegram
- Skip already downloaded files
- CLI and programmatic API

## Requirements

- Python 3.10+
- Telegram API credentials (get from [my.telegram.org](https://my.telegram.org))

## License

MIT License
