Vk library for working with VK API in Python

Hello, Habr! This article is intended for those who want to understand the basics of the VK API in Python, since there are no articles on this subject (there is one article on the Habré, but it is no longer quite relevant, as some methods do not work), and on other resources I managed to find only user questions, but no guides and other things.
There are two popular libraries for working with VK API in Python: vk and vk_api. Which library is better I won’t judge, but I’ll say one thing: vk has too little documentation (so I understood it practically by typing) in English, and vk_api has more documentation (so I don’t see any sense in writing about this library) in Russian. For me, the documentation in which language is not the main thing, but for some users it plays a big role when choosing.
As you already understood, this article discusses working with the vk library.
This library is installed with the following standard command:
pip install vkAfter the module is installed, we need to create an application on the website of the social network. I think that most users can do this, so I skip the information on this step. If someone does not know how, then google, do not be shy.
After registering the application, we only need its ID.
Let's start with authorization. In principle, some information can be obtained without entering personal data, which is of course good, for example:
import vk
session = vk.Session()
vk_api = vk.API(session)
vk_api.users.get(user_id=1)
Thus, we get the last name, first name and id of the user with user_id = 1. If you need to get some more information about the user, then in the method call you need to specify additional fields, information about which should be returned:
vk_api.users.get(user_id=1, fields=’online, last_seen’)Those. in this case, we will get not only information about the name and surname of the user with id = 1, but also information about whether the user is currently on the site (fields = 'online') and the time of the last visit, as well as the type of device (fields = ' last_seen ').
Actions without authorization do not provide us with the opportunity to use the VK API to its full potential, therefore, we will consider authorization with the input of personal data. There are two ways: entering a username and password, entering a token. To log in using a token, you need to slightly supplement the first example, namely this line:
session = vk.Session(access_token='tocken')Then everything remains the same as it was before, without any changes.
The next method of authorization is to enter a username and password. In this case, too, everything is quite simple and clear:
session = vk.AuthSession('id_app', 'login', 'pass')
vk_api = vk.API(session)As you can see, nothing complicated and everything is so simple and clear that it does not even need additional comments.
With this authorization, you need to specify not only the username, password and application ID, but what we want to access.
For example, we do not currently have access to the user's wall, so when we try to add a record to the wall, we get an error:
vk_api.wall.post(message="hello")
Ошибка: vk.exceptions.VkAPIError: 15.In order for this code to work correctly, during authorization you need to specify an additional argument with the name scope and list the methods that we want to access, separated by commas.
session = vk.AuthSession('id_app', 'login', 'pass', scope=’wall, messages’)
vk_api = vk.API(session)
vk_api.wall.post(message="hello")In this example, I am requesting access to the wall and posts. The execution of the program ends correctly, and on the wall appears an entry with the text 'hello'. The names of methods that can be accessed can be found on this documentation page .
That's all. Methods are called according to one pattern:
vk_api.метод.название(параметры=значения)
Например: vk_api.messages.send(users_id=0, messages=’hello’)Thus, we send a hello message to the user with id = 0 (i.e. to ourselves). The names of the parameters that need to be passed when calling any method can be found in the documentation, in the description of the method itself.
For a more visual work of the library, I implemented a small program that monitors when a user logs in to VK and when he logs out of it (it is hard to believe, but it might be of interest to anyone). The program code is below and on GitHub .
Sample program using vk library
import datetime
from time import sleep
import vk
def get_status(current_status, vk_api, id):
profiles = vk_api.users.get(user_id=id, fields='online, last_seen')
if (not current_status) and (profiles[0]['online']): # если появился в сети, то выводим время
now = datetime.datetime.now()
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
print('Появился в сети в: ', now.strftime("%d-%m-%Y %H:%M"))
return True
if (current_status) and (not profiles[0]['online']): # если был онлайн, но уже вышел, то выводим время выхода
print('Вышел из сети: ', datetime.datetime.fromtimestamp(profiles[0]['last_seen']['time']).strftime('%d-%m-%Y %H:%M'))
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
return False
return current_status
if __name__ == '__main__':
id = input("ID пользователя: ")
session = vk.Session()
vk_api = vk.API(session)
current_status = False
while(True):
current_status = get_status(current_status, vk_api, id)
sleep(60)This article was intended only to understand the basics of working with VK API in Python using the VK library.
Good to all!