• Tutorial

Chat bots are a rather interesting topic that is of interest to both geek enthusiasts and companies that want to organize interaction with their customers in the most convenient way for them.


Today I will describe to you a simple example of creating a Telegram bot using the API.AI conversational interface building platform that will greet the user and answer questions about the weather. For the most part I followed these instructions, in real practice, you can go beyond the weather and implement interfaces
for automated support or sales.

Step one: Prepare the infrastructure.

In this case, we will only use the Telegram bot and API.AI, both services are provided free of charge - all we have to do is create accounts.

Create a Telegram bot

To create a bot, just write @BotFather (this is a bot that can create and configure other bots):

  1. Send the command /newbot - this is how we tell @BotFather that we need a new bot
  2. Now @BotFather will ask us to name the new bot. This name will be seen by our
    future users, so the name should be clear and simple.
  3. The last step is to indicate the username for the bot, at the end of which you must
    write “bot”.
  4. If the name is not taken, we receive a confirmation message and an access token.

To make it clearer, below is a screenshot with all the actions:

A little theory

It's time to create an API.AI agent, which is essentially a project or container (whatever you prefer to call it). The agent contains settings for contexts, entities and responses:

  • “context” (Intent) reflects the connection between what the user said And
    those what should our program do
  • “entities” is a tool for extracting parameter values ​​for
    our program from natural language (what was said or written
    user)
  • “answers” is the final result of our program, which we
    send to the user his message

Sometimes information from the current dialogue is enough to respond to the user; in this case, you can set up static answers V contexts. In reality, to get a specific answer, we may need an external service or our own business logic, for example, to get information about the weather for tomorrow, we need to call the external API of the corresponding service. Later I will tell you how to receive information from external systems, but first, let’s prepare the base.

Create a project in API.AI

To register with API.AI, you will need a Google account (just add it to your Gmail account). Now go to https://api.ai/, click on the “SIGN UP FOR FREE” button, and then select the account on behalf of which you want to log in.


Now let's move on to creating the agent itself. Click on “Create agent” and specify at least a Name, Language and Time Zone.


Step two: Set up an agent.

Context reflects the relationship between what the user says and what our agent should do. In our case, consider the case of a weather forecast:


  1. Click on in the “Context” section. The agent has already configured “contexts” for greetings and errors; let’s leave them unchanged for now.
  2. Indicate a name for the “context” - any name, as long as it is understandable to you and your colleagues.
  3. In the “User Says” section, provide examples of questions your user can ask. Since we are talking about the weather, a person can ask a question based on time and place - let’s take this into account. The more examples you provide in the settings, the more accurate the agent will work. I gave some examples in the screenshot:


In the last example, the words “tomorrow” and “Nizhny Tagil” are highlighted in different colors - thus the words are associated with entities ( Entities) (in our case, system entities). Using these parameters, the agent will “understand” in which city and for which date the weather needs to be checked.


Add a couple more of your examples and click “SAVE”.

Let's test!

Let’s check the agent’s performance using simple questions, for example, “Weather in Perm on Wednesday”:



All this time, the inscription “Try it now” loomed in the upper right part of the screen - write in this field or say a simple question about the weather and press “Enter”.


We have not yet configured an automatic response, but the agent has already learned to determine some parameters! The INTENT section reflects that, according to the agent’s “opinion,” the user is interested in the weather (the “context” we set up), and the PARAMETER shows the date and name of the city in the corresponding variables.

Add automatic replies

Let's make our agent more talkative! Until we learn how to receive weather information from external sources, we will add simple phrases as answers.


Go to the “Response” section and enter simple answers in the same way as you filled out “User Replies”:



As you can see, you can use links to identified entities in responses; start typing $ - and the interface will prompt you to select a specific variable.


When generating a response, the agent takes into account the number of certain entities and does not use responses for which there is insufficient data. For example, for a question without specifying a city, the agent uses the answer from the second line.


Save the settings and test again:



Now we also have the answer!

Step three: Add an external service.

Our agent already “understands” in what cases the user wants to know the weather, on what date and in what city. Now all that remains is to obtain this data from a suitable service and transfer it to the agent. To do this, you need to write a couple of scripts in JS and place them in a cloud service, in our case, Google Cloud Project.

Create a starter JS file

To begin, create and go to a directory with the name of your project:

    Linux or Mac OS X:


    mkdir ~/
    cd ~/


    mkdir %HOMEPATH%
    cd %HOMEPATH%

Now create an index.js file with the following content:


index.js code

/* * HTTP Cloud Function. * * @param (Object) req Cloud Function request context. * @param (Object) res Cloud Function response context. */ exports.itsm365Weather = function itsm365Weather (req, res) ( response = "This is a sample response from your webhook!" //Default response from the webhook to show it"s working res.setHeader("Content-Type", "application/json"); //Requires application/json MIME type res.send(JSON.stringify(( "speech": response, "displayText": response //"speech" is the spoken version of the response, "displayText " is the visual version)));

Set up Google Cloud Project

  • Make settings “Before you
    begin” from 1 to 5 points
  • Deploy the function in the cloud by running in the console:


    gcloud beta functions deploy itsm365Weather --stage-bucket --trigger-http

where itsm365Weather is the name of the function, and is the name of the storage
data for the project.


After the operation is completed, you will see the result with the http trigger URL:


Enable Webhook in API.AI

  1. Make sure you are in the correct agent and then click “ Fulfillment” in the left hiding menu.
  2. Enable Webhook at the top right of the screen.
  3. Enter the URL obtained in the previous step.
  4. Save your changes.

Enable the execution of a new function in the “context” settings

  1. Go to the weather forecast “context” settings
  2. Expand the block Fulfillment at the bottom of the page
  3. Check the box “Use Webhook”
  4. Save the settings and check the result:

Set up the weather API

For simplicity, we will use the WWO (World Weather Online) service, where you need to get an API key (just register via Facebook or Github).


Update the code in the starting JS file, remembering to enter the API key to get weather information:


Source code for the weather forecast service

// Copyright 2017, Google, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. "use strict"; const http = require("http"); const host = "api.worldweatheronline.com"; const wwoApiKey = "98cfb8e40ecc47c4a2f205209172608"; exports.itsm365Weather = (req, res) => ( // Get the city and date from the request let city = req.body.result.parameters["geo-city"]; // city is a required param // Get the date for the weather forecast (if present) let date = ""; if (req.body.result.parameters["date"]) ( date = req.body.result.parameters["date"]; console.log ("Date: " + date); ) // Call the weather API callWeatherApi(city, date).then((output) => ( // Return the results of the weather API to API.AI res.setHeader("Content -Type", "application/json"); res.send(JSON.stringify(( "speech": output, "displayText": output ))); )).catch((error) => ( // If there is an error let the user know res.setHeader("Content-Type", "application/json"); res.send(JSON.stringify(( "speech": error, "displayText": error ))); )) ; ); function callWeatherApi (city, date) ( return new Promise((resolve, reject) => ( // Create the path for the HTTP request to get the weather let path = "/premium/v1/weather.ashx?format=json&num_of_days= 1" + "&q=" + encodeURIComponent(city) + "&key=" + wwoApiKey + "&date=" + date + "&lang=ru"; console.log("API Request: " + host + path); // Make the HTTP request to get the weather http.get((host: host, path: path), (res) => ( let body = ""; // var to store the response chunks res.on("data", (d) => ( body += d; )); // store each response chunk res.on("end", () => ( // After all the data has been received parse the JSON for desired data let response = JSON.parse(body); let forecast = response["data"]["weather"]; let location = response["data"]["request"]; let conditions = response["data"]["current_condition "]; let currentConditions = conditions["lang_ru"]["value"]; // Create response let output = `On $(forecast["date"]) in $(location["query"]) $(currentConditions) , air temperature from $(forecast["mintempC"])°C to $(forecast["maxtempC"])°C. `; // Resolve the promise with the output text console.log(output); resolve(output); )); res.on("error", (error) => ( reject(error); )); )); )); )


Redeploy the function to the cloud project.

Step Four: Configuring Dialog Branches

When interacting with a user, we cannot be sure that he will provide us with all the information necessary to prepare a response in an external service immediately in the very first message. In our example, to obtain a forecast, the service will need a date and city. If the date is unknown, we can safely assume that the user means “today,” but we can only learn about the city from the user himself.

Make “location” a required parameter


Open the “Weather Forecast” context settings and specify the geo-city parameter as required. Then set up a clarifying question using the link in the “Prompts” column.


Save the settings and test the agent's behavior by asking it a simple weather question:



The agent asked us a clarifying question; the console displays the parameters of the current
situations.

Create a return refiner for location

To use data obtained from previous user journeys, you will need to configure the appropriate refinements.



In the “weather forecast” context setting, enter the name of the returned clarification “location” into the “Add output context” field and save the settings.

Create a new context for clarification

It’s convenient when you can ask several questions about the same location without asking the user which city he means. You've already configured a return qualification that you can use to process follow-up questions.


  1. Create a new context in the section Intents or click on the icon in the line
    Intents left pull-out menu.
  2. Name the new context “Weather Update” (or any other name that makes sense to you).
  3. Set incoming and outgoing refiners to “location”
  4. Add user remarks, for example, “What about tomorrow?”
  5. Add an entity parameter with the following values:
    - Parameter Name:
    geo-city
    - Value:#location.geo-city
  6. Add a response for the user to the “ section Response”:
    - “Sorry, but I can’t get a forecast for $date-period in #location.geo-city”
  7. Enable use webhook on the menu Fulfillment.
  8. Save the settings and test in the console:

Step Five: Greeting and Handling Unexpected Situations

The main skeleton of the agent is ready, now it’s a good idea to make the robot
greeted the user and also knew how to respond to unexpected questions.

Set up default responses for unexpected situations

If the user asks an unexpected question (in our case, not about the weather), the agent will include a context for handling unexpected situations ( Default Fallback Intent):



Go to setting up this context, customize your answer options if necessary.

Set up the greeting context

The greeting can be customized in a similar way in the corresponding content -
Default Welcome Intent


Step Six: Launch the Bot

Connect Telegram bot to agent

Go to the “Integrations” settings and enable the bot in the section
“One-click integrations”:



Copy the token you received from @botFather into the “Telegram token” field and
click on START.

Check the bot's performance

Go to your bot and try to write something to it, in my case it’s
@itsm365_weather_bot (I used free weather accounts, so after 500 requests a day the bot will turn into a pumpkin).


Conclusion

API.AI can already be used to build interactive interfaces in instant messengers and support chats with social networks. Considering that the tool can be easily integrated with your services, it is a convenient workhorse for automating communication with your users.


P.S. This is my first post, I would appreciate constructive feedback!

Tags:

  • api.ai
  • telegram
  • telegram bots
Add tags If a beginner just comes to the Telegram messenger, then he immediately has a question about how to use it or even how to register for the service. To do this, you will need a mobile phone number and one of the Telegram applications, which can be found and downloaded on any platform and operating system at: https://www.telegram.org. After all this is done, we get a new Telegram user on the network and a potential client of our channels, promoted using the VTope service.

Telegram.me download or open to access the channel

As the newcomer continues his journey through Telegram, a hitherto unknown world of various channels gradually opens up to him. Links like Telegram.me need to be downloaded or opened on your device to get to the channel you are interested in. There, in the chat feed with other users and service bots, while viewing news, pictures, videos, the user (now a channel subscriber) will from time to time see advertising messages from which this channel makes money. Of course, each of us would like to have such a channel, but not everyone knows how.

Telegram API in Russian is available even for beginners

Creating your own business on Telegram is now not as difficult as it used to be. The open Telegram API has long been in Russian and allows, with the help of templates and constructors, even not very experienced programmers to create their own bot channel for it.
The hardest part of the work - getting subscribers - will be taken over by the VTope boosting service. Why are subscribers needed? The more there are, the more the advertising post costs and the more money it will bring to the channel owner. Such things happen in the Telegram world.

Application Telegram can honestly boast of opening a new, absolutely unique base for creating bots. Although the bot platform was developed at the beginning of summer (the presentation took place on June 24), only a small part of active external developers began intensively polishing and developing their own applications. Today the bot is an indispensable assistant for Telegram, because with its help a connection is established with the requested servers TelegramBot API. In addition, the process of the bot itself is aimed at appealing to URL with the specified parameters, after which Telegram issues JSON- answer. Let's dive deeper into the issue and look at an example of creating a bot (of a trivial type).

Application (bot) registration procedure

Before you start directly developing and uploading the bot to the common interface and chat, you need to assign your mini-program an individual code (such as id), which is a unique personifying token. In order to carry out this operation, you need to send a request to a specific bot - @BotFather.

In order to carry out this operation, you must follow the following algorithm of actions:

  • write a text message with information content “ start»;
  • after this, we get a list of all possible optional commands and functions;
  • then we send the bot a message with the text content “ newbot"and based on an incoming request from an existing bot, we come up with a nickname for our bot (the only condition: the name must have the suffix/prefix " bot»);
  • if all the conditions and rules are taken into account, then the existing bot issues you a request and a permission link (quickly adding the created bot to the list of available contacts).

In principle, at this point you can already launch the bot or, if desired, you can create a welcome message for future users and a description of the bot. Perhaps, if you want to hit a specific target audience, you can add a consonant musical composition or image. Important advice: it is worth checking the uniqueness and suitability of your token by clicking on the address link (api.telegram.org/bot/getMe). Bot programming process

Usually bots are created in the mode Python3, but thanks to the progressiveness of IT technologies, you can use any convenient and familiar mode. Telegram is configured to automatically download messages, so it is appropriate to create a confidential cloud that will significantly speed up the process of downloading text messages (the fastest and most applicable is tornado.web.). Let the frame part of the bot be reflected in a certain phrase (it is more logical to use one that reflects the information content of the programmed bot). Then, before you launch the bot, you need to carry out the activation procedure WebHook with localization to your own address. Next, we configure the usual signal (output 6) and display the load of ongoing events/actions.

  • lexicon;
  • functional feature of sending (forwarding) text replies;
  • generation of messages.

After you have entered all the nuances into the bot’s logic, you need to start developing the main commands that your program will have.

Creating Teams

According to the rules of the Telegram program, absolutely every bot (regardless of its specifics, popularity and workload) must respond to 2 commands:

  • Start;
  • Help.

The first command was created to identify the bot, and not to view embedded information. Often, its use is closely related to the authorization procedure for any programs.

Team " Help"is aimed at reflecting the main parameters of the bot, its specific characteristics, features and commands.

To create commands, the main bot is a permanent assistant @BotFather, which will help you create the necessary and required list of commands according to your classification.

Universality

You have already noticed that the Telegram program sends messages that are absolutely holistic and meaningful in terms of meaning, without breaking them into separate absurd parts. Therefore, it becomes possible to program your bot to voice human speech (voice notification). The only caveat is that the “talkative” bot will only be available in private messages, because this feature is not possible in chat. In order to start the process of “speaking” the bot, we perform a number of connected operations:

  • send a text message “setprivacy” to @BotFather;
  • switch to privacy;
  • in the list of commands we add the “pseudo-speech” option.

After this, the bot can read messages and provide information in voice mode.

Media aspects and opportunities

Bots are not much different from real users of the Telegram messenger, so they also have the opportunity to communicate using pictures, music files, videos and stickers.

In order to get a pack of stickers you need to send a text message " at_sticker» and modify the parameters send_reply. Thus, in addition to text, your bot will also send funny stickers and display time indicators.

Potential

Using a reliable platform API, bots can become indispensable assistants and the basis for automating processes, creating quizzes, surveys, competitions and sending notification messages. The main emphasis can be placed on the specifics of CTF, DozoR.

Framework

Today there are strict limits on the use WebHook. The fact is that it functions only on the basis of https (with a valid certificate). Not every developer has a valid certificate. And the reason is that there is no support from the DNS. But, thanks to the presence of manual mode in Telegram, it is possible to differentiate the codes and services of the available data from those to which your program is tailored, pumping and forwarding messages to local addresses.

Other materials about Telegram bots:

  • Robot Anton - robots on Telegram
  • Telegram api developer capabilities
  • Telegram bots
  • Telegram 3.0 has the function of launching useful Bots

  • Tutorial

Chat bots are a rather interesting topic that is of interest to both geek enthusiasts and companies that want to organize interaction with their customers in the most convenient way for them.


Today I will describe to you a simple example of creating a Telegram bot using the API.AI conversational interface building platform that will greet the user and answer questions about the weather. For the most part I followed these instructions, in real practice, you can go beyond the weather and implement interfaces
for automated support or sales.

Step one: Prepare the infrastructure.

In this case, we will only use the Telegram bot and API.AI, both services are provided free of charge - all we have to do is create accounts.

Create a Telegram bot

To create a bot, just write @BotFather (this is a bot that can create and configure other bots):

  1. Send the command /newbot - this is how we tell @BotFather that we need a new bot
  2. Now @BotFather will ask us to name the new bot. This name will be seen by our
    future users, so the name should be clear and simple.
  3. The last step is to indicate the username for the bot, at the end of which you must
    write “bot”.
  4. If the name is not taken, we receive a confirmation message and an access token.

To make it clearer, below is a screenshot with all the actions:

A little theory

It's time to create an API.AI agent, which is essentially a project or container (whatever you prefer to call it). The agent contains settings for contexts, entities and responses:

  • “context” (Intent) reflects the connection between what the user said And
    those what should our program do
  • “entities” is a tool for extracting parameter values ​​for
    our program from natural language (what was said or written
    user)
  • “answers” is the final result of our program, which we
    send to the user his message

Sometimes information from the current dialogue is enough to respond to the user; in this case, you can set up static answers V contexts. In reality, to get a specific answer, we may need an external service or our own business logic, for example, to get information about the weather for tomorrow, we need to call the external API of the corresponding service. Later I will tell you how to receive information from external systems, but first, let’s prepare the base.

Create a project in API.AI

To register with API.AI, you will need a Google account (just add it to your Gmail account). Now go to https://api.ai/, click on the “SIGN UP FOR FREE” button, and then select the account on behalf of which you want to log in.


Now let's move on to creating the agent itself. Click on “Create agent” and specify at least a Name, Language and Time Zone.


Step two: Set up an agent.

Context reflects the relationship between what the user says and what our agent should do. In our case, consider the case of a weather forecast:


  1. Click on in the “Context” section. The agent has already configured “contexts” for greetings and errors; let’s leave them unchanged for now.
  2. Indicate a name for the “context” - any name, as long as it is understandable to you and your colleagues.
  3. In the “User Says” section, provide examples of questions your user can ask. Since we are talking about the weather, a person can ask a question based on time and place - let’s take this into account. The more examples you provide in the settings, the more accurate the agent will work. I gave some examples in the screenshot:


In the last example, the words “tomorrow” and “Nizhny Tagil” are highlighted in different colors - thus the words are associated with entities ( Entities) (in our case, system entities). Using these parameters, the agent will “understand” in which city and for which date the weather needs to be checked.


Add a couple more of your examples and click “SAVE”.

Let's test!

Let’s check the agent’s performance using simple questions, for example, “Weather in Perm on Wednesday”:



All this time, the inscription “Try it now” loomed in the upper right part of the screen - write in this field or say a simple question about the weather and press “Enter”.


We have not yet configured an automatic response, but the agent has already learned to determine some parameters! The INTENT section reflects that, according to the agent’s “opinion,” the user is interested in the weather (the “context” we set up), and the PARAMETER shows the date and name of the city in the corresponding variables.

Add automatic replies

Let's make our agent more talkative! Until we learn how to receive weather information from external sources, we will add simple phrases as answers.


Go to the “Response” section and enter simple answers in the same way as you filled out “User Replies”:



As you can see, you can use links to identified entities in responses; start typing $ - and the interface will prompt you to select a specific variable.


When generating a response, the agent takes into account the number of certain entities and does not use responses for which there is insufficient data. For example, for a question without specifying a city, the agent uses the answer from the second line.


Save the settings and test again:



Now we also have the answer!

Step three: Add an external service.

Our agent already “understands” in what cases the user wants to know the weather, on what date and in what city. Now all that remains is to obtain this data from a suitable service and transfer it to the agent. To do this, you need to write a couple of scripts in JS and place them in a cloud service, in our case, Google Cloud Project.

Create a starter JS file

To begin, create and go to a directory with the name of your project:

    Linux or Mac OS X:


    mkdir ~/
    cd ~/


    mkdir %HOMEPATH%
    cd %HOMEPATH%

Now create an index.js file with the following content:


index.js code

/* * HTTP Cloud Function. * * @param (Object) req Cloud Function request context. * @param (Object) res Cloud Function response context. */ exports.itsm365Weather = function itsm365Weather (req, res) ( response = "This is a sample response from your webhook!" //Default response from the webhook to show it"s working res.setHeader("Content-Type", "application/json"); //Requires application/json MIME type res.send(JSON.stringify(( "speech": response, "displayText": response //"speech" is the spoken version of the response, "displayText " is the visual version)));

Set up Google Cloud Project

  • Make settings “Before you
    begin” from 1 to 5 points
  • Deploy the function in the cloud by running in the console:


    gcloud beta functions deploy itsm365Weather --stage-bucket --trigger-http

where itsm365Weather is the name of the function, and is the name of the storage
data for the project.


After the operation is completed, you will see the result with the http trigger URL:


Enable Webhook in API.AI

  1. Make sure you are in the correct agent and then click “ Fulfillment” in the left hiding menu.
  2. Enable Webhook at the top right of the screen.
  3. Enter the URL obtained in the previous step.
  4. Save your changes.

Enable the execution of a new function in the “context” settings

  1. Go to the weather forecast “context” settings
  2. Expand the block Fulfillment at the bottom of the page
  3. Check the box “Use Webhook”
  4. Save the settings and check the result:

Set up the weather API

For simplicity, we will use the WWO (World Weather Online) service, where you need to get an API key (just register via Facebook or Github).


Update the code in the starting JS file, remembering to enter the API key to get weather information:


Source code for the weather forecast service

// Copyright 2017, Google, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. "use strict"; const http = require("http"); const host = "api.worldweatheronline.com"; const wwoApiKey = "98cfb8e40ecc47c4a2f205209172608"; exports.itsm365Weather = (req, res) => ( // Get the city and date from the request let city = req.body.result.parameters["geo-city"]; // city is a required param // Get the date for the weather forecast (if present) let date = ""; if (req.body.result.parameters["date"]) ( date = req.body.result.parameters["date"]; console.log ("Date: " + date); ) // Call the weather API callWeatherApi(city, date).then((output) => ( // Return the results of the weather API to API.AI res.setHeader("Content -Type", "application/json"); res.send(JSON.stringify(( "speech": output, "displayText": output ))); )).catch((error) => ( // If there is an error let the user know res.setHeader("Content-Type", "application/json"); res.send(JSON.stringify(( "speech": error, "displayText": error ))); )) ; ); function callWeatherApi (city, date) ( return new Promise((resolve, reject) => ( // Create the path for the HTTP request to get the weather let path = "/premium/v1/weather.ashx?format=json&num_of_days= 1" + "&q=" + encodeURIComponent(city) + "&key=" + wwoApiKey + "&date=" + date + "&lang=ru"; console.log("API Request: " + host + path); // Make the HTTP request to get the weather http.get((host: host, path: path), (res) => ( let body = ""; // var to store the response chunks res.on("data", (d) => ( body += d; )); // store each response chunk res.on("end", () => ( // After all the data has been received parse the JSON for desired data let response = JSON.parse(body); let forecast = response["data"]["weather"]; let location = response["data"]["request"]; let conditions = response["data"]["current_condition "]; let currentConditions = conditions["lang_ru"]["value"]; // Create response let output = `On $(forecast["date"]) in $(location["query"]) $(currentConditions) , air temperature from $(forecast["mintempC"])°C to $(forecast["maxtempC"])°C. `; // Resolve the promise with the output text console.log(output); resolve(output); )); res.on("error", (error) => ( reject(error); )); )); )); )


Redeploy the function to the cloud project.

Step Four: Configuring Dialog Branches

When interacting with a user, we cannot be sure that he will provide us with all the information necessary to prepare a response in an external service immediately in the very first message. In our example, to obtain a forecast, the service will need a date and city. If the date is unknown, we can safely assume that the user means “today,” but we can only learn about the city from the user himself.

Make “location” a required parameter


Open the “Weather Forecast” context settings and specify the geo-city parameter as required. Then set up a clarifying question using the link in the “Prompts” column.


Save the settings and test the agent's behavior by asking it a simple weather question:



The agent asked us a clarifying question; the console displays the parameters of the current
situations.

Create a return refiner for location

To use data obtained from previous user journeys, you will need to configure the appropriate refinements.



In the “weather forecast” context setting, enter the name of the returned clarification “location” into the “Add output context” field and save the settings.

Create a new context for clarification

It’s convenient when you can ask several questions about the same location without asking the user which city he means. You've already configured a return qualification that you can use to process follow-up questions.


  1. Create a new context in the section Intents or click on the icon in the line
    Intents left pull-out menu.
  2. Name the new context “Weather Update” (or any other name that makes sense to you).
  3. Set incoming and outgoing refiners to “location”
  4. Add user remarks, for example, “What about tomorrow?”
  5. Add an entity parameter with the following values:
    - Parameter Name:
    geo-city
    - Value:#location.geo-city
  6. Add a response for the user to the “ section Response”:
    - “Sorry, but I can’t get a forecast for $date-period in #location.geo-city”
  7. Enable use webhook on the menu Fulfillment.
  8. Save the settings and test in the console:

Step Five: Greeting and Handling Unexpected Situations

The main skeleton of the agent is ready, now it’s a good idea to make the robot
greeted the user and also knew how to respond to unexpected questions.

Set up default responses for unexpected situations

If the user asks an unexpected question (in our case, not about the weather), the agent will include a context for handling unexpected situations ( Default Fallback Intent):



Go to setting up this context, customize your answer options if necessary.

Set up the greeting context

The greeting can be customized in a similar way in the corresponding content -
Default Welcome Intent


Step Six: Launch the Bot

Connect Telegram bot to agent

Go to the “Integrations” settings and enable the bot in the section
“One-click integrations”:



Copy the token you received from @botFather into the “Telegram token” field and
click on START.

Check the bot's performance

Go to your bot and try to write something to it, in my case it’s
@itsm365_weather_bot (I used free weather accounts, so after 500 requests a day the bot will turn into a pumpkin).


Conclusion

API.AI can already be used to build interactive interfaces in instant messengers and support chats with social networks. Considering that the tool can be easily integrated with your services, it is a convenient workhorse for automating communication with your users.


P.S. This is my first post, I would appreciate constructive feedback!

Tags: Add tags