📜 ⬆️ ⬇️

How to write a chat bot for vk.com in 3 minutes

Unfortunately, at the moment there are no good libraries on Python2, in order to quickly create a chat bot. Below I will show how easy it is to write a primitive chat bot for VK using the VK API.


The article is written for beginners to show that there is nothing difficult to write bots in Python.


Authorization


We need a library vk_api . You can log in to VK in two ways:
- as user
- As a community


In the first case, you will need to enter a username and password. In the second case, in the group, you must enable "Community Messages" and create an API access key:


image


image


Authorization in two lines:


import time import vk_api vk = vk_api.VkApi(login = 'login', password = 'password') #vk_api.VkApi(token = 'a02d...e83fd') #   vk.auth() 

Sending messages


Now we will write a short function that sends the message to the selected person.


PS The community can send messages only to previously written users.


 def write_msg(user_id, s): vk.method('messages.send', {'user_id':user_id,'message':s}) 

In vk.method we can call any method from the VK API and pass parameters in the form of a dictionary.


In this case, we call the messages.send method and pass the user id and message text as parameters.


Receive messages


Fine! We learned how to send messages, it remains to learn how to receive them. For this we need the messages.get method.


Several parameters to pay attention to:


1) out - if this parameter is 1, the server will return outgoing messages.
2) count - the number of messages that must be received.
3) time_offset - the maximum time elapsed from the moment of sending the message to the current moment in seconds.
4) last_message_id - ID of the message received before the one that needs to be returned last (provided that no more than count messages were received after it)


 values = {'out': 0,'count': 100,'time_offset': 60} vk.method('messages.get', values) 

In our case, this method will return all received messages in the last 60 seconds, if there have of course been less than 100, and if more, then the last 100.


As a result, we get a list of items:


 {u'count': 3441, u'items': [{u'body': u'\u041f\u0438\u0448\u0435\u043c \u0431\u043e\u0442\u0430 \u0434\u043b\u044f \u0432\u043a!', u'date': 1491934484, u'id': 7387, u'out': 0, u'read_state': 0, u'title': u' ... ', u'user_id': 23107592}, {u'body': u'\u041f\u0440\u0438\u0432\u0435\u0442 \u0425\u0430\u0431\u0440!', u'date': 1491934479, u'id': 7386, u'out': 0, u'read_state': 0, u'title': u' ... ', u'user_id': 23107592}]} 

Explained in simple terms, items are what can be distinguished in the dialogue.


image


The final chord, we make an eternal cycle, where we will reply "Hello, Habr!" To each message.


 while True: response = vk.method('messages.get', values) if response['items']: values['last_message_id'] = response['items'][0]['id'] for item in response['items']: write_msg(item[u'user_id'],u', !') time.sleep(1) 

Chat bot ready.


PS We remember the last_message_id parameter to process only new messages next time.


Full code
 # -*- coding: utf-8 -*- import time import vk_api vk = vk_api.VkApi(login = 'login', password = 'password') #vk_api.VkApi(token = 'a02d...e83fd') #   vk.auth() values = {'out': 0,'count': 100,'time_offset': 60} def write_msg(user_id, s): vk.method('messages.send', {'user_id':user_id,'message':s}) while True: response = vk.method('messages.get', values) if response['items']: values['last_message_id'] = response['items'][0]['id'] for item in response['items']: write_msg(item[u'user_id'],u', !') time.sleep(1) 

It turned out 17 lines of code. Successes!


UPD 9/17/18:
Unfortunately, in the new version (5.80) VK API, the 'messages.get' method was removed and this article is no longer relevant. Now use the longpoll system to create bots. An example on the vk_api module for Python can be found here .


')

Source: https://habr.com/ru/post/326312/


All Articles