Telegram bot that downloads Instagram reels, video posts, photos and carousels in the best available quality, identifies the music used in reels, shows public profile info and keeps a per-user download history. An optional FastAPI service exposes the same downloader over HTTP.
- Smart link detection – paste a message containing any Instagram link (
/p/,/reel/,/reels/,/tv/, profile). Query strings, mobile and short domains are handled; everything else is rejected before any network request (SSRF-safe). - Maximum quality – all renditions are compared and the highest-resolution progressive MP4 is chosen. Separate audio/video streams are muxed losslessly with FFmpeg. Files are only converted when they are not already H.264/AAC MP4 (resolution and aspect ratio are never changed).
- Carousels – every video and image is sent as a Telegram album (10 items per album).
- Instant re-sends – the Telegram
file_idof every uploaded item is cached; the same post is re-sent without touching Instagram again. Concurrent requests for the same post are coalesced into one fetch. - Music recognition – inline 🎵 Identify song button on every video and the
/songcommand for any audio/video/voice file. Pluggable providers: Shazam (free) or AudD (paid). - Song search by name – type an artist or song title (or
/search …) and get the top matches with cover art, Apple Music link, Spotify/YouTube search links and a 30-second preview. - Audio only – inline 🎧 Audio only button extracts the original AAC track.
- Profile info –
/profile usernamewith picture, counters, bio and recent public posts. - History –
/historylists the last 10 downloads with status and size. - Progress – throttled status messages (fetching → downloading with progress bar → processing → uploading); downloads run as background tasks so other users are never blocked.
- Production hardening – global concurrency cap, per-user rate limit and single active job, retries with
exponential backoff, HTTP connection pooling, size caps, per-job temp directories (0700, always
cleaned), structured/JSON logging with credential redaction,
/healthendpoint, Docker image with FFmpeg.
| Command | Description |
|---|---|
/start |
Welcome + help |
/help |
Usage and limits |
/song |
Identify music – reply to a video/audio/voice, or send one (or a reel link) after the command. /song <text> searches by name |
/search <artist or song> |
Find a song by name (plain text in a private chat does the same) |
/profile <username or URL> |
Public profile information |
/history |
Your last 10 downloads |
| (any Instagram link) | Download the post |
- Python 3.12, uv
- FFmpeg (
apt install ffmpeg) – needed for muxing, conversion, audio extraction and music recognition - PostgreSQL (or SQLite for local development via
DATABASE_URL) - A Telegram bot token from @BotFather
- Strongly recommended: an Instagram session (see below). Instagram blocks most anonymous requests.
git clone https://github.com/mexmonjonovuz/Instadownloader_bot.git
cd Instadownloader_bot
uv sync --extra api # --extra api only if you also want the HTTP API
cp .env.example .env # fill in BOT_TOKEN and database settings
uv run alembic upgrade head # create / upgrade the schema (existing data is preserved)
uv run python -m bot.main # or: make botQuick local run without PostgreSQL: set DATABASE_URL=sqlite+aiosqlite:///./bot.db in .env.
Instagram rate-limits and login-walls anonymous clients aggressively. Configure one of:
- Browser cookies for yt-dlp (preferred) – export a Netscape
cookies.txtfrom a browser logged into a throwaway Instagram account (e.g. the Get cookies.txt LOCALLY extension) and setINSTAGRAM_COOKIES_FILE=/path/to/cookies.txt. - instaloader session –
uv run instaloader --login YOUR_USERcreates a session file; setINSTAGRAM_USERNAMEandINSTAGRAM_SESSION_FILE.
Use a dedicated account – Instagram may challenge or block accounts used for automated access.
| Variable | Default | Description |
|---|---|---|
BOT_TOKEN |
– | Telegram bot token (required) |
ADMIN_LIST |
– | Comma-separated Telegram user ids exempt from rate limits |
HEALTH_PORT |
8081 |
Port for GET /health (0 disables) |
DB_NAME, DB_USER, DB_PASS, DB_HOST, DB_PORT |
– | PostgreSQL connection |
DATABASE_URL |
– | Full SQLAlchemy URL overriding the fields above (e.g. sqlite+aiosqlite:///./bot.db) |
DB_POOL_SIZE / DB_MAX_OVERFLOW |
5 / 10 |
Connection pool |
TEMP_DIR |
./media |
Working directory for downloads (cleaned automatically) |
MAX_CONCURRENT_DOWNLOADS |
3 |
Global cap on simultaneous Instagram downloads |
DOWNLOAD_TIMEOUT |
180 |
Seconds per resolve/download step |
DOWNLOAD_RETRIES |
3 |
Attempts with exponential backoff for transient errors |
MAX_UPLOAD_MB |
49 |
Telegram bot upload limit (50 MB; 2000 with a local Bot API server) |
MAX_DOWNLOAD_MB |
500 |
Hard cap on what is downloaded from Instagram at all |
DOWNLOAD_CACHE_TTL |
3600 |
Seconds to cache post metadata in memory |
INSTAGRAM_COOKIES_FILE |
– | Netscape cookies.txt for yt-dlp |
INSTAGRAM_USERNAME / INSTAGRAM_SESSION_FILE |
– | instaloader session |
PROXY_URL |
– | HTTP(S)/SOCKS proxy for Instagram traffic |
FFMPEG_PATH / FFPROBE_PATH |
auto | Override binary lookup |
PUBLIC_BASE_URL |
– | Public URL of the FastAPI service; enables direct links for files above MAX_UPLOAD_MB |
MUSIC_PROVIDER |
shazam |
shazam | audd | none |
AUDD_API_TOKEN |
– | Required when MUSIC_PROVIDER=audd |
MUSIC_CLIP_SECONDS / MUSIC_CLIP_OFFSET |
12 / 0 |
Clip window sent to the recognizer (up to 3 windows are tried) |
MUSIC_TIMEOUT |
30 |
Recognizer timeout |
MUSIC_AUTO_IDENTIFY |
false |
Identify music automatically after every reel download |
MUSIC_SEARCH_LIMIT / MUSIC_SEARCH_COUNTRY |
5 / us |
Song search by name (iTunes Search API, free, no key) |
RATE_LIMIT_PER_MINUTE |
6 |
Requests per user per minute |
RATE_LIMIT_ACTIVE_JOBS |
1 |
Simultaneous long jobs per user |
LOG_LEVEL / LOG_JSON |
INFO / false |
Logging |
The recognizer is a pluggable interface (bot/services/music/base.py). Two providers ship:
| Provider | Cost | Notes |
|---|---|---|
Shazam (shazamio) – default |
Free, no key | Uses Shazam's undocumented endpoint; may be throttled or break without notice. Returns title, artist, album, cover art, Shazam/Apple Music/YouTube links. No numeric confidence. |
AudD (audd.io) |
Paid, per-request (small free trial; see audd.io pricing) | Official API with a score and real Spotify/Apple Music/Deezer links. Set MUSIC_PROVIDER=audd and AUDD_API_TOKEN. |
Recognition tries up to 4 clip windows (middle of the track first, since intros are rarely recognisable); clips are clamped to 4–15 s because fingerprinting a 30 s clip takes ~100 s. Remixed, sped-up or voice-over audio can still fail – the bot then suggests searching by name.
Search by name uses Apple's public iTunes Search API (free, no key, same index the Shazam library uses).
When the provider has no direct link, the buttons are labelled 🔍 Spotify / YouTube / Apple Music and open a
search for artist – title – nothing is fabricated. When recognition fails the bot says so.
Set MUSIC_PROVIDER=none to disable the feature entirely.
cp .env.example .env # set BOT_TOKEN, DB_PASS, (INSTAGRAM_COOKIES_FILE) …
docker compose up -d --build
docker compose logs -f botdocker-compose.yml starts PostgreSQL, runs alembic upgrade head once (migrate), then the bot and the
optional api service (port 8000). The image includes FFmpeg, runs as a non-root user and has a
HEALTHCHECK on /health. Mount your cookies file read-only into the bot container and point
INSTAGRAM_COOKIES_FILE at it.
The first migration creates the users table only if it is missing, so a database created by the old
create_all() code is upgraded in place: alembic upgrade head. Nothing is dropped or reset.
POST /api/download {"url": "https://www.instagram.com/reel/…/"}
→ {"status":"ok","download_link":"…/static/videos/<uuid>.mp4","media_type":"REEL","author":"…","files":[…],"expires_in":600}
GET /health
Errors map to 404 (not found), 403 (private / login wall), 429 (Instagram rate limit), 413 (too large), 415 (unsupported). Served files are random UUID names and are removed after 10 minutes.
uv sync --extra api
uv run pytest -q # 89 tests; ffmpeg tests skip when no binary is available
uv run alembic revision --autogenerate -m "describe change"External services (Instagram, Shazam, Telegram) are mocked in the test-suite. The dev dependency
imageio-ffmpeg provides an FFmpeg binary for local tests when none is installed system-wide.
bot/
main.py startup, middlewares, health server, graceful shutdown
config.py typed configuration from environment
handlers/ start/help · download (links, albums, audio) · song · history · profile
middlewares/ user registration · rate limiting
keyboards/ inline buttons + callback data
services/
instagram/ urls (validation) · ytdlp_provider · instaloader_provider · downloader (orchestrator)
music/ base (interface) · shazam · audd · service (clip extraction + provider)
ffmpeg.py probe / remux / merge / audio / thumbnail
http.py pooled aiohttp session, streaming downloads with size caps
jobs.py background task registry
database/models/ users (existing) · downloads · media_caches · music_recognitions
utils/ cache (TTL + coalescing) · ratelimit · retry · tempfiles · progress · formatting · logging
app/ FastAPI service reusing bot.services
migrations/ Alembic (async)
tests/ pytest (SQLite, mocked externals)
| Symptom | Cause / fix |
|---|---|
| "Instagram is blocking anonymous access…" | Configure INSTAGRAM_COOKIES_FILE or an instaloader session; rotate the account/IP if it persists. |
| "Instagram is rate-limiting requests…" | Lower MAX_CONCURRENT_DOWNLOADS, use a session, wait a few minutes. |
| "above Telegram's 50 MB bot upload limit" | Bot API limit. Run the api service with PUBLIC_BASE_URL to hand out direct links, or use a local Bot API server and raise MAX_UPLOAD_MB. |
| "Audio processing is not available" | FFmpeg is missing – install it or set FFMPEG_PATH. |
| "Music recognition is unavailable" | Shazam throttled/unreachable, or AudD quota/invalid token – check logs. |
| "I couldn't identify the music" | Genuine no-match (remix / sped-up / speech over music). Logs show every window tried (music: window …). Use /search by name. |
database connection failed at startup |
Check DB_*/DATABASE_URL; the bot keeps working without history/caching. |
Stale files in TEMP_DIR |
Swept automatically every 15 min (older than 1 h); safe to delete manually. |