Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I receive file in python-telegram-bot?

I have a problem about file messages in python telegram bot. How can I receive file and read that file ? Or save it.

like image 402
DR8002 Avatar asked Apr 20 '26 15:04

DR8002


2 Answers

You can:

  • Register a handler that listens to Document
  • get File object from the update (inside the listener using get_file)
  • then simply call .download() to download the document

Here a sample code to get you started:

from telegram.ext import Updater, MessageHandler, Filters

BOT_TOKEN = ' ... '

def downloader(update, context):
    context.bot.get_file(update.message.document).download()

    # writing to a custom file
    with open("custom/file.doc", 'wb') as f:
        context.bot.get_file(update.message.document).download(out=f)


updater = Updater(BOT_TOKEN, use_context=True)

updater.dispatcher.add_handler(MessageHandler(Filters.document, downloader))

updater.start_polling()
updater.idle()
like image 113
Tibebes. M Avatar answered Apr 23 '26 03:04

Tibebes. M


Here is some changes for python-telegram-bot v20.

from telegram.ext import Application, MessageHandler, filters


async def downloader(update, context):
    file = await context.bot.get_file(update.message.document)
    await file.download_to_drive('file_name')



def main() -> None:
    application = Application.builder().token('BOT_TOKEN').build()

    application.add_handler(MessageHandler(filters.Document.ALL, downloader))

    application.run_polling()

if __name__ == '__main__':
    main()
like image 37
jak bin Avatar answered Apr 23 '26 04:04

jak bin