【问题标题】:How can I receive file in python-telegram-bot?如何在 python-telegram-bot 中接收文件?
【发布时间】:2020-06-08 01:29:30
【问题描述】:

我对 python 电报机器人中的文件消息有疑问。如何接收文件并读取该文件?或者保存它。

【问题讨论】:

标签: python python-3.x telegram-bot python-telegram-bot


【解决方案1】:

你可以:

  • 注册一个监听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()

【讨论】:

  • 谢谢兄弟下载到同一个目录?
  • 是的,但是您可以传递自定义路径。检查python-telegram-bot.readthedocs.io/en/stable/…
  • 还有一个问题,如何更改文件名?
  • 是的,将可写文件处理程序作为out 传递。我已经更新了答案,向您展示如何做到这一点
  • 我写了这个:` def file_(update:Update,context:CallbackContext): with open("file.txt","w") as f: context.bot.get_file(update.message .document).download(out=f)` 但它没有在 file.txt 中写入任何内容
猜你喜欢
  • 1970-01-01
  • 2016-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-25
相关资源
最近更新 更多