Доброго времени суток, использую
https://github.com/python273/vk_api для работы с апи vk.
Сегодня понадобилось отправить изображению на стенку группы и постоянно получал ошибки
vk_api.vk_api.ApiError: [121] Invalid hash
Решил проверить правильность действий через вк инструменты
https://vk.com/dev/photos.saveWallPhoto
https://vk.com/dev/photos.getWallUploadServer
получал 121
Пример кода
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import argparse
import datetime
from getpass import getpass
import os
import sys
__version__ = '0,1'
try:
from vk_api import VkApi
except ImportError:
print("Cannot find 'vk_api' module. Please install it and try again.")
sys.exit(0)
def openPhotos(photo_paths, path):
photos = {}
for i, filename in enumerate(photo_paths):
photos.update({'file%s' % i: open(os.path.join(path, filename), 'rb')})
return photos
def closePhotos(photos):
for i in photos:
photos[i].close()
def connect(login, password):
"""Initialize connection with `vk.com <https://vk.com>`_ and try to authorize user with given credentials.
:param login: user login e. g. email, phone number
:type login: str
:param password: user password
:type password: str
:return: :mod:`vk_api.vk_api.VkApi` connection
:rtype: :mod:`VkApi`
"""
return VkApi(login, password)
def photo_wall(connection, photo, group_id=None):
values = {'group_id': group_id}
response = connection.method('photos.getWallUploadServer', values)
url = response['upload_url']
photos_files = openPhotos(photo, args.upload_path)
response = connection.http.post(url, files=photos_files)
closePhotos(photos_files)
response = connection.method('photos.saveWallPhoto', response.json())
return response
def split_by_three(lst, n=3):
return [lst[i:i + n] for i in range(0, len(lst), n)]
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='', version='%(prog)s ' + __version__)
parser.add_argument('username', help='vk.com username')
parser.add_argument('-gid','--group_id', help='group id', default=False)
parser.add_argument('-upl', '--upload_path', help='path to upload photo',
default=os.path.abspath(os.path.join(os.path.dirname(__file__), 'vk_upload')))
args = parser.parse_args()
# expand user path if necessary
if args.upload_path.startswith('~'):
args.upload_.path = os.path.expanduser(args.upload_path)
if not os.path.exists(args.upload_path):
os.makedirs(args.upload_path)
start_time = datetime.datetime.now()
try:
password = getpass("Password: ")
# Initialize vk.com connection
connection = connect(args.username, password)
if args.group_id:
processed = 0
treeple_list = split_by_three(os.listdir(args.upload_path))
for filename_pack in treeple_list:
percent = round(float(processed) / float(len(os.listdir(args.upload_path))) * 100, 2)
sys.stdout.write(
"\r export %s... %s of %s (%2d%%)\n" % (', '.join(filename_pack), processed, len(os.listdir(args.upload_path)), percent))
sys.stdout.flush()
upl = photo_wall(connection, filename_pack, args.group_id)
processed += 3
except Exception as e:
print(e)
sys.exit(1)
except KeyboardInterrupt:
print('Stopped by keyboard')
sys.exit(0)
finally:
print("Done in %s" % (datetime.datetime.now() - start_time))