Search code examples
pythonpython-3.xpython-requeststelegramtelegram-bot

What makes the 'Request Entity Too Large' error when sending an image to Telegram?


File size: 51.2 KB Trying to send:

>>> send_img_url = 'https://api.telegram.org/botXXXXXXXXXXXXXXXXXXXXX/sendPhoto'
>>> img_name = 'C:/Users/Administrator/Downloads/WhatsApp Image 2019-05-30 at 20.54.40.jpeg'
>>> r = requests.post(send_img_url, data={'chat_id': '-351543550', 'photo': open(img_name, 'rb')})
>>> r
<Response [413]>
>>> r.reason
'Request Entity Too Large'
>>> r.content
b''
>>>

Also i try some another requests like:

photo = open(('C:/Users/Administrator/Downloads/WhatsAppImage.jpeg').encode('utf-8'), 'rb')
r = requests.post(send_img_url, data={'chat_id': '-351543550', 'photo': photo})

and:

 with io.open('C:/Users/Administrator/Downloads/WhatsAppImage.jpeg', encoding='utf-8', errors='ignore') as f:
    r = requests.post(send_img_url, data={'chat_id': '-351543550', 'photo': f})

Last option give me next error:

>>> r
<Response [400]>
>>> r.reason
'Bad Request'

Solution

  • You're probably doing it wrong.

    As Bot API docs says:

    Post the file using multipart/form-data in the usual way that files are uploaded via the browser. 10 MB max size for photos, 50 MB for other files.

    In requests lib, by using data= keyword argument, you're sending payload using form-encoded type, not multipart/form-data.

    Try to make your request like that:

    import requests
    
    
    chat_id = '-351543550'
    url = 'https://api.telegram.org/botXXXXXXXXXXXXXXX/sendPhoto?chat_id={}'.format(chat_id)
    filepath = 'C:\correct\path\to\your\file.jpg'
    r = requests.post(url, files={"photo": open(filepath, 'rb')})  # note: files, not data
    print(r.status_code)
    

    P.S.: you can also send chat_id as form-encoded param by using

    url = 'https://api.telegram.org/botXXXXXXXXXXXXXXX/sendPhoto'
    ...
    r = requests.post(url, data={'chat_id': '-351543550'}, files={"photo": open(filepath, 'rb')})