V
V
Vladislav Vozian2019-02-11 19:07:22
Python
Vladislav Vozian, 2019-02-11 19:07:22

How to upload a picture to public via vk api?

import vk
#import pic_gen
import requests
#import SizeChecker

session = vk.AuthSession(access_token='ТОКЕН ДОСТУПА', scope=ПРАВА ДОСТУПА)
vk_api = vk.API(session, v='5.92')
filename = 'sample.png'
group_id = 'ID ГРУППЫ'

UplServ = vk_api.photos.getWallUploadServer(group_id=group_id)
upload_url = UplServ['upload_url']
img = {'photo': ('sample.png', open(r'sample.png', 'rb'))}
request = requests.post(upload_url, files=img)

params = {'server': request.json()['server'],
          'photo': request.json()['photo'],
          'hash': request.json()['hash'],
          'group_id': group_id}

photo_id = vk_api.photos.saveWallPhoto(**params)
photo_id = photo_id[0]
photo_id = 'photo'+ '-' + str(photo_id['owner_id']) + '_' + str(photo_id['id'])


params = {'attachments': photo_id,
          'message': 'Просто текст...',
          'owner_id': '-' + group_id,
          'from_group': '1'}
vk_api.wall.post(**params)

There is this piece of code. In theory, he should upload the picture to the VK server, and then post it.
The problem is that the post is created without an image, only text. It is noteworthy that after the getWallUploadServer function has run, the UplServ variable takes incomprehensibly whose ['album_id'] and ['user_id'] (these are not my user or group id, and moreover, I don’t have such an album)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
Hello World, 2019-02-11
@VladislavVozian

For example, there is a group
To find out the available albums, go to https://vk.com/albums-178172381
And click on the available / create a new album. After, the url will change to https://vk.com/album-178172381_XXX, where XXX is album_id

import vk
import requests # or httplib2

album_id = 260909009 # XXX - 260909009
group_id = 178172381
filename = 'simple.png'
token = '7opnd...2nfds'
api = vk.API(vk.Session(access_token=token), v=5.92)
upload_url = api.photos.getWallUploadServer(group_id=group_id)['upload_url'] 
resp = requests.post(upload_url, files = {'file': open(filename, 'rb')}).json() # вот не знаю, можно ли много картинков за раз загружать
s = api.photos.saveWallPhoto(group_id=group_id, server = resp['server'], photo= resp['photo'], hash = resp['hash'])
api.wall.post(owner_id = -group_id, message="Test!", attachments=f"photo{s[0]['owner_id']}_{s[0]['id']}")

As a result: https://vk.com/club178172381

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question