Upload photo to Telegram API with Python Requests

Viewed 5647

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 Answers

You can use the following code:

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

Cheers

Related