Skip to content

About

⬇️ Telegram bot downloading video and audio from YouTube, Instagram and TikTok via yt-dlp, with AI summaries

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

4 Commits

Folders and files

Repository files navigation

dreamDownloader

Telegram bot + REST API for downloading media from YouTube, Instagram, TikTok and SoundCloud — with AI-powered voice transcription & summarization, QR tools, a web admin panel, and an MCP server so AI agents can use everything as tools.

Send a link — get the file.

Features

📥 Download from anywhere

Platform What you get
YouTube Video in any quality / audio only
Instagram Posts, reels, stories
TikTok Videos and photo sets
SoundCloud Tracks with full metadata

🔄 Any format you need

The same link can be returned as an original video/audio file, extracted MP3, a Telegram voice note (ogg/opus) or a video circle (round note). Plus transcription of any file — speech-to-text for voice, audio or video.

⚡ Instant delivery via Telegram cache (the best part)

After the first download, the file is re-uploaded to Telegram's own servers and the bot remembers its file_id per URL. Every next request for the same link is served instantly from cache:

  • no re-downloading from Instagram/TikTok/YouTube — files don't come from slow, geo-blocked origin CDNs, but from Telegram's CDN, the fastest path
  • zero disk usage on the server — nothing is stored locally after the first upload
  • URL-level deduplication in SQLite + auto-cleanup of expired cache entries

First request downloads, all following requests are instant.

🤖 For bots, services & AI agents

  • Inline mode — download media right inside any chat via inline query, without opening the bot
  • REST API — /api/download, /api/transcribe, /api/summarize, /api/clean, /api/qr, … so any external service can use it as a download backend
  • AI summarization — short summary of any transcription plus a "clean up" pass that fixes ASR artifacts
  • MCP server — exposes the whole stack as Model Context Protocol tools for Claude, Cursor and other agents
  • Admin panel — /admin with stats, users, downloads, transcriptions and activity feed
  • QR codes — generate and decode via bot or API

Stack

Python Flask aiogram yt-dlp SQLite

Project layout

main.py            # Bot (aiogram) + Flask API + admin panel + database, single entrypoint
config.py          # Optional config module (env-based defaults)
site.html          # Public landing page served at /
admin.html         # Single-page admin UI served at /admin
mcp/               # MCP server for AI agents (see mcp/README.md)
  mcp_server.py    #   FastMCP server: 8 tools over the REST API
  openapi.yaml     #   OpenAPI spec of the REST API
  install.sh       #   systemd deployment helper (Linux)
  mcp-download.service

Setup

pip install -r requirements.txt
python main.py        # starts the bot and the API together

Environment variables

Variable Description
BOT_TOKEN Telegram bot token (required)
ADMIN_ID Telegram user ID of the admin
ADMIN_USERNAME / ADMIN_PASSWORD_SALT / ADMIN_PASSWORD_HASH Admin panel credentials (pbkdf2_sha256, 200k iterations)
ADMIN_SECRET_KEY Flask session signing secret
BOT_API_BASE_URL Optional local Telegram Bot API server (removes the 20 MB upload limit)
DREAMAI_API_URL / DREAMAI_API_KEY OpenAI-compatible LLM endpoint used for summaries
DREAM_ASR_URL / DREAM_ASR_TOKEN Speech-to-text endpoint used for transcriptions

For age-restricted content, provide your own ig_cookies.txt / yt_cookies.txt next to main.py (git-ignored).

REST API

Runs on port 5030 by default (served publicly through nginx in production):

Endpoint Method Description
/health GET Service status
/api/download POST {url, format} → task id + list of files with direct links. Formats: original, mp3, voice, note
/api/transcribe POST {url} or multipart file → recognized text
/api/summarize POST {text} → AI summary
/api/clean POST {text} → cleaned-up transcript
/api/qr POST {text} → PNG image
/api/qr/decode POST multipart file → decoded text

Full machine-readable spec: mcp/openapi.yaml.

MCP server (new)

The mcp/ directory contains an MCP server ("Download API") built with FastMCP. It lets any AI agent use the downloader as a set of tools instead of raw HTTP calls:

Tool What it does
download_content Download content from a link (Instagram/TikTok/YouTube/SoundCloud), optionally converting to MP3 / voice note / video circle; returns direct file URLs
transcribe_media Speech-to-text from an audio/video URL or local file
summarize_text AI summary of a text (in Russian)
clean_text Clean up "dirty" ASR text (artifacts, punctuation)
generate_qr Generate a QR code (returns a PNG image)
decode_qr Decode a QR code from a local image or URL
get_status Health check of the service
supported_platforms List of supported platforms and formats

Transports:

  • streamable-http (default) — remote access for agents; listens on 127.0.0.1:5031, typically exposed via nginx at https://your-domain/mcp
  • stdio — for local clients (Claude Desktop, Cursor): python mcp/mcp_server.py stdio

Quick start:

pip install -r mcp/requirements.txt
python mcp/mcp_server.py          # HTTP transport
python mcp/mcp_server.py stdio    # local stdio transport

Example MCP client config:

{
  "mcpServers": {
    "download-api": {
      "command": "python",
      "args": ["mcp/mcp_server.py", "stdio"]
    }
  }
}

Environment variables: DOWNLOAD_API_BASE (default http://127.0.0.1:5030), DOWNLOAD_PUBLIC_BASE, DOWNLOAD_MCP_PORT, DOWNLOAD_HTTP_TIMEOUT.

See mcp/README.md for full docs, including Node.js/Python connection examples (connect-ai-site.md) and a systemd unit for deployment.

Security notes

All secrets are read from environment variables — nothing sensitive is committed. Never commit *.db, cookies*.txt, .env, logs or downloads; they are covered by .gitignore.

Contact

Telegram: @dreamcatch_r


dreamDownloader (RU)

Telegram-бот + REST API для скачивания медиа с YouTube, Instagram, TikTok и SoundCloud — с AI-транскрибацией и суммаризацией голоса, QR-инструментами, веб-админкой и MCP-сервером, позволяющим AI-агентам использовать всё это как инструменты.

Отправьте ссылку — получите файл.

Возможности

📥 Скачивание отовсюду

Платформа Что получаешь
YouTube Видео в любом качестве / только аудио
Instagram Посты, reels, сторис
TikTok Видео и фотосеты
SoundCloud Треки с полными метаданными

🔄 Любой нужный формат

По одной и той же ссылке файл можно получить как оригинальное видео/аудио, извлечённый MP3, Telegram голосовое (ogg/opus) или видеокружок. Плюс транскрибация любого файла — speech-to-text для голосовых, аудио и видео.

⚡ Мгновенная выдача через кеш Telegram (главная фишка)

После первого скачивания файл перезаливается на серверы Telegram, а бот запоминает его file_id по ссылке. Каждый следующий запрос по той же ссылке отдаётся мгновенно из кеша:

  • без повторного скачивания с Instagram/TikTok/YouTube — файлы идут не с медленных и геоблокированных исходных CDN, а с CDN Telegram, самым быстрым путём
  • ноль места на диске сервера — после первой загрузки ничего локально не хранится
  • дедупликация ссылок в SQLite + автоочистка устаревших записей кеша

Первый запрос скачивает, все последующие — мгновенны.

🤖 Для ботов, сервисов и AI-агентов

  • Инлайн-режим — скачивай медиа прямо в любом чате через inline-запрос, не открывая бота
  • REST API — /api/download, /api/transcribe, /api/summarize, /api/clean, /api/qr, … — любой внешний сервис может использовать его как бэкенд скачивания
  • AI-суммаризация — краткое содержание любой транскрипции плюс «чистка», исправляющая артефакты ASR
  • MCP-сервер — весь стек доступен как инструменты Model Context Protocol для Claude, Cursor и других агентов
  • Админ-панель — /admin со статистикой, пользователями, загрузками, транскрипциями и лентой активности
  • QR-коды — генерация и декодирование через бота или API

Стек

Python Flask aiogram yt-dlp SQLite

Структура проекта

main.py            # Бот (aiogram) + Flask API + админ-панель + база данных, единая точка входа
config.py          # Опциональный модуль конфигурации (значения по умолчанию из env)
site.html          # Публичная лендинг-страница, отдается на /
admin.html         # Одностраничный админский UI, отдается на /admin
mcp/               # MCP-сервер для AI-агентов (см. mcp/README.md)
  mcp_server.py    #   FastMCP-сервер: 8 инструментов поверх REST API
  openapi.yaml     #   OpenAPI-спецификация REST API
  install.sh       #   Помощник развертывания через systemd (Linux)
  mcp-download.service

Установка

pip install -r requirements.txt
python main.py        # запускает бота и API вместе

Переменные окружения

Переменная Описание
BOT_TOKEN Токен Telegram-бота (обязательно)
ADMIN_ID Telegram user ID администратора
ADMIN_USERNAME / ADMIN_PASSWORD_SALT / ADMIN_PASSWORD_HASH Учетные данные админ-панели (pbkdf2_sha256, 200k итераций)
ADMIN_SECRET_KEY Секрет подписи Flask-сессий
BOT_API_BASE_URL Опциональный локальный сервер Bot API (снимает лимит загрузки 20 МБ)
DREAMAI_API_URL / DREAMAI_API_KEY OpenAI-совместимый эндпоинт LLM для саммари
DREAM_ASR_URL / DREAM_ASR_TOKEN Эндпоинт speech-to-text для транскрибации

Для контента с возрастными ограничениями положите свои ig_cookies.txt / yt_cookies.txt рядом с main.py (в git-игноре).

REST API

По умолчанию работает на порту 5030 (в продакшене публикуется через nginx):

Эндпоинт Метод Описание
/health GET Статус сервиса
/api/download POST {url, format} → id задачи + список файлов с прямыми ссылками. Форматы: original, mp3, voice, note
/api/transcribe POST {url} или multipart file → распознанный текст
/api/summarize POST {text} → AI-саммари
/api/clean POST {text} → очищенный текст транскрипции
/api/qr POST {text} → PNG-изображение
/api/qr/decode POST multipart file → декодированный текст

Полная машиночитаемая спецификация: mcp/openapi.yaml.

MCP-сервер

Каталог mcp/ содержит MCP-сервер («Download API») на FastMCP. Он позволяет любому AI-агенту использовать загрузчик как набор инструментов вместо сырых HTTP-запросов:

Инструмент Что делает
download_content Скачивает контент по ссылке (Instagram/TikTok/YouTube/SoundCloud), при необходимости конвертируя в MP3 / голосовое / видеокружок; возвращает прямые URL файлов
transcribe_media Speech-to-text по ссылке на аудио/видео или локальному файлу
summarize_text AI-саммари текста (на русском)
clean_text Чистка «грязного» ASR-текста (артефакты, пунктуация)
generate_qr Генерация QR-кода (возвращает PNG)
decode_qr Декодирование QR-кода из изображения или ссылки
get_status Проверка работоспособности сервиса
supported_platforms Список поддерживаемых платформ и форматов

Транспорты:

  • streamable-http (по умолчанию) — удаленный доступ для агентов; слушает 127.0.0.1:5031, обычно публикуется через nginx как https://your-domain/mcp
  • stdio — для локальных клиентов (Claude Desktop, Cursor): python mcp/mcp_server.py stdio

Быстрый старт:

pip install -r mcp/requirements.txt
python mcp/mcp_server.py          # HTTP-транспорт
python mcp/mcp_server.py stdio    # локальный stdio-транспорт

Пример конфигурации MCP-клиента:

{
  "mcpServers": {
    "download-api": {
      "command": "python",
      "args": ["mcp/mcp_server.py", "stdio"]
    }
  }
}

Переменные окружения: DOWNLOAD_API_BASE (по умолчанию http://127.0.0.1:5030), DOWNLOAD_PUBLIC_BASE, DOWNLOAD_MCP_PORT, DOWNLOAD_HTTP_TIMEOUT.

Полная документация, включая примеры подключения Node.js/Python (connect-ai-site.md) и systemd-unit для развертывания — в mcp/README.md.

Заметки о безопасности

Все секреты читаются из переменных окружения — ничего чувствительного не коммитится. Никогда не коммитьте *.db, cookies*.txt, .env, логи или загрузки; они покрыты .gitignore.

Контакты

Telegram: @dreamcatch_r

About

⬇️ Telegram bot downloading video and audio from YouTube, Instagram and TikTok via yt-dlp, with AI summaries

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages