📜 ⬆️ ⬇️

How to write a chat bot in PHP for the VKontakte community

Currently, most large VKontakte communities already have bots, the relevance of this topic is conditioned by the huge demand for the application’s 24-hour operation, notification when joining and leaving the community, sending informational messages, it’s the VK bot that can solve these problems. In this article, we will look at solving basic problems that often arise in any large community.

Configuring the Callback API for the VK community bot


Preparing the server part for connection


Callback API is a tool for tracking user activity in your VKontakte community. With it, you can implement new useful features, for example:

  • A bot to send instant replies to incoming messages.
  • Automatic content moderation system.
  • Service for collecting and processing indicators of audience involvement.

To start using the Callback API , connect your server in the community settings and select the types of events you want to receive information about (for example, new comments and new photos). When the event of the selected type occurs in the community, VK will send a request in JSON format to your server with basic information about the object that triggered the event (for example, an added comment). You no longer need to make regular requests to the API to track updates - now you will receive them instantly.

Connection instructions are described in detail in the excellent documentation for VK developers.
')
Let us examine it in more detail; to host the chat bot script, we must have a functioning web server.

To work with the callback API, VKontakte recommends using the https protocol, instructions for free obtaining a cloudflare certificate and server settings can be found in the article that can be found in the Google search engine upon request Free SSL certificate CloudFlare .

After setting up the server, you should have a working web-server on which we upload the script of our bot.

Setting up the VKontakte community


Access key generation


An important point in the work of the community bot is to respond to user messages and various events, so that we can interact with the user on behalf of the community, we need to create a special key. To do this, go to the tab " Community Management ".



Next, go down to the section " Working with API " → " Access keys ".



To create a key, you must click " Create a key " and select the necessary rights that we will give our bot.



In our case, we have enough access to community messages.



Save this key, we need it when setting up the backend.

Setting up callback API


Now we have to connect our server and community, for this we need to specify the data of our server and create a secret key. To do this, we need to go to the community management section and go down to the " Working with API" tab .



Next comes a very important point, we need to enter the address of our server and come up with a secret key, any string acts as a key, and the address to the php script on the server, as the address, respectively.



Enter the secret key and click "Save", after we need to receive a notification about the successful installation of the key. The "Confirm" button in front of the server address field is not pressed.
The secret key you specified will be transmitted with each notification from the server in a separate secret field. This will allow you to reliably determine that the notification came precisely from our server.



We also need to remember the code that the server should return, write it down, we will need it when setting up the backend.



Setting Event Types


An important point in the work of the community bot is the responses to user messages and various events, so that we can interact with the user on behalf of the community, we need to specify which events we want to receive. Since we are going to track incoming messages, entry to the community and exit from it, we need to set the appropriate checkboxes. To do this, go to the tab " Community Management ".


Next, go down to the section " Working with API " → " Types of events ".



Set the necessary items in this section.

Setting backend bot VKontakte


The next step is to create a special script that will receive requests from the VK callback API and react to events in a certain way. Let's create, for example, the handler.php php script, the address to this script, after setting up the backend, we need to specify in the community settings.

Note the values ​​of the following variables:

  $ confirmationToken $ token $ secretKey 

The confirmationToken stores the code that the server must return, in our case:

  004eec27 

token stores the access key that we generated in the chapter “Generating an Access Key”

secretKey we asked in the community management section of the callback API. The final code looks like this (handler.php):

The final code is handler.php
<?php if (!isset($_REQUEST)) { return; } //       Callback API $confirmationToken = '004eec27'; //   $token = ' '; // Secret key $secretKey = 'testSecureKey'; //    $data = json_decode(file_get_contents('php://input')); //  secretKey if(strcmp($data->secret, $secretKey) !== 0 && strcmp($data->type, 'confirmation') !== 0) return; //,     "type" switch ($data->type) { //      ... case 'confirmation': //...     echo $confirmationToken; break; //     ... case 'message_new': //... id   $userId = $data->object->user_id; //   users.get     $userInfo = json_decode(file_get_contents("https://api.vk.com/method/users.get?user_ids={$userId}&v=5.0")); //      $user_name = $userInfo->response[0]->first_name; //  messages.send       $request_params = array( 'message' => "{$user_name},   !<br>". "     .", 'user_id' => $userId, 'access_token' => $token, 'v' => '5.0' ); $get_params = http_build_query($request_params); file_get_contents('https://api.vk.com/method/messages.send?' . $get_params); // "ok"  Callback API echo('ok'); break; //        case 'group_join': //... id   $userId = $data->object->user_id; //   users.get     $userInfo = json_decode(file_get_contents("https://api.vk.com/method/users.get?user_ids={$userId}&v=5.0")); //      $user_name = $userInfo->response[0]->first_name; //  messages.send       $request_params = array( 'message' => "      .  5 2016, {$user_name}!<br>" . "    ,        .<br>" . "       .<br>" . "  !", 'user_id' => $userId, 'access_token' => $token, 'v' => '5.0' ); $get_params = http_build_query($request_params); file_get_contents('https://api.vk.com/method/messages.send?' . $get_params); // "ok"  Callback API echo('ok'); break; } ?> 


After you upload the code, you should return to the section “Community Management” → “Working with API” → “Callback API”, enter the address to the script and click “Confirm”



After that, the configuration of the community to work with the bot is complete, now, if we send a message to the community, we will receive a response.



Additional features


Greetings when joining the VKontakte community


At this stage, we already have a configured server and bot handler, all possible events are listed in the documentation , it is well written, I recommend reading it.



We will catch the group_join event, for this we will create a new section in the switch statement. We will not consider join_type in detail, since we have an open group, but you can handle this parameter at your discretion.

Community entry alert code snippet
  //        case 'group_join': //... id   $userId = $data->object->user_id; //   users.get     $userInfo = json_decode(file_get_contents("https://api.vk.com/method/users.get?user_ids={$userId}&v=5.0")); //      $user_name = $userInfo->response[0]->first_name; //  messages.send       $request_params = array( 'message' => "      .  5 2016, {$user_name}!<br>" . "    ,        .<br>" . "       .<br>" . "  !", 'user_id' => $userId, 'access_token' => $token, 'v' => '5.0' ); $get_params = http_build_query($request_params); file_get_contents('https://api.vk.com/method/messages.send?' . $get_params); // "ok"  Callback API echo('ok'); break; 




The full code of the VK bot handler with the welcome message function:

Source code handler.php. Welcome message
 <?php if (!isset($_REQUEST)) { return; } //       Callback API $confirmationToken = '004eec27'; //   $token = ' '; // Secret key $secretKey = 'testSecureKey'; //    $data = json_decode(file_get_contents('php://input')); //  secretKey if(strcmp($data->secret, $secretKey) !== 0 && strcmp($data->type, 'confirmation') !== 0) return; //,     "type" switch ($data->type) { //      ... case 'confirmation': //...     echo $confirmationToken; break; //     ... case 'message_new': //... id   $userId = $data->object->user_id; //   users.get     $userInfo = json_decode(file_get_contents("https://api.vk.com/method/users.get?user_ids={$userId}&v=5.0")); //      $user_name = $userInfo->response[0]->first_name; //  messages.send       $request_params = array( 'message' => "{$user_name},   !<br>". "     .", 'user_id' => $userId, 'access_token' => $token, 'v' => '5.0' ); $get_params = http_build_query($request_params); file_get_contents('https://api.vk.com/method/messages.send?' . $get_params); // "ok"  Callback API echo('ok'); break; //        case 'group_join': //... id   $userId = $data->object->user_id; //   users.get     $userInfo = json_decode(file_get_contents("https://api.vk.com/method/users.get?user_ids={$userId}&v=5.0")); //      $user_name = $userInfo->response[0]->first_name; //  messages.send       $request_params = array( 'message' => "      .  5 2016, {$user_name}!<br>" . "    ,        .<br>" . "       .<br>" . "  !", 'user_id' => $userId, 'access_token' => $token, 'v' => '5.0' ); $get_params = http_build_query($request_params); file_get_contents('https://api.vk.com/method/messages.send?' . $get_params); // "ok"  Callback API echo('ok'); break; } ?> 

Implementing a farewell to a member after he left the community


The implementation is identical, in the specific case we process group_leave
Community exit code snippet
  //        case 'group_leave': //... id   $userId = $data->object->user_id; //   users.get     $userInfo = json_decode(file_get_contents("https://api.vk.com/method/users.get?user_ids={$userId}&v=5.0")); //      $user_name = $userInfo->response[0]->first_name; //  messages.send       $request_params = array( 'message' => "{$user_name},       😔<br>" . "        .<br>" . "   -    <br>" . " - https://vk.com/kulakovkostya", 'user_id' => $userId, 'access_token' => $token, 'v' => '5.0' ); $get_params = http_build_query($request_params); file_get_contents('https://api.vk.com/method/messages.send?' . $get_params); // "ok"  Callback API echo('ok'); break; 


Full code listing:

The final code handler.php with extended functionality
 <?php if (!isset($_REQUEST)) { return; } //       Callback API $confirmationToken = '004eec27'; //   $token = ' '; // Secret key $secretKey = 'testSecureKey'; //    $data = json_decode(file_get_contents('php://input')); //  secretKey if(strcmp($data->secret, $secretKey) !== 0 && strcmp($data->type, 'confirmation') !== 0) return; //,     "type" switch ($data->type) { //      ... case 'confirmation': //...     echo $confirmationToken; break; //     ... case 'message_new': //... id   $userId = $data->object->user_id; //   users.get     $userInfo = json_decode(file_get_contents("https://api.vk.com/method/users.get?user_ids={$userId}&v=5.0")); //      $user_name = $userInfo->response[0]->first_name; //  messages.send       $request_params = array( 'message' => "{$user_name},   !<br>". "     .", 'user_id' => $userId, 'access_token' => $token, 'v' => '5.0' ); $get_params = http_build_query($request_params); file_get_contents('https://api.vk.com/method/messages.send?' . $get_params); // "ok"  Callback API echo('ok'); break; //        case 'group_join': //... id   $userId = $data->object->user_id; //   users.get     $userInfo = json_decode(file_get_contents("https://api.vk.com/method/users.get?user_ids={$userId}&v=5.0")); //      $user_name = $userInfo->response[0]->first_name; //  messages.send       $request_params = array( 'message' => "      .  5 2016, {$user_name}!<br>" . "    ,        .<br>" . "       .<br>" . "  !", 'user_id' => $userId, 'access_token' => $token, 'v' => '5.0' ); $get_params = http_build_query($request_params); file_get_contents('https://api.vk.com/method/messages.send?' . $get_params); // "ok"  Callback API echo('ok'); break; //        case 'group_leave': //... id   $userId = $data->object->user_id; //   users.get     $userInfo = json_decode(file_get_contents("https://api.vk.com/method/users.get?user_ids={$userId}&v=5.0")); //      $user_name = $userInfo->response[0]->first_name; //  messages.send       $request_params = array( 'message' => "{$user_name},       😔<br>" . "        .<br>" . "   -    <br>" . " - https://vk.com/kulakovkostya", 'user_id' => $userId, 'access_token' => $token, 'v' => '5.0' ); $get_params = http_build_query($request_params); file_get_contents('https://api.vk.com/method/messages.send?' . $get_params); // "ok"  Callback API echo('ok'); break; } ?> 


GitHub source code: github.com/KostyaKulakov/vksocialbot

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


All Articles