The translation was generated automatically and may contain mistakes

Quick start

Chatbot is a script on your server that receives notifications of new events from the VKontakte and processes them. For example, it detects a text command in a message from the user and sends an image in response.

To create a bot, you will need:

  • A community on whose behalf your bot will communicate with VKontakte users..
  • A server that will receive notifications about events.
  • The logic of the bot itself is a script that determines how the bot reacts to an event.

First of all, you need to think about the functionality of the chatbot. Make a list of possible text commands or events that the bot should respond to and the corresponding actions of the bot. It is worth remembering that people can make mistakes when typing commands, and send the bot text that is different from all the options you have taken into account — it is important to provide a default action (in this case, you can send the user a list of all supported commands).

If you have not previously worked with the VKontakte API, before starting work, we recommend that you read this management .

Examples of implementation

PHP

VK PHP Bot created by our PHP developer. Callback API is used to process events, voice messages are generated using API Yandex SpeechKit . GitHub project code .

Java

Youtrack bot created by our Java developers ( Java SDK ). The Callback API is used to handle events. GitHub project code .

JS

Node JS bot library, author Mikhail Semin . Long Poll is used, it is possible to quickly and conveniently add new commands and reactions. GitHub project code .

Community

To connect a chatbot, you can use any of your VKontakte community — a group, a meeting or a public page. Your bot must comply with the rules, you can find out more about them here.. .

First of all, you need to indicate that a bot will work in your community. To do this in the community, go to ManagementCommunicationsSettings for the bot and include the item The capabilities of bots .

A community is an entry point for users who will communicate with your bot. It is worth taking care that it looks attractive and contains a description of your bot, otherwise its actions may come as a surprise to users. Don’t forget to include messages in your community ( ManagementCommunications ), when the bot is ready to use so that it can be written.

So, if you have chosen a community, you can start setting up notifications.

Obtaining the access key

You will need the access key to receive updates (in Long Poll), as well as to work with the API.

  1. 1.

    Open the vk.com and go to the community where you are an administrator.

  2. 2.

    Select the menu on the right.. Management and then Working with API .

  3. 3.

    Press Creating a Key . Note the necessary access rights and confirm your choice.

You can create multiple keys with different access rights. Keys should not be posted publicly — after recognizing it, a third party can access the API VKontakte on behalf of your community. If the key has been compromised, it is necessary to remove it from the list - after that it will become invalid.

You can also get the access key using OAuth. Use an Authorization Scheme Authorization Code Flow .

Adding bots to conversations

In order for users to be able to add a bot to conversations, you need to enable this feature in the community settings. Go to ManagementCommunicationsSettings for the bot and check the box at the point Allow community to be added to conversations . There will be a button in the community.. Invitation to a conversation , which opens a modal window with a list of conversations.

The bot now has three levels of access in conversation:

Only mentions

This level of access is issued immediately after adding to the conversation. The bot can:

  • See all the messages that relate to it. These are mentions of the bot and responses to its messages
  • Sending Messages in Conversation

Access to all correspondence

Any administrator of the conversation can issue it. The bot can:

  • See all messages in conversation
  • Sending Messages in Conversation

Administrator

It can be issued only by the creator of the conversation or the administrator, if he has the rights “Who can appoint administrators?2?. The bot can:

  • See all messages in conversation
  • Sending Messages in Conversation
  • Receiving participants in the conversation

Important! To receive events from the conversation, the API version of the callback server must be at least 5.80.

Receiving Events and Updates

To react to any events, your script needs to know about them. There are two approaches to this — Callback API and Long Poll.

Callback API

The Callback API sends notifications to your server as soon as the right event occurs in the community. The event can be anything: a comment on a photo, a new entry on the wall, joining a community, sending a message, and much more. See the full list of available events, as well as read more about the setup you can in the Callback API documentation .

To connect the Callback API in the community, you need to specify the script address on your server and select the events you want to receive. For example, if your bot needs to recognize text commands, mark the event Incoming message .

Notifications from the Callback API look like JSON with basic event information:

JSON
{ "type":"message_new", "object":{ "id":694, "date":1499441696, "out":0, "user_id":123456, "read_state":0, "title":" ... ", "body":"start" }, "group_id":1, "secret":"sjr948dff3kjnfd3" }

In this example, the user c id = 123456 Send a message to the community start .

For each event, the Callback API sends a separate request to your server. Your script should confirm receipt of each request by sending a string in response ok .

Example in PHP

PHP
<? define('CALLBACK_API_CONFIRMATION_TOKEN', '213fefef3'); // Строка, которую должен вернуть сервер define('VK_API_ACCESS_TOKEN', '016cb552 ... 989fb8345'); // Ключ доступа сообщества define('CALLBACK_API_EVENT_CONFIRMATION', 'confirmation'); // Тип события о подтверждении сервера define('CALLBACK_API_EVENT_MESSAGE_NEW', 'message_new'); // Тип события о новом сообщении define('VK_API_ENDPOINT', '[https://api.vk.ru/method/]'); // Адрес обращения к API define('VK_API_VERSION', '5.131'); // Используемая версия API $event = json_decode(file_get_contents('php://input'), true); switch ($event['type']) { // Подтверждение сервера case CALLBACK_API_EVENT_CONFIRMATION: echo(CALLBACK_API_CONFIRMATION_TOKEN); break; // Получение нового сообщения case CALLBACK_API_EVENT_MESSAGE_NEW: $message = $event['object']; $peer_id = $message['peer_id'] ?: $message['user_id']; send_message($peer_id, "Hello world! (peer_id: {$peer_id})"); echo('ok'); break; default: echo('Unsupported event'); break; } function send_message($peer_id, $message) { api('messages.send', array( 'peer_id' => $peer_id, 'message' => $message, )); } function api($method, $params) { $params['v'] = VK_API_VERSION; $query = http_build_query($params); $url = VK_API_ENDPOINT . $method . '?' . $query; $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . VK_API_ACCESS_TOKEN, ]); $json = curl_exec($curl); $error = curl_error($curl); if ($error) { error_log($error); throw new Exception("Failed {$method} request"); } curl_close($curl); $response = json_decode($json, true); if (!$response || !isset($response['response'])) { error_log($json); throw new Exception("Invalid response for {$method} request"); } return $response['response']; }

Full script on GitHub

Bots Long Poll API

The second way to get updates is to connect to the Bots Long Poll API. You can read more about the Bots Long Poll API on this page .

When a new event occurs or the wait time expires, the server will return a JSON response to you:

JSON
{ "ts": "4", "updates": [ { "type": "wall_post_new", "object": { "id": 28, "from_id": -123456, "owner_id": -123456, "date": 1519631591, "marked_as_ads": 0, "post_type": "post", "text": "Post text", "can_edit": 1, "created_by": 564321, "can_delete": 1, "comments": { "count": 0 } }, "group_id": 123456 } ] }

Information about the functions available to the user

Some bot features may not be available because users:

  • transition to new versions of official applications VKontakte gradually;
  • open VKontakte on different platforms (iOS, Android, mobile and web versions);
  • Use applications from third-party developers. For example, the bot keyboard may not be available in the older version of the official VKontakte app..

Send messages in the desired format, based on the capabilities that are available to the user. If he can’t use the keyboard, offer options and number them — so that you can answer with a number. Conversely, if a user can interact with a bot using a keyboard, there is no need to send him response options in the text of the message.

Starting with API version 5.103, information about available features will come along with the event message_new The Callback API and the Bots Long Poll API. It will be in the facility.. client_info :

JSON
"client_info": { "button_actions": [ "text", "vkpay", "open_app", "location", "open_link", "callback" ], "keyboard": true, "inline_keyboard": true, "carousel": false, "lang_id": 0 }

As new features appear in the object client_info and array button_actions New entities may appear.

Object fields:

  • button_actions An array of buttons that the client supports. See the possible values in the section Keyboard ;
  • keyboard ( bool • Whether the bot keyboard is supported by the client;
  • inline_keyboard ( bool ) — whether the inline keyboard of bots is supported by the client;
  • carousel ( bool ) is supported carousels the client;
  • lang_idID the language used.