R
R
RIKUDO052015-07-29 12:32:24
Python
RIKUDO05, 2015-07-29 12:32:24

How to upload an image to a VK wall using the VK API in Python?

There is an image on the computer. How to upload this image to VK group wall via VK API in Python? The official documentation didn't help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Samoilov, 2015-07-29
@RIKUDO05

There are detailed instructions on the VK website.
For this operation, you need to get a token for your application.
You can use vk_auth
To send requests, you can use the requests library

import requests
import json
import vk_auth

# Ваши данные ВК
email = ''
password = ''
client_id = ''
# Необходимые нам права
scope = 'wall,photos'
# Идентификаторы группы
gid = ''

token = vk_auth(email, password, client_id, scope)[0]

# путь к вашему изображению
img = {'photo': ('img.jpg', open(r'img.jpg', 'rb'))}

# Получаем ссылку для загрузки изображений
method_url = 'https://api.vk.com/method/photos.getWallUploadServer?'
data = dict(access_token=token, gid=gid)
response = requests.post(method_url, data)
result = json.loads(response.text)
upload_url = result['response']['upload_url']

# Загружаем изображение на url
response = requests.post(upload_url, files=img)
result = json.loads(response.text)

# Сохраняем фото на сервере и получаем id
method_url = 'https://api.vk.com/method/photos.saveWallPhoto?'
data = dict(access_token=token, gid=gid, photo=result['photo'], hash=result['hash'], server=result['server'])
response = requests.post(method_url, data)
result = json.loads(response.text)['response'][0]['id']

# Теперь этот id остается лишь прикрепить в attachments метода wall.post
method_url = 'https://api.vk.com/method/wall.post?'
data = dict(access_token=token, owner_id='-' + gid, attachments=result, message='')
response = requests.post(method_url, data)
result = json.loads(response.text)

# На выходе мы получим в ответе post_id если не было ошибки

R
Riedel87, 2015-07-30
@Riedel87

Hey! Try this package, I think it will help you.
https://github.com/dimka665/vk

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question