Upload photo to Telegram API with Python Requests

时间:2016-03-04 18:01:58

标签: python telegram-bot

I've seen the other questions on this but I can't figure out where I'm going wrong. I can upload a file no problem using a PHP page that looks like this:

<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>

But I want to do it from Python with Requests:

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)

Which then gives me the r.text error:

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

And I'm thinking I am mishandling the chat_id parameter also and it needs to be passed in a different way.

Any guidance much appreciated!

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码:

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()

欢呼

答案 1 :(得分:-2)

此错误与文件类型有关。像这样(在HTML中):

 <input type="file" name="photo" />

你应该将文件类型更改为图像或照片,但我不知道python。