BotNetwork

Handling files in Telegram bots: getFile, file_id reuse and size limits

Photos, documents and voice notes are where many Telegram bots first break. The Bot API handles files in a specific way, with different limits for downloading, uploading and resending, and knowing those rules up front saves you from bandwidth waste and confusing errors.

Published 8 min read

What this post covers

Sooner or later a user sends your bot a photo, a PDF or a voice note, or your bot needs to send one back. This post explains how files work in the Telegram Bot API: how to download what users send, how to send files efficiently, which limits apply to each path and what changes if you run your own Bot API server. Everything here is based on the official Bot API documentation at the time of writing. Telegram updates the Bot API regularly, so check the sources at the end before relying on a specific limit.

If you have not built a bot that receives updates yet, start with our guides to webhooks vs polling and setting up setWebhook.

How a file arrives in an update

When a user sends a file, the update does not contain the bytes. It contains a Message with one of several file objects: photo, document, audio, video, voice, video_note, animation or sticker. Each of them has at least these fields:

  • file_id: an identifier you can use to download the file or send it again.
  • file_unique_id: an identifier that, per the documentation, is supposed to be the same over time and for different bots, but cannot be used to download or reuse the file.
  • file_size (optional): the size in bytes.

Photos are a special case. message.photo is an array of PhotoSize objects, the available sizes of the same picture. You normally pick the last or the largest element, but check file_size if you only need a thumbnail-sized version.

One detail worth handling correctly: the documentation notes that file_size can be bigger than 2^31, but it has at most 52 significant bits. Store it as a signed 64-bit integer, not a 32-bit one.

Downloading a file with getFile

Downloading is a two-step process:

  1. Call getFile with the file_id. On success it returns a File object with a file_path.
  2. Download the bytes from https://api.telegram.org/file/bot<token>/<file_path>.

The rules that matter, quoted from the documentation:

  • Bots can currently download files of up to 20 MB through the cloud Bot API.
  • The download link is guaranteed to be valid for at least 1 hour. When it expires, call getFile again to get a new one.

Because of the 20 MB limit, check file_size before calling getFile and tell the user politely when a file is too large, instead of letting the call fail. Here is a minimal Python example using requests:

import os
import requests

TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
API = f"https://api.telegram.org/bot{TOKEN}"
MAX_DOWNLOAD = 20 * 1024 * 1024  # cloud Bot API download limit

def download_telegram_file(file_obj: dict, dest_path: str) -> bool:
    size = file_obj.get("file_size")
    if size is not None and size > MAX_DOWNLOAD:
        return False  # tell the user the file is too large

    r = requests.get(f"{API}/getFile",
                     params={"file_id": file_obj["file_id"]}, timeout=15)
    r.raise_for_status()
    file_path = r.json()["result"]["file_path"]

    url = f"https://api.telegram.org/file/bot{TOKEN}/{file_path}"
    with requests.get(url, stream=True, timeout=60) as resp:
        resp.raise_for_status()
        with open(dest_path, "wb") as f:
            for chunk in resp.iter_content(chunk_size=64 * 1024):
                f.write(chunk)
    return True

Two security notes. First, the download URL contains your bot token, so never log it, never send it to users and never put it in an error message; our post on securing bot tokens explains why. Second, treat every file as untrusted input: check the type you actually expect, do not trust the file name, and store files outside any web-served folder.

Three ways to send a file

The Bot API documentation lists three ways to send a file, and each has different limits:

Method How Size limit at the time of writing
By file_id Pass an existing file_id as the parameter No limits for files sent this way
By URL Pass an HTTP URL; Telegram downloads it 5 MB for photos, 20 MB for other content
Upload multipart/form-data, like a browser upload 10 MB for photos, 50 MB for other files

Reuse file_id whenever you can

If your bot sends the same file repeatedly, such as a welcome image, a price list PDF or a help video, upload it once, save the file_id from the returned Message, and send that file_id from then on. It avoids re-uploading the bytes every time and is not subject to the upload size limits.

The documentation lists a few rules for resending by file_id:

  • You cannot change the file type: a video cannot be resent as a photo, and a photo cannot be resent as a document.
  • Thumbnails cannot be resent.
  • Resending a photo by file_id sends all of its sizes.
  • A file_id is unique to each bot and cannot be transferred from one bot to another. If you run separate bots for development and production, each one needs its own stored file_id.
  • The same file can have several valid file_id values even for the same bot, so do not use file_id as a deduplication key.

Use file_unique_id for deduplication

Since file_unique_id is stable over time and across bots, it is the right key when you want to know whether you have already processed a file, for example to avoid storing the same upload twice. Just remember it cannot be used to download or send the file; keep the file_id next to it for that.

A small cache table is enough:

CREATE TABLE telegram_files (
  file_unique_id TEXT PRIMARY KEY,
  file_id        TEXT NOT NULL,
  kind           TEXT NOT NULL,   -- photo, document, voice...
  file_size      BIGINT,
  stored_path    TEXT,
  created_at     TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

Sending by URL: the fine print

Sending by URL is convenient when the file already lives on a web server, but the documentation adds some conditions: the target file must have the correct MIME type (for example audio/mpeg for sendAudio), and in sendDocument sending by URL currently only works for PDF and ZIP files. For sendVoice, the file must be audio/ogg and no more than 1 MB; voice notes from 1 to 20 MB are sent as files.

If you serve those files yourself, a stable domain with HTTPS makes the URLs predictable. You can register one with Namecheap domains and follow our guide to a custom domain and HTTPS for your bot for DNS and certificates.

Uploading with multipart/form-data

For a new file, post it as multipart/form-data. With requests:

def send_document(chat_id: int, path: str, caption: str = "") -> str:
    with open(path, "rb") as f:
        r = requests.post(f"{API}/sendDocument",
                          data={"chat_id": chat_id, "caption": caption},
                          files={"document": f}, timeout=120)
    r.raise_for_status()
    msg = r.json()["result"]
    return msg["document"]["file_id"]  # store this for reuse

For photos, sendPhoto adds its own constraints: at most 10 MB, width plus height must not exceed 10000, and the width to height ratio must be at most 20. Captions are limited to 0 to 1024 characters after entities parsing. Custom thumbnails must be JPEG, under 200 kB and no larger than 320 pixels on either side, and they are ignored unless the file itself is uploaded with multipart/form-data.

Uploads take longer than plain text messages. If your bot runs on webhooks, acknowledge the update quickly and do slow uploads or downloads in a background job, so Telegram does not wait on your handler; see idempotent message handling for why retries make this important.

When a local Bot API server makes sense

Telegram publishes the Bot API server source code as telegram-bot-api, and you can run it yourself instead of sending requests to https://api.telegram.org. According to the documentation, a local server lets your bot:

  • Download files without a size limit.
  • Upload files up to 2000 MB.
  • Upload files using a local path and the file:// URI scheme.
  • Receive the absolute local path in file_path after getFile, without downloading the file.
  • Use an HTTP URL, any local IP address and any port for the webhook, and set max_webhook_connections up to 100000.

The trade-offs are real. You need your own api_id and api_hash from Telegram, a server you maintain around the clock, and enough disk space for the files it handles. Before switching, you must call logOut on the cloud server; otherwise there is no guarantee your bot receives updates, and you cannot log back in to the cloud server for 10 minutes after that call. Your code must also handle absolute file paths in getFile responses.

The documentation is clear that most bots are fine with the default cloud server. Consider a local server only when the 20 MB download or 50 MB upload limit is a real blocker for your use case.

A checklist before you ship

  • Check file_size before calling getFile and explain the 20 MB limit to users.
  • Never log download URLs, because they contain the token.
  • Store file_id after the first upload and resend by file_id.
  • Deduplicate with file_unique_id, never with file_id.
  • Keep a separate file_id cache per bot.
  • Validate file types and keep stored files out of public folders.
  • Move slow transfers out of the webhook handler.
  • Publish a short privacy page that says which files you keep and for how long. Namecheap hosting can serve a static page like that while the bot runs elsewhere, and keeping it with your domain in one Namecheap account keeps renewals in one place.

Sources