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

问题描述 投票:-1回答:1

我在python电报bot中遇到有关文件消息的问题。如何接收文件并读取该文件?或保存。

python python-3.x telegram-bot python-telegram-bot
1个回答
0
投票

您可以:

  • 注册一个监听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", 'w') 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()
© www.soinside.com 2019 - 2024. All rights reserved.