【问题标题】:How can I send a Document with telegram bot API?如何使用电报机器人 API 发送文档?
【发布时间】:2020-11-16 09:18:59
【问题描述】:

大家早上好。我想使用 Python 和 Telegram Bot 的 API 发送文档。 Bot 已成功创建,我也可以发送消息,但不幸的是,我无法发送笔记本电脑上的文档。

我的代码如下:

import requests


def telegram_bot_send_document():

    bot_token = '####'
    bot_chatID = '####'

    file = open('test.txt', 'rb')
    send_document = 'https://api.telegram.org/bot' + bot_token + '/sendDocument?chat_id=' + bot_chatID + '&multipart/form-data=' + str(file.read())

    r = requests.post(send_document)
    print(r.url)

    return r.json()

输出总是:

{'ok': False, 'error_code': 400, 'description': 'Bad Request: there is no document in the request'}

【问题讨论】:

    标签: python-requests python-telegram-bot


    【解决方案1】:

    首先,我从来没有使用过电报 API 或者用电报发送文档。

    来自他们的文档:

    (来源:https://core.telegram.org/bots/api#sending-files

    发送文件共有三种发送文件的方式(照片、贴纸、 音频、媒体等):

    1. 如果文件已经存储在 Telegram 服务器的某个位置,您 不需要重新上传:每个文件对象都有一个 file_id 字段, 只需将此 file_id 作为参数传递,而不是上传。那里 以这种方式发送的文件没有限制。
    2. 为 Telegram 提供 HTTP 要发送的文件的 URL。 Telegram 将下载并发送文件。 照片最大为 5 MB,其他类型的内容最大为 20 MB。
    3. 使用 multipart/form-data 以通常的方式发布文件 通过浏览器上传。照片最大 10 MB,最大 50 MB 其他文件。

    您需要先上传文件并引用 ID,或者您需要一个POST-请求,而不是附加到URL

    【讨论】:

    • 非常感谢您的快速回答。如果我不将文件附加到 url,我该如何上传?我阅读了文档,我想使用第三种方式:使用 multipart/form-data 发布文件。
    猜你喜欢
    • 2019-02-25
    • 2017-06-16
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 2016-07-18
    • 2019-10-30
    • 1970-01-01
    相关资源
    最近更新 更多