A
A
Andrey Grinevich2014-08-16 00:08:38
PHP
Andrey Grinevich, 2014-08-16 00:08:38

How to send an image to the wall of a group in VK?

Good day, I use https://github.com/python273/vk_api to work with api vk.
Today I needed to send an image to the group wall and constantly received errors
vk_api.vk_api.ApiError: [121] Invalid hash
I decided to check the correctness of the actions through VK tools
https://vk.com/dev/photos.saveWallPhoto
https://vk.com/ dev/photos.getWallUploadServer
was getting 121
Code example

#!/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))

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mat0thew, 2014-08-16
@mat0thew

You need authorization. token

A
Andrey Grinevich, 2014-08-16
@Derfirm

print connection.__dict__
'token': {u'access_token': u'token_there', u'expires_in': u'0', u'user_id': u'Id_there'}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question