Skip to content
↑ ↓ move↵ openEvery page also as Markdown: add .md

Guide

Files and media

Files and media

Sending photos, documents and albums from a path, from bytes or from a file id, and getting the files back out of messages.

Example

use vaegram::prelude::*;
use vaegram::types::{FileSource, Upload};

async fn send(client: &Client) -> Result<()> {
    // From a path on disk: &str, &Path and &PathBuf all convert.
    client.send_photo("me", "/tmp/cat.jpg").caption("My cat").await?;

    // From bytes in memory. The name's extension picks the MIME type.
    client.send_document("me", Upload::bytes("chart.png", b"\x89PNG\r\n\x1a\n")).await?;

    // From a file id, to send what Telegram already holds.
    let id = "AgACAgIAAxkBAAIENGfeY4AfRquwTL2LpDrzqvFMVNt_AAIG9DEbXX3wSq3oI7t_PqQGAQADAgADbQADNgQ";
    client.send_photo("me", FileSource::file_id(id)?).await?;

    // Or let Telegram fetch it from a URL; only photos and plain documents take one.
    client.send_document("me", FileSource::url("https://example.com/report.pdf")?).await?;
    Ok(())
}

How it works

Every media sender takes a FileSource, which converts from:

  • &str, &Path, &PathBuf: a file on disk, uploaded.
  • Upload::bytes(name, data): bytes in memory, uploaded under name; its extension picks the MIME type.
  • FileSource::file_id(id)?: a file Telegram already stores.
  • FileSource::url(url)?: a link Telegram downloads itself; photos and plain documents only.
  • &UploadedFile, &Photo, &Document and the other media types: something already uploaded or received.

There is one sender per kind: send_photo, send_document, send_video, send_animation, send_audio, send_voice, send_video_note, send_sticker, send_live_photo. Awaiting one uploads the file if needed and returns the sent Message; .caption(..), .file_name(..), .has_spoiler() and the rest are in the API docs. On a Message, answer_photo(..) and reply_photo(..) send into the same chat, and every kind has the same pair.

Upload once, send many

upload_file(..) and upload_stream(..) upload without sending and give an UploadedFile, which any sender takes as &file; it exposes name(), the name given at upload time. Telegram keeps the uploaded parts “between several minutes and several hours” (https://core.telegram.org/api/files#uploading-files); after that a send fails with Error::Rpc and a name such as FILE_PART_1_MISSING. To resend later, keep the sent message’s file_id.

use vaegram::prelude::*;
use vaegram::types::Upload;

async fn once(client: &Client) -> Result<()> {
    let file = client.upload_file(Upload::bytes("report.pdf", b"%PDF-1.7")).await?;
    client.send_document("me", &file).caption("The report").await?;
    client.send_document("@some_channel", &file).await?;
    Ok(())
}

Albums

send_media_group takes 2 to 10 items and returns the sent Messages sorted by id. An album is photos and videos, only audio, or only documents; any other mix or count fails with Error::InvalidArgument.

use vaegram::prelude::*;
use vaegram::types::Upload;

async fn album(client: &Client) -> Result<()> {
    let sent = client
        .send_media_group("me", [
            InputMedia::photo("/tmp/a.jpg").caption("First"),
            InputMedia::photo(Upload::bytes("b.jpg", b"\xff\xd8\xff")).caption("Second"),
            InputMedia::video("/tmp/c.mp4").caption("Clip").duration(12),
        ])
        .await?;
    println!("{} messages", sent.len());
    Ok(())
}

What comes back

The returned Message holds the media as message.media, read through message.photo(), message.document(), message.video() and the rest. A Photo carries file_id, file_unique_id, width, height and file_size; a Document carries file_id, file_unique_id, file_name, mime_type and file_size. file_id is what you send again and can change between sessions; compare file_unique_id to tell whether two values are the same file. A received &Photo or &Document goes back into any sender, as in the list above, so message.answer_photo(photo) resends a photo the user sent.

Downloading

message.download() returns a DownloadMedia: awaiting it gives the whole file as Vec<u8>, .save(path) writes it to disk (creating missing parent directories, replacing the target only on success), and .stream() yields chunks. .progress(|done, total| ..), .offset(..) and .limit(..) are available on all three.

client.download_media(..) does the same for anything that is a Photo, a Document, a FileLocation or a file_id string.

use vaegram::prelude::*;

async fn download(message: &Message) -> Result<()> {
    let bytes = message.download().await?;
    println!("{} bytes", bytes.len());
    message.download().save("downloads/file.jpg").await?;
    Ok(())
}

A FILE_REFERENCE_* error means the file reference is stale: message.download() fetches the message again and retries once. A download of a business connection’s message can’t do that, so download it while handling it.

Over the Bot API

A client in Bot API mode sends and downloads through the HTTP API. Two limits sit there: getFile serves files of up to 20 MB, so a larger download fails with Error::InvalidArgument pointing at MTProto or a local server, and a file uploaded with upload_file can’t be sent, only a path, bytes or a file id can. Uploads from a path or bytes travel inside the request that sends them.

Common mistakes

  • Using a file_id from another bot or account, or comparing file_ids to deduplicate. An id is per account; compare file_unique_id, and keep one id per account.
  • Keeping an UploadedFile for a day. Telegram drops the parts after minutes to hours; resend the message’s media.
  • Sending a photo id to send_document (or the reverse) through FileSource::file_id, which fails with Error::InvalidArgument; check the kind first when it isn’t known.
  • Passing a name taken from an incoming message straight to .save(..): the sender chose it and it can contain .. or an absolute path.

See also