One two Three! Chat bot from Google Tables on the example of PvP-game for Alice


    Appearing, Alice enticed users with unexpectedly high-quality speech synthesis and chat bot. Today, they are expected to use useful skills and interesting games with a backend that can take into account the user's context and implement a wide range of scenarios. This article discusses creating a skill based on Google Spreadsheets, familiar to many tools with great potential for small chat bots.

    Playing with a real person can be more interesting than with a virtual character, so as an example we will develop a multiplayer game for Alice.

    Time! Dialogue


    The game begins with the rules. I came up with these: each of the two players first places a treasure and a trap behind the three doors, and then opens any of the opponent’s doors. Open the treasure - get the opponent's coins, open the trap - give the coins to him. The number of coins, from 1 to 3, is determined by the player himself. For the remaining door is a Pandora's box, opening which you can find / lose a random amount of coins. You can play both with Alice and against other users.

    Alice's interface is solved in the form of a dialogue, and all game interaction should be implemented through messaging. Processing each message by the game server is represented by the following steps:

    1. restore user context;
    2. interpreting the request in the restored context;
    3. formation of the response message;
    4. saving changed user context.

    Restore and save user context


    The user's context includes his state in the game, including previous results, a step inside the script and the current opponent, as well as the user name and other information necessary for the game logic.

    In each request, according to the protocol , Alice sends the user ID. This is enough to save and then restore its context.

    Let's take Google Spreadsheets as data storage. The objective advantages of this solution include free use, clarity and ease of use. The built-in script editor allows you to describe the logic of the game on Apps Script (based on JavaScript), referring to the tables API, and publish it as a web application.

    Having created a table with the necessary headings, you can go to the script editor:


    The logic of the game can be described in the Apps Script project, organized in the form of a set of gs-files, and proceed to the publication:


    When publishing, you need to specify the availability of the application to anonymous users:


    At the output, you will receive the URL of the published web application. The doGet () and doPost () functions in the script will process requests of the appropriate types in order to receive and save user contexts.

    Below is a diagram of working with table API for operating data:

    //получение листаvar sheet = SpreadsheetApp.openById("<id таблицы>").getSheetByName("<название вкладки>");
       //получение диапазонаvar range = sheet.getRange(<нужные ячейки>);
       //извлечение данных диапазона
        var values = range.getValues();
       //сохранение данных в диапазон
        range.setValues(<нужные данные>);
    

    Interpreting the query in the restored context


    In general, correct interpretation of text queries requires the use of intelligent NLU algorithms. And although such algorithms are available in simple tools like Aimylogic described by me , in this case I decided to abandon the processing of natural language in favor of simplicity.

    In the proposed game, the player’s interaction with Alice is limited to a dozen possible states and can be reduced to a small set of intentions. For simplicity, I always offer the player three possible actions: send “One”, “Two” or “Three”. For any other request, Alice asks for clarification of the action.

    The script in this case comes down to the following code on Apps Script:

    //для каждого состояния в игреswitch(user.state){
        case"start":
          //прописываем реакцию на каждое из возможных действийswitch(utterance){
            case1️⃣ Раз”:
            case2️⃣ Два”:
            case3️⃣ Три”:
              //формируем ответ на ожидаемые действияdefault:
              //формируем ответ на неожиданное действие
          }
          break;
       //здесь все другие состоянияdefault:
         //формируем ответ на случай непредвиденного состояния
    }
    

    For the user, the interaction thus solved is presented as a choice of one of three options, the meaning of which is clearly defined in each answer of Alice. The variants themselves are represented by the “One”, “Two”, “Three” buttons, which significantly speed up the gameplay.

    Formation of the response message


    Alice’s answer consists of several parts, each of which needs to be formed, including:

    • text to display on the screen;
    • text for speech synthesis;
    • a set of buttons, tips.

    Recently, I formulated the concept of the EASY dialogue , which describes the principles of designing a conversational interface, including for Alice. Alice's answer format allows you to implement these principles.

    So the separation of the displayed and spoken text allows you to make the answers more concise and natural. You can not force Alice to synthesize a long text with which the user is already familiar, and also use emoji in the text of the message and the name of the buttons.

    Buttons-tips implement the initiative principle: Alice always designates and suggests possible actions to continue the dialogue. In the proposed game scenario, the list of buttons does not depend on the context and is added to each message.

    So, we have a Google Table with user data, which is saved and obtained through the URL of the web application. The application is written in Apps Script, it interprets the user's action in accordance with its context and generates data for the response message.

    It remains to connect to Alice ...

    Two! Integration


    Yandex.Dialogs allow developers to add their skills to Alice. Connecting a skill comes down to three main things:

    • activation;
    • registration;
    • web hook.

    Activation and design


    To activate it, it is important to choose a phrase that Alice recognizes is consistent with the formal requirements of Yandex. If there are numbers in the activation name, separately check the activation when entering from the keyboard and voice.

    The design of the skill includes the name, description, icon, category, etc.
    It should be noted that in the list of skills in the catalog only the icon and the activation phrase are displayed, and the search in the catalog is carried out mainly by description.

    Getting a web hook


    A web hook is the address where Alice will send messages to your skill and wait for the JSON response in the described format.



    A web application created on Apps Script returns a response by default in the form of an html page, but with the help of the ContentService you can also force it to return JSON:

    return ContentService.createTextOutput(JSON.stringify(<JSON ответа>))
      .setMimeType(ContentService.MimeType.JSON);

    However, Google, when using the ContentService, redirects the user's request to a temporary URL, for which Yandex.Dialogies are not ready. Therefore, the address of the web application as a web hook is not suitable.

    There are free services that offer a suitable web hook for Alice, such as Zenbot . In Zenbot for the proposed game, you can write a short script that accesses the google web application and returns the answer with the buttons. By the way, in this way the game can be integrated not only with Alice, but also with other channels.

    Below is an example of a script that provides the “One, Two, Three!” Game in the Telegram-bot @RazDvaTriBot:

    <context><inputpattern="$Text"><varname="Utterance"value="$Text"scope="input"/><geturl="https://script.google.com/macros/s/<id веб-приложения>/exec"var="Result"><paramname="userId"value="$req_telegram_chat"/><paramname="utterance"value="$Utterance"/><paramname="channel"value="telegram"/></get><varname="Answer"value='javascript: $Result.text'/><outputvalue="$Answer"/><sample><itemvalue="Раз"/><itemvalue="Два"/><itemvalue="Три"/></sample></input></context>

    For more flexibility in processing requests, you can write your server using, for example, Google App Engine. This tool can also be used for free.

    After creating a project in Google App Engine, the Cloud Shell interface allows you to write server code on one web page and deploy it to the desired URL of the form https: // <project id> .appspot.com, which will be the address of the web hook.

    Server operation consists of the following steps:

    1. retrieving request data from Alice;
    2. interaction with the game web application;
    3. send response in Alice format.

    Alice Receive / Send Data


    It is important for Alice to get session identifiers, user IDs, messages, and the request text. Below is an example in PHP:

    	$data = json_decode(file_get_contents("php://input"));
    	$session_id = $data->session->session_id;
    	$user_id = $data->session->user_id;
    	$utterance = $data->request->original_utterance;
    	$messageId = $data->session->message_id;
    

    As an answer, hint buttons and texts for display and pronunciation are returned to the game:

    	$button1 = array('title' => '1️⃣ Раз', 'hide' => true);
    	$button2 = array('title' => '2️⃣ Два', 'hide' => true);
    	$button3 = array('title' => '3️⃣ Три', 'hide' => true);
    	$yaButtons = array($button1, $button2, $button3);
    	$yaResponse = array('text' => $text, 'tts' => $tts, 'buttons' => $yaButtons, 'end_session' => false);
    	$yaSession = array('session_id' => $session_id, 'message_id' => $messageId, 'user_id' => $user_id);
    	$yaResult = array('response' => $yaResponse, 'session' => $yaSession, 'version' => '1.0');
    	echo json_encode($yaResult);
    

    Three! Synchronization


    Sending / receiving data from a web application takes time, and Alice is impatient to answer the user, so synchronization issues interfere.

    Naturally, for large projects, the tables of Alice’s Google skill in Google are not suitable: the response time increases with a large number of parallel queries. Nevertheless, there are recommendations to optimize the chat bot, which allow you to make a small project viable in a real-time interactive system.

    Alice's synchronous protocol timeout - 1.5 seconds to respond. If the server does not have time to give an answer during this time, the user sees a sad message in the spirit of “Sorry, <dialogue name> does not respond”. No prompts what to do next, the system does not offer.

    To avoid such a situation, it is possible and necessary to speed up the service, as well as to track and process timeouts. The longest operations during the game script operation are reading and writing table data. Therefore, firstly, the number of these operations should be minimized, and secondly, it is desirable to parallelize them.

    It is enough to read these tables once. After the logic is executed, the script is ready to give the user an answer immediately, before the end of the recording of the results.

    A limited time should be given to receive a response - for example, 1100 ms:

    	$request_params = array(
    	  'userId' => $user_id, 
    	  'utterance' => $utterance,
    	  'channel' => 'alice'
    	); 
    	$get_params = http_build_query($request_params);
    	$ctx = stream_context_create(array('http'=>
    	    array(
    	        'timeout' => 1.1
    	    )
    	));
    	$answer = file_get_contents('https://script.google.com/macros/s/<id веб-приложения>/exec?'. $get_params, false, $ctx);
    

    If a response by a GET request is received in time, we can give it to the user and initiate saving the results by a POST request in the background. Otherwise, we give the user a text stub with buttons to continue, and ignore the results of the script execution so that the user can repeat his request in the current context.

    if($answer === FALSE) {
    		$text = ' Помедленнее, я не успеваю.';
    		$tts = 'Помедленнее, я не успеваю.';
    	} else {
    	    $answer = json_decode($answer);
                $text = $answer->text;
    	    $tts = $answer->tts;
    	    //сохранение в таблице
    	    $data2store = $answer->data;
                $postdata = json_encode(array(
    	          'data' => $data2store
    	      ));
    	   $opts = array('http' =>
    	      array(
    	          'method'  => 'POST',
    	          'header'  => 'Content-Type: application/json',
    	          'content' => $postdata,
    	          'timeout' => 0.1
    	      )
    	  );
              $context  = stream_context_create($opts);
    	  file_get_contents("https://script.google.com/macros/s/<id веб-приложения>/exec", false, $context);
    	}
    


    In a multiplayer game for Alice, synchronization tasks must be solved both between the game servers and Yandex, and between players. If a player wants to play against another user, the game itself selects an opponent - from those who wanted to play lately. Users must confirm their readiness to play with each other for the game to start.

    Currently, the skill cannot initiate sending a message to Alice’s user. Therefore, the game's script provides for checking the readiness of the opponent and the minute allotted for the round of the game. If the opponent delays the game, the user is asked to wait for him: “Let's wait for the opponent a little more?” Agreeing to wait, the user launches the next check. If the minute of the game ends, the game ends.

    Conclusion


    The advantages of Google Tables as a backend for a chat bot, apart from being free of charge, include the fact that it is a debugging tool during development, and then it becomes a skill administrator console with all the benefits of co-editing from any device. By cons - the delay in the simultaneous work of a large number of users.

    I hope this article will help enthusiasts and developers to quickly create useful skills for Alice or other channels. The proposed game is available in the Yandex.Dialogs skills store called “ One, Two, Three! Multiplayer game .

    Along with general-purpose tools, there are specialized solutions for developing chat bots. I suggest that readers take part in a short survey on the services I know about in this area. Far from all existing products got into the list - I will be grateful for comments with names and short reviews if you used other tools.

    Only registered users can participate in the survey. Sign in , please.

    What chat bot development tools have you tried?


    Also popular now: