E
E
Evgeny Lavrov2022-01-28 06:11:12
Python
Evgeny Lavrov, 2022-01-28 06:11:12

How to send a photo via api to classmates in python?

I'm trying to upload a photo to the server in classmates via https://apiok.ru/dev/graph_api/methods/graph.user/...
for later sending in group messages
Here is my code:

import requests

import config

url = f"https://api.ok.ru/graph/me/fileUploadUrl?access_token={config.access_token}&type=IMAGE"
response = requests.get(url)
response = response.json()
print(response)
with open("bot.png", "rb") as f:
    response = requests.post(response['url'], data=f.read(), headers={"Content-Type": "image/png"})
    print(response.json())

And here is what I get:
{'url': 'https://pu.mycdn.me/uploadImage?apiToken=bXZTK13IkVAlV0fncKrLwB%2FQzs6oeEPsdXgUXutB%2BSlNFZXxOVzBAglmprptq622vWLYpTIc3LY752uocokS9qwG7utgtd8wt8pVmGwGEFTpWtRKDwxuA2MJbpZNoW4r%2F2TW9shGgAdU9M4IsBNS8Q%3D%3D&photoIds=Ba4SfICf58KhEQ1WZeOUHECdEDaG9sbew9ZqSUNXyTMbldMf9GgDEw%3D%3D', 'file_id': 'Ba4SfICf58KhEQ1WZeOUHECdEDaG9sbew9ZqSUNXyTMbldMf9GgDEw=='}
{'error_msg': 'one.image.upload.client.ContentUploadServerException: BAD_REQUEST', 'error_code': '4', 'error_data': 'BAD_REQUEST'}

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Lavrov, 2022-01-28
@lavrov2002

import requests

import config

url = f"https://api.ok.ru/graph/me/fileUploadUrl?access_token={config.access_token}&type=IMAGE"
response1 = requests.get(url)
response1 = response1.json()
print(response1)

multiple_files = [
    ('images', ('bot.png', open('bot.png', 'rb'), 'image/png'))
]
response2 = requests.post(response1['url'], files=multiple_files)
response2 = response2.json()
print(response2)

chat_id = "chat:C7d78ad3d0000"

token = response2['photos'][response1['file_id']]['token']
print(token)
params = {
    "recipient": {"chat_id": chat_id},
    "message": {
        "attachment": {
            "type": "IMAGE",
            "payload": {"token": token}
        }
    }
}

url = f"https://api.ok.ru/graph/{chat_id}/messages?access_token={config.access_token}"

response3 = requests.post(url, json=params, headers={"Content-Type": "application/json;charset=utf-8"})
response3 = response3.json()
print(response3)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question