A Python bot that automatically downloads media files from a specified Telegram channel, organizing them into folders by chapters/topics.
- Downloads all media (videos, documents, photos) from a specified Telegram channel
- Automatically organizes files into chapter folders based on message content
- Resumes downloads from where it left off if interrupted
- Shows download progress in real-time
- Handles rate limiting with automatic pauses
- Downloads media in the original quality
- Python 3.7+
- A Telegram account
- Telegram API credentials (API ID and Hash)
-
Clone this repository or download the script
-
Install the required dependencies:
pip install pyrogram tgcrypto python-dotenv
-
Create a
.envfile in the same directory as the script with the following content:API_ID=your_telegram_api_id API_HASH=your_telegram_api_hash CHANNEL_USERNAME=target_channel_username
- Visit https://my.telegram.org/auth and log in with your phone number
- Go to "API development tools"
- Create a new application (fill in any required fields)
- Copy the "API ID" and "API Hash" values to your
.envfile
-
Configure the download folder in the script:
base_download_folder = r"C:\Users\your_username\Videos\your_folder"
-
Run the script:
python downloader.py
-
The first time you run the script, you'll be prompted to enter your phone number and the authentication code sent to your Telegram account.
Base Download Folder/
├── 01 - Chapter Title/
│ ├── file1.mp4
│ ├── file2.pdf
│ └── ...
├── 02 - Another Chapter/
│ ├── file1.mp4
│ └── ...
└── Uncategorized/
├── file1.jpg
└── ...
- The script connects to Telegram using your API credentials
- It retrieves messages from the specified channel
- It automatically detects chapter titles from messages using regex patterns
- For each media file, it:
- Creates the appropriate chapter folder
- Downloads the file with a progress bar
- Saves the last processed message ID for resuming later
The script creates a last_id.txt file that stores the ID of the last successfully downloaded message. If the script is interrupted, it will resume from this point when restarted.
Telegram has rate limits for downloads. If an error occurs, the script will pause for 10 seconds before continuing, helping to avoid temporary blocks.
-
To change the number of messages to retrieve, modify the
limitparameter:messages = list(app.get_chat_history(CHANNEL_USERNAME, limit=10000))
-
To customize the chapter detection pattern, modify the regex in the code:
match = re.match(r'^\s*(\d{1,2})[\s\-\.:]+(.+)', text_to_check.strip())
This project is open source and available for personal use.
This script uses Pyrogram, a powerful Telegram client library for Python.