【问题标题】:API send photo to telegram bot by URLAPI 通过 URL 将照片发送到电报机器人
【发布时间】:2021-02-04 18:25:24
【问题描述】:

您好,我想通过telegram API 向我的机器人发送照片,我必须使用 API URL 发送并且不能使用库。

我试过了:

token = " "
chat_id = " "
pic = ("C:\\Windows\\pic\\hello.jpg")

url = requests.post("https://api.telegram.org/bot"+token+"/sendPhoto?chat_id="+chat_id+"&photo="+pic)

print(url)

结果:

{"ok":false,"error_code":400,"description":"Bad Request: wrong HTTP URL specified"}

【问题讨论】:

  • 它对我有用,你到底是什么问题?

标签: api telegram telegram-bot


【解决方案1】:

首先,是sendPhoto而不是sendphoto

这是link for docs 供您参考。

请注意,您将 post requets 的 url 提供为: https://api.telegram.org/bot"+token+"/sendphoto?chat_id="+chat_id+"&photo="+pic 但实际上应该是 https://api.telegram.org/bot"+token+"/sendPhoto?chat_id="+chat_id+"&photo="+pic


其次,您正在尝试发送本地托管的图像。发送本地托管的图片与发送在线图片的 URL 有点不同。

您必须将图像文件作为字典与发布请求一起发送,如下所示:

import requests

img = open(your/local/image, 'rb')
TOKEN = 
CHAT_ID = 

url = f'https://api.telegram.org/bot{TOKEN}/sendPhoto?chat_id={CHAT_ID}'


print(requests.post(url, files={'photo': img}))

输出:

<Response [200]>


【讨论】:

  • 我更新了我的问题并改进了,请检查 agian tnx
  • 我已经更新了答案,看看。您应该使用 sendPhoto 并将本地托管的图像作为 dict 在 post 请求中传递。
  • 兄弟,我将您的代码完全复制到我的项目中,但又得到了 我不知道为什么
  • 我的代码工作得很好,请确保您在img 中将您的本地图像 传递为img = open("C:\\Windows\\pic\\hello.jpg", 'rb') 并将url 设置为url = "https://api.telegram.org/bot"+TOKEN+"/sendPhoto?chat_id="+CHAT_ID") 如果您不想要像我在答案中那样使用 f-strings 。 `
  • 兄弟非常感谢你的代码工作,TNX
猜你喜欢
  • 1970-01-01
  • 2016-10-17
  • 2021-02-10
  • 2016-07-18
  • 2016-06-29
  • 2017-10-13
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多