Guide

Social media downloader Telegram bot in PHP (webhook + InterAPI)

We will build a Telegram bot in plain PHP 8 and cURL: a webhook with secret verification, an API call for the link in the message and the video or photos sent back to the chat. All the code fits in one file.

9 min read

What you will build

We will write a Telegram bot in plain PHP 8: no framework, no Composer and no third-party libraries — only cURL, which every host has. The bot runs on a webhook: Telegram POSTs every incoming message to your script. A user sends a link from TikTok, Instagram, YouTube, X, Facebook, Pinterest, RuTube or Likee, and the bot replies with the video or a photo album.

The media data comes from InterAPI: one GET /api/v1/auto request detects the platform from the link and returns JSON with direct file URLs, so you do not write scrapers for each social network. The finished script is about 280 lines — one file plus a small config.

If you prefer Python and long polling, there is the same bot in Python with aiogram 3. It covers the API response format, platform quirks and cost math in more detail — here we focus on PHP and webhooks.

Webhook or long polling

With long polling the bot keeps asking Telegram for updates, so it needs a process that runs around the clock — a VPS and something like systemd. A webhook works the other way round: Telegram calls your script whenever a message arrives. That lets a PHP file live happily on ordinary hosting and run only on demand, with no daemons or background processes. The price is a domain with HTTPS and a time limit on your answer: Telegram will not wait for a webhook forever, so we do the heavy work after replying.

Requirements

  • PHP 8.0 or newer with the curl, json and mbstring extensions — they are enabled almost everywhere.
  • A domain with HTTPS. Telegram sends webhooks only to an address with a valid certificate (ports 443, 80, 88 or 8443). Ordinary shared hosting with a free certificate is fine.
  • A bot token from @BotFather (the /newbot command).
  • An InterAPI key. Sign up at interapi.dev/register and 1,000 free credits are added to your balance right away.

Step 1. Configuration and a webhook secret

The bot token and the API key must not live in your site’s public folder — one server misconfiguration and everyone can read them. Put them into config.php one level above the web root:

php
<?php
// config.php — keep this file OUTSIDE the web root (for example one level above public_html)
return [
    'bot_token'      => '123456789:AAExampleTokenFromBotFather',
    'interapi_key'   => 'YOUR_API_KEY',
    'webhook_secret' => 'paste-the-output-of-openssl-rand-hex-32-here',
    // optional: your own Bot API server, needed only for files above 50 MB
    // 'tg_base'     => 'http://127.0.0.1:8081',
];

The webhook_secret lets you tell genuine Telegram requests from everyone else’s: your script sits at a public URL, and without a check anybody could call it and spend your credits. Generate a long random string (Telegram allows letters, digits, _ and -, up to 256 characters):

bash
openssl rand -hex 32

Step 2. Register the webhook

Tell Telegram the script’s address and the secret with the setWebhook method. Telegram will add the secret to the X-Telegram-Bot-Api-Secret-Token header of every request:

bash
curl -s "https://api.telegram.org/botYOUR_BOT_TOKEN/setWebhook" \
  --data-urlencode "url=https://example.com/bot/webhook.php" \
  --data-urlencode "secret_token=YOUR_WEBHOOK_SECRET" \
  --data-urlencode 'allowed_updates=["message"]' \
  --data-urlencode "max_connections=10" \
  --data-urlencode "drop_pending_updates=true"

The allowed_updates parameter limits the stream to ordinary messages, and drop_pending_updates clears any queue that piled up. Check the result with getWebhookInfo:

bash
curl -s "https://api.telegram.org/botYOUR_BOT_TOKEN/getWebhookInfo"
json
{
  "ok": true,
  "result": {
    "url": "https://example.com/bot/webhook.php",
    "has_custom_certificate": false,
    "pending_update_count": 0,
    "max_connections": 10,
    "allowed_updates": ["message"]
  }
}

When something is wrong, the same response also contains last_error_date and last_error_message — the first place to look when debugging.

Step 3. The complete webhook.php

Save the code as webhook.php in a folder reachable at the address you gave to setWebhook. It verifies the secret, answers Telegram quickly, calls the API and sends the result.

php
<?php
declare(strict_types=1);

// config.php lives outside the web root and returns:
// ['bot_token' => '123:ABC', 'interapi_key' => 'ia_live_...', 'webhook_secret' => 'long-random-string']
$cfg = require __DIR__ . '/config.php';
$apiBase = $cfg['api_base'] ?? 'https://api.interapi.dev';
$tgBase  = $cfg['tg_base'] ?? 'https://api.telegram.org';   // or your own Bot API server

const MAX_UPLOAD = 50 * 1024 * 1024;   // bots can upload files up to 50 MB

const 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 %d 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:',
];

// 1. Only Telegram may call this script: it sends our secret in a header.
$sent = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '';
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !hash_equals($cfg['webhook_secret'], $sent)) {
    http_response_code(403);
    exit;
}

$update = json_decode((string) file_get_contents('php://input'), true);

// 2. Answer 200 right away so Telegram does not retry; keep working after the response is sent.
ignore_user_abort(true);
set_time_limit(180);
http_response_code(200);
header('Content-Type: text/plain');
echo 'ok';
if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
} else {
    header('Connection: close');
    header('Content-Length: 2');
    flush();
}

function tg(string $method, array $params = []): array
{
    global $cfg, $tgBase;
    $upload = array_filter($params, fn ($v) => $v instanceof CURLFile) !== [];
    if ($upload) {   // multipart/form-data: arrays must be JSON strings, booleans plain text
        foreach ($params as $key => $value) {
            if (is_array($value)) {
                $params[$key] = json_encode($value, JSON_UNESCAPED_UNICODE);
            } elseif (is_bool($value)) {
                $params[$key] = $value ? 'true' : 'false';
            }
        }
        $body = $params;
        $headers = [];
    } else {
        $body = json_encode($params, JSON_UNESCAPED_UNICODE);
        $headers = ['Content-Type: application/json'];
    }
    $ch = curl_init("$tgBase/bot{$cfg['bot_token']}/$method");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $body,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 120,
    ]);
    $raw = curl_exec($ch);
    curl_close($ch);
    return is_string($raw) ? (json_decode($raw, true) ?: ['ok' => false]) : ['ok' => false];
}

function interapi(string $link): array
{
    global $cfg, $apiBase;
    for ($attempt = 0; $attempt < 3; $attempt++) {
        $ch = curl_init("$apiBase/api/v1/auto?" . http_build_query(['url' => $link]));
        $retryAfter = 0;
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_HTTPHEADER => ['X-API-Key: ' . $cfg['interapi_key']],
            CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$retryAfter) {
                if (stripos($line, 'Retry-After:') === 0) {
                    $retryAfter = (int) trim(substr($line, 12));
                }
                return strlen($line);
            },
        ]);
        $raw = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);   // 0 on network errors
        curl_close($ch);
        $body = is_string($raw) ? (json_decode($raw, true) ?: []) : [];

        $retry = $status === 0 || $status >= 500 || ($status === 429 && $retryAfter <= 10);
        if ($status === 200 || !$retry || $attempt === 2) {
            return ['status' => $status, 'body' => $body, 'retry_after' => $retryAfter];
        }
        sleep($retryAfter ?: 2 * ($attempt + 1));   // 5xx is free, so retrying costs nothing
    }
    return ['status' => 0, 'body' => [], 'retry_after' => 0];
}

/** Instagram lists every slide in several sizes (largest first). Keep one URL per slide. */
function photoSlides(array $media): array
{
    $slides = [];
    $lastWidth = null;
    foreach ($media as $item) {
        if (($item['type'] ?? '') !== 'photo' || ($item['quality'] ?? '') === 'cover') {
            continue;
        }
        $width = preg_match('/^(\d+)x\d+$/', $item['quality'] ?? '', $m) ? (int) $m[1] : null;
        if ($width === null || $lastWidth === null || $width > $lastWidth) {
            $slides[] = $item['url'];   // the size went up again: a new slide starts
        }
        $lastWidth = $width;
    }
    return $slides;
}

/** @return array{kind: string, urls: string[], private: bool}|null */
function pickResult(array $data, string $link): ?array
{
    global $cfg, $apiBase;
    if (($data['source'] ?? '') === 'youtube') {
        // For YouTube video_url is an HLS manifest. Use the free file endpoint (itag 18 = 360p MP4 with sound).
        $query = http_build_query(['url' => $link, 'kind' => 'video', 'format_id' => '18', 'mode' => 'file', 'api' => $cfg['interapi_key']]);
        return ['kind' => 'video', 'urls' => ["$apiBase/api/v1/youtube/file?$query"], 'private' => true];
    }
    $video = $data['video_hd_url'] ?? $data['video_url'] ?? null;
    if ($video) {
        return ['kind' => 'video', 'urls' => [$video], 'private' => false];
    }
    $slides = photoSlides($data['media'] ?? []);
    return $slides ? ['kind' => 'photos', 'urls' => $slides, 'private' => false] : null;
}

/** Download to a temp file. Returns null if the file is bigger than $limit or the download fails. */
function download(string $url, int $limit): ?string
{
    $path = tempnam(sys_get_temp_dir(), 'dl');
    $fh = fopen($path, 'wb');
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_FILE => $fh,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 120,
        CURLOPT_NOPROGRESS => false,
        // abort as soon as more than $limit bytes have arrived
        CURLOPT_PROGRESSFUNCTION => fn ($ch, $dlTotal, $dlNow) => $dlNow > $limit ? 1 : 0,
    ]);
    $ok = curl_exec($ch) !== false && curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200;
    curl_close($ch);
    fclose($fh);
    if (!$ok) {
        unlink($path);
        return null;
    }
    return $path;
}

function say(int $chatId, string $text): void
{
    tg('sendMessage', ['chat_id' => $chatId, 'text' => $text, 'link_preview_options' => ['is_disabled' => true]]);
}

function sendVideo(int $chatId, array $result, string $caption): void
{
    $url = $result['urls'][0];
    if (!$result['private']) {   // 1) let Telegram fetch the URL itself (files up to 20 MB)
        $r = tg('sendVideo', ['chat_id' => $chatId, 'video' => $url, 'caption' => $caption, 'supports_streaming' => true]);
        if ($r['ok']) {
            return;
        }
    }
    $path = download($url, MAX_UPLOAD);   // 2) download and upload ourselves (up to 50 MB)
    if ($path !== null) {
        $r = tg('sendVideo', ['chat_id' => $chatId, 'caption' => $caption, 'supports_streaming' => true,
            'video' => new CURLFile($path, 'video/mp4', 'video.mp4')]);
        unlink($path);
        if ($r['ok']) {
            return;
        }
    }
    // 3) link fallback, but never reveal a URL that contains our API key
    say($chatId, $result['private'] ? MSG['failed'] : MSG['failed_link'] . "\n" . $url);
}

function sendPhotos(int $chatId, array $urls): void
{
    foreach (array_chunk($urls, 10) as $chunk) {   // a media group holds 2-10 items
        if (count($chunk) === 1) {
            $r = tg('sendPhoto', ['chat_id' => $chatId, 'photo' => $chunk[0]]);
        } else {
            $media = array_map(fn ($u) => ['type' => 'photo', 'media' => $u], $chunk);
            $r = tg('sendMediaGroup', ['chat_id' => $chatId, 'media' => $media]);
        }
        if ($r['ok']) {
            continue;
        }
        // Telegram could not fetch the URLs: download the photos and upload them ourselves
        $files = [];
        $paths = [];
        foreach ($chunk as $i => $url) {
            if ($path = download($url, 10 * 1024 * 1024)) {   // photos: 10 MB upload limit
                $paths[] = $path;
                $files[] = new CURLFile($path, 'image/jpeg', "photo$i.jpg");
            }
        }
        if (count($files) === 1) {
            $r = tg('sendPhoto', ['chat_id' => $chatId, 'photo' => $files[0]]);
        } elseif ($files) {
            $params = ['chat_id' => $chatId, 'media' => []];
            foreach ($files as $i => $file) {
                $params["file$i"] = $file;
                $params['media'][] = ['type' => 'photo', 'media' => "attach://file$i"];
            }
            $r = tg('sendMediaGroup', $params);
        } else {
            $r = ['ok' => false];
        }
        array_map('unlink', $paths);
        if (!$r['ok']) {
            say($chatId, implode("\n", $chunk));
        }
    }
}

function explain(array $reply): string
{
    switch ($reply['status']) {
        case 400: return MSG['bad_link'];
        case 403: return MSG['private'];
        case 404: return MSG['not_found'];
        case 429: return sprintf(MSG['rate_limit'], max(1, intdiv($reply['retry_after'], 60)));
        case 401:
        case 402:   // our problem, not the user's: wrong key or no credits left
            error_log('InterAPI rejected the key: ' . json_encode($reply['body']));
            return MSG['unavailable'];
        default: return MSG['unavailable'];
    }
}

// 3. Handle the update.
$message = $update['message'] ?? null;
$chatId = $message['chat']['id'] ?? null;
$text = $message['text'] ?? '';
if ($chatId === null || $text === '') {
    exit;
}
if (str_starts_with($text, '/start')) {
    say($chatId, MSG['start']);
    exit;
}
if (!preg_match('~https?://[^\s<>"\']+~u', $text, $found)) {
    say($chatId, MSG['no_link']);
    exit;
}

tg('sendChatAction', ['chat_id' => $chatId, 'action' => 'upload_video']);
$reply = interapi($found[0]);
if ($reply['status'] !== 200) {
    say($chatId, explain($reply));
    exit;
}
$result = pickResult($reply['body'], $found[0]);
if ($result === null) {
    say($chatId, MSG['nothing']);
} elseif ($result['kind'] === 'video') {
    sendVideo($chatId, $result, mb_substr($reply['body']['title'] ?? '', 0, 200));
} else {
    sendPhotos($chatId, $result['urls']);
}

How it works

  • Secret check. The first thing the script does is compare the header with your secret using hash_equals (a constant-time comparison) and answer 403 to everyone else.
  • A fast response. Telegram redelivers an update if it does not get a 200 in reasonable time, and downloading a video can take tens of seconds. So the script answers “ok” immediately, calls fastcgi_finish_request() (under PHP-FPM) and does the real work after the response is out. Without FPM it falls back to Connection: close.
  • The tg() function is a thin wrapper over the Bot API. Normal calls go out as JSON, and when a file (CURLFile) is attached it switches to multipart automatically.
  • The interapi() function sends the link to /api/v1/auto with the X-API-Key header and retries on 5xx and short 429 responses. 5xx failures cost no credits, so retries are free.
  • Choosing the media. pickResult() takes video_hd_url or video_url, and if there is no video it collects the photos. Instagram lists every picture in several sizes in a row, so photoSlides() keeps one link per slide. For YouTube, video_url is an HLS manifest, so the script uses the file endpoint with format_id=18 (a 360p MP4 with sound) instead; that URL contains your key, which is why the script never shows it to a user.
  • Three levels of sending. First sendVideo with a URL — Telegram downloads the file itself (up to 20 MB). If it refuses, the script downloads the file to a temporary file on disk (not into memory) and uploads it through CURLFile (up to 50 MB). If that fails too, it sends the direct link as text.
  • Albums. sendMediaGroup accepts 2 to 10 items, so the slide list is cut into chunks of ten with array_chunk, and a single photo goes through sendPhoto.
  • API errors. 400 means an unrecognized link, 403 private content, 404 a missing post, 429 a rate limit, and 401 or 402 a problem with the key or the balance: those are written to error_log while the user sees a neutral message.

Testing and debugging

Send the bot a link in Telegram — the video should arrive within a few seconds. If nothing happens, check in this order: getWebhookInfo (is there a last_error_message), the PHP error log and write permissions on the temp directory. You can also call the script by hand and imitate a Telegram update:

bash
curl -i https://example.com/bot/webhook.php \
  -H "Content-Type: application/json" \
  -H "X-Telegram-Bot-Api-Secret-Token: YOUR_WEBHOOK_SECRET" \
  -d '{"update_id":1,"message":{"chat":{"id":123456789},"text":"https://vt.tiktok.com/XXXX/"}}'

Without the right secret header the server answers 403, which means the protection works. For development on a home machine you can temporarily expose a port through a tunnel such as cloudflared or ngrok and register its address with setWebhook.

Hosting and reliability tips

  • Time limits. The script calls set_time_limit(180), but on shared hosting PHP-FPM may have its own ceiling (request_terminate_timeout), so check it. If your host kills scripts after 30 seconds, long videos will be cut off; in that case move the sending into a cron worker or a queue.
  • Duplicate updates. Telegram occasionally delivers an update twice. Guard against it by checking update_id:
php
// Right after the early "200 ok" response: skip updates that Telegram redelivers.
$stamp = sys_get_temp_dir() . '/bot-last-update-id';
$last = is_file($stamp) ? (int) file_get_contents($stamp) : 0;
if (($update['update_id'] ?? 0) <= $last) {
    exit;
}
file_put_contents($stamp, (string) $update['update_id'], LOCK_EX);
  • Cache by link. Once Telegram has sent a video, it returns a file_id. Resending by that id costs nothing — no time and no credits. SQLite, which ships with PHP, is a convenient place to keep “link → file_id” pairs:
php
$db = new PDO('sqlite:' . __DIR__ . '/cache.sqlite');
$db->exec('CREATE TABLE IF NOT EXISTS files (link TEXT PRIMARY KEY, file_id TEXT NOT NULL)');

function cachedFileId(PDO $db, string $link): ?string
{
    $stmt = $db->prepare('SELECT file_id FROM files WHERE link = ?');
    $stmt->execute([$link]);
    return $stmt->fetchColumn() ?: null;
}

function rememberFileId(PDO $db, string $link, string $fileId): void
{
    $db->prepare('INSERT OR REPLACE INTO files (link, file_id) VALUES (?, ?)')->execute([$link, $fileId]);
}

// In the handler, before calling InterAPI:
if ($fileId = cachedFileId($db, $found[0])) {
    tg('sendVideo', ['chat_id' => $chatId, 'video' => $fileId]);   // a file_id costs no credits
    exit;
}
// ...and after a successful sendVideo:  $r['result']['video']['file_id'] -> rememberFileId()
  • Big files. A bot can upload up to 50 MB. If you need more, run your own Telegram Bot API server and put its address into tg_base — files up to 2,000 MB then work.
  • Abuse protection. Limit requests per user (for example one link every 5 seconds, with a counter in SQLite) and watch your balance through GET /api/v1/account, which does not charge credits.

Cost math

The price depends on the platform: TikTok and Instagram cost 6 credits per request, YouTube 15, the others 5. The 1,000 free credits you get at sign-up cover about 166 TikTok downloads. Downloading files through the proxy endpoints does not charge credits, 5xx responses are free and 4xx responses cost at most one credit. Credits never expire and there is no subscription — see the pricing page for current packages. Endpoint parameters are in the docs for TikTok, Instagram and YouTube.

Download only content you are entitled to use: your own, with the author’s permission, or within the platform’s terms.

FAQ

Do I need Composer or a library for a Telegram bot in PHP?

No. A webhook needs only cURL plus json_encode and json_decode — the script in this guide runs on plain PHP 8 without dependencies. Libraries such as telegram-bot-sdk start to pay off when a bot has many commands, keyboards and states.

Why does the webhook need a secret_token?

The script sits at a public URL, so without a check anyone could call it, forge updates and spend your credits. Telegram adds the secret to the X-Telegram-Bot-Api-Secret-Token header, and the script compares it with hash_equals and rejects other callers with a 403.

What if my hosting kills scripts after 30 seconds?

Answer Telegram immediately and move the video upload into a background worker, a cron job or a queue. For short clips the default limits are usually enough, because Telegram downloads the file from the URL itself.

How do I avoid paying credits for repeated links?

Store the file_id that Telegram returns after sending a video in SQLite, keyed by the link. Resending by file_id does not call the API and costs nothing.

More guides

All guides