如何在 python-telegram-bot 中接收文件?

DR8*_*002 9 python python-3.x python-telegram-bot telegram-bot

我对 python telegram bot 中的文件消息有疑问。我如何接收文件并读取该文件?或者保存它。

Tib*_*. M 10

你可以:

  • 注册一个监听的处理程序Document
  • File从更新中获取对象(在侦听器内使用get_file
  • 然后只需调用即可.download()下载文档

这里有一个示例代码可以帮助您入门:

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()
Run Code Online (Sandbox Code Playgroud)


jak*_*bin 6

以下是 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()
Run Code Online (Sandbox Code Playgroud)