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

Mushanya
  • 13
  • 2
  • It's not obvious from the python-requests docs, but the library does not easily support sending a request with JSON body and multipart files together (e.g. see the src here https://requests.readthedocs.io/en/latest/_modules/requests/models/#PreparedRequest.prepare_body) ...it looks like you have to send your json body as a 'file' too as shown in this answer https://stackoverflow.com/a/35940980/202168 – Anentropic Sep 14 '22 at 13:08
  • Changed it to `_files = { "json":(None, json.dumps(_json), "application/json"), "media":("photo1.jpg", open(r"../photo1.jpg", 'rb'), "application/octet-stream"), } temp = r.post("https://api.telegram.org/bot/sendMediaGroup", files=_files)` But the problems remains the same – Mushanya Sep 14 '22 at 13:29

1 Answers1

2

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

0stone0
  • 34,288
  • 4
  • 39
  • 64