The first PHP bot for VKontakte

Hello, Khabrovites. In this publication, I will write about how to make my first chat bot for VKontakte. I think that this will not be interesting for experienced programmers, but those who are just starting their journey will be interested, since I myself have not gone very far and understand the problems of beginners. And I warn you right away that most of the screenshots will be in English.



First we need to create a community. I think everyone can handle it.



Then we go into the community settings and select the “API usage” item and click on the “Create token” button.



image



Next, you need to choose, in fact, what we can use with the help of this token. We need access to community messages, but we can choose all access rights so that we don’t have to remember about creating tokens in the future.



image



And so we got the coveted token. By the way, it needs to be kept in a safe place and not shown to anyone. Now you can proceed to the code.



image



We will write code in PHP, so you can download Visual Studio code or PHPStorm. In principle, the code can be written in notepad, only it will not be convenient. After the code, we will move on to further setting up the group.



So, for starters, we need to get information about the incoming message and translate it from the JSON format into an understandable one for PHP.



<?php $data = json_decode(file_get_contents('php://input')); ?>
      
      





In the data variable we now have an array with a message, user ID and chat ID.

“What kind of“ json_decode (file_get_contents ('php: // input')) ”, you ask.



Let's start from this moment:



 file_get_contents('php://input')
      
      





In simple terms, we ask the script what came to our input, that is, what request the VK sent. Below is an example of such a request.



 {"type":"message_new","object":{"date":1568464037,"from_id":450829055,"id":5400,"out":0,"peer_id":450829055,"text":" .","conversation_message_id":1478,"fwd_messages":[],"important":false,"random_id":0,"attachments":[],"is_hidden":false},"group_id":171524656}
      
      





I think it’s easy to understand what is written in the request, if you have minimal knowledge in English.



Well, "json_decode ()" is a function that translates the above JSON into an array that PHP can work with.



Now we’ll write a code that looks at what event happened, and if a new message arrives to us, it compares the message with those to which we have a response and looks at the chat ID.



 <?php $data = json_decode(file_get_contents('php://input')); switch ($data->type) { case 'confirmation': echo $confirmation_token; break; case 'message_new': $message_text = $data -> object -> text; $message_text = $data -> object -> peer_id; if ($message_text == ""){ // -  } if ($message_text == ""){ // -  } echo 'ok'; break; } ?>
      
      





Now we need to somehow respond to these messages. To do this, we write a simple function.



 <?php function vk_msg_send($peer_id,$text){ $request_params = array( 'message' => $text, 'peer_id' => $peer_id, 'access_token' => "TOKEN", 'v' => '5.87' ); $get_params = http_build_query($request_params); file_get_contents('https://api.vk.com/method/messages.send?'. $get_params); } ?>
      
      





What is going on here? Here we build a request to VK API (I recommend reading the documentation) with the message text, chat ID and token that we created earlier, and send it to the VK server.



Now connect these pieces of code and write the bot’s reactions to a particular message.



 <?php $confirmation_token = 'CONF_TOKEN' function vk_msg_send($peer_id,$text){ $request_params = array( 'message' => $text, 'peer_id' => $peer_id, 'access_token' => "TOKEN", 'v' => '5.87' ); $get_params = http_build_query($request_params); file_get_contents('https://api.vk.com/method/messages.send?'. $get_params); } $data = json_decode(file_get_contents('php://input')); switch ($data->type) { case 'confirmation': echo $confirmation_token; break; case 'message_new': $message_text = $data -> object -> text; $chat_id = $data -> object -> peer_id; if ($message_text == ""){ vk_msg_send($chat_id, ",  ,    ."); } if ($message_text == ""){ vk_msg_send($chat_id, ".    - ,     ,    ."); } echo 'ok'; break; } ?>
      
      





“Well, why do we have to write 'ok' after sending the message?”



Since we will use the update method called Call Back API, that is, VK will talk about new messages to us, we need to say that we heard it, otherwise it will be repeated to us several times.



Now let's move on to setting up the group.



We go into the settings and select the API version 5.87 (you can, of course, have newer versions, but it is better to have a unity of API versions).



image



From the same section, we take the line that the server should return, and substitute it into the confirmation_token variable.



After that, fill in the server address. To do this, you need to have a domain and hosting. The address you specify should be just a file with a bot. I hope the reader can handle this himself.



Then we select what events in the community will be reported to us by VKontakte. We only need incoming messages.



image



Next, confirm the server address, and our first bot is ready to use.



image



Since this is my first publication on Habré, I want to get comments on the article and only improve further.



Thanks for reading.



All Articles