How to send photos with multipart/form-data in media group with python requests?

Question:

json = {"chat_id":chat_id, "media":[{"type" : "photo", "media" : "attach://photo1.jpg"}, {"type" : "photo", "media" : "attach://photo2.jpg"}]}

files = {"photo1.jpg" : open(r"../photo1.jpg", 'rb'), "photo2.jpg" : open(r"../photo2.jpg", 'rb')}

temp = r.post("https://api.telegram.org/bot<TOKEN>/sendMediaGroup", json=json, files=files)

print(temp.json())

I keep getting this response: {'ok': False, 'error_code': 400, 'description': 'Bad Request: parameter "media" is required'}

How can I send photo.jpg with sendMediaGroup using multipart/form-data?

Asked By: Mushanya

||

Answers:

I’d recommend using data with a custom dict.

Then the only thing you should note is the media array inside data, should be JSON encoded using json.dumps

So the code becomes:

import json
import requests as r

#####
chat_id = 1010011
TOKEN = 'ABCDEF....'
#####

data = {
    "chat_id": chat_id,
    "media": json.dumps([
        {"type": "photo", "media": "attach://photo1.png"},
        {"type": "photo", "media": "attach://photo2.png"}
    ])
}

files = {
    "photo1.png" : open("./photo1.png", 'rb'),
    "photo2.png" : open("./photo2.png", 'rb')
}

temp = r.post("https://api.telegram.org/bot" + TOKEN + "/sendMediaGroup", data=data, files=files)

print(temp.json())

Result in Telegram desktop:
enter image description here

Answered By: 0stone0