Last active
December 16, 2020 18:57
-
-
Save trolleway/f3b489f025bab923b8a5e1c9600e3b71 to your computer and use it in GitHub Desktop.
Post photo from web to vk.com in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
vk_gid = '' #user id | |
#obtain client_id from VK: create new standalone app at https://vk.com/editapp?act=create | |
vk_client_id = '' | |
vk_scope = 'wall,photos' | |
#open in browser https://oauth.vk.com/authorize?client_id=0000000000&scope=wall,photos&v=5.60&response_type=token&redirect_uri=https://oauth.vk.com/blank.html | |
#and paste token here | |
vk_token = '' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import config | |
import urllib | |
import urllib2 | |
import requests | |
import json | |
token = config.vk_token | |
def post(): | |
url='http://trolleway.nextgis.com/api/component/render/image?resource=642&extent=-9273652.2898957,5017436.116284987,-9273230.09474728,5017965.801004432&size=708,888' | |
img = {'photo': ('img32.jpg', urllib.urlopen(url, 'rb'))} | |
message_text_utf='Загрузка карты в vk.com из nextgis.com через api' | |
message_text = message_text_utf.decode('utf-8') | |
# Получаем ссылку для загрузки изображений | |
method_url = 'https://api.vk.com/method/photos.getWallUploadServer?' | |
data = dict(access_token=token, gid=config.vk_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=config.vk_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 | |
# 'идентификатор сообщества в параметре owner_id необходимо указывать со знаком "-"' | |
method_url = 'https://api.vk.com/method/wall.post?' | |
data = dict(access_token=token, owner_id='' + config.vk_gid, attachments=result, message=message_text) | |
response = requests.post(method_url, data) | |
result = json.loads(response.text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment