How to write a chatbot for vk.com in 3 minutes

Unfortunately, at the moment there are no good libraries in 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.


This article is written for beginners to show that there is nothing complicated in writing bots in Python.


Login


We will need the vk_api library . There are two ways to
log in to VK: - As a 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 need to enable "Community Messages" and create an API access key:


image


image


Two-line authorization:


import time
import vk_api
vk = vk_api.VkApi(login = 'login', password = 'password')
#vk_api.VkApi(token = 'a02d...e83fd') #Авторизоваться как сообщество
vk.auth()

Sending messages


Now write a short function that sends a 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 in the user id and message text as parameters.


Receive messages


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


Some parameters to pay attention to:


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


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 were certainly 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}]}

To explain in simple words, then items are what can be highlighted in the dialog.


image


The final chord, we do an eternal cycle where we will answer "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)

Chatbot is ready.


PS We remember the parameter last_message_id, so that next time only new messages will be processed.


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. Good luck!


UPD 09/17/18:
Unfortunately, the 'messages.get' method has been removed in the new version (5.80) of the VK API and this article has lost its relevance. Now to create bots use the longpoll system. You can find an example on the vk_api module for Python here .


Also popular now: