Skip to content

Smart Telegram bot that downloads and organizes your media files. Automatically creates clean folder structures for movies and TV shows, detects seasons/episodes, manages concurrent downloads with queue system, monitors disk space, supports multi-user access with whitelist. Docker-ready for easy self-hosting. Your personal media librarian!

License

Notifications You must be signed in to change notification settings

ChromuSx/MediaButler

Repository files navigation

🎬 MediaButler - Telegram Media Organizer Bot

MediaButler

Python 3.8+ Docker Ready MIT License Telegram Bot

GitHub Sponsors Ko-fi Buy Me a Coffee PayPal

Modular Telegram bot for automatic organization of your media library

✨ Features

  • 🎬 Smart Organization - Automatically creates folders for movies and TV series
  • πŸ“Ί Series Detection - Recognizes season/episode patterns (S01E01, 1x01, etc.)
  • 🎯 TMDB Integration - Metadata, posters, and automatic renaming
  • πŸ“ Clean Structure - Movies in individual folders, series organized by season
  • ⏳ Queue Management - Multiple downloads with configurable limits
  • πŸ’Ύ Space Monitoring - Real-time control with automatic queue management
  • πŸ‘₯ Multi-user - Whitelist system for authorized users
  • πŸ”„ Resilience - Resume and automatic retry support
  • 🐳 Docker Ready - Easy deployment with Docker Compose

πŸ—οΈ Architecture

The project uses a modular architecture for maximum maintainability and extensibility:

mediabutler/
β”œβ”€β”€ main.py                 # Main entry point
β”œβ”€β”€ core/                   # Core system modules
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ config.py          # Centralized configuration
β”‚   β”œβ”€β”€ auth.py            # Authentication management
β”‚   β”œβ”€β”€ downloader.py      # Download and queue management
β”‚   β”œβ”€β”€ space_manager.py   # Disk space monitoring
β”‚   └── tmdb_client.py     # TMDB API client
β”œβ”€β”€ handlers/              # Telegram event handlers
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ commands.py        # Command handlers (/start, /status, etc.)
β”‚   β”œβ”€β”€ callbacks.py       # Inline button handlers
β”‚   └── files.py           # Received file handlers
β”œβ”€β”€ models/                # Data models
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── download.py        # Download info dataclass
β”œβ”€β”€ utils/                 # Utilities and helpers
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ naming.py          # File name parser and management
β”‚   β”œβ”€β”€ formatters.py      # Message formatting
β”‚   └── helpers.py         # Generic helpers
└── requirements.txt       # Python dependencies

πŸ“¦ Main Modules

Core

  • config: Centralized configuration management with validation
  • auth: Multi-user authorization system with admin
  • downloader: Download manager with queues, retry, and error handling
  • space_manager: Space monitoring and smart cleanup
  • tmdb_client: TMDB integration with rate limiting

Handlers

  • commands: All bot commands (/start, /status, /space, etc.)
  • callbacks: Inline button and interaction management
  • files: Processing of received files with content recognition

Utils

  • naming: Smart file name parsing and folder structure creation
  • formatters: Telegram message formatting and progress bar
  • helpers: Retry logic, validation, rate limiting, async helpers

πŸš€ Quick Start

Prerequisites

  • Python 3.8+ or Docker
  • Telegram API credentials (my.telegram.org)
  • Bot token from @BotFather
  • (Optional) TMDB API key for metadata

Docker Installation (Recommended)

  1. Clone the repository:
git clone https://github.com/yourusername/mediabutler.git
cd mediabutler
  1. Configure environment:
cp .env.example .env
nano .env  # Enter your credentials
  1. Start with Docker Compose:
docker compose up -d

Manual Installation

  1. Setup Python environment:
python -m venv venv
source venv/bin/activate  # Linux/Mac
# or
venv\Scripts\activate  # Windows
  1. Install dependencies:
pip install -r requirements.txt
  1. Configure and start:
cp .env.example .env
nano .env  # Configure credentials
python main.py

πŸ“– Configuration

Main Environment Variables

# Telegram (Required)
TELEGRAM_API_ID=123456
TELEGRAM_API_HASH=abcdef123456
TELEGRAM_BOT_TOKEN=123456:ABC-DEF

# TMDB (Optional but recommended)
TMDB_API_KEY=your_tmdb_api_key
TMDB_LANGUAGE=en-US

# Paths
MOVIES_PATH=/media/movies
TV_PATH=/media/tv
TEMP_PATH=/media/temp

# Authorizations
AUTHORIZED_USERS=123456789,987654321

# Limits
MAX_CONCURRENT_DOWNLOADS=3
MIN_FREE_SPACE_GB=5
WARNING_THRESHOLD_GB=10

See .env.example for all available options.

🎯 Usage

Bot Commands

Command Description Permissions
/start Start bot and show info All
/status Show active downloads and queue All
/space Disk space details All
/waiting Files waiting for space All
/cancel_all Cancel all downloads All
/help Show command guide All
/users List authorized users Admin
/stop Stop the bot Admin

Download Workflow

  1. Send/forward a video file to the bot
  2. Bot analyzes the name and searches TMDB
  3. Confirm or select Movie/TV Series
  4. For series, select season if needed
  5. Automatic download or queued

Resulting Folder Structure

/media/
β”œβ”€β”€ movies/
β”‚   β”œβ”€β”€ Avatar (2009)/
β”‚   β”‚   └── Avatar (2009).mp4
β”‚   └── Inception (2010)/
β”‚       └── Inception (2010).mp4
└── tv/
    β”œβ”€β”€ Breaking Bad [EN]/
    β”‚   β”œβ”€β”€ Season 01/
    β”‚   β”‚   β”œβ”€β”€ Breaking Bad - S01E01 - Pilot.mp4
    β”‚   β”‚   └── Breaking Bad - S01E02 - Cat's in the Bag.mp4
    β”‚   └── Season 02/
    └── The Office/
        └── Season 04/

πŸ”§ Development

Extending the Bot

The modular design makes it easy to add new features:

Add a New Command

  1. Create the method in handlers/commands.py:
async def mycommand_handler(self, event):
    """Handler for /mycommand"""
    if not await self.auth.check_authorized(event):
        return
    
    # Command logic
    await event.reply("Command response")
  1. Register in register():
self.client.on(events.NewMessage(pattern='/mycommand'))(self.mycommand_handler)

Add a Metadata Provider

  1. Create a new module in core/:
# core/metadata_provider.py
class MetadataProvider:
    async def search(self, query: str):
        # Implement search
        pass
  1. Integrate in FileHandlers or where needed

Testing

# Unit tests
python -m pytest tests/

# Test with coverage
python -m pytest --cov=core --cov=handlers --cov=utils tests/

Code Style

The project follows PEP 8:

# Formatting
black .

# Linting
flake8 . --max-line-length=100

# Type checking
mypy .

🐳 Docker

Build Image

docker build -t mediabutler:latest .

Custom Docker Compose

version: '3.8'

services:
  mediabutler:
    image: mediabutler:latest
    container_name: mediabutler
    restart: unless-stopped
    env_file: .env
    volumes:
      - ${MOVIES_PATH}:/media/movies
      - ${TV_PATH}:/media/tv
      - ./session:/app/session
    networks:
      - media_network

networks:
  media_network:
    external: true

πŸ“Š Monitoring

Logs

# Docker logs
docker logs -f mediabutler

# Log file (if configured)
tail -f logs/mediabutler.log

Metrics

The bot exposes internal metrics via the /status command:

  • Active downloads
  • Queued files
  • Available space
  • Download speed

🚧 Roadmap

  • Web UI for management
  • Jellyfin/Plex integration
  • Subtitle support
  • Playlist/channel downloads
  • Customizable notifications
  • Configuration backup/restore
  • REST API for integrations
  • Full multi-language support

🀝 Contributing

Contributions welcome! See CONTRIBUTING.md for guidelines.

  1. Fork the project
  2. Create feature branch (git checkout -b feature/AmazingFeature)
  3. Commit changes (git commit -m 'Add AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open Pull Request

πŸ’– Support the Project

This project is completely free and open source. If you find it useful and would like to support its continued development and updates, consider making a donation. Your support helps keep the project alive and motivates me to add new features and improvements!

GitHub Sponsors Ko-fi Buy Me a Coffee PayPal

Every contribution, no matter how small, is greatly appreciated! ❀️

πŸ“ License

Distributed under the MIT License. See LICENSE for details.

πŸ™ Acknowledgements

  • Telethon - Telegram MTProto client
  • TMDB - Metadata database
  • aiohttp - Asynchronous HTTP client
  • Self-hosted community ❀️

⚠️ Disclaimer

Bot for personal use. Respect copyright laws and only download content you have rights to.


Developed with ❀️ for the self-hosted community

About

Smart Telegram bot that downloads and organizes your media files. Automatically creates clean folder structures for movies and TV shows, detects seasons/episodes, manages concurrent downloads with queue system, monitors disk space, supports multi-user access with whitelist. Docker-ready for easy self-hosting. Your personal media librarian!

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published