Skip to main content
 首页 » 编程设计

python之使用 Python 请求将照片上传到 Telegram API

2025年05月04日8daizhj

我已经看到了关于此的其他问题,但我无法弄清楚我哪里出错了。我可以使用如下所示的 PHP 页面毫无问题地上传文件:

<form action="https://api.telegram.org/bot190705145:AAH17XDRrPtDO1W1qHCoZ8i0_KqAAAAAAA/sendPhoto" method="post" enctype="multipart/form-data"> 
 
    <input type="text" name="chat_id" value="XXXXXXXX" /> 
    <input type="file" name="photo" /> 
    <input type="submit" value="send" /> 
 
</form> 

但我想通过请求从 Python 中完成:

url = 'https://api.telegram.org/bot190705145:AAH17XDRrPtDO1W1qHCoZ8i0_KAAAAAAAAA/sendPho    to?chat_id=XXXXXXXXX' 
files = {'file':open('/Users/stephen/desktop/Sample.png', 'rb')} 
r = requests.post(url, files=files) 

然后出现 r.text 错误:

u'{"ok":false,"error_code":400,"description":"[Error]: Bad Request: there is no photo in request"}' 

而且我认为我也对 chat_id 参数处理不当,需要以不同的方式传递它。

非常感谢任何指导!

请您参考如下方法:

您可以使用以下代码:

import requests 
 
_TOKEN = "YOUR TOKEN HERE" 
 
 
def send_photo(chat_id, image_path, image_caption=""): 
    data = {"chat_id": chat_id, "caption": image_caption} 
    url = "https://api.telegram.org/%s/sendPhoto" % _TOKEN 
    with open(image_path, "rb") as image_file: 
        ret = requests.post(url, data=data, files={"photo": image_file}) 
    return ret.json() 

干杯