# Introduction

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LdiYPXs2J5w_V4bhJhv%2F-LdiYSyyQCGHVdOSlBU_%2FLogo.png?alt=media\&token=bd9363d9-a72c-40e9-9648-c728c5b7cd32)

Welcome to the CosmoBots platform tutorial. The content here is intended to help users with or without experience in creating ChatBots.

To register, just access <https://cosmobots.io/user/register>

We split this tutorial into 2 parts

* **Bot Builder:** has all the information you need to build, publish and manage your bot.
* **Cosmo Desk:** where you can monitor how the bot is interacting with users as well as put a person to interact directly with the user.

We are constantly launching new features, and leaving this tutorial ever more complete! So always keep an eye on the news.

If you have questions or feedback, feel free to contact us at <support@cosmobots.io>

We hope you enjoy Cosmo 😃


# Register

Hello Cosmonaut 🚀!! In this article I will explain you step by step how to register on the platform.

1- Enter the Cosmobots website ( <https://cosmobots.io/> ) and click on Register:

![](/files/-Mg62QlFne85bTtXT_0l)

2- Fill in all the fields and click on Register again:

![](/files/-Mg6304OlUXG9UgTMGZ0)

3- You will receive an email containing the activation code, copy the code:

![](/files/-Mg63ES82ub0xuvNt5Vx)

4- Enter the code and click on Validate:

![](/files/-Mg63I1C5T7rtlJJKs1m)

There, your account is created!\
\
**Welcome to Cosmobots!**


# Definitions

Let's list here some definitions that we consider important so that you do not get lost in the rest of the tutorial.

## ChatBot

**Bot** is a program that performs actions simulating how a human would have executed them. And when we speak **ChatBot** means that the context of the Bot actions are related to a dialog environment. They can be dialogues of diverse forms (voice, text, image) where the interactions can be with a human or even another Bot.&#x20;

In CosmoBots when we mention Bot we are referring to ChatBots in the form of text.

## User

In CosmoBots, when the Bot makes a conversation with the human, we define that this human is the user.

## Conversation Context

During a conversation, we can store information about the reason for the conversation. It may be, for example, that the user has one or more intentions and for the bot to be able to answer them, it is necessary to request and store user information.

Therefore we have defined that this information is part of the conversation context. That is, the actions performed by the bot may have influence of this information. In CosmoBots you can define how long the context can last.

![](https://lh5.googleusercontent.com/_2QL6tioLZ9QD-2GxKk8WPkYSkrW-mFe1ykklp00hG7e44w_WKV6w_WSQtuIggRols0BeZYJukxZlp_as1PhQ5rbqTbTCMakDg-l3GkGLz71LQ-wQZRLZaE3w3ZurWKtd5po1s_t)

{% hint style="info" %}
15 minutes is the recommended time for the context, as the conversations usually last around 3 to 5 minutes, 15 minutes are enough to store the information/options/user choice's
{% endhint %}

## NLP (Artificial Intelligence)

The meaning of NLP is Natural Language Processing. It refers to an area of Artificial Intelligence focused on the interaction between computer and the language that we humans understand (be it Portuguese, English, etc).

In CosmoBots when we mention NLP, we will generally be talking about a NLP sub-area known as NLU (Natural Language Understanding). In NLU we analyze each message sent by the user to understand some points related to the semantics of the text of the message: Intentions and Entities. We'll go into more detail in the [NLP section](/bot-builder/nlp).


# Create Bot

When entering the platform the 1st step is to create your bot. Here you have 2 options:

## Bot <a href="#bot" id="bot"></a>

When creating the bot you will only have a few basic pre-defined settings. So it's a free bot for you to set it up any way you prefer.

You will also have the option to set the [Conversation Context](/definitions#conversation-context). Refers to the maximum wait time, since the last interaction between bot and user, so that the conversation context is restarted.

To create, simply enter the **My Bots** section located on the top bar, and then click on the **New Bot** button.

![](https://lh3.googleusercontent.com/a1u7gda8CoyAZl1LMrrtYAO3dQbU_-_AwwU6ztb56gtBzrf8RAdGxpNsPb8C05u8gQiqbvm7Ws1DFvFmNzcqq6P2iPCoreDt0uA7Er2SGGrq_yQwoocU1spLCED0725lCcgVNTmd)

## Bot Template <a href="#bot-modelo" id="bot-modelo"></a>

You also have the option to create a bot already customized, that is, with predefined configurations depending on the use case of the bot.

As an example, you can choose the Restaurant bot and already start working with the bot that already has basic customer service for a restaurant. Just like the Simple Bot, the custom bot is also free for you to configure it the way you prefer. Including the [Conversation Context ](/definitions#conversation-context)definition (explained above).

The main advantage of this type of bot is that you can better understand how to configure it already having some settings created as an example.

To create it, simply enter the **Bots templates** section located on the top bar, and then select the bot template you want.

![](https://lh3.googleusercontent.com/_v9p1p0__hiNR0eKN0R90-XsxKuwJfSyd21JYrvCip_9VDAQyXP5m8_bu76x4cpIL6DXfYqHJ5t_yumap8WflqfiYWnGUi4iSOLXq484F0tcNj4Ombs0jNElUbNYaiqWkx8ZJppb)


# Version Control

Hello Cosmonaut! In this article I will explain how version control works.

Version control is so you can tinker with your bot without impacting the end user.\
\
When you activate this control and publish the bot version for the first time, the end user will always have access to the last published version, that is, even if you delete part of the bot flow, as long as you don't publish the latest version it will only be visible for you.\
\
Here's how to enable Version control:

1 - In the bot you want to activate version control, click Edit, then click Versions:

![](/files/-Mg6GIo-lL2KGgi-aZEa)

2- In versions, enable the button Use Version Control in Bot, and click Publish New Version:

![](/files/-Mg6GbfANR2q0sjUnxOc)

Okay, your bot already has Version control enabled

To see when the last version was published and the number of versions published, just click on edit and then click on Versions:

{% hint style="info" %}
NOTE: Version control is so that the modifications you make to your bot don't reach the end user without you wanting to, It is suitable for when you need to make adjustments to bots that are in production Once the new version is published, it is not possible to go back to the previous version.
{% endhint %}


# Creating my first Bot

Hello Cosmonaut!! In this article, I'm going to show you an example of how to create your first bot on the platform! I will also give you valuable tips on good practices.

## **Do you know how to create a bot?**

To make it easier, we can separate the creation of the Bot into 3 parts, namely:

1. Set a Bot Requirement&#x20;
2. Create a Flowchart
3. Insert the Bot on the Plataform

{% hint style="info" %}
Tip #1: Understanding what the bot's purpose is (Define a bot usage) and how to activate it (Create a flowchart) is essential before you really get down to business! (Insert the bot into the platform)
{% endhint %}

### 1. Define a Bot need

Register users on the platform.

{% hint style="info" %}
Tip #2: The bot must have a main need! Be informative, transactional, collect data between other... You can delete by expanding your bot's functionality or create another one that meets or needs, this way you ensure that the bot's scope is smaller and easier to maintain !
{% endhint %}

### 2. Create a Flowchart

This will be the scope of our bot:

{% hint style="info" %}
Tip #3: There are many tools to create streams quickly, including:\
[Driagram.io](http://diagram.io/)  ,  [Whimscal](https://whimsical.com/) .
{% endhint %}

Let's work on it now!

Follow this step-by-step:

1. After accessing the platform, click on the new bot button. (as the image below)
2. Name your bot, for example: Enroll Bot.

![](/files/-Mg6M13JC7Zg9V83IYWm)

{% hint style="info" %}
Tip #5: You can also define your bot, add an image to identify it, and you can also clone another bot you've already made!
{% endhint %}

**Flows:**

After following step 2, the bot will open a screen that displays the Flows it has. By default, a tool will always come with 3 flows already created, namely:

&#x20;\- Welcome

&#x20;\- Exception

&#x20;\- Delete

\*From here our Bot will be separated by streams.

Flow: Welcome

* Change the Welcome Flow main message to "Welcome to our platform":

![](/files/-Mg6P-sA14HrfOyCH81l)

{% hint style="info" %}
Tip #6: Within the Message you can also create option buttons for the user, choose between saving or not the obtained response, among other options.
{% endhint %}

Flow : Filter

1. Create another Stream named Filter;
2. Insert a filter with a function to identify if the user is registered or not in the tool

![](/files/-Mg6lc_TeE6vp-RcQ6h7)

{% hint style="info" %}
Tip # 7 : Filters provide an option to enter conditions that allow you to make routings, if you prefer, it is also possible to create Filters with Complex Functions.
{% endhint %}

Flow: Registered User

1. Create a new Stream with the registered user name;
2. Create a message and inform the user that he or she is already registered:

![](/files/-Mg7-qOdmv0uOLntnkWZ)

{% hint style="info" %}
Tip #8: When you need to save the response only for the duration of a bot interaction or use the user response in some other step, for example in a filter, you can save it as context.
{% endhint %}


# Conversation Flow

When entering the bot we will configure the Conversation Flow. The flow has the shape of a flowchart that can be defined by several Actions (also known as Flow Steps).

The purpose of the flow is for the bot to understand which action to perform at each point in the conversation with the user.

A flow can represent an activity the bot can perform. An example of an activity would be, for example, send an initial "hello", check and save the user's address. Therefore a bot can have multiple flows, and consequently can perform various activities.

## Standard Flows

Every bot created in CosmoBots has 2 standard flows:

* **Welcome:** flow that can be executed in 2 cases: 1) the first time the user interacts with the bot, or 2) every time the [conversation context](/definitions#conversation-context) is restarted.
* **Exception:** flow executed whenever the bot does not know which action to perform. So the ideal is to build flows and NLP good enough that this flow is little used.

Let's now comment on the Steps (or types of actions) that can be performed today in the flow


# Message

Message is the step of the flow responsible for performing interactions with the user.

![](https://lh5.googleusercontent.com/_uQtcWibmwsaKNY6naIudXelghb5HYr0N3r8n8M-RWbuXjCCqiQ5rsp5MKucPM4oG_gmKQvYGiNIGcVS9GtSolI-4KdggiIaI3TFfW6cxIZNb8-P2JLO0fHdtZFcPu13Tr0LmOaq)

{% hint style="info" %}
Whenever possible, use emoji! This causes greater engagement with the user. Each message bubble can receive 3 different messages.As interações podem ser as seguintes:
{% endhint %}

## Text

In this type, we first need to include the text that will be sent to the user by filling in the **Text** field. The maximum length of this field is 320 characters. But we recommend that you try not to exceed 40 characters, after all the user definitely does not want to read a long text.

If the message text is long, try splitting the message, for example, by clicking to add new text.

And if you want to add some user information (which is in [context](/definitions#conversation-context)) or some [field](/bot-builder/data/fields), just make reference by typing the **@**

![](/files/-LdtR7Xo6rJ0qUPmrMTM)

{% hint style="info" %}
You can use **{{user.first\_name}}** to metion the user name.
{% endhint %}

You can save the response that the user gives related to your message. Just click Save Response and select the field you want to save the response to. Remembering that this saved answer will be available only in the time that you set to the [context of the conversation](/definitions#conversation-context). You can choose from the default fields or create a new custom field:

![](https://lh6.googleusercontent.com/hlWVfwtVDmx-uqGlh819mF_kb51XTfyKOKWqAH5TZgSPIN3qyG2Kwur6EP0B9wHQq6atOPs3cmUzO2Y1ZJbIm9PxSNNjKwPXGUabaH3-2cYxnSLpeMB172ecg5-ots0Bo1iMC_7e)

To facilitate interaction with the user, you can also define Quick Answers. Each **Quick Reply** can have a title (which will be visible to the user) and represent one of 3 types / values:

* Running a **Flow**
* Running a Flow **Step**
* Response to be saved, represented by the [Type of field](/bot-builder/data/fields) to be used.

![](https://lh6.googleusercontent.com/48Xb15y0OZPurKvexfJwd0OswO5mMcNbQvdFHVV3dimMd9ph519-_RtUtb5_f5JkF9y54C3XSpWz1z1pg2yq2p40j1Wr0L-NLRv8CBpkqZRHafk4TG3Shi2LSu4TCmmXBI2bfQSc)

{% hint style="info" %}
You can have up to 10 Quick Reply's. Quick Reply's are great for putting your secondary options available for something! For example: Types of payment (Debit, Credit, etc.)
{% endhint %}

## Cards

The second type is sending a message in the form of cards, which are visible horizontally from the dialog environment.

![](https://lh5.googleusercontent.com/UeDFaFjCPEkNmkB6fOmqFgOjihUEF9B43ACU0s2_0mW8LnzFmw43K4nJXt6x74BLf6qkOzoZv-t5wusW7Srqyufn0eACaVgRkM5T-RwWfVisFqI3n9_1W1Nwq-9VSGZ6J10oG6my)

{% hint style="info" %}
You can have up to 10 cards and put up to 3 buttons on each. Some places refer to cards like Carousels. They are great for showing the main options for the user, since they can receive images which help a lot to engage the user.
{% endhint %}

For each card you can set the following information:

* **Title:** text up to 80 characters in bold. It is the only information required.
* **Subtitle:** text up to 80 characters.
* **Image:** provided it is up to 1 MB in size. Whenever possible, use images as they greatly enrich the interaction with the user.
* **Buttons:** can add up to 3 buttons per card. It behaves similarly to fast responses (described above), with the additional option of being able to open an external URL or a [webview](/bot-builder/conversation-flow/webview) if the user clicks the button.

From the information above, only the **Title** is required.

## Random Text

![](/files/-LdtR1te8DucoM4bv5bg)

By clicking on this icon we can access the Random Texts, where you can place variations of the message that was created. The bot will send one of those messages to the user, thus creating the feeling that he never repeats the same thing.

![](/files/-LdtR3SLmuO4r2lhw7Me)

{% hint style="info" %}
The more variations you put on, the more human and intelligent the Bot will look.
{% endhint %}


# Filter

Filter is the flow step responsible for evaluating conversation information and can direct the conversation to a different path in the flow. This information can be from the user or the context of the conversation, either through a custom object or some context variable.

![](https://lh6.googleusercontent.com/7b4e1BPSxE0xEgBRZkuGTmropJt32zE_J_IpkglguqBQtBPZYpxbB4dgbd7ermtB8WoSgZokuqKnrr2Q7ZQ2AV_lEutFVJDkvdQNJSPXp2hiaMvn6ftoUMkPV9DkKt59Zkm4PAOY)

## Criteria

Filter evaluation is defined by logic criteria.

![](https://lh3.googleusercontent.com/vWeh5IkcwpuQvoyTp9c92_NqjDHbgv655_e1kxrhkEnvpjHHWZCeEaAAsr7-RwqyD_O2x3Zn8VxkP9_nPCSXLxh1o7B8zMQec3wmtM3Gja7eLHfOf8nzQO8DLkppKgO311vIxs_G)

These criteria can be grouped in E and OU respecting always the rules of [conjunction in mathematical logic](https://pt.wikipedia.org/wiki/Conjun%C3%A7%C3%A3o_l%C3%B3gica).

The 3 information that represents one criterion are:

* **Field:** referring to a field related to the user or to a context information.
* **Condition:** operation that will be used to evaluate the selected field.
* **Value:** represents the reference value for evaluation of the operation and the selected field. This value is directly related to the type of the selected field. Therefore if the field is of type "Options", the value may be only one of the options registered for this field.

#### Result <a href="#resultado" id="resultado"></a>

The filter can take 1 of 2 decisions:

* **Yes:** if the result of the defined criteria (or conjunction) is "True", the flow will continue vertically.
* **No:** if the result of the defined criteria (or conjunction) is "False", the flow will take the path to the right.

## Business hours

You can also create a filter that makes human service hours! To trigger this filter, you must select "Business Hours" under Filter Type

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-Lc6ZXcOVPs9dBAi3yVv%2F-Lc6_iyiMQyjNx7FnYyQ%2FScreen%20Shot%202019-04-10%20at%2011.10.19.png?alt=media\&token=acc2fe49-e817-4009-bd49-90f20da0e43a)

For example, you can define the message that the Bot will send if it is in the service hours, and if it is not, a message explaining that the Bot is out of business hours.[<br>](https://help.cosmobots.io/help/bot-builder/fluxo-da-conversa/mensagem)

![You can redirect the user to the initial flow if you are out of business hours](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-Lc6ZXcOVPs9dBAi3yVv%2F-Lc6_yxdjsx6Lpc685-8%2FScreen%20Shot%202019-04-10%20at%2011.10.39.png?alt=media\&token=9590ac47-d3d5-456d-9588-88783eeb7496)


# Existing Step

**Existing Step** is responsible for redirecting the conversation to an existing step and / or flow.

![](https://lh4.googleusercontent.com/cTHmZlNxrkQSFGuaQv6Ru_L1g7P7W40aMPEp9j0FN1Xv9M_ub9PwxeahZG6taey1HhYmqtVBTXl2uwg5PRkLUpyz-qSb9f6xgn5BujkJx0FanbtzduEzjc4yL5rG4Ihdlxd40J3q)

{% hint style="info" %}
Whenever a flow is over, create a "Get by Hand" flow that shows the initial options for the user. Use the existing Step to always send the user to that flow.
{% endhint %}

So the action of this step is quite simple. If the flow arrives at this step, the conversation is directed to another existing step.

The primary goal of using this step is to reuse steps that have already been created and consequently not to redo steps.[<br>](https://help.cosmobots.io/help/bot-builder/fluxo-da-conversa/filtro)


# Rest API

While running the conversation flow you have the option to call any API. Just define the **Method** to be used, the API **Url**, and, if you prefer, the **Parameters** and **Type of Parameters** to be sent.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LTwEBn5aIc3l6dlfomF%2F-LTwECN7NZFQCnyGdlXn%2Fimage.png?alt=media\&token=4c32428c-546c-46c0-9bba-6c0a77b856b1)

If you want to handle the API return response, you can use **Javascript** code. The response will be available through the variable: **response\_\_x**.

If the return is a Javascript object (JSON format), when treating it in the code remember to check if it is not Null to avoid errors. And if the return is a string and you want to use it in the code as JSON, remember to convert it to JSON using the **JSON.parse (response\_\_x)**

If you want to save the return in some custom object field, remember that the JSON format is not allowed as field type. So you'll have to convert it to String, using the **JSON.stringify (return\_example)** method, and then save it. Then, if you want to use this field in the future, remember to convert it back to JSON using the **JSON.parse method (return\_example)**

{% hint style="warning" %}
There is a 15-second execution timeout. So if you pass this limit the API call will be interrupted and an error will be returned that can be queried in the conversation history.
{% endhint %}


# Javascript

Here you have the possibility to manipulate the context information of the conversation and its database using Javascript. It is ideal to set more advanced rules that would not be possible using the "Filter" step.

We mentioned a lot here about database, custom objects and records. So if you want to understand better access the [Data](/bot-builder/data) section.

Let's mention below the features available when using code:

## Conversation Context Variables

During the conversation flow, information about the context of the conversation can be saved in one of these steps or actions:

* **Text or Card Message:**
  * By 'Save Reply', the information can be a field of the User object or some other custom object. If it is the user the information will be saved directly in the database, otherwise it will be stored temporarily as a variable of the context of the conversation, being accessible through the name of the object followed by the name of the field, for example: **adress.zip**
* **Intentions:**
  * In the case of NLP, I have some intention matching, entities of this intention will be temporarily stored as context variables of the conversation, being able to be accessed added 'context.objetcs.' the name of the variable of the intentions, as an example: **context.objetcs.meal**

## Object Query and Record Update

You have the option here to query custom object records queries. To make them available during code execution. The result will be returned as array type. To access the result of a query simply add '\_\_s' to the right side of the object name, for example: **request\_\_s**

For now the query execution options are:

* **Record Limit**: responsible for limiting the number of records returned by the query.
* **Condition of Time:** if the number of records in the query is greater than the limit, it defines a return order of the records: for more recent or older.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LTwEWJ6QouJgElx779x%2F-LTwEXQlFCy_auFrmZB2%2Fimage.png?alt=media\&token=253294cf-d126-4954-b0c6-7543dcaf7a12)

In addition to the custom fields each query record will have the following system fields available:

* **id:** Record ID
* **obj\_id:** Record Object ID
* **parents:** controller object of the current object (or parent of the current object)
  * **parents.id:** Controller object ID
  * **parents.name:** Controller object name
* **grandparents:** Controller object of the controller object of the current object (or grandfather of the current object)
  * **grandparents.id:** Controller object ID
  * **grandparents.name:** Controller object name
* **createdAt:** Time (in milliseconds) of when the record was created.
* **updatedAt:** Time (in milliseconds) of when the record was updated.

Here's an example of how to handle the query return:

```javascript
// Sums the total value of the last requests of the current user
var total = 0;
for (var x in pedido__s){
   // Access one order at a time
   var pedido = pedido__s[x];

   // Within each order, accesses the Value field and adds to Total
   total += pedido.valor;
}
```

By default the **User** object record for the current user and Chat Context variables will always be available. So you do not have to query for the **User** object. To access the current **user ID** system field, just use: **user.id**. And to access, for example, a context variable called **current\_product** just use: **context.objetcs.current\_product**

Any change in the value of the custom fields of these objects will be reflected in the database after the code has been executed.

## Record Creation

You can also create new custom object records. Just set these records as javascript object type (JSON format). Remember to fill in the required fields. And when you have ready, add them to the respective object that can be used as follows: Object Name + '\_\_c', for example: **item\_of\_order\_c**

Here is an example of how to create a record:

```javascript
// Declares the variable that will have the information of the new Order Item
var novo_item_pedido = {}

// Fill in the fields of the new record
novo_item_pedido.numero = '12345';
novo_item_pedido.produto = context.objetcs.produto_id;
novo_item_pedido.quantidade = context.objetcs.produto_quantidade;
novo_item_pedido.valor = context.objetcs.produto_valor;

// Fill in the controller field that came from the querym in this case the Order ID
if (pedido__s[0]){
   novo_item_pedido.pedido = pedido__s[0].id;

   // Adds the new record to be created
   item_do_pedido__c.push(novo_item_pedido);
}
```

If you are creating a record of an object that has a Controller object (that is, it has a relationship of 1 to N), you need to enter the ID of this controller record in its field. Otherwise this record will not be created.

## Deletion of Records

There is also the option to exclude custom object records. Just do the query, as mentioned above, take the id of the records that should be deleted, and add them to the respective object that can be used as follows: Object name + '\_\_d', eg: **request\_\_d**

Here's an example of how to delete a record:

```javascript
// Scrolls all requests returned by the query
for (var i in pedido__s){

   // Identifies the request with Status Incomplete
   if (pedido__s[i].status === 'incompleto'){

      // Adds the record ID to be deleted
      pedido__d.push( pedido__s[i].id );
   }
}
```

{% hint style="danger" %}
If you are deleting a record of an object that has some Controlled object below it (that is, it has a relationship of 1 to N), all records controlled by it will be deleted as well.
{% endhint %}

## Send Text Message

There is an alternative to sending messages to the user using Javascript code. It is important for cases, for example, where message sending depends on available information after a query has been performed. Here's an example of how to send a message:

```javascript
// Defines a variable with the information needed to send the message
var message_1 = {
   type: 'text',
   text: 'O total do seu pedido atual é R$ ' + context.objetcs.pedido_total,
   quick_replies: [{
      caption: 'Confirmar',
      type: 'context_variable',
      value: {pedido_confirmado: context.objetcs.pedido}
   }]
};

// Add message to be sent
send_message.push(message_1);
```

Below is the information you need to provide to create a text message. When used in the code it must be with the JavaScript object type (JSON format).

* **type:** always put 'text'. Required.
* **text:** enter the text you want to send here. Required and 320 character limit.
* **quick\_replies:** array with information of each quick reply. Not mandatory and limit up to 10 replies.
  * **caption:** text that appears visible to the user. Required and limit of up to 20 characters.
  * **type:** can be 'text' representing simple text. Or it can be 'context\_variable' representing a JavaScript object type containing information that can be accessed during the time of the current conversation context. Required.
  * **value:** depends on the type above, if it is 'text', fill in the text here. If 'context\_variable' fill in the object in JSON format here. Required.

## Card Message Submission

Here we have the option to send messages that contain cards.

```javascript
// Defines a variable with the information needed to send the message
var message_2 = {
   type: 'cards',
   cards: [{
      title: 'Opção 1',
      subtitle: 'Detalhes da opção',
      image_url: '
https://cosmobots.io/static/media/testing.png
',
      buttons: [{
         caption: 'Selecionar',
         type: 'context_variable',
         value: {produto_selecionado: produto__s[0].id}
      },{
         caption: 'Acessar Detalhes',
         type: 'url',
         value: '
www.teste.com
'
      }]
   }],
};

// Add message to be sent
send_message.push(message_2);
```

Below is the information you need to provide to create a greeting card message. When used in the code it must be with the JavaScript object type (JSON format).

* **type:** always put 'cards'. Required.
* **cards:** array with information from each card. Required.
  * **title:** title of the card. Required and limit of up to 80 characters.
  * **subtitle:** subtitle. No Mandatory and limit of up to 80 characters
  * **image\_url:** card image url. No Required and limit of up to 120 characters.
  * **buttons:** array with information for each button. No Mandatory and up to 3 button limit.
    * **caption:**&#x74;ext that appears visible to the user. Required and limit of up to 20 characters
    * **type:** can be 'url' or 'context\_variable' representing a JavaScript object type containing information that can be accessed during the time of the current conversation context. Required.
    * **value:** depends on the type above, if it is 'url', fill here the valid url. If 'context\_variable' fill in the object in JSON format here. Required.

There is a 15-second execution time limit of the javascript code. So if you pass this limit the execution of the code will be interrupted and an error will be returned that can be consulted in the conversation history.

## Uploading Images / Attachments / Videos

You can send media via JS using the template below:

```javascript
​// Defines a variable with the information needed to send the message
var message_1 = {
   type: 'text',
   text: 'Muito obrigado, ' + user.first_name,
};
var message_2 = {
   type: 'text',
   text: 'Use esse QR code para entrar no evento:',
};
var message_3 = {
   type: 'media',
   mime_type: 'image/png',
   url: user.qr_code
};
// Add message to be sent
send_message.push(message_1);
send_message.push(message_2);
send_message.push(message_3);
```


# Email

The E-mail plugin allows you to send an automated email to the user, containing the personalized information.

![](/files/-Ldtekq4I13LqdGcgmKJ)

It is necessary that you register the E-mail service that you want to use. To do this, just click on the "+" link in the "Email Service" link.

![](/files/-LdtenMoazkHFZBCssnP)

Once this step is activated the user will receive an email!

{% hint style="info" %}
You can use the information that the user sent during the flow to send a personalized email with a general summary or to confirm a schedule.
{% endhint %}


# Human Control

If the bot is having difficulty understanding the user we recommend using this plugin. Responsible for directing the conversation so that a person can attend the user directly.

{% hint style="warning" %}
This step can only be performed as the End Step of a conversation flow.
{% endhint %}

![](https://lh4.googleusercontent.com/AralCY8MYHe4Xk_en647EjmUBm2v4J8xW3hbHhCBZ6XAXm7PRCO0k-sI_uIPvah_dAqBeUIhEo2kAIa0QhrQQzrFp0vruF6CbJkeuE6QfAtRmL_xw3Epb97_w2hDG6d1ulP804ps)

{% hint style="info" %}
You can put this option the third time the bot does not understand a message
{% endhint %}


# Webview

To enrich user interaction we use **Webview**, which is responsible for picking up or displaying information more efficiently during the conversation flow. The idea here is for the user to have the experience of being in a conversation with the bot and at the same time using features of a web or mobile application.

{% hint style="warning" %}
The Webview can be triggered during the conversation flow only through the button of a card-type message.
{% endhint %}

We are currently providing 3 types of Webviews: **Form Fields**, **Advanced**, and **External URLs**.

## **Forms Fields** <a href="#campos-de-formularios" id="campos-de-formularios"></a>

Here we have the option to present a form with fields of the User object to be filled. All behavior is controlled by the CosmoBots platform.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LTwFTW6k6WstNX8tCyR%2F-LTwFUuDQKL05W7h1TvW%2Fimage.png?alt=media\&token=2a701785-1e10-45b8-b562-cc44ed5faef9)

The **Webview Height** defines which percentage of the screen will be occupied by Webview. It is interesting to use a height that does not cover 100% of the screen, so the user will realize that he is still in chatbot.

Here is an example of how this Webview looks to the user:

![](https://lh3.googleusercontent.com/JLslKRDsmwqJTGr83AyKkI40LIJ6R1Vei3YSmAC4M46_xPztjCH1V0aRVVEbiqFJx9SjlXdN7PanBJAjKbEFCPCUEfzOwWFTV5ARP3y5rr2XgLAkVugk2FF92KgbuRFOH-f0W7Ac)

Upon completion of Webview all form data will be saved to the CosmoBots database.

## **Advanced** <a href="#avancado" id="avancado"></a>

This type of Webview has more features. And it relies on different layouts to present information to the user.

Layouts need to be populated and placed in the variable called **webview**. The following are the attributes available for all layouts:

| Atributo | Tipo          | Descrição                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| -------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| id       | String        | Identifier of the layout. Any String can be defined. **Required**.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| header   | String        | Layout header. **Required**.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| buttons  | Array         | <p>Set of navigation buttons that appear at the end of the layout. Required.</p><p>The fields are:</p><p><strong>label:</strong> button label</p><p><strong>next\_id:</strong> if it is within a Layout Set, define here the id of the next layout</p><p><strong>go\_back:</strong> if it is within a Layout Set, it defines if the button action is to go back to the previous layout</p><p><strong>required:</strong> indicates whether you need to select an item before proceeding</p><p><strong>save\_record:</strong> indicates whether to save the record of the current layout data.</p>        |
| options  | Object (JSON) | <p>Additional layout options:</p><p><strong>min\_select:</strong> minimum of items to be selected (Number)</p><p><strong>max\_select:</strong> number of items to be selected (Number)</p><p><strong>min\_item\_quantity:</strong> minimum quantity of each item (Number)</p><p><strong>max\_item\_quantity:</strong> maximum quantity of each item (Number)</p><p><strong>show\_limit\_select:</strong> shows message about the limit of items to be selected (Boolean)</p><p><strong>show\_limit\_quantity:</strong> shows message about the quantity limit of each item to be selected (Boolean)</p> |

And now we go to the details of each layout, containing examples of use:

### List and Select Item <a href="#lista-e-seleciona-item" id="lista-e-seleciona-item"></a>

![](https://lh3.googleusercontent.com/O8ikfYzlyN43bkPFpMvZ25MqQ3FinQelYm_CNpUEjUVMKaJENbTX6oftjdB6nrJ5GyAOc9CKRwe-PUeG_2OdKqw_wiETWeqb1anfYP10M4fkmLzcVTmYYvtAxcok_X5E-FpdTApf)

Here are the additional attributes for this type of layout:

| Atributo | Tipo          | Descrição                                                                                                                    |
| -------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| type     | String        | Layout type: select. **Required**.                                                                                           |
| data     | Array         | Data that will be used to assemble the list. **Required**.                                                                   |
| selected | Array         | Items already selected.                                                                                                      |
| response | String        | Name of the variable that will have the items selected after Webview is completed. **Required**.                             |
| fields   | Object (JSON) | Name of the fields used to display information about each item. Required. The options are: title, subtitle, price, currency. |

Here's an example of how to fill out this layout:

```javascript
webview = [{
   id: 'escolhe_item',
   type: 'select',
   header: 'Item',
   data: itens,
   selected: itens,
   response: 'itens',
   fields: {
      title: 'nome_produto',
      subtitle: 'descricao_produto',
   },
   options: {
      show_limit_select: false,
      min_select: 1,
      max_select: 1,
   },
   buttons: [{
      label: 'Voltar',
      next_id: 'total',
      go_back: true,
   },{
      label: 'Confirmar',
      required: true
   }]
}];
```

### List and Select Item Quantity <a href="#lista-e-seleciona-quantidade-do-item" id="lista-e-seleciona-quantidade-do-item"></a>

![](https://lh4.googleusercontent.com/wOGz-meXUmAGN5Azyk66KUdr9XFHodr__Bw_8oQH59j5zuvJ4j62BqQeKAc_5RmBzzAq8x5yBoE7nVMmoBXXufB-dJ5q3CxNJsB7cd_zVNe2mUT3LMmgn4j0rbPsTUTb4Ff2pIzq)

Here are the additional attributes for this type of layout:

| Atributo | Tipo          | Descrição                                                                                                                                  |
| -------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| type     | String        | Layout type: select\_product\_quantity. **Required**.                                                                                      |
| data     | Array         | Data that will be used to assemble the list. **Required**.                                                                                 |
| selected | Array         | Items already selected.                                                                                                                    |
| response | String        | Name of the variable that will have the items with the quantities selected after Webview is completed. **Required**.                       |
| fields   | Object (JSON) | Name of the fields used to display information about each item. **Required**. The options are: title, subtitle, quantity, price, currency. |

Here's an example of how to fill out this layout:

```javascript
webview = [{
   type: 'select_product_quantity',
   header: cabecalho,
   data: lista_produtos,
   selected: context['itens_pedido'] | [],
   response: 'itens_pedido',
   fields: {
      title: 'nome',
      subtitle: 'descricao',
      image_url: 'url_da_imagem',
      quantity: 'quantidade',
      price: 'valor',
      currency: 'BRL',
   },
   options: {
      show_limit_select: false,
      min_select: 1,
      max_select: 2,
      show_limit_quantity: false,
      min_item_quantity: 1,
      max_item_quantity: 5,
   },
   buttons: [{
      label: 'Confirmar',
      required: true
   }]
}];
```

## List and Select Adress

![](https://lh4.googleusercontent.com/TWTHgBWFNLsL7j03zaFqLx24H14oEZEHmFmiONhY6X_Fh6FTDaHPeSlFVu9Xm9UfJ6tWCqmUHspJB4d6TWiz33Wviv9rTtaUN6lopDt7oVdvlLfF2YMVw5R_Pl-i-dFcGt_DYuv6)

Here are the additional attributes for this type of layout:

| Atributo | Tipo          | Descrição                                                                                                                                                                |
| -------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| type     | String        | Layout type: select\_address. **Required**.                                                                                                                              |
| data     | Array         | Data that will be used to assemble the list. **Required**.                                                                                                               |
| selected | Array         | Address record already selected.                                                                                                                                         |
| response | String        | Name of the variable that will have the address record selected after Webview is completed. **Required**.                                                                |
| fields   | Object (JSON) | Name of the fields used to display information about each address record. **Required**. The options are: street, number, complement, neighborhood, city, state, zipcode. |

Here's an example of how to fill out this layout:

```javascript
webview = [{
   id: 'escolhe_endereco',
   type: 'select_address',
   header: '2. Escolhe Endereço',
   data: enderecos,
   selected: context ? context['endereco'] : [],
   response: 'endereco',
   fields: {
      street: 'rua',
      number: 'numero',
      complement: 'complemento',
      neighborhood: 'bairro',
      city: 'cidade',
      state: 'estado',
      zipcode: 'cep',
   },
   options: {
      show_limit_select: false,
      min_select: 1,
      max_select: 1,
   },
   buttons: [{
      label: 'Voltar',
      next_id: 'itens_pedido',
      go_back: true
   },
   {
      label: 'Novo Endereço',
      next_id: 'novo_endereco'
   },{
      label: 'Próximo',
      next_id: 'total',
      required: true
   }]
}];
```

### List of Orders <a href="#lista-pedidos" id="lista-pedidos"></a>

![](https://lh6.googleusercontent.com/-ITuld7RJg6gabyrMIswygQ35uMF7qnnT4jJQL1EtSqHpWoq9O_kRHCuguXzhmEDlr0iyXhah5jNiv08oXzDbkVZ2npPmUjF6uTEwFUoa-B5MnExY5xZlu-E8lezV1FH20_QAthp)

Here are the additional attributes for this type of layout:

| Atributo | Tipo          | Descrição                                                                                                                                                                                                  |
| -------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| type     | String        | Layout type: list\_orders. **Required**.                                                                                                                                                                   |
| data     | Array         | Data that will be used to assemble the list. **Required**.                                                                                                                                                 |
| fields   | Object (JSON) | Name of the fields used to display information about each item in the list. **Required**. The options are: order\_number, status, confirmation\_date, payment\_method, subtotal, freight, total, currency. |

Here's an example of how to fill out this layout:

```javascript
webview = [{
   type: 'list_orders',
   header: 'Meus Pedidos',
   data: pedido__s,
   fields: {
      order_number: 'codigo',
      status: 'status',
      confirmation_date: 'data_confirmacao',
      payment_method: 'forma_de_pagamento',
      subtotal: 'valor_subtotal',
      freight: 'valor_frete',
      total: 'valor_total',
      currency: 'BRL'
   },
   buttons: [{
      label: 'Ok',
   }]
}];
```

## Total

![](https://lh6.googleusercontent.com/JyMvXgRqiDtCLDtE3UhgQC5WRhH7jF_iQgG1IgaCKTCBJNXyQzJ3G6c4JIwpwsGH3o5fmuyB0oD3r_YoOZCIpIjCURoQJm2KgkA86duLI2zHHCOrrwSkqiySJ-FOfvN8W5R0elfc)

Here are the additional attributes for this type of layout:

| Atributo | Tipo          | Descrição                                                                                                                                                    |
| -------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| type     | String        | Layout type: show\_total. **Required**.                                                                                                                      |
| response | String        | Name of the variable that will have the information about the total values after Webview completes. **Required**.                                            |
| fields   | Object (JSON) | Name of the fields of the selected items that will be used to calculate the total values. **Required**. The options are: freight, price, quantity, currency. |

Here's an example of how to fill out this layout:

```javascript
webview = [{
   id: 'total',
   type: 'show_total',
   response: 'total',
   header: '3. Total',
   fields: {
      freight: 15,
      price: 'valor',
      quantity: 'quantidade',
      currency: 'BRL',
   },
   buttons: [{
      label: 'Voltar',
      next_id: 'escolhe_endereco',
      go_back: true
   },
   {
      label: 'Próximo',
      next_id: 'escolhe_pagamento',
   }]
}];
```

## New Record

![](https://lh3.googleusercontent.com/q0wDD2tuKi0oC2b5OUNm2WuC2DfurwdoL7o6CasEZGlccEPXY__ZjLsb7Pn-k8te14aBJBV7s6smw9_dgKBe1YMzeDZtj4imy3XcphabeUZO_WJDqZPqpPHuDuGokO2lQS4C2XsH)

Here are the additional attributes for this type of layout:

| Atributo | Tipo          | Descrição                                                                                                                                                                                                                                                  |
| -------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| type     | String        | Layout type: new\_record. **Required**.                                                                                                                                                                                                                    |
| response | String        | Name of the variable that will have the new record information after Webview is completed. **Required**.                                                                                                                                                   |
| fields   | Object (JSON) | Name the fields of the new record to be created. **Required**. The options depend on which fields you want the user to fill. As an example of creating a new address, the fields would be: street, number, complement, neighborhood, city, state, zipcode. |

Here's an example of how to fill out this layout:

```javascript
webview = [{
   id: 'novo_endereco',
   type: 'new_record',
   object: 'endereco',
   header: 'Novo Endereço',
   response: 'endereco',
   fields: {
      street: 'rua',
      number: 'numero',
      complement: 'complemento',
      neighborhood: 'bairro',
      city: 'cidade',
      state: 'estado',
      zipcode: 'cep',
   },
   buttons: [{
      label: 'Voltar',
      next_id: 'escolhe_endereco',
      go_back: true
   },{
      label: 'Próximo',
      next_id: 'total',
      save_record: true,
      required: true
   }]
}];
```

## Layouts Set

And finally, we have the option of defining a Layout Set. It would be like a step by step that the user needs to follow to complete the Webview. To do this simply add each layout inside the [webview](/bot-builder/conversation-flow/webview) variable to the order that you want them to appear to the user.

Here is an example where the scenario here would be to finalize a purchase:

```javascript
webview = [{
   id: 'itens_pedido',
   type: 'select_product_quantity',
   header: '1. Itens do Pedido',
   data: context['itens_pedido'] | [],
   selected: context['itens_pedido'] | [],
   response: 'itens_pedido',
   fields: {
      title: 'nome',
      subtitle: 'descricao',
      image_url: 'url_da_imagem',
      quantity: 'quantidade',
      price: 'valor',
      currency: 'BRL',
   },
   options: {
      show_limit_select: false,
      min_select: 1,
      max_select: 10,
      show_limit_quantity: false,
      min_item_quantity: 0,
      max_item_quantity: 5,
   },
   buttons: [{
      label: 'Próximo',
      next_id: 'escolhe_endereco',
      required: true
   }]
},
{
   id: 'escolhe_endereco',
   type: 'select_address',
   header: '2. Escolhe Endereço',
   data: enderecos,
   selected: context['endereco'] | [],
   response: 'endereco',
   fields: {
      street: 'rua',
      number: 'numero',
      complement: 'complemento',
      neighborhood: 'bairro',
      city: 'cidade',
      state: 'estado',
      zipcode: 'cep',
   },
   options: {
      show_limit_select: false,
      min_select: 1,
      max_select: 1,
   },
   buttons: [{
      label: 'Voltar',
      next_id: 'itens_pedido',
      go_back: true
   },
   {
      label: 'Novo Endereço',
      next_id: 'novo_endereco'
   },{
      label: 'Próximo',
      next_id: 'total',
      required: true
   }]
},
{
   id: 'novo_endereco',
   type: 'new_record',
   object: 'endereco',
   header: '2. Novo Endereço',
   response: 'endereco',
   fields: {
      street: 'rua',
      number: 'numero',
      complement: 'complemento',
      neighborhood: 'bairro',
      city: 'cidade',
      state: 'estado',
      zipcode: 'cep',
   },
   options: {
   },
   buttons: [{
      label: 'Voltar',
      next_id: 'escolhe_endereco',
      go_back: true
   },{
      label: 'Próximo',
      next_id: 'total',
      save_record: true,
      required: true
   }]
},
{
   id: 'total',
   type: 'show_total',
   response: 'total',
   header: '3. Total',
   fields: {
      freight: 15,
      price: 'valor',
      quantity: 'quantidade',
      currency: 'BRL',
   },
   buttons: [{
      label: 'Voltar',
      next_id: 'escolhe_endereco',
      go_back: true
   },
   {
      label: 'Próximo',
      next_id: 'escolhe_pagamento',
   }]
},
{
   id: 'escolhe_pagamento',
   type: 'select',
   header: '4. Pagamento',
   data: forma_de_pagamentos,
   selected: context['pagamento'] | [],
   response: 'pagamento',
   fields: {
      title: 'label',
   },
   options: {
      show_limit_select: false,
      min_select: 1,
      max_select: 1,
   },
   buttons: [{
      label: 'Voltar',
      next_id: 'total',
      go_back: true,
   },{
      label: 'Confirmar',
      required: true
   }]
},
];
```

## External URL

There is also the option of having Webview originated in some external URL to CosmoBots. So the control would not be on the CosmoBots platform but could use a step following it to, for example, call an API to query or update information from the context of the conversation.[<br>](https://help.cosmobots.io/help/bot-builder/fluxo-da-conversa/pessoa-no-chat)

![](https://lh6.googleusercontent.com/91_X22tJHUH5NWSVAkyk0Sdcs5TlB9ji3j7goTnBnY9qRMLuXwEa2pkaQXjtGA2TXqduEl5hdWPE2gtRqtKTfGJ7u_ARGHdo7jFnUAg5PJhCdjQcUu67iyL2AjLEYf-At1vur0kO)


# Forward to another bot

With this plugin, you have the possibility to at some point in your flow you forward the user to another bot.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LTwEirBaNckPY1lehrg%2F-LTwF3-XErS5ykkaHfma%2Fimage.png?alt=media\&token=cb378815-983d-4ec7-b01a-4dc86e8bed30)

{% hint style="warning" %}
This step can only be performed as the End Step of a conversation flow.
{% endhint %}


# Test Bot

During the construction of the conversation flows you always have to layout a way to test the bot.

To access, just be on the Chat Flow page, and click on a circle at the bottom right of your screen, written **Test**.

![](https://lh4.googleusercontent.com/KfDB9IcuIEhux8oczli9oZW1lGPzMa89B-nD1pnGMGGqzcFdiQmR8O5lXq58843lis2PKkRFe8RN5yh_XBHZ64ndOI-3TMzZh9J-Uc79cB10dcutaONe1S6xfjog77UXwnd_3GZj)

This test is done in a web version, similar to what you can put on your website ([web widget](/bot-builder/channels/chat-widget)). It is ideal to validate that the steps of the flow you are creating are actually behaving as expected.[<br>](https://help.cosmobots.io/help/bot-builder/fluxo-da-conversa/encaminha-a-outro-bot)

![](https://lh4.googleusercontent.com/eAD5ElQn_nlxv7AthWcqC6jYhOZ5fGJtD2BrJfRZoLi29j3jvVXLj62TRINtZEL2rjuS9OeXOhnKENV-ChYO0fze13ii0QRupopIEkUSBhMxnve7ZJ2SQBoB4io4_m0VqmEOOGJ3)


# Time Action

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-Lc6apBHoPZ753s7UK5T%2F-Lc6avVJU6vDXKHn1Wwr%2FScreen%20Shot%202019-04-10%20at%2011.15.49.png?alt=media\&token=670cefab-1868-4e91-b3b5-79d9f096030a)

The time action is a function that serves for the Bot to send a message (Push) to the user if it is 10 minutes ago without interacting with the Bot. It functions as a Timer, which reminds the user to interact with the Bot.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-Lc6apBHoPZ753s7UK5T%2F-Lc6c7lLUdAVIc2FhMFk%2FScreen%20Shot%202019-04-10%20at%2011.21.46.png?alt=media\&token=5ac418b1-1bd5-424e-b351-c810b4c6b6f0)

In addition to Repeating a Step, it can still start the next step, go to a specific step, or Disable Existing Action\![<br>](https://help.cosmobots.io/help/bot-builder/fluxo-da-conversa/testar-bot)


# NLP

Let's now configure the intelligent part of the bot, the artificial intelligence (NLP). We set NLP [in this section](/bot-builder/nlp) in case you are lost.

During a conversation, when the user does not click buttons or cards, but writes something and sends the bot. This message is processed by the bot so that it can understand the user's intent and perform an action according to that intent.

But before we can better explain how the bot treats these Intentions, let us first explain what Entity is.


# Entity

Entities are very important information contained in the text message sent by the user. Extracting Entities is an important feature of NLP.

If Intent is to understand "what the user is wanting". Entity is to understand "about what the user is talking about".

Let's give an example to see if it gets clearer. Assuming we have a bot that accepts pizza orders, during the conversation the user can ask for something like:

"I want a **large pizza** of **pepperoni**"

Here we have 3 values that can represent the following entities:

* **Meal**: represented by "pizza".

![](/files/-Ldtqg3DfsDLJ7Hszr6Y)

* **Size**: represented by "large".

![](/files/-Ldtqhpmm_Uvwjv_HEOq)

* **Meal Option:** represented by "pepperoni".

![](/files/-LdtqkTgfSTDZrge5e0i)

So if the user's intention here is to want to make a pizza request (something that we will understand better in [Intentions](/bot-builder/nlp/intent)), the bot would understand the entities as follows:

*"The user wants a **meal** (pizza) of a c**ertain size** (large) and a certain **meal option** (pepperoni)."*

The **Main** column tells you that the first option of each value will be used by default and helps you maintain consistency of information if any of these values are saved in your database.


# Intent

As mentioned before, Intent is to understand "**what** the user is wanting". Therefore knowing how to identify the intentions of the user during a conversation is essential so that the attendance can flow naturally.

To start using Intentions in the bot, my suggestion is to first list the main intentions the user might have when talking to the bot.

For example, if the bot is responsible for serving a restaurant and jotting down the orders, these could be examples of intentions:

* **Show Menu**
* **Meal Request**
* **Order Closing**

Also understand that the Intention must be directly related to an action (or step) of the conversation flow. That is, once we identify the Intention of the user, an action must be performed to serve this Intent.

Okay, let's first understand how to identify an intention, then we come back to this action.

## Message Samples

For bot to understand how to identify an intention we need to include some samples of messages (or examples) of how the user could express about this intention.

So we included 3 to 10 samples just to "teach" the bot to understand that when he reads a message similar to this, he should consider the intent of this sample. How similar the bot should consider will be defined in the **Matching Probability** field.

When placing each sample message, if you have registered the entities, an extraction is done just below the message to validate how it will be done when the user sends a similar message.

![](/files/-Ldtrc8i0FHsJRINwVg5)

![](/files/-Ldtrd_4gwEw6u9rmwbe)

## Variables of Intention

At the same time that you define message samples, you also define the variables that can be made available for this Intent.

Using the samples from the example above, we have:

![](/files/-LdtrgYae1pXhkJ_AP5W)

The variables can be used, for example, in the Flow Plugin step Javascript. Just make reference added 'context.' the front of the variable name.&#x20;

{% hint style="warning" %}
The variables will be available only during the time of the current context, so after the [context timeout](/definitions#conversation-context) these variables will be cleared.
{% endhint %}

## Intention Actions

At the end, when the intent identification is completed and the possible variables defined, an action of the Flow is indicated to be executed, in order to proceed in the service to the user.

![](/files/-LdtriU22fom7ZvzhUcS)

## Summing up

Good considering that you have already registered one or more intentions. Let's summarize now how bot deals with this.

When the user sends a text message the bot performs 3 steps:

1\. Query between registered intentions, and evaluate which intention best represents the message. This evaluation is done by comparing the message with all samples (or examples) of messages and calculates if the probability of Matching is greater than or equal to that defined in the intention register.

2\. Given matching, the intention is chosen with the highest matching, and verifies if this intention has **Intention Variables**. These variables are responsible for identifying Entities and their respective values. This variable can be accessed within the conversation stream later, by accessing the context object.

3\. To conclude, a conversation flow action is performed to continue the conversation with the user.


# Channels

After the created flows and defined NLP, it is time to launch the bot for its users.

An important point here is: **everything created in the bot (Flows and NLP) will serve any channel**. So CosmoBots follows the Omni-Channel concept, the user experience with the bot must be the same regardless of which channel it accesses.

For now we are offering integration for 4 channels. But we are working to launch more channels soon.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LWGge974aSqmlxc1vQU%2F-LWGgevZoUQUYu73ohB4%2Fimage.png?alt=media\&token=3c8bc000-7105-4c57-a12f-8dcdeed45069)


# Google Assistant

## Creating your project in Actions Console

In order for us to link your Bot to Google Assistant, we'll first need you to create a project in the Google Actions Console (<https://console.actions.google.com/u/0/>). Log in with your Google account and remember to put the project in Portuguese - Brazil and the locality in Brazil "

![](/files/-LdtyB-lAT-lWSFyvIxn)

With your project created, click on the "Actions SDK"

![](/files/-LdtyDEiuwZYyHiDiZNd)

## Gactions

Now, with your project created, let's prepare your PC / Mac to get Gactions commands, so we can link your Bot with your project in Google Actions.

First go to: <https://developers.google.com/actions/tools/gactions-cli> and download Gactions for your operating system.

![](/files/-LdtyFa392mnObpVoymF)

{% hint style="info" %}
To find out the version of your MAC, open the Terminal and type "uname -a
{% endhint %}

With Gactions downloaded, place it in a folder of your choice. Now we have to make it become an executable:

* **Windows:** \
  Let's use the Downloads folder as an example, gactions.exe will be there, first open the Terminal as Administrator (type cmd in the search and open the Command Prompt as administrator), now type in the console "cd DOWNLOAD FOLDER PATH". Ex: cd C:\Users\Teste\Downloads\
  \
  Now, we are inside the downloads folder, run the "gactions.exe init" command, this will create a .json inside the downloads folder that will not allow us to use the gactions commands.\ <br>
* **Mac:**\
  Let's use the Downloads folder as an example, gactions.exe will be there, first open the Terminal (cmd + space bar and type Terminal), now type in the console ls and then cd Downloads\
  \
  &#x20;Inside the Downloads folder execute the command "chmod + x gactions", this will make the gactions an executable binary, execute it (double clicking on the file) and return to the terminal. This will install the gactions commands on your machine.\
  \
  Finally, it still does not end, type: ./gactions init, this will create the file action.json

## Editing Json

With json, action.json installed, open it as notepad / text so we can edit it with your project information.

Before we start editing it, we'll get the url from the Channels-> Google Actions tab of CosmoBots.

![](/files/-LdtyHRi6K8Gpx7hCriB)

Below you have a sample json file filled in, in "URL" you will use the URL present on your Google Assistant page in CosmoBots (as explained above).

![](/files/-LdtyIs5Da6HonHdtnC-)

With json edited, return to the terminal and do the following:

* **Windows:** \
  At the terminal, enter the code below:

  gactions update --action\_package PACKAGE\_NAME.JSON --project PROJECT\_ID\
  Where in PACKAGE\_NAME.JSON you will enter the name of your Json and PROJECT\_ID will be the ID you were informed in Actions SKD, done in the first step.
* **Mac:** \
  At the terminal, enter the code below:

  ./gactions update --action\_package PACKAGE\_NAME.JSON --project PROJECT\_ID\
  Where in PACKAGE\_NAME.JSON you will enter the name of your Json and PROJECT\_ID will be the ID you were informed in Actions SKD, done in the first step.

Once this is done, he will ask for a token and will inform you of a Link. Enter this link, log in with the Google account where the project is and paste the token into the terminal.

By placing the Token, go back to the Google Actions Console page and enter your project, it will already be linked to your Bot.


# Facebook

The integration with Facebook Messenger allows the bot created to be responsible for all the conversation initiated in this channel. Be a user by logging into your Facebook page or chatting directly through the Facebook Messenger application.

The first step of the integration is to click on the **Login with Facebook** button so CosmoBots can have access to your page. This access is necessary so that the page can be configured to accept the conversations with the bot created in CosmoBots.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LTbcoFQEG3rkUfEVnoe%2F-LTbcp7eflZ7Qt6ugc2n%2Fimage.png?alt=media\&token=e4495383-47ed-4d44-9ec9-dccc9925b1ca)

The second step is to choose your Facebook page. Because you can have multiple pages, the purpose here is to define which page will be used by the Bot. By confirming this step Bot will already be available for conversations on your Facebook. If you want to revoke this access, simply go back to the previous step and click Revoke.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LTbcoFQEG3rkUfEVnoe%2F-LTbdb09M3opRaqIGMoo%2Fimage.png?alt=media\&token=c4fe0a42-b9ef-480e-84bf-107d0fa5ea67)

The third step is to set a welcome message for when the user first interacts with your Bot. That is, when it clicks the **Get Started** button.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LTbcoFQEG3rkUfEVnoe%2F-LTbdfBXqIQy1FmAglPF%2Fimage.png?alt=media\&token=b535f4b4-61c9-4695-a408-b5a8669fb454)

The fourth step is to define a menu with options that will always be available to the user during the bot conversation. The idea is that it serves as a shortcut for the user if he wants to change the subject of the conversation considerably.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LTbcoFQEG3rkUfEVnoe%2F-LTbdj5IzSwk0f202MrO%2Fimage.png?alt=media\&token=162d7cf3-21a4-46f5-815f-b17f9bccc919)


# Workplace

Workplace integration allows the created bot to be responsible for all conversation initiated on this channel. For all users present in your Workplace.

For this we will need 3 Tokens, the **App ID**, **App Secret** and **App Access Token**. Let's teach you step by step how to get them.

![](/files/-Ldu-ZxJQD6CgPrnD-fJ)

## Creating the APP in the Workplace

Go to **Integrations** in the control panel of the company.

![](/files/-Ldu-Yap6X4V9uf0KGmu)

At the bottom of the page click **Create Custom Integration**

![](/files/-Ldu-XOSgh1Mzs6kQMjL)

## Obtaining the Secret APP and APP Access Token

As soon as you create your APP, a dialog box will appear and in it you will find your **App Secret** and **App Acces Token**

![](/files/-Ldu-Vgn7VRnv8RMcw7s)

Click Create Access Token and another dialog box will appear. In it you will find your **App Access Token**

![](/files/-Ldu-T_Z7LNCfVMfEVsE)

Finally, in the Permissions section select the Read content and Message any member options.

![](/files/-Ldu-RZBb7XJy9XvBGEk)

## Obtaining your APP ID

Now with your created APP and generated token, you will find your **App ID** in the messages.

![If it is not there, enter into integrations and send a message for its integration](/files/-Ldu-IPuNM4nDd7hnNGV)

![](/files/-Ldu-GrVoUldbT826xOE)

The **App ID** is at the page address.

Okay, with the 3 Tokens you just need to insert them into the Workplace area on the CosmoBots Channels and you will have your bot integrated into that [channel](/bot-builder/channels).


# Chat Widget

Here you also have the option of placing the bot available on your site. So just copy the code below and add to the code of the page of your site.

For now we are offering some minimal settings on how your bot will appear on your site, but we are working to offer more customization options soon.

![](/files/-Ldu0QEEEGoD66UDSuXp)

When the user logs in the first time, he will have a form with 3 fields to fill in (as below), before starting the conversation with the bot. For now we define these fields as essential to have the user's contact. But soon you will have the option to remove these fields and / or add other fields.


# Data

Let's set up the Cosmo database now. Here you can store the data of the conversation, be it information of the users or information related to the users.


# Objects

Objects represent a set, or type, of information. For example, if you want the bot to access a list of products, first we need to create an object called **Product** and then create fields within this object that define the properties of this product, for example: Name, Color, Size, etc.

For developer readers, objects are similar to a database table.

## **Standard Objetcs** <a href="#objetos-padroes" id="objetos-padroes"></a>

There are now 2 standard objects in the Cosmos:

* **User**: refers to user properties. Here are the standard fields:
* &#x20;\- First Name \
  \- Last Name \
  \- Email \
  \- Telephone \
  \- Age \
  \- Language \
  \- Sex
* **Conversation**: refers to the messages exchanged with the user during the conversation. Here are the standard fields:
* \- User (related to the User object)\
  \- Channel (Website, Facebook, etc...) \
  \- Duration (Duration of current conversation context) \
  \- First Message (Time) \
  \- Last Message (Time) \
  \- Messages (List all messages in the context of the current conversation) \
  \- Message (Message sent by the user) \
  \- Perception (Sets message characteristics, including NLP) \
  \- Steps (The steps covered by the current message) \
  \- Time (referring to sending the message)

Of the 2 objects above, only in User can create custom fields.

## Creating Custom Object <a href="#criando-objeto-personalizado" id="criando-objeto-personalizado"></a>

And of course you can create new objects, with custom fields, related or not to each other.

To create, simply go to the **Data** tab and click **New Object**.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LTwUXNyWdseK-KZJ7hu%2F-LTwUYcZwCrWLPWbgf3i%2Fimage.png?alt=media\&token=35c9c210-e45d-490e-8f55-97e46191a2cd)

Here, for example, we are creating the Request Object and defining that the Controller Object is **User**, that is, we want 1 user to have 1 or more related requests. Therefore to exist 1 request there must be 1 user.

In the Cosmo, for now, you can have an object with at most 2 levels of hierarchy if the controller object is **User**, and at most 1 level of hierarchy if the controller object is a custom object.

The hierarchy level here is defined as the relationship between an object and its controller object. That is, a parent object relationship to child object, where a parent record can be related to 1 or more child records. Therefore considering 2 levels we would have: Object Grandfather> Father Object> Son Object.

CAUTION: With this controller object model, if you delete any record from the controller object, for example the user, all records controlled by this user record are also deleted.

### Editing Custom Object <a href="#editando-objeto-personalizado" id="editando-objeto-personalizado"></a>

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LTwUXNyWdseK-KZJ7hu%2F-LTwUoF_LFMxG0Idt6uW%2Fimage.png?alt=media\&token=ad2a7736-2525-4f3a-b9a4-e4bd7e0d3f82)

The **Name** field refers to how this field can be used as a reference in the conversation flow.

The **Controller object** can not be changed after the object is created.

The **Reference Field** means which field is used when the request appears in the search list or is referenced in other objects. In the example above, the order record will be represented by the Order Number field.

{% hint style="danger" %}
Remember that in case you need to download your custom objects, you need to follow a [JavaScript](/bot-builder/conversation-flow/javascript) code, which you can find [here](/bot-builder/conversation-flow/javascript).
{% endhint %}

​[<br>](https://help.cosmobots.io/help/bot-builder/dados)


# Fields

## Creating Custom Fields

When you enter the object, you may notice a button in the top bar called Fields. By clicking we can create new fields or edit existing fields.

Here are the information we can define about the field:

\- **Field Label:** visible in page layouts\
\- **Field Path:** to be used in code\
\- **Field Type and Subtype:**\
&#x20;   \- **Text**\
&#x20;       \- Free\
&#x20;       \- Email\
&#x20;       \- Phone\
&#x20;       \- Address\
&#x20;   \- **Number**\
&#x20;       \- Free\
&#x20;       \- Currency\
&#x20;   \- [**Booleano**<br>](https://pt.wikipedia.org/wiki/Booleano)    - **Options**\
&#x20;   \- **Date Time**\
&#x20;       \- Date\
&#x20;       \- Date Time\
&#x20;   \- **Reference**\
\- **Field Size:** when the type is Text, the character size limit can be set\
\- **Decimal:** When the type is Number, you can define how many decimal places the number has\
\- **Options:** when the type is Options, the options available in that field can be set. Each line represents an option\
\- **Layouts:** the field can be visible in 3 types of layouts\
&#x20;   \- Record: refers to the record page when accessed through the Data tab\
&#x20;   \- Search: refers to the object page of this record that contains a table with all records.\
&#x20;   \- Message Center: Referring to the support agent page in the chat with the user\ <br>

## Defining Page Layouts

You can also change which fields are part of each layout by going to the Object page and directly accessing the button called **Page Layouts** directly in the top bar.


# Integrations

With the Integrations section, you can access CosmoBots from another system or link analytics from Chatbase or Dashbot.


# API

API Integration allows you to access CosmoBots from another system, serving as a channel that is responsible for processing the sending and returning of messages between the user and the bot.

First you must choose which type of API you want and Enable it.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LU10bAJrdMZA4C4Fm5u%2F-LU1109roEzXSC8hDAzu%2Fimage.png?alt=media\&token=b040e37f-7010-4cfd-8466-dcf7dfcf7386)

There are four API types: Messages, Conversations, Intentions and Users.

Below you will have a summary of the chosen API, with the method type, API Url, a brief description and the version.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LU10bAJrdMZA4C4Fm5u%2F-LU11Sh5h-Vqc3bj4ZDj%2Fimage.png?alt=media\&token=736549bf-c3a8-4a59-bd9b-10729411e0e3)

## &#x20;Authentication <a href="#autenticacao" id="autenticacao"></a>

In this section you will have the botid and token required to perform the authentication.

| Nome  | Tipo   | Descrição                                                                                                                                           |
| ----- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| botid | string | ID of your bot on CosmoBots: 1866e980-d661-15e7-b7bf-cb2aa1b94640 (**Illustrative ID**)                                                             |
| token | string | Token key specific to this bot, and can be used in any of the available API services: 2973f350-06db-11e9-92ad-5b7ab3d1568c (**illustrative token**) |

## Parameters <a href="#parametros" id="parametros"></a>

| Nome | Tipo    | Descrição                                                                                                                                                                                                         |
| ---- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| uid  | string  | ID of the user who talks to the bot. If it is a new user sending the first message send 'new\_user'.                                                                                                              |
| user | object  | If you are a new user, you have the option to send the following default user fields: first\_name, last\_name, email                                                                                              |
| type | string  | Type of message being sent. There can be 5 options: text (plain text), payload (response to clicking a button, for example), image (content of an image), audio (content of an audio), video (content of a video) |
| time | integer | Date / Time in milliseconds when the message was sent.                                                                                                                                                            |
| data | object  | Depending on the type of message defined above, the content / value of this data will be placed here.                                                                                                             |

## Return <a href="#retorno" id="retorno"></a>

| Nome | Tipo    | Descrição                                                                                                                                                                                   |
| ---- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| uid  | string  | ID of the user who talks to the bot. In return, the ID created for this user will be entered and used in subsequent calls.                                                                  |
| time | integer | Date / Time in milliseconds when the message was processed.                                                                                                                                 |
| data | object  | This will place an array containing 1 or more data types returned. There are 6 options of type: text, text\_buttons, cards, image, audio (content of an audio), video (content of a video ) |

## Examples <a href="#exemplos" id="exemplos"></a>

The examples section is for you to understand and test, you can test a Simple Text, Text with Buttons and Cards. Taking into account the two tables above Parameters and Return, let's look at the example below:

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LU5cqKG0ucAVXJnlv6W%2F-LU5dIyrk7ASdJW_sAvs%2Fimage.png?alt=media\&token=a2b23f28-e78e-4538-b4a5-2cbdb7a32dc6)

In that case we sent the bot a "Hey There" type text. Now let's see how the Return will work:

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LU5cqKG0ucAVXJnlv6W%2F-LU5dY6zbqK7a60UdcNz%2Fimage.png?alt=media\&token=a6963603-806b-4109-bb7b-f95962d23e8c)


# Analytics

Here you can integrate all the conversations of the bot with [Chatbase](https://chatbase.com/) or [Dashbot](https://www.dashbot.io/), you just need to insert the Token API.

![](/files/-Ldu5g6Oc2PYSoLvWYHC)


# RD Station

## **Introduction**

By integrating with RD Station, you'll be able to collect crucial information from your Lead during the flow and save directly to RD!

First, you must already have an RD Station account, having an account created just go to Cosmo and select the "Integrations" tab and choose the "RD Station" option.

![](/files/-LsqrMajRYTCAAVPSZ8x)

Here you will be able to **connect with your RD account**, just click "Start". Having this account connected, we can start connecting the points in the flow where we will save Lead information.

{% hint style="danger" %}
If the option does not appear, press Ctrl + Shift + F5 (Windows) or Cmd + Shift + R (Mac)
{% endhint %}

## **Saving Information**

Let's say you want to ask what color is your Lead's favorite. To do this, let's go to the message flow step where you want to get this information and click "[Save Reply](/bot-builder/conversation-flow/message)". Now let's create the favorite color field in the **User object** by clicking "New Field”

![](/files/-LsqrjTvcUp1jwLHkFJh)

{% hint style="danger" %}
Attention: Always create new fields in the User object, it is the only object that works with RD Station integration.
{% endhint %}

With this information saved, we should go to the RD Station platform and create a new field of the same name in the new Leads information. To create a custom field, select "Convert", then "Custom Field" and finally "Create Custom Field”.

![](/files/-Lsqs6K307qmuhDs0Vp7)

With this new field created, we can go back to the RD Station tab and select the "+ Add Field" option.

![](/files/-Lsqs_aFGwDbiXB_A0he)

Here, we will relate the field we created in CosmoBots with the field created in RD Station.

Ready! Having this, every time the user goes through that point of the flow, and tells us its favorite color, it will be computed in the Lead present in the RD Station.

{% hint style="danger" %}
Attention: It is always necessary to request the user's email, either in the form or during the flow. Email is the way RD registers a Lead.
{% endhint %}


# Dashboard

The Dashboard is responsible for the analytical data of your bot!

They are vital to the success of your bot. The insights you can get by analyzing this data allow you to improve and streamline your flows, relate the right message to the user, and find out where the user is missing out.

In addition, you can filter by the date you want and even include your own analytics in the integrations tab, just inform the Token API.

In the "users" tab we have the number of users that interacted with the bot that day. They can be new users (represented by blue color) and user recurring (represented by green color).

![](https://lh4.googleusercontent.com/zzcFbK0dkcRyswu3vcOQfMV_xC2KNyuHEGoos80Ys75PROXV5E0sI_szUdMLLa1BGBpkkNnTKLlOMPcP4sibPeu9X8ym8Zlw-PEq4wKf-6_ueu_2CtufdVgh2OrlMt5tAGiUaAlb)

{% hint style="info" %}
By clicking on the "\~" underneath the graph, you can turn off one of the colors to see the other more accurately.
{% endhint %}

Beside user analytics, we have a general summary about them and the channels they were using.

![](https://lh3.googleusercontent.com/8ImjP-ptY2ItHJXJJnJW7qS56hpf533TiydJMyf6LakJZEKmKpDOBV0Udll9JGubICzm_2erjjT7D0WYEgpP44WweU_DMlV2GhT9TzzsWbQTH-D47EoEa-acrtvgQxQNFJeUioEf)

You can create a custom funnel in the "Custom Funnel" tab, you choose a condition, a flow and a part of the stream you want to analyze. In the example below we create a funnel to see how many users are going to the Exception flow.

![](https://lh3.googleusercontent.com/B8KGxGeZ7xI8Za0Lg9wi549dhYXhiqzdUvEwUlz2XtPx2ylTZ_H22ue1k4__lOado6CHHjWQ1etI5EfDkN7MXmFRrxQMnU6o9Ua3XDCPX5JWU3RNwMdDUKPNoDc1CFVHNKHbj64u)

By creating this funnel, the analyst will only tell you about the condition you have chosen.

![](https://lh4.googleusercontent.com/uHfOf7fDD46x6sJSMYEBGTiE_JnRZBslUbUVwtv-zwQxO4fyJiVrYQXvQ0N342B5yZ8vEveJFxXxkaDf7lj8ma8qSyEXfryzDaBfUTLA_tNmpPYHC5BXMpiwWDrj0psr40bif_NN)

{% hint style="info" %}
An "exception funnel" is very useful for you to know how many users are going to the "I do not understand".
{% endhint %}

Below the analytics of users, conversations and personalized funnel we have those of intentions, in it we have a frequency of how many users went through a certain part of the flow. Beside we have the unrequited intentions, which are all those that the Bot did not understand, this flap is crucial for you to leave the Bot increasingly intelligent, in it you will analyze the misunderstandings and add the intentions that you deem pertinent.

![](https://lh5.googleusercontent.com/TArfh_qNmD-GfhGKNmuIU6FIo70I1VWYFDAezVwKGbnjjuXkb0t58hmGawdDR8D_esOc4RXozDaEh8xKzLHmjZsGcxveISjZ8-SOdV2_teujNLA6tR98BIli9ihFmNO44m6ZrpUQ)

Finally, we have the analytics of interactions that are responsible for showing a general summary of the types of messages that appear the most in the flow. Next we have an average in minutes of how long the conversation lasts in total.

![](https://lh5.googleusercontent.com/_l-LtmX_-KghW1HMjHdo3y1cEfM4axg1kGlIcac9aYbCQ9x_FF-mz9lbaFDQKek_PdlSzzK9P7VBHOpeVjSN0UTmjQ6xDxeXJvTb09hNBSJvMyeKTfUpwEg88NZ64Hp3xWL7xsSe)


# Explorer

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-Lc6g2jKz-4Arg2FbNQO%2F-Lc6gA8rrFF07BazCzd8%2FScreen%20Shot%202019-04-10%20at%2011.39.20.png?alt=media\&token=85b12195-f082-4207-9a82-cce31898fb5c)

Explorer is responsible for saving your JavaScript templates and for showing changes made by your team.


# Codes

The codes serve as templates that can be used during the flow!

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-Lc6eMV6NG2ZWFqc6UaF%2F-Lc6fAgevhjbLMILoGaT%2FScreen%20Shot%202019-04-10%20at%2011.31.37.png?alt=media\&token=a89f0433-8127-4714-8951-097b5d3bf6de)

Whenever you create a [JavaScript](/bot-builder/conversation-flow/javascript) step, you can use one of the code templates. Just click on "Existing Code"

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-Lc6eMV6NG2ZWFqc6UaF%2F-Lc6fOYnGgJdxp-gu3qE%2FScreen%20Shot%202019-04-10%20at%2011.31.05.png?alt=media\&token=21ead02e-c31d-49f6-9991-ac74d14aa088)


# Changes

The Changes page shows the changes your team has recently made, for example, if someone modifies a JavaScript code, this page will create a history of this change


# Live Chat

In the Live Chat section you can monitor all user interactions with the bot, as well as being able to take the conversation using the [Human Control](/bot-builder/conversation-flow/human-control) plugin.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LTwVjNZ3mJiebrhd33u%2F-LTwWzZU6UWNsgVEnrZO%2Fimage.png?alt=media\&token=d4b4fcfd-eff1-4fb7-a805-6146466b3b37)

You can still filter the messages to have a greater control than you want to analyze.

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LTwXIz0xOF8WXqU40z2%2F-LTwXMvYUWLdQESHmUS8%2Fimage.png?alt=media\&token=b8dfcef1-3b7b-4caf-b55a-a8163063888a)


# Settings

In the settings tab of your Cosmo Desk you configure how the messages will be sent to the user when there is [Human Control](/bot-builder/conversation-flow/human-control).[<br>](https://help.cosmobots.io/help/cosmo-desk/live-chat)

![](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LSnqDgLbXBccdKMOdEJ%2F-LTwXP1Yka2vfskMZvIO%2F-LTwXiD7lJH9m89-nV5X%2Fimage.png?alt=media\&token=3daeb5d0-7826-41b7-a90e-6524d349b711)


# V1 - Records

Cosmo API - Query Records

Overview This document is intended to be used for developers using the CosmoBots API to retrieve records processed over the CosmoBots platform.

Endpoint POST <https://api.cosmobots.io/data/v1/records>


# V1 - Index

List of Cosmobots API resources.

{% content-ref url="/pages/LHK0OBqlH6CXy9hBXCl1" %}
[V1 - Send Message](/api/v1-send-message)
{% endcontent-ref %}

Send and receive messages, to single contacts per request, on channels connected to CosmoBots


# V1 - Send Message

Send and receive messages, to single contacts per request, on channels connected to CosmoBots

This document is intended to be used for developers using CosmoBots API to send and receive messages, to single contacts per request, on channels connected to CosmoBots.

To send messages to registered channels we are considering you already have connected the channel to your Bot on CosmoBots.

***

## Endpoint

```
POST https://api.cosmobots.io/messages/v1/send
```

## Authentication

Every request needs to have these two parameters on the header. You may retrieve both on the Integration section of the platform. Follow these steps:

* Login into the platform
* Choose the Bot
* On the left sidebar menu, choose Integrations, then API
* Choose the Send Message API
* Click on Enable API
* Now you can copy both token and channelId to use on the requests

| Header          | Type   | Description                                                       |
| --------------- | ------ | ----------------------------------------------------------------- |
| **token**       | String | **Required.** Token exclusive to the Bot, to be used on this API. |
| **channel\_id** | String | **Required.** ID of the Channel that will receive the messages    |

## Sending Message

Here are the body fields used during this request. The format is JSON.

| Field           | Type   | Description                                                                                                                                                                                                                                                                                                                                                                                                                         |
| --------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **destination** | String | <p><strong>Required.</strong> </p><p>Destination that the message will go.</p><ul><li>bot</li><li>contact</li><li>desk</li></ul><p><strong>If bot:</strong> it will send to the bot and reply through the webhook if sync or on the same request through a response if async).<br></p><p><strong>If contact:</strong> it will send to the contact. And any reply back from the contact will be handled through the webhook.<br></p> |

### Contact *`Object`*

| Field             | Type               | Description                                                                                                                                                                                               |
| ----------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **id**            | String             | **Required.** ID of the Contact on CosmoBots. If it is a new contact then just inform "new\_contact"                                                                                                      |
| **external\_id**  | String             | ID of the Contact on any external Database                                                                                                                                                                |
| **first\_name**   | String             | First Name of the Contact                                                                                                                                                                                 |
| **last\_name**    | String             | Last Name of the Contact                                                                                                                                                                                  |
| **mobile\_phone** | String             | <p>Mobile Phone of the Contact. It is required when using these channels: WhatsApp, rcs, apple. It needs to provide the number with complete format, including country code.</p><p>Ex.: 5511999999999</p> |
| **custom**        | Object (Key/Value) | Custom fields about the contact profile                                                                                                                                                                   |

### Session *Object*

| Field       | Type   | Description                                                                                                     |
| ----------- | ------ | --------------------------------------------------------------------------------------------------------------- |
| **id**      | String | **Required.** ID of the Session                                                                                 |
| **control** | String | <p>It shows who controls the conversation.</p><p></p><p>The options are:</p><ul><li>Bot</li><li>Human</li></ul> |
| **desk**    | Object | Provide the desk platform that is being used by the human agent                                                 |
| **context** | Object | Information about the context of the conversation                                                               |

### Desk *`Object`*

| Field      | Type              | Description                                                                                                                |
| ---------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------- |
| **broker** | String            | **Required.** Provider of the Desk platform                                                                                |
| **agent**  | Object < String > | <p>Information about the person handling the conversation</p><ul><li>id</li><li>name</li><li>email</li><li>group</li></ul> |

### Message *`Array [Object]`*

| Field    | Type   | Description                                                                                                                            |
| -------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------- |
| **data** | Object | **Required.** Data related to the message                                                                                              |
| **type** | String | <p>Types of Message. </p><p></p><p>Options are: </p><ul><li>text</li><li>buttons</li><li>cards</li><li>media</li><li>payload</li></ul> |

### Message > Data (If Type is Text)

| Field    | Type   | Description         |
| -------- | ------ | ------------------- |
| **text** | String | Text of the message |

### Message > Data (If Type is Buttons)

| Field     | Type   | Description                                                                                                                                                                   |
| --------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **title** | String | **Required.** Text of the Button (Caption)                                                                                                                                    |
| **type**  | String | <p><strong>Required.</strong> Type of Button, having the value related to the field payload.</p><p></p><p>Options are: </p><ul><li>text</li><li>url</li><li>payload</li></ul> |
| **value** | String | **Required.** Data related to the payload when the button is clicked                                                                                                          |

### Message > Data (If Type is Cards)

| Field          | Type              | Description                     |
| -------------- | ----------------- | ------------------------------- |
| **title**      | String            | **Required.** Title of the Card |
| **subtitle**   | String            | Subtitle of the Card            |
| **image\_url** | String            | Image Url of the Card           |
| **buttons**    | Array \[ Object ] | List of Buttons                 |

### Message > Data (If Type is Media)

| Field          | Type   | Description                                                                                                                                      |
| -------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| **type**       | String | <p><strong>Required.</strong> Type of media. </p><p></p><p>Options are: </p><ul><li>image</li><li>audio</li><li>video</li><li>document</li></ul> |
| **url**        | String | **Required.** Url of the Media                                                                                                                   |
| **name**       | String | Name of the Media (Caption)                                                                                                                      |
| **mime\_type** | String | The media type standard                                                                                                                          |

### Response *Sync*

| Field            | Type            | Description                                                             |
| ---------------- | --------------- | ----------------------------------------------------------------------- |
| **status**       | String          | <p></p><p>Status of the Message</p><ul><li>sent</li><li>error</li></ul> |
| **contact\_id**  | String          | ID of the Contact                                                       |
| **session\_id**  | String          | ID of the Session of the ongoing conversation                           |
| **message\_ids** | Array \[String] | Array with the ID's of the messages sent                                |

### Response *Async*

| Field  | Type   | Description                       |
| ------ | ------ | --------------------------------- |
| **id** | String | ID confirmation of message queued |

## Examples Of Request

### Sending Text `Destination: Contact`

```
POST https://api.cosmobots.io/messages/v1/send

{
    "destination": "contact",
        "contact": {
        "id": "5511999999999",
            "firtName": "Jerry",
                "phone": "5511999999999"
    },
    "message": [{
        "type": "text",
        "data": {
            "text": "Escreva Seu Texto Aqui"
        }
    }]
}
```

### Sending Text With Buttons `Destination: Contact`

```
POST https://api.cosmobots.io/messages/v1/send

{
    "destination": "contact",
        "contact": {
        "id": "5511999999999",
            "phone": "5511999999999"
    },
    "message": [{
        "type": "buttons",
        "data": {
            "text": "Escreva Seu Texto Aqui",
            "buttons": [
                {
                    "title": "Botão 1",
                    "type": "text",
                    "value": "Botão 1"
                },
                {
                    "title": "Botão 2",
                    "type": "text",
                    "value": "Botão 2"
                }
            ]
        }
    }]
}
```

### Sending Media `Destination: Contact`

```
POST https://api.cosmobots.io/messages/v1/send

{
    "destination": "contact",
        "contact": {
        "id": "5511999999999",
            "firstName": "Jerry",
                "phone": "5511999999999",
                    "custom": {
            "email": "test@test.com"
        }
    },
    "message": [{
        "type": "media",
        "data": {
            "type": "image",
            "name": "name_image",
            "url": "URL_Image",
            "mime_type": "image/png"
        }
    }]
}
```

## Receiving Message

To receive messages coming from CosmoBots, you have to register your endpoint on our webhook. You may find the webhook setup on the Channels section of the platform. Follow these steps:

* Login into the CosmoBots platform
* Choose the Bot
* On the left sidebar menu, choose Channel, then the specific channel you are using
* On the Webhook Url field, include the endpoint that will receive the requests

The Body fields are the same as the fields from the Body of the Sending Message request above.


# V1 - Broadcast Messages

Send messages to multiple contacts on channels connected to CosmoBots

This document is intended to be used for developers using CosmoBots API to send messages to multiple contacts on channels connected to CosmoBots.

Remember that to send messages to these channels we are considering you already have connected the channel to your Bot on CosmoBots.

## Endpoint

```
POST https://api.cosmobots.io/messages/v1/broadcast
```

## Authentication

* Login into the platform
* Choose the Bot
* On the left sidebar menu, choose Integrations, then API
* Choose the Broadcast Messages API
* Click on Enable API
* Now you can copy channelId and token to use on the requests

Every request needs to have these two parameters on the header. You may retrieve both on the Integration section of the platform. Follow these steps:

| Header          | Type   | Description                                                       |
| --------------- | ------ | ----------------------------------------------------------------- |
| **channel\_id** | String | **Required.** ID of the Channel that will receive the messages    |
| **token**       | String | **Required.** Token exclusive to the Bot, to be used on this API. |

## Broadcasting Messages

Here are the body fields used during this request. The format is JSON.

| Field       | type             | Description                                                                  |
| ----------- | ---------------- | ---------------------------------------------------------------------------- |
| **message** | Object           | **Required.** Information about the content of the message                   |
| **contact** | Array \[Objects] | **Required.** Information about the contacts that will receive the messages. |

## Message *`Object`*

| Field              | Type             | Description                                                                                                                         |
| ------------------ | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| **type**           | String           | <p><strong>Required.</strong> Types of Message. Options are: </p><ul><li>Text</li><li>Buttons</li><li>Cards</li><li>Media</li></ul> |
| **template\_id**   | String           | ID of the Template being used to send the message                                                                                   |
| **language\_code** | String           | <p>Code for the language of the message.</p><p>Ex.: "pt\_BR"</p>                                                                    |
| **params**         | Array \[Strings] | When using Templates the values in this array represent the parameters values on messages for all contacts                          |
| **data**           | Object           | **Required.** Data related to the content of the message                                                                            |

### Message > Data (If Type is Text)

| Field    | Type   | Description         |
| -------- | ------ | ------------------- |
| **text** | String | Text of the message |

### Message > Data (If Type is Buttons)

| Field     | Type   | Description                                                                                                                                                      |
| --------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **title** | String | **Required.** Text of the Button (Caption)                                                                                                                       |
| **type**  | String | <p><strong>Required.</strong> Type of Button, having the value related to the field payload. Options are: </p><ul><li>Text</li><li>Url</li><li>Payload</li></ul> |
| **value** | String | **Required.** Data related to the payload when the button is clicked                                                                                             |

### Message > Data (If Type is Cards)

| Field          | Type            | Description                     |
| -------------- | --------------- | ------------------------------- |
| **title**      | String          | **Required.** Title of the Card |
| **subtitle**   | String          | Subtitle of the Card            |
| **image\_url** | String          | Image Url of the Card           |
| **buttons**    | Array \[Object] | List of Buttons                 |

### Message > Data (If Type is Media)

| Field       | Type   | Description                                                                                                                        |
| ----------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| **type**    | String | <p><strong>Required.</strong> Type of media. Options are: </p><ul><li>Image</li><li>Audio</li><li>Video</li><li>Document</li></ul> |
| **url**     | String | **Required.** Url of the Media                                                                                                     |
| **caption** | String | Caption of the Media                                                                                                               |

### Contacts *`Array [Object]`*

| Field       | Type             | Description                                                                                                                                          |
| ----------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| **id**      | String           | <p><strong>Required.</strong> ID of the Contact.</p><p>When the channel is WhatsApp, the id is equivalent to the phone number (complete format).</p> |
| **params**  | Array \[Strings] | When using Templates the values in this array represent the parameters values on the template message for each contact.                              |
| **context** | Object           | Custom Data related to the message, that can be used by the Bot during conversation.                                                                 |

### Response *Async*

| *Field*           | Type   | Description                                                      |
| ----------------- | ------ | ---------------------------------------------------------------- |
| **status**        | String | <p>Status of the Message</p><ul><li>Sent</li><li>Error</li></ul> |
| **broadcast\_id** | String | ID of the Broadcast                                              |

## Examples Of Request

### Sending Text

```
POST https://api.cosmobots.io/messages/v1/broadcast

{
   "message": {
      "type": "text",
      "template_id": "XXXXXXXXX",
      "language_code": "pt_BR",
      "data": {
          "text": "The product {{1}} arrived!"
      }
   },
   "contacts":[
      {
        "id":"5511999999999",
        "params": ["123"]
      },
      {
        "id":"55163333333333",
        "params": ["abc"]
      }
   ]
}
```

### Sending Image

```
POST https://api.cosmobots.io/messages/v1/broadcast

{
   "message": {
      "type": "media",
      "template_id": "XXXXXXXXX",
      "language_code": "pt_BR",
      "data": {
          "type": "image",
          "url": "URL_Image",
          "text": "The product arrived!"
      }
   },
   "contacts":[
      {
        "id":"551199999999"
      }
   ]
}
```

```
POST https://api.cosmobots.io/messages/v1/broadcast

{
   "message": {
      "type": "media",
      "template_id": "XXXXXXXXX",
      "language_code": "pt_BR",
      "data": {
          "type": "image",
          "text": "The product arrived!"
      }
   },
   "contacts":[
      {
        "id":"551199999999"
      }
   ]
}
```

### Sending Buttons`Type: Text`

```
POST https://api.cosmobots.io/messages/v1/broadcast

{
   "message": {
      "type": "text",
      "template_id": "XXXXXXXXX",
      "language_code": "pt_BR",
      "data": {
          "text": "The product {{1}} arrived! | [Button 1] | [Button 2]"
      }
   },
   "contacts":[
      {
        "id":"551199999999",
        "params": ["123"]
      }
   ]
}
```

### Sending Buttons `Type: URL`

```
POST https://api.cosmobots.io/messages/v1/broadcast

{
   "message": {
      "type": "interactive",
      "template_id": "XXXXXXXXX",
      "language_code": "pt_BR",
      "data": {
          "type": "URL",
          "text": "The product {{1}} arrived! | [Button 1,https:url.com.br]"
      }
   },
   "contacts":[
      {
        "id":"55119999999",
        "params": ["123"]
      },
      {
        "id":"55113333333",
        "params": ["ABC"]
      }
   ]
}
```


