📜 ⬆️ ⬇️

Yandex.Alisa and bot Telegram for PHP with a single functionality

Good day.

There are a lot of articles on the subject of Telegram bots, but I don’t find much about the skills for Alice, but I didn’t find information on how to make a single bot, so I decided to share my experience on how to make a simple Telegram bot and the Yandex.Alis skill for the site having a single functionality.

So, I will not tell you how to raise the web server and get an ssl-certificate, it’s written enough.

Creating a Telegram bot


First, create a Telegram bot, go to Telegram for this and find a BotFather bot there.
')




Choose / newbot



Enter the name of the bot, according to which it will respond, then we enter the name of the bot, in response we get a token to control the bot, write this key, it will be useful to us in the future.



The next step is to inform the Telegram servers on which server to send data from the bot. To do this, make a link of the form:

https: //api.telegram.org/bot______/setWebhook?url=https://_________ 

___ TOKEN ___ are replaced with our bot token received earlier

____ PATH_DO_SCRPITA ___ is replaced with the address of the script on our server, where data processing will take place (for example, www.my_server.ru/webhook_telegram.php ).

There is a problem, the api.telegram.org server is under blocking, but you can do this: rent the cheapest server where there are no restrictions and issue a command from the console of this server

 wget _______ 

Everything, the Telegram-bot is created and connected with your server.

Creating skill for Yandex. Alice


Let's move on to creating a skill for Yandex. Alice.

To create a skill, go to the Yandex.Dialogs developers page, the Yandex.Dialogs developers page , click Create Dialogue there, and select Alice Skill.



The skill settings dialog opens.



We begin to enter the skill settings.

Enter the name of your skill.



The activation name should be selected very carefully, so that Alice understands it correctly, from the nuances - a mobile application with Alice and columns like Yandex. Station or Irbis A can perceive words differently.

We enter the path to the script on our server as well as for the Telegram, but this will be the script for Alice, for example, www.my_server.ru/webhook_alice.php .



Choosing a voice that will speak skill, I prefer the voice of Alice.



If you plan to work only on mobile devices or in a browser, then select "We need a device with a screen."

Next, enter the settings for Alice's skill catalog. If you plan to use the word - brand for activation, you need to go through the verification of the brand site in the webmaster.yandex.ru service.



With all the settings, go to the scripts.

Script Telegram-bot


Let's start with the script for Telegram.

We are connecting the library where the messages from the bot and Alice will be processed:

 include_once 'webhook_parse.php'; 

We set our bot's token:

 $tg_bot_token = "_____YOUR_BOT_TOKEN_____"; 

Get the data:

 $request = file_get_contents('php://input'); $request = json_decode($request, TRUE); 

Parse the data into variables:

 if (!$request) { die(); // Some Error output (request is not valid JSON) } else if (!isset($request['update_id']) || !isset($request['message'])) { die(); // Some Error output (request has not message) } else { $user_id = $request['message']['from']['id']; $msg_user_name = $request['message']['from']['first_name']; $msg_user_last_name = $request['message']['from']['last_name']; $msg_user_nick_name = $request['message']['from']['username']; $msg_chat_id = $request['message']['chat']['id']; $msg_text = $request['message']['text']; $msg_text = mb_strtolower($msg_text, 'UTF-8'); $tokens = explode(" ", $msg_text); } 

Now you can work with variables:

$ tokens - here now all the words that the user entered

$ user_id - here is the user id

$ msg_chat_id - chat, in which the bot received a command

$ msg_user_name - username

Next, call Parse_Tokens function for processing:

 $Out_Str = Parse_Tokens($tokens); 

And send the answer:

 Send_Out($user_id, $Out_Str); 

The Send_Out function is simple and looks like this:

 function Send_Out($user_id, $text, $is_end = true) { global $tg_bot_token; if (strlen($user_id) < 1 || strlen($text) < 1) {return;} $json = file_get_contents('https://api.telegram.org/bot' . $tg_bot_token . '/sendMessage?chat_id=' . $user_id . '&text=' . $text); } 

Skill script for Yandex. Alice


Now let's move on to the script for Alice, it is almost the same as for Telegram.

Also connect the library where the messages from the bot and Alice will be processed, plus the library with classes for Alice:

 include_once 'classes_alice.php'; include_once 'webhook_parse.php'; 

Get the data:

 $data = json_decode(trim(file_get_contents('php://input')), true); 

Parse the data into variables:

 if (isset($data['request'])) { //original_utterance if (isset($data['meta'])) { $data_meta = $data['meta']; if (isset($data_meta['client_id'])) {$client_id = $data_meta['client_id'];} } if (isset($data['request'])) { $data_req = $data['request']; if (isset($data_req['original_utterance'])) { $original_utterance = $data_req['original_utterance']; } if (isset($data_req['command'])) {$data_msg = $data_req['command'];} if (isset($data_req['nlu'])) { $data_nlu = $data_req['nlu']; if (isset($data_nlu['tokens'])) {$tokens = $data_nlu['tokens'];} // $data_token_count = count($data_tokens); } } if (isset($data['session'])) { $data_session = $data['session']; if (isset($data_session['new'])) {$data_msg_new = $data_session['new'];} if (isset($data_session['message_id'])) {$data_msg_id = $data_session['message_id'];} if (isset($data_session['session_id'])) {$data_msg_sess_id = $data_session['session_id'];} if (isset($data_session['skill_id'])) {$skill_id = $data_session['skill_id'];} if (isset($data_session['user_id'])) {$user_id = $data_session['user_id'];} } } 

There are a few less needed variables:

$ tokens - here now all the words that the user entered

$ user_id - here is the user id

Yandex constantly pings published skills, and I added a line to immediately exit the script, without starting the full processing of the message:

  if (strpos($tokens[0], "ping") > -1) {Send_Out("pong", "", true);} 

Call Parse_Tokens function for processing, it is the same as for Telegram:

 $Out_Str = Parse_Tokens($tokens); 

And send the answer:

 Send_Out($user_id, $Out_Str); 

The Send_Out function is more complicated here:

 function Send_Out($user_id, $out_text, $out_tts = "", $is_end = false) { global $data_msg_sess_id, $user_id; ///// GENERATE BASE OF OUT ////// $Data_Out = new Alice_Data_Out(); $Data_Out->response = new Alice_Response(); $Data_Out->session = new Alice_Session(); ///// GENERATE BASE OF OUT End ////// ///// OUT MSG GENERATE ///// $Data_Out->session->session_id = $data_msg_sess_id;; $Data_Out->session->user_id = $user_id; $Data_Out->response->text = $out_text; $Data_Out->response->tts = $out_tts; if (strlen($out_tts) < 1) {$Data_Out->response->tts = $out_text;} $Data_Out->response->end_session = $is_end; header('Content-Type: application/json'); print(json_encode($Data_Out, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT)); die(); } 

Finished the script for Alice.

The Parse_Tokens processing script itself was made purely for example; you can do any checks and processing there.

 function Parse_Tokens($tokens) { $out = ""; // do something with tokens // $out = "Your eneter " . count($tokens) . " words: " . implode($tokens, " "); return $out; } 

If you need to communicate with a user of a more complex type than a question-answer, you will need to save the user’s $ user_id and the data already received from the user in the database (for example, mysql) and analyze them in the Parse_Tokens function.

Actually, this is almost everything, if everything is done correctly, the Telegram-bot is already available, Alice's skill can be checked dialogs.yandex.ru/developer , by going to your new skill on the testing tab.



If everything works correctly, you can send the skill to moderation by clicking the "To moderation" button.

Now you have two bots for different platforms that work the same way.

Documentation on the service Yandex. Dialogues here

Full scripts are posted on github download .

Update: wrapped everything up in classes and updated the repository on github

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


All Articles