Answer the question
In order to leave comments, you need to log in
Python VK_API How to upload an image to a group album?
I log in as a group, and I try to upload to it. It
gives an error:vk_api.exceptions.ApiError: [121] Invalid hash
import vk_api, json
vk=vk_api.VkApi(token='blablabla')
vk.auth()
a=vk.method('photos.getMessagesUploadServer')
print(a) #{'album_id': -64, 'group_id': 151313066, 'upload_url': 'https://pu.vk.com/c836728/upload.php?act=do_add&mid=140420515&aid=-64&gid=151313066&hash=9882bffc4752d5a87a37a35bccf6517f&rhash=3385661e41a2933caaad0fe88fcc9a40&swfupload=1&api=1&mailphoto=1'}
b=json.loads(requests.get(a['upload_url']).text)
print(b) #{'photo': '[]', 'hash': 'd6d59d2bad3bc5ea497f82b4867cfc82', 'server': 836728}
vk.method('photos.saveMessagesPhoto', {'photo': {'photo': open('1.jpg', 'rb')}, 'server': b['server'], 'hash': b['hash']})
Answer the question
In order to leave comments, you need to log in
Loading into messages:
import requests, vk_api
vk = vk_api.VkApi(token='blablabla')
vk.auth()
a = vk.method('photos.getMessagesUploadServer')
b = requests.post(a['upload_url'], files={'photo': open('blabla', 'rb')}).json()
c = vk.method('photos.saveMessagesPhoto', {'photo': b['photo'], 'server': b['server'], 'hash': b['hash']})[0]
d = 'photo{}_{}'.format(c['owner_id'], c['id'])
vk.method('messages.send', {'user_id': 'bla', 'attachment': d})
From the documentation:
Upload files to the upload_url obtained in the previous paragraph by making a POST request with the photo field . This field must contain images in multipart/form-data format.
You get it like this:
- called photos.getMessagesUploadServer, got the address where to upload the photo
- then just pulled this address with a GET
- you try to put the photo in a method that simply confirms saving after uploading.
In general, before calling photos.saveMessagesPhoto , send the photo with a POST request to upload_url , and only then call the photos.saveMessagesPhoto method .
You can also see an example from your module
. And I just noticed that you want to upload an image to a group album: look at the photos.getUploadServer method , you can specify the group album there
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question