Developers » API for Chatbots
API for Chatbots
Implementation examples
1. Communities
    1.1. Acquiring The Access Token
    1.2. Adding bots to chats
2. Receiving Events And Updates
    2.1. Callback API
    2.2. Bots Long Poll API
    2.3. Information about features available to the user
3. Bot Messages
    3.1. Sending Messages
    3.2. Attachments
4. Bot keyboards
    4.1. Setup
    4.2. Data structure
    4.3. Sending the keyboard
    4.4. Error handling
5. Bot monetization
    5.1. Advertising API
    5.2. Intents

A chatbot is a script on your server that receives notifications about new VK events and processes them. For example, it determines a text command in a message from a user and sends some image in response.

To create bots, you need:
  • a community from which the bot can communicate with VK users.
  • a server that will receive event notifications.
  • the bot’s logic. In other words, the script that establishes how a bot responds to an event.

First, the chatbot’s functionality needs to be determined. Then create a list of possible text commands or events to which the bot should react to and appropriate actions the bot may take. Be aware that people may make mistakes while writing commands and send the bot text that differs from options you considered. It is impossible to foresee this action each time. In this case, you can send the user a list of all supported commands.

If you have not worked with the VK API, we recommend you read this manual before beginning work.
Implementation examples

PHP
The VK PHP bot was created by our developers in PHP. Callback API is used for processing events, and voice messages are generated with the API Yandex Speechkit. The project code is on GitHub:
Java
A bot for working with Youtrack, it was created by our developers in Java (Java SDK). Callback API is used for processing events, and the project code is on GitHub:
JS
A library developed by Mikhail Semin for working with codes on Node JS. Long Poll is used to quickly and comfortably add new commands and responses. The project code is on GitHub:
If you want to add your project to this list, message us at [email protected].
1. Communities

You can connect a chatbot to any VK community, whether it is a group, event or public page. Your bot must comply with the rules, about which you can learn more here.

Communities are entrances for users who want to communicate with your bot. Make sure that the community looks appealing and contains a description of your bot, or else its actions may surprise users. Don’t forget to enable messages in your community (“Manage community” -> “Messages”) when the bot is ready for use so that users can send messages to your community.

So, if you have chosen a community, you may begin configuring notification settings.

1.1. Acquiring The Access Token

The access token is necessary for receiving updates (in Long Poll) as well as working with the API.

Open the section “Manage ñommunity” (“Manage ñage” if you have a public page), choose the tab “API Usage” and click on “Create token”.

Select the required access rights and confirm your choice.


You can create several tokens with different access rights. Tokens cannot be displayed publically as a third party may access the VK API on behalf of your community using your access token. If the token has been compromised, delete it from the list in order to invalidate it.

Additionally, you can acquire the access token using OAuth. Use the Authorization Code Flow scheme.

1.2. Adding bots to chats
For users to be able to add a bot to their chats, this feature needs to be enabled in Settings. Go to Manage -> Messages -> Bot settings and enable the “Ability to add this community to chats” option. The Add to chat button that opens a chat list in a modal window will appear on the community page.

Currently, the bot has 3 levels of access in the chat:

Notifications only
This access level is granted immediately after adding the bot to the chat. The bot can do the following:
  • See all the messages that relate to it, such as mentions of it and responses to its messages
  • Send messages to the chat

Access to the full chat
This access level can be granted by a chat administrator. The bot can do the following:
  • See all the messages in the chats
  • Send messages to the chat

Administrator
This access level can only be granted by the chat creator. The bot can do the following:
  • See all the messages in the chats
  • Send messages to the chat
  • Get the chat object
  • Get the chat participants


Note that to get the chat events, the API version of the callback server must be 5.80 or higher.
2. Receiving Events And Updates

To respond to certain events, your script must know them. For this to happen, two possible solutions exist, Callback API and Long Poll.

2.1. Callback API
Callback API sends notifications to your server as soon as some compulsory event happens in a community. The event can be anything from photo comments, new wall posts, community subscriptions, sending messages and many more. The full list of available events, as well as learning more about settings, can be found in the Callback API documentation.

To enable Callback API in a community, indicate the script address in your server and select the events you wish to receive. For example, if your bot should recognize text commands, select the event “Incoming messages”.

A Callback API notification looks like JSON with the basic event information:
{
   "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, a user with ID 123456 sent the message “start” to a community.

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

PHP example
define('ÑALLBACK_API_EVENT_CONFIRMATION', 'confirmation');
define('ÑALLBACK_API_EVENT_MESSAGE_NEW', 'message_new');
define('CALLBACK_API_CONFIRMATION_TOKEN', '213fefef3');

$event = json_decode(file_get_contents('php://input'), true)

switch ($event['type']) {
      //Ïîäòâåðæäåíèå ñåðâåðà
      case ÑALLBACK_API_EVENT_CONFIRMATION:
        echo(CALLBACK_API_CONFIRMATION_TOKEN);
        break;
      //Ïîëó÷åíèå íîâîãî ñîîáùåíèÿ
      case ÑALLBACK_API_EVENT_MESSAGE_NEW:
        echo('ok');
        break;
      default:
        echo('Unsupported event');
        break;
    }

Full script on GitHub

2.2. Bots Long Poll API
The second way to get updates is to connect to the Bots Long Poll API. You can learn more about how to use Bots Long Poll API here.

When a new event occurs or the timeout expires, the server will return a JSON response:

[
   4,
   2105994,
   561,
   123456,
   1496404246,
   "hello",
   {
      "attach1_type":"photo",
      "attach1":"123456_417336473",
      "attach2_type":"audio",
      "attach2":"123456_456239018",
      "title":" ... "
   }
]


In this example, a user with ID 123456 sent the message “hello” with an audio and a photo attachments.

Long Poll sent several events in response to your request. To receive all updates immediately, remain constantly connected to Long Poll.

2.3. Information about features available to the user
Some bot features might be unavailable due to the user:
  • upgrading to the new official VK app versions gradually.
  • opening VK on different platforms (iOS, Android, mobile and desktop versions);
  • using third-party applications. For example, the bot keyboard might not be available on an old version of the official VK app.

The user’s ability to send messages in the desired format depends on the features available to them. If the user cannot use the keyboard, offer a list of numbered answers so the user can select one with a number. Or vice versa: If the user can interact with the bot via the keyboard, there is no need to send a list of numbered answers in a message.

Starting with API version 5.103, the information about the available features will be sent with the message_new event in the Callback API and the Bots Long Poll API. It will be available in the client_info object:
"client_info": {
    "button_actions": [
     "text",
     "vkpay",
     "open_app",
     "location"
    ],
    "keyboard": true,
    "inline_keyboard": true,
    "lang_id": 0
}


As new features get implemented, new properties will be added to the client_info object and the button_actions array.

Object properties:
  • buttons_actions: an array of buttons that the client supports. You can see the available values in Bots keyboards -> Data structure
  • keyboard (bool): bot keyboard support
  • inline_keyboard (bool): bot inline-keyboard support
  • lang_id: id of the language used

Continue