Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Working with Files and Media

Bibo-Joshi edited this pageAug 2, 2024 ·17 revisions

Bots interacting with users in plain text messages is often times not enough for a pleasant user experience.Providing the users with images, videos, files and other media is therefore a common use case for bot programmers and the Bot API provides several ways to do this.On this wiki page, we explain how files and media are handled in thepython-telegram-bot framework.

Sending files

If you want to send a file (e.g. send a document or a photo) with the bot, you have three options:

  • Upload the file
  • Send an HTTP URL that leads to the file
  • Send afile_id of a file that has already been sent.

Note that not every method is supported everywhere (e.g. for thumbnails you can't pass afile_id). Make sure to check out the documentation of the corresponding bot method for details.

Please also check out theofficial Telegram API docs on sending files.

Let's have a look at how sending a document can be done. In these examples, we'll be usingBot'ssend_document() method.

Note

In discussion and examples below, we will be using methods ofBot, but most of them(includingsend_document())have shortcut methods in classes likeUser,Chat orMessage that can be moreconvenient to use in your particular situation. Documentation for every method inBotcontains links to shortcut methods in other classes.

  1. Uploading a file

    awaitbot.send_document(chat_id=chat_id,document=open('tests/test.png','rb'))

    or even just

    awaitbot.send_document(chat_id=chat_id,document='tests/test.png')

    When you pass a file path (note that bothstr andpathlib.Path are accepted asdocument parameter), PTB will automatically check if your bot is running inlocal mode. If it is, the file does not need to be uploaded. Otherwise, the file is read in binary mode, so just as when you passopen('tests/test.png', 'rb').

Tip

For advanced use cases, it's also possible to manually build anInputFile object and pass that object to thedocument parameter.This can for example be useful, to passread_file_handle.However, for most use cases, this is not necessary.

  1. Sending an HTTP URL

    awaitbot.send_document(chat_id=chat_id,document='https://python-telegram-bot.org/static/testfiles/telegram.gif')
  2. Sending byfile_id:

    awaitbot.send_document(chat_id=chat_id,document=file_id)

    Two further notes on this:

    1. Each bot has its ownfile_ids, i.e. you can't use afile_id from a different bot to send a photo

    2. How do you get afile_id of a photo you sent? Read it from the return value ofbot.send_document() (or any otherMessage object you get your hands on):

      message=awaitbot.send_document(...)file_id=message.document.file_id

This pretty much works the same way for all the othersend_<media_type>() methods likesend_photo(),send_video() etc. There is one exception, though:send_media_group().

Sending a media group

A call tosend_media_group() looks like this:

awaitbot.send_media_group(chat_id=chat_id,media=[media_1,media_2, ...])

Each of the items in themedia sequence (list or tuple) must be an instances ofInputMediaAudio,InputMediaDocument,InputMediaPhoto orInputMediaVideo. The media comes into play like so:

media_1=InputMediaDocument(media=open('tests/test.png','rb'), ...)media_1=InputMediaDocument(media='https://python-telegram-bot.org/static/testfiles/telegram.gif', ...)media_1=InputMediaDocument(media=file_id, ...)

Caution

For theInputMedia* classes, passing a file path only works if your bot is running inlocal mode.

Sending files via inline mode

You may want to allow users to send media via your bots inline mode. This works a little bit different than posting media viasend_*. Most notably, you can't upload files for inline mode! You must provide either an HTTP URL or afile_id.

Let's stick to example of sending a document. You have to providebot.answer_inline_query() with anInlineQueryResult that represents that document. There are two ways of doing that:

  1. HTTP URL:

    result=InlineQueryResultDocument(document_url='https://python-telegram-bot.org/static/testfiles/telegram.gif', ...)
  2. file_id:

    result=InlineQueryResultCachedDocument(document_file_id=file_id, ...)

In this example, we are usingInlineQueryResultDocument for option #1 andInlineQueryResultCachedDocument for option #2. The schemeInlineQueryResult<media_type> vsInlineQueryResultCached<media_type> is similar for the other media types.Again, please check out the docs for details on required and optional arguments.

Editing a file

When you have sent a file, you may want to edit it. This works similarly assend_media_group, i.e. the media must be wrapped into aInputMedia<media_type> object. Again, withdocument as example, we'll callbot.edit_message_media() and pass an instance ofInputMediaDocument asmedia:

awaitbot.edit_message_media(chat_id=chat_id,message_id=message_id,media=InputMediaDocument(media=open('tests/test.png'), ...))

Please check out the restrictions on editing media in the official docs ofeditMessageMedia.

Downloading a file

When you receive files from a user, you sometimes want to download and save them. If it's a document, that could look like this:

file_id=message.document.file_idnew_file=awaitbot.get_file(file_id)awaitnew_file.download_to_drive()

For a received video/voice/... changemessage.document tomessage.video/voice/.... However, there is one exception:message.photo is alist ofPhotoSize objects, which represent different sizes of the same photo. Usemessage.photo[-1].file_id to get the largest size.

See also:

Documentation forBot.get_file()

Moreover, the above snippet can be shortened by using PTB's built-in utility shortcuts:

new_file=awaitmessage.effective_attachment.get_file()awaitnew_file.download_to_drive('file_name')

message.effective_attachment automatically contains whichever media attachment the message has. In case of a photo, you'll again have to use e.g.message.effective_attachment[-1].get_file().

See also:

Documentation forFile.download_to_drive() andFile.download_to_memory()

Wiki ofpython-telegram-bot © Copyright 2015-2025 – Licensed byCreative Commons

Must read

  1. Introduction to the API
  2. Tutorial: Your first bot
  3. FAQ
  4. How to ask good questions
  5. How to write an MWE

Concepts & Important Elements

  1. Architecture Overview
  2. Builder Pattern forApplication
  3. Types of Handlers
  4. Working with Files and Media
  5. Exceptions, Warnings and Logging
  6. Concurrency in PTB

Notable Features

  1. Advanced Filters
  2. Storing data
  3. Making your bot persistent
  4. Adding Defaults
  5. Job Queue
  6. Arbitrarycallback_data
  7. Avoiding flood limits
  8. Webhooks
  9. Bot API Forward Compatiblity

Code Resources

  1. Frequently requested design patterns
  2. Code snippets
  3. Performance Optimizations
  4. Telegram Passport
  5. Bots built with PTB
  6. Automated Bot Tests

Examples explained

  1. InlineKeyboard Example

Networking

  1. Working Behind a Proxy
  2. Handling network errors

Other resources

  1. Where to host Telegram Bots
  2. How to host your bot
  3. Local API Server
  4. Type Checking with PTB
  5. Press
  6. Notes on GAE
  7. Related Projects
  8. Emoji

Transition Guides

Administration

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp