Stephen Flanagan
Stephen Flanagan

Reputation: 311

Upload photo to Telegram API with Python Requests

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!

Upvotes: 6

Views: 9042

Answers (3)

Miro
Miro

Reputation: 112

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 = f"https://api.telegram.org/bot{_TOKEN}/sendPhoto?chat_id={chat_id}"
    with open(image_path, "rb") as image_file:
        ret = requests.post(url, data=data, files={"photo": image_file})
    return ret.json()

Cheers

Upvotes: 5

Fernando
Fernando

Reputation: 83

It's from a comment from Ashwini Chaudhary (it seems so obvious once said, thank you very much).

Changing:

files = {'file':open('/Users/stephen/desktop/Sample.png', 'rb')}

to:

files = {'photo':open('/Users/stephen/desktop/Sample.png', 'rb')}

worked for me and it seems that it was the issue for several others.

Upvotes: 0

user6622161
user6622161

Reputation: 1

this error related to file type. like this(in html):

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

you should change file type to image or photo, but i don't know python.

Upvotes: -2

Related Questions