python - 向 Telegram 发送图像时出现 'Request Entity Too Large' 错误是什么原因?

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

文件大小:51.2 KB 尝试发送:

>>> send_img_url = 'https://api.telegram.org/botXXXXXXXXXXXXXXXXXXXXX/sendPhoto'
>>> img_name = 'C:/Users/Administrator/Downloads/WhatsApp Image 2019-05-30 at 20.54.40.jpeg'
>>> r = requests.post(send_img_url, data={'chat_id': '-351543550', 'photo': open(img_name, 'rb')})
>>> r
<Response [413]>
>>> r.reason
'Request Entity Too Large'
>>> r.content
b''
>>>

我还尝试了其他一些请求,例如:

photo = open(('C:/Users/Administrator/Downloads/WhatsAppImage.jpeg').encode('utf-8'), 'rb')
r = requests.post(send_img_url, data={'chat_id': '-351543550', 'photo': photo})

和:

 with io.open('C:/Users/Administrator/Downloads/WhatsAppImage.jpeg', encoding='utf-8', errors='ignore') as f:
    r = requests.post(send_img_url, data={'chat_id': '-351543550', 'photo': f})

最后一个选项给我下一个错误:

>>> r
<Response [400]>
>>> r.reason
'Bad Request'

最佳答案

使用本地 Bot API 服务器,您可以发送高达 2GB 的大文件。

GitHub 源代码:

https://github.com/tdlib/telegram-bot-api

官方文档

https://core.telegram.org/bots/api#using-a-local-bot-api-server

您可以build and install按照此链接 https://tdlib.github.io/telegram-bot-api/build.html 上的说明将其发送到您的服务器

基本设置:

  1. https://my.telegram.org/apps 生成 Telegram 应用程序 ID
  2. 启动服务器 ./telegram-bot-api --api-id=<your-app-id> --api-hash=<your-app-hash> --verbosity=20
  3. 默认地址为http://127.0.0.1:8081/端口是8081。
  4. 所有官方 API 都适用于此设置。只需将地址更改为 http://127.0.0.1:8081/bot<token>/METHOD_NAME引用:https://core.telegram.org/bots/api

示例代码:

import requests

url = "http://127.0.0.1:8081/bot<your-bot-token>/sendVideo"

payload={'chat_id': 'chat_id',
'supports_streaming': 'true'}
files=[
  ('video',('your_file_name.mp4',open('path_of_file','rb'),'application/octet-stream'))
]
headers = {}

response = requests.request("POST", url, headers=headers, data=payload, files=files)

print(response.text)

关于python - 向 Telegram 发送图像时出现 'Request Entity Too Large' 错误是什么原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56384652/

相关文章:

python - Boost Python enum_ max 问题

python - 使用配置文件打包 Python 应用程序

python-3.x - Python EasyGUI 模块 : how to change the font

Python3 - 迭代具有相似名称的对象方法

python - 类的方法是否应该至少有一个引用实例的参数?

python - 设置 `aiohttp.ClientSession` 默认参数

python - 使用 python 发出 POST 请求失败,而使用 curl 发出相同请求成功。我错过了什么?

python - 为不同的函数分离 **kwargs

python - 与 tkinter 同时使用 .pack() 和 .grid()

python - 使用 openweathermap api 解析字典(json)中的数据