Code for updating the profile photo of Vkontakte using the VK API. Consider working with captcha and upload the code to the server to automatically update the photo.
Required Libraries
Install the vk_api library to work with the VK API for Python: pip install vk_api
Import the necessary libraries
import os import time import random import requests import vk_api from vk_api.utils import get_random_id from urllib import urlretrieve
Login
Authorization in VK using API
vk_session = vk_api.VkApi('+7999132****', '*********') vk_session.auth() vk = vk_session.get_api()
Upload Images
Upload images to the VKontakte server.
photos.getOwnerPhotoUploadServer () returns the server address for uploading the main photo to the userβs page.
url = vk.photos.getOwnerPhotoUploadServer()['upload_url']
To upload the image to the VKontakte server, you need to transfer the file to the upload_url address obtained in the previous paragraph by generating a POST request with the photo field.
Save the server and hash values. They will be needed to update your profile photo.
server = request['server'] hash = request['hash']
Profile photo update
photos.saveOwnerPhoto () saves the user's photo.
After updating the photo, a post with this photo is added to the wall. If you do not delete these posts, then the friends feed will be clogged with posts about your avatar update.
posts = vk.wall.get() post_id = posts["items"][0]["id"] vk.wall.delete(post_id = post_id)
If we run the code, then the photo of our profile will be updated.
For automation, just add an endless loop and make a minute delay after each photo update.
y = 0 while(True): x = random.randint(0, len(photo)-1) while(x == y): x = random.randint(0, len(photo)-1) y = x
Full code import os import time import random import requests import vk_api from vk_api.utils import get_random_id from urllib import urlretrieve vk_session = vk_api.VkApi('+7999132****', '***********') vk_session.auth() vk = vk_session.get_api() images = os.listdir("images") url = vk.photos.getOwnerPhotoUploadServer()['upload_url'] photo = [] for image in images: request = requests.post(url, files={'photo': open('images/'+image, 'rb')}).json() photo.append(request['photo']) server = request['server'] hash = request['hash'] y = 0 while(True): x = random.randint(0, len(photo)-1) while(x == y): x = random.randint(0, len(photo)-1) y = x vk.photos.saveOwnerPhoto(server = server, hash = hash, photo = photo[x]) posts = vk.wall.get() post_id = posts["items"][0]["id"] vk.wall.delete(post_id = post_id) photos = vk.photos.getAll() if (photos['count']>1): photo_id = photos["items"][1]["id"] vk.photos.delete(photo_id = photo_id) time.sleep(60)
But after a few dozen profile photo updates, an error will occur
Captcha: Captcha needed
Let's see how to work with captcha in VK API.
Work with captcha
The vk_api.VkApi () method has already implemented work with captcha. In addition to the login and password, it is necessary to transfer the captcha processing function captcha_handler.
Change vk_session
vk_session = vk_api.VkApi('+7999132****', '**********', captcha_handler=captcha_handler)
We add the captcha_handler (captcha) function, which takes the captcha address, sends the captcha image to the user's messages and waits for the captcha message from the user.
def captcha_handler(captcha):
Function for sending messages with captcha image to user.
The message methods are not accessible to the user from the server, so you need to create a group and get token.
- Create a group / public page
- Management => Work with API => Create a key
- Choose:
- Allow application to access community messages
- Allow app access to community photos
- Copy the key
You must also enable Messages in the group settings (Control => Messages) and enable messages (in the group menu)
def send_captcha(captcha_url):
If we run the code, it will be executed until we interrupt its work. When it is necessary to enter captcha, the captcha image will be sent to private messages and after sending characters from the image, updating the profile photo will continue.
Full code import os import time import random import requests import vk_api from vk_api.utils import get_random_id from urllib import urlretrieve def captcha_handler(captcha): captcha_url = captcha.get_url() urlretrieve(captcha_url, "captcha.jpg") key = send_captcha(captcha_url) print(key) return captcha.try_again(key) def send_captcha(captcha_url): token = "" vk_session = vk_api.VkApi(token = token) vk = vk_session.get_api() url = vk.photos.getMessagesUploadServer()['upload_url'] request = requests.post(url, files={'photo': open("captcha.jpg", 'rb')}).json() photo = vk.photos.saveMessagesPhoto(server=request['server'], photo = request['photo'], hash = request['hash']) attachment = 'photo{}_{}'.format(photo[0]['owner_id'], photo[0]['id']) vk.messages.send( user_id=_ID, attachment = attachment, random_id=get_random_id()) os.remove("captcha.jpg") key = '' while (key == ''): messages = vk.messages.getDialogs()['items'][0] if 'attachments' not in messages['message'].keys(): key = messages['message']['body'] return key vk_session = vk_api.VkApi('+7999132****', '*********', captcha_handler=captcha_handler) vk_session.auth() vk = vk_session.get_api() images = os.listdir("images") url = vk.photos.getOwnerPhotoUploadServer()['upload_url'] photo = [] for image in images: request = requests.post(url, files={'photo': open('images/'+image, 'rb')}).json() photo.append(request['photo']) server = request['server'] hash = request['hash'] y = 0 while(True): x = random.randint(0, len(photo)-1) while(x == y): x = random.randint(0, len(photo)-1) y = x vk.photos.saveOwnerPhoto(server = server, hash = hash, photo = photo[x]) posts = vk.wall.get() post_id = posts["items"][0]["id"] vk.wall.delete(post_id = post_id) photos = vk.photos.getAll() if (photos['count']>1): photo_id = photos["items"][1]["id"] vk.photos.delete(photo_id = photo_id) print("Successfully", x) time.sleep(60)
For round-the-clock code execution I use VPS hosting. I load images and execute the code on the server.
Github code
If you have questions, write in the comments or in the PM.