Guide

How to build a Telegram video downloader bot in Python (TikTok, Instagram, YouTube)

We will build a Telegram bot with Python and aiogram 3: a user sends a TikTok, Instagram or YouTube link and the bot replies with the video or a photo album. All the code is below, ready to copy and run in an evening.

10 min read

What we are building

The bot accepts any message that contains a link, detects the platform, fetches direct media URLs and sends the result back to the chat: a video as a video, an Instagram carousel as a photo album. TikTok, Instagram, YouTube, X (Twitter), Facebook, Pinterest, RuTube and Likee work out of the box, and you do not write any per-platform code.

Writing your own scrapers for social networks is a thankless job: markup and anti-bot protection change every couple of weeks, and yt-dlp on a server sooner or later hits “Sign in to confirm you’re not a bot”. So we will use a ready-made API instead: InterAPI takes a link and returns JSON with direct file URLs. That keeps the bot small — about 250 lines including error handling.

The flow looks like this:

  1. The user sends a link.
  2. The bot makes one GET /api/v1/auto request — the endpoint detects the platform on its own.
  3. We pick a video or photos from the response.
  4. We ask Telegram to fetch the file by URL. If that fails, we download and upload the file ourselves. If that fails too, we send the direct link.

Requirements

  • Python 3.10 or newer — the code uses annotations like str | None.
  • aiogram 3, aiohttp and python-dotenv.
  • A bot token. Open a chat with @BotFather in Telegram, send /newbot and save the token it gives you.
  • An InterAPI key. Sign up at interapi.dev/register — 1,000 free credits are added right away. You create the key in the dashboard.

Step 1. Project setup and environment variables

Create a folder, a virtual environment and install the dependencies:

bash
mkdir video-bot && cd video-bot
python3 -m venv .venv
source .venv/bin/activate
pip install "aiogram>=3.4" aiohttp python-dotenv

Next to the future bot.py, create a .env file with two values. Keep it out of git: the token and the key are secrets.

ini
BOT_TOKEN=123456789:AAExampleTokenFromBotFather
INTERAPI_KEY=YOUR_API_KEY

Step 2. What the request and response look like

Before writing code, let us look at the API itself. Authentication is the X-API-Key header, and the link goes into the url parameter:

bash
curl -G "https://api.interapi.dev/api/v1/auto" \
  -H "X-API-Key: YOUR_API_KEY" \
  --data-urlencode "url=https://www.tiktok.com/@scout2015/video/6718335390845095173"

The answer is JSON. Here is an abridged real response for TikTok (long URLs shortened, and the optional download_url omitted from the media items):

json
{
  "status": "success",
  "platform": "InterAPI",
  "source": "tiktok",
  "title": "Scramble up ur name & I’ll try to guess it #foryoupage #PetsOfTikTok",
  "media": [
    { "type": "video", "url": "https://v16m.tiktokcdn-us.com/…", "quality": "SD" },
    { "type": "video", "url": "https://v16.tokcdn.com/…_original.mp4?dl=1", "quality": "HD" },
    { "type": "audio", "url": "https://v16-ies-music.tiktokcdn-us.com/…", "quality": "MP3" },
    { "type": "photo", "url": "https://p19-common-sign.tiktokcdn-us.com/…", "quality": "cover" }
  ],
  "video_url": "https://v16.tokcdn.com/…_original.mp4?dl=1",
  "video_hd_url": "https://v16.tokcdn.com/…_original.mp4?dl=1",
  "music_url": "https://v16-ies-music.tiktokcdn-us.com/…",
  "thumbnail": "https://p19-common-sign.tiktokcdn-us.com/…",
  "duration_sec": 0,
  "author": "",
  "duration_ms": 0
}

A few fields matter to us:

  • source — the platform that /api/v1/auto detected;
  • video_url and video_hd_url — the main and HD versions of the video;
  • media — the full list of files: type (video, photo or audio), url, quality and, when present, download_url;
  • title — a caption that works well as the message text;
  • thumbnail and music_url — the cover image and the music track.

Platforms differ in a few ways, and these are the easiest places to trip up:

  • Instagram lists every picture several times in a row in different sizes, from 1440×1440 down to 150×150. If you send everything in media, the album is full of duplicates. The code keeps one URL per slide.
  • TikTok puts the cover into media as a photo item with quality: "cover". That is not a slide, so we skip it.
  • YouTube: video_url is an HLS manifest (.m3u8) and cannot be sent to Telegram as a video. For YouTube we use the file endpoint /api/v1/youtube/file with format_id=18 (a regular 360p MP4 with sound). It is free — downloading the file costs no credits — and accepts the key in the api parameter. Such a URL contains your key, so it must never be shown to users; the private flag in the code takes care of that.

Errors come with ordinary HTTP status codes, and the message sits in the detail field:

json
{ "detail": "TikTok: media not found — the post may be deleted, private or unavailable" }
CodeMeaningWhat the bot does
400The link is not recognized or not supportedAsks for another link
401, 402Invalid key or out of creditsLogs an error, tells the user the service is unavailable
403, 404Private content or the post is goneExplains the reason
429Rate limit exceededWaits and retries after a short pause, tells the user about a long one
5xxA failure on the service sideRetries up to three times

Retrying is safe for your budget: 5xx responses cost no credits, and 4xx responses cost at most one credit. More in the status codes section of the docs.

Step 3. The complete bot code

Save the code as bot.py. It is a fully working bot that handles videos, photo albums and API errors.

python
import asyncio
import logging
import os
import re
from dataclasses import dataclass
from urllib.parse import urlencode

import aiohttp
from aiogram import Bot, Dispatcher, F, Router
from aiogram.exceptions import TelegramAPIError
from aiogram.filters import CommandStart
from aiogram.types import BufferedInputFile, InputMediaPhoto, Message
from aiogram.utils.chat_action import ChatActionSender
from dotenv import load_dotenv

load_dotenv()
BOT_TOKEN = os.environ["BOT_TOKEN"]
API_KEY = os.environ["INTERAPI_KEY"]
API_BASE = "https://api.interapi.dev"

BOT_UPLOAD_LIMIT = 50 * 1024 * 1024  # bots can upload files up to 50 MB
PHOTO_UPLOAD_LIMIT = 10 * 1024 * 1024  # ...and photos up to 10 MB
URL_RE = re.compile(r"https?://[^\s<>\"']+")

MSG = {
    "start": "Send me a link to a video or post from TikTok, Instagram, YouTube, X, Facebook, Pinterest, RuTube or Likee.",
    "no_link": "I don't see a link in your message.",
    "bad_link": "I couldn't recognize that link. Make sure it points to a public post.",
    "private": "This content is private, so I can't download it.",
    "not_found": "Post not found. It may have been deleted.",
    "rate_limit": "Too many requests. Please try again in {minutes} min.",
    "unavailable": "The service is temporarily unavailable. Please try again in a minute.",
    "nothing": "This post has no video or photos to download.",
    "failed": "I couldn't send the file: it is larger than 50 MB or temporarily unavailable.",
    "failed_link": "I couldn't send the file (it may be larger than 50 MB). Here is the direct link:",
}

log = logging.getLogger("downloader")
router = Router()
FILE_IDS: dict[str, str] = {}  # post link -> Telegram file_id (resending a file_id costs nothing)


class ApiError(Exception):
    def __init__(self, status: int, detail: str, retry_after: int = 0) -> None:
        super().__init__(f"HTTP {status}: {detail}")
        self.status = status
        self.detail = detail
        self.retry_after = retry_after


async def fetch_media(http: aiohttp.ClientSession, link: str) -> dict:
    """Call /api/v1/auto. 5xx is free and 429 is cheap, so both are retried a couple of times."""
    for attempt in range(3):
        async with http.get(
            f"{API_BASE}/api/v1/auto",
            params={"url": link},
            headers={"X-API-Key": API_KEY},
            timeout=aiohttp.ClientTimeout(total=60),
        ) as resp:
            if resp.status == 200:
                return await resp.json()
            try:
                body = await resp.json(content_type=None)
            except ValueError:
                body = None
            detail = str(body.get("detail", "")) if isinstance(body, dict) else ""
            retry_after = int(resp.headers.get("Retry-After") or 0)
            status = resp.status
        short_wait = status == 429 and retry_after <= 10  # an hourly limit has a long Retry-After
        if attempt < 2 and (status >= 500 or short_wait):
            await asyncio.sleep(retry_after or 2 * (attempt + 1))
            continue
        raise ApiError(status, detail, retry_after)
    raise RuntimeError("unreachable")


@dataclass
class Result:
    kind: str  # "video" or "photos"
    urls: list[str]
    private: bool = False  # the URL contains our API key: never show it to users or hand it to Telegram


def photo_slides(media: list[dict]) -> list[str]:
    """Instagram lists every slide in several sizes (largest first). Keep one URL per slide."""
    slides: list[str] = []
    last_width = None
    for item in media:
        if item.get("type") != "photo" or item.get("quality") == "cover":
            continue
        m = re.match(r"(\d+)x\d+$", item.get("quality") or "")
        width = int(m.group(1)) if m else None
        if width is None or last_width is None or width > last_width:
            slides.append(item["url"])  # a new slide starts whenever the size goes up again
        last_width = width
    return slides


def pick_result(data: dict, link: str) -> Result | None:
    if data.get("source") == "youtube":
        # For YouTube video_url is an HLS manifest, so use the free file endpoint instead.
        # format_id=18 is the classic muxed 360p MP4 (video + audio), small enough for a bot.
        query = urlencode({"url": link, "kind": "video", "format_id": "18", "mode": "file", "api": API_KEY})
        return Result("video", [f"{API_BASE}/api/v1/youtube/file?{query}"], private=True)
    video = data.get("video_hd_url") or data.get("video_url")
    if video:
        return Result("video", [video])
    slides = photo_slides(data.get("media", []))
    return Result("photos", slides) if slides else None


async def download(http: aiohttp.ClientSession, url: str, limit: int) -> bytes | None:
    """Download a file into memory. Returns None if it is larger than `limit` or the download fails."""
    try:
        async with http.get(url, timeout=aiohttp.ClientTimeout(total=120)) as resp:
            if resp.status != 200 or (resp.content_length or 0) > limit:
                return None
            data = bytearray()
            async for chunk in resp.content.iter_chunked(256 * 1024):
                data += chunk
                if len(data) > limit:
                    return None
            return bytes(data)
    except (aiohttp.ClientError, asyncio.TimeoutError):
        return None


async def send_video(message: Message, http: aiohttp.ClientSession, result: Result, caption: str) -> str | None:
    url = result.urls[0]
    if not result.private:
        try:  # 1) let Telegram fetch the URL itself (works for files up to 20 MB)
            sent = await message.answer_video(url, caption=caption)
            return sent.video.file_id if sent.video else None
        except TelegramAPIError as exc:
            log.info("Telegram could not fetch the URL (%s), downloading it ourselves", exc)
    blob = await download(http, url, BOT_UPLOAD_LIMIT)  # 2) download and upload (up to 50 MB)
    if blob:
        try:
            file = BufferedInputFile(blob, filename="video.mp4")
            sent = await message.answer_video(file, caption=caption, supports_streaming=True)
            return sent.video.file_id if sent.video else None
        except TelegramAPIError as exc:
            log.warning("upload failed: %s", exc)
    if result.private:  # 3) fall back to a link, but never leak the URL that contains our key
        await message.answer(MSG["failed"])
    else:
        await message.answer(f"{MSG['failed_link']}\n{url}")
    return None


async def send_photos(message: Message, http: aiohttp.ClientSession, urls: list[str]) -> None:
    for i in range(0, len(urls), 10):  # a media group holds 2-10 items
        chunk = urls[i : i + 10]
        try:
            if len(chunk) == 1:
                await message.answer_photo(chunk[0])
            else:
                await message.answer_media_group([InputMediaPhoto(media=u) for u in chunk])
            continue
        except TelegramAPIError as exc:
            log.info("Telegram could not fetch the photos (%s), downloading them", exc)
        blobs = [await download(http, u, PHOTO_UPLOAD_LIMIT) for u in chunk]
        files = [BufferedInputFile(b, filename=f"photo{n}.jpg") for n, b in enumerate(blobs) if b]
        try:
            if len(files) == 1:
                await message.answer_photo(files[0])
            elif files:
                await message.answer_media_group([InputMediaPhoto(media=f) for f in files])
            else:
                await message.answer("\n".join(chunk))
        except TelegramAPIError as exc:
            log.warning("photo upload failed: %s", exc)
            await message.answer("\n".join(chunk))


def explain(err: ApiError) -> str:
    if err.status in (401, 402):  # our problem, not the user's: wrong key or no credits left
        log.error("InterAPI rejected the key: %s", err)
        return MSG["unavailable"]
    if err.status == 403:
        return MSG["private"]
    if err.status == 404:
        return MSG["not_found"]
    if err.status == 429:
        return MSG["rate_limit"].format(minutes=max(1, err.retry_after // 60))
    if err.status == 400:
        return MSG["bad_link"]
    return MSG["unavailable"]


@router.message(CommandStart())
async def on_start(message: Message) -> None:
    await message.answer(MSG["start"])


@router.message(F.text.contains("http"))
async def on_link(message: Message, http: aiohttp.ClientSession) -> None:
    found = URL_RE.search(message.text)
    if not found:
        await message.answer(MSG["no_link"])
        return
    link = found.group(0)

    async with ChatActionSender.upload_video(bot=message.bot, chat_id=message.chat.id):
        if link in FILE_IDS:  # seen before: no API call, no credits
            await message.answer_video(FILE_IDS[link])
            return
        try:
            data = await fetch_media(http, link)
        except ApiError as err:
            await message.answer(explain(err))
            return
        except (aiohttp.ClientError, asyncio.TimeoutError):
            await message.answer(MSG["unavailable"])
            return

        result = pick_result(data, link)
        if result is None:
            await message.answer(MSG["nothing"])
        elif result.kind == "video":
            file_id = await send_video(message, http, result, (data.get("title") or "")[:200])
            if file_id:
                FILE_IDS[link] = file_id
        else:
            await send_photos(message, http, result.urls)


@router.message()
async def on_other(message: Message) -> None:
    await message.answer(MSG["no_link"])


async def main() -> None:
    logging.basicConfig(level=logging.INFO)
    bot = Bot(BOT_TOKEN)
    dp = Dispatcher()
    dp.include_router(router)
    async with aiohttp.ClientSession() as http:
        await dp.start_polling(bot, http=http)


if __name__ == "__main__":
    asyncio.run(main())

How it works

  • Finding the link. The on_link handler catches any message containing “http”, pulls out the first URL with a regular expression and passes it to the API. That way the bot also copes with text like “look what I found: https://…”.
  • fetch_media calls /api/v1/auto and retries on 5xx and short 429 responses. A long Retry-After (an hourly limit) is pointless to wait for in a chat, so the bot immediately tells the user how many minutes to wait.
  • pick_result and photo_slides decide what to send: the video if there is one, otherwise an album. A new slide starts whenever the picture size goes up again, which filters out the duplicate resolutions.
  • send_video has three levels. First Telegram downloads the file from the URL itself (fast, and no load on your server). If it refuses, the bot downloads the file and uploads it as a BufferedInputFile. If that fails as well, it sends the direct link.
  • ChatActionSender.upload_video keeps the “sending video…” status visible in the chat for as long as processing takes.
  • FILE_IDS is the simplest possible cache: after the first send, Telegram returns a file_id, and resending the same video costs nothing — no time and no credits.

About Telegram limits. When a file is sent by URL, Telegram accepts up to 5 MB for photos and up to 20 MB for everything else. When the bot uploads a file itself, the limits are 10 MB for photos and 50 MB for other files. Anything bigger is only possible with your own Bot API server. That is why the code has a chain of fallbacks.

Step 4. Running and deploying

For a quick check, just run the bot by hand: python bot.py. Send it a link to any public video in Telegram and make sure the video arrives.

On a server, it is convenient to run the bot as a systemd service: it starts after a reboot and restarts if it crashes. Put the project into /opt/video-bot, create a dedicated user and add the file /etc/systemd/system/video-bot.service:

ini
[Unit]
Description=Telegram video downloader bot
After=network-online.target
Wants=network-online.target

[Service]
User=botuser
WorkingDirectory=/opt/video-bot
ExecStart=/opt/video-bot/.venv/bin/python bot.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

Start it and follow the logs:

bash
sudo systemctl daemon-reload
sudo systemctl enable --now video-bot
sudo journalctl -u video-bot -f

The bot uses long polling, so it needs neither a domain nor an HTTPS certificate — the cheapest VPS will do. If you prefer webhooks and regular web hosting, see the PHP version: social media downloader Telegram bot in PHP (webhook + InterAPI).

Cost math

The price depends on the platform and is charged only for a successful request. /api/v1/auto costs the same as the endpoint of the platform it detects. With the 1,000 free credits you get at sign-up:

PlatformCredits per requestRequests per 1,000 credits
TikTok6166
Instagram6166
YouTube1566
X, Facebook, Pinterest, RuTube, Likee5200

File endpoints (/api/v1/media/file, /api/v1/youtube/file) do not charge credits, 5xx responses are free, and 4xx responses cost at most one credit. Credits never expire and there is no subscription. For scale: the $5 Start package is 60,000 credits, which is roughly 10,000 TikTok downloads (check the pricing page for current prices). Until your first top-up there is a limit of 30 requests per hour, which is plenty for testing.

Production tips

  • Cache results by link. The same clip gets posted in popular chats dozens of times. The FILE_IDS dictionary from the example lives until a restart; for a persistent cache, store “link → file_id” pairs in SQLite or Redis. Normalize links while you are at it by stripping tracking parameters such as ?igsh=….
  • Limit how often a single user can call the bot. Otherwise one prankster can burn through your credits in an evening. A simple check at the start of on_link is enough:
python
import time

LAST_REQUEST: dict[int, float] = {}  # user id -> time of the last accepted link

def too_fast(user_id: int, pause: float = 5.0) -> bool:
    now = time.monotonic()
    if now - LAST_REQUEST.get(user_id, 0.0) < pause:
        return True
    LAST_REQUEST[user_id] = now
    return False


# first lines of on_link():
if too_fast(message.from_user.id):
    return  # or reply with a short "slow down" message
  • Watch your balance. The /api/v1/account endpoint returns the remaining credits and does not charge any. Call it on a schedule and alert yourself when the balance drops below a threshold:
bash
curl -H "X-API-Key: YOUR_API_KEY" https://api.interapi.dev/api/v1/account
  • Cap parallel downloads. If the bot lives in large chats, wrap downloading in an asyncio.Semaphore(5) so you do not run out of memory or bandwidth.
  • Big files. If you need videos longer than a few minutes in good quality, run a local Telegram Bot API server: the upload limit grows from 50 MB to 2,000 MB.
  • Mind the rights. Download only what you may legally use: your own clips, material shared with the author’s permission, or whatever the platform’s terms allow.

What next

The finished bot is easy to extend: add a “download audio only” button (the response has music_url), a quality picker based on media, or an inline mode. Per-platform details live in the docs: TikTok, Instagram, YouTube. To run the bot on real data all you need is a key with the free credits that come with sign-up.

FAQ

How much does one download cost with this bot?

From 5 to 15 credits per successful request depending on the platform: TikTok and Instagram cost 6, YouTube 15, the rest 5. The 1,000 free credits cover about 166 TikTok downloads. Resending the same video by file_id is free.

Why does the bot not send large videos?

The standard Telegram Bot API lets bots upload files up to 50 MB, and up to 20 MB when sending by URL. If a video is bigger, the bot replies with a direct link. To send files up to 2,000 MB you need your own local Bot API server.

Which is better for a bot — polling or webhook?

For a VPS, long polling is simpler: no domain or HTTPS needed. Webhooks fit regular web hosting and high load better — see the PHP version in the companion guide.

Does the bot work with YouTube Shorts and long videos?

Shorts and short clips work: the bot sends a 360p MP4 with sound. A long video may not fit into 50 MB, in which case the bot says that it could not send the file.

More guides

All guides