【问题标题】:Telegram Bot how to use the sendDocumentTelegram Bot 如何使用 sendDocument
【发布时间】:2020-08-29 15:47:16
【问题描述】:

我无法发送位于 app 目录中的 *.txt 文件:
我在 /app 中有文件,我想用 sendDocument 方法发送它,

  • telepot 库案例:
file = open('report.txt', 'w')
file.write('report')
file.close()

telepot_bot.sendDocument(os.environ['ADMIN0'], document=file, caption='report.txt')
# or
telepot_bot.sendDocument(os.environ['ADMIN0'], document=file.name, caption='report.txt')
# or
telepot_bot.sendDocument(os.environ['ADMIN0'], document=os.path.realpath(file.name), caption='report.txt')

返回:

ValueError: I/O operation on closed file.
# or
telepot.exception.TelegramError: ('Bad Request: wrong file identifier/HTTP URL specified', 400, {'ok': False, 'error_code': 400, 'description': 'Bad Request: wrong file identifier/HTTP URL specified'})
# or
telepot.exception.TelegramError: ('Bad Request: URL host is empty', 400, {'ok': False, 'error_code': 400, 'description': 'Bad Request: URL host is empty'})

  • python-telegram-bot 库案例:
context.bot.send_document(os.environ['ADMIN0'], document=file, filename='report.txt')
# or
context.bot.send_document(os.environ['ADMIN0'], document=file.name, filename='report.txt')
# or
context.bot.send_document(os.environ['ADMIN0'], document=os.path.realpath(file.name), filename='report.txt')

返回:

ValueError: I/O operation on closed file.
# or
telegram.error.BadRequest: Wrong file identifier/http url specified
# or
telegram.error.BadRequest: Url host is empty

手册说:
“...使用 multipart/form-data 上传一个新的。最后你可以传递一个现有的 :class: telegram.Document 对象来发送。”
但是我该怎么做呢?

【问题讨论】:

    标签: python python-telegram-bot telepot


    【解决方案1】:

    检查文件是否存在于当前工作目录中。

    发送文件的实际代码:

    with open("report.txt", "rb") as file:
        context.bot.send_document(chat_id=1234, document=file,  
              filename='this_is_for_tg_name.txt')
    

    参考使用send_document的正确格式here

    【讨论】:

    • 我也做了这个变种,但结果是 telegram.error.BadRequest: Wrong file identifier/http url specified 这和document=file.name 一样
    • @Vadim 我再次检查了一些更改 :)
    • @Vadim 欢迎您,顺便说一句,python-telegram-bot API 真的很旧且无效。尝试使用第三方库,例如 telethon、pyrogram 等。
    猜你喜欢
    • 2020-11-05
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多