# SDK - Chatbot

This section gathers the main features available for integration with Tatodesk, including SDK resources, sending messages via WhatsApp and SMS, as well as operations related to notifications, CRM and session metadata.\
Below, you will find an interactive menu that facilitates navigation between topics, allowing quick access to descriptions and usage examples for each feature.

**Click the topics below to quickly navigate between subjects:**

* [Sending texts and multimedia;](#envio-de-textos-e-multimidias)
* [Sending multimedia with Headers - Creating URL;](#envio-de-multimidia-passando-headers-criacao-de-url)
* [Dynamic construction of buttons;](#construcao-dinamica-de-botoes)
* [Registering and capturing variables in the session;](#registrando-e-capturando-variaveis-na-sessao)
* [Channels](#canais);
* [Registering Additional Information;](#registrando-informacoes-adicionais)
* [CRM](#crm);
* [Ticket](#ticket);
* [Contact Center;](#contact-center)
* [ChatBot;](#chatbot)
* [Marketing.](#marketing)

### Sending texts and multimedia <a href="#envio-de-textos-e-multimidias" id="envio-de-textos-e-multimidias"></a>

These functions are used to interact with the SDK and send formatted messages of different types, such as text, image, file, video, audio and link.

{% code lineNumbers="true" %}

```typescript
sdk.send.text("your text")

sdk.send.image(url)

sdk.send.file(url)

sdk.send.video(url)

sdk.send.audio(url)

sdk.send.link("Text","Url")
```

{% endcode %}

### Sending multimedia with Headers - Creating URL <a href="#envio-de-multimidia-passando-headers-criacao-de-url" id="envio-de-multimidia-passando-headers-criacao-de-url"></a>

{% code lineNumbers="true" %}

```typescript
sdk.chatbot.externalMedia(method, url, options, body)
```

{% endcode %}

Here a call is made to an external API and the parameters (method, url, options and body) are used to request data from that API.

**Example of use case:**

{% code overflow="wrap" lineNumbers="true" fullWidth="true" %}

```typescript
  const method = 'GET'
  
  const url = `https://www.clientbackend.xx.gov.br/certificate/pdf idProfessional=${idProfessional}`
  
  const options = {
    headers: {
      'Authorization': token,
      'Application': 4
    }
  }
  
  const res = await sdk.chatbot.externalMedia(method, url, options, body)
  { chatbotExternalMedia, error } = res

  chatbotExternalMedia: String | null  (Access link to the external media) 
 error: Error | null
```

{% endcode %}

In this example, using the GET method (data request), a request is made for an external link passing a parameter through the URL, and through the '**options**' the headers are included with authorization information.

The constant '**res**' makes the API call, which has the requested external link.

The result of the API call can have two properties: '**chatbotExternalMedia**', which can be a string or null. If the response is successful, the link will be returned. Otherwise, the property '**error**', which is an error object or null, will contain information about the error that occurred.

### Dynamic construction of buttons <a href="#construcao-dinamica-de-botoes" id="construcao-dinamica-de-botoes"></a>

{% code lineNumbers="true" %}

```typescript
const buttonMessage = `Title above the buttons`

const buttons = [
  {
    title: "First button",
    payload: "First button",
    without_bold: true
  },
  {
    title: "Second button",
    payload: "Second button",
    without_bold: true
  }
]

sdk.send.buttons(buttonMessage, buttons)
```

{% endcode %}

The buttons function is called from the SDK send object and receives two arguments.&#x20;The first is a string, which defines the title displayed above the buttons.&#x20;The second is an array of objects, where each object represents a button.

Each object may contain the following properties:

* title: text displayed on the button;
* payload: value that identifies the button when it is clicked;
* without\_bold: boolean value (true or false) that defines whether the text will be displayed without bold;

### Registering and capturing variables in the session

{% code lineNumbers="true" %}

```typescript
await sdk.session.setAttribute(key,value)

let myVariable = await sdk.session.getAttribute(key)

await sdk.session.deleteAttribute(key)
```

{% endcode %}

In `sdk.session.setAttribute(key, value)`, the function **`setAttribute`** is called on the **`session`** object of the SDK to **set an attribute in the session**, where `key` represents the **attribute key** and `value` the **value associated with that key**.

Meanwhile, in `sdk.session.getAttribute(key)`, the function **`getAttribute`** is called on the same object to **retrieve the stored value** for the given key. The returned result is stored in the variable **`myVariable`**.

Finally, in `sdk.session.deleteAttribute(key)`, the function **`deleteAttribute`** is used to **remove an attribute from the session**, identified by the key `key`.

Thus, one expression **sets**, another **retrieves** and another **deletes** specific user information during the session.

#### Get Request

{% code lineNumbers="true" %}

```typescript
const config = {
  headers: {
    'Agreement':agreement,
    'Origin':origin,
    'Authorization': authorization
  }
}
const res = await sdk.net.get(`https://yourdomain.com`,config)
```

{% endcode %}

In the example, the object **`config`** contains the property **`headers`**, which gathers three headers composed of **key and value pairs**:

* **Agreement**: key `'Agreement'` and the variable value `agreement`;
* **Origin**: key `'Origin'` and the variable value `origin`;
* **Authorization**: key `'Authorization'` and the variable value `authorization`.

The constant **`res`** stores the **result of the request**, and the use of **`await`** causes the code to **wait for the completion of the get call `before proceeding with execution.`** Thus, the program only continues after the request finishes and the server response is received.&#x20;

Post Request

#### The object

<pre class="language-typescript" data-line-numbers><code class="lang-typescript"><strong>const config = {
</strong>  headers: {
    'Agreement':agreement,
    'Origin':origin,
    'Authorization': authorization
  }
<strong>}
</strong></code></pre>

has the property **`config`** , which contains three headers defined as key and value pairs: **`headers`**&#x6B;ey and value: **key and value:**

* **Agreement**: key `'Agreement'` and the variable value `agreement`;
* **Origin**: key `'Origin'` and the variable value `origin`;
* **Authorization**: key `'Authorization'` and the variable value `authorization`.

#### Response

{% code lineNumbers="true" %}

```typescript
const req = {
  field_name: composed_value,
  field_name_2: field_value_2
}
```

{% endcode %}

Here an object is created that has the properties **`field_name`** and **`field_name_2`**, each receiving a corresponding value of the same name.

#### Request

```typescript
const res = await sdk.net.post(`https://yourdomain.com`, req, config);
```

In ``sdk.net.post(https://yourdomain.com`, req, config)`` the function **`post`** of the **`net`** object of the sdk is being used to make an HTTP POST request to the url.

### Channels

{% code lineNumbers="true" %}

```typescript
sdk.channel.isWebchat()
sdk.channel.isWhatsapp()
sdk.channel.isInstagram()
sdk.channel.isTelegram()
sdk.channel.isFacebookMessenger()
```

{% endcode %}

The SDK functions are used to identify the channel in use.\
Each of them returns a boolean value (`true` or `false`), indicating whether the specific channel is active.

### Registering Additional Information

**Chatbot Info:**

{% code lineNumbers="true" %}

```typescript
await sdk.chatbot.addInfo(key, value)
```

{% endcode %}

Digital Service Info:

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.setDataItem(key, value)

const zapObj = sdk.session.getMetadataWhatsapp()

await sdk.chatbot.addInfo('WHATSAPP_NUMBER', zapObj['phone'])
```

{% endcode %}

The function `getMetadataWhatsapp` is called on the `session` of the SDK to capture information from the current WhatsApp session and store the result in the variable `zapObj`.

&#x20;Then, the function `addInfo` is called on the `chatbot` of the SDK, passing two arguments: the key `'WHATSAPP_NUMBER'` and the corresponding value `zapObj['phone']`.

### CRM

{% code lineNumbers="true" %}

```typescript
const person = await sdk.crm.getPersonByText("81900000000")
{
  person: {
    ID: string
  },
  customFields: [
    {
      key: string,
      value: string
    }
  ],
  tags: [
    {
      name: string
    }
  ]
}
```

{% endcode %}

Performs a query by phone number via `before proceeding with execution.` and returns an object with the properties:

* `person` — basic person data (e.g.: `ID`);
* `customFields` — array of custom fields `{ key, value };`
* `tags` — array of tags `{ name }`.

{% code lineNumbers="true" %}

```typescript
const person = {
  firstName:"person's name",
  emails:["email@gmail.com"],
  phones:["81900000000"],
  tags:["WHATSAPP-OPT-IN"]
}

const p = await sdk.crm.createPerson(person)
```

{% endcode %}

has the property `person` is created with the properties `firstName`, `emails`, `phones` and `tags`, which store the information of the person to be registered.\
Then, the method `createPerson` receives this object as an argument, using its data to create a new person record in the CRM.

#### Adding Tag in CRM

{% code lineNumbers="true" %}

```typescript
await sdk.crm.addTag(PERSON_ID,"TAG_NAME")
```

{% endcode %}

The method `addTag` is called on the `crm` object of the `sdk`, receiving as parameters `PERSON_ID` and `TAG_NAME`. It uses this information to add the specified tag to the record of the corresponding person in the CRM.

#### Adding Custom Fields in CRM

{% code lineNumbers="true" %}

```typescript
const persons = await sdk.crm.listCRMPersonsByCustomField("KEY",value)
```

{% endcode %}

In the constant `persons`, the object `sdk`is called, which returns a list of people stored in the `crm`.\
The parameters `"KEY"` and `value` are used in the search to filter records according to the provided custom field.

#### Example Full Structure of the Object

<pre class="language-typescript" data-line-numbers><code class="lang-typescript"><strong>[
</strong>  {
    "person": {
      "ID"
    },
    "customFields": [
      {
        "key": "string",
        "value": "string"
      }
    ],
    "tags": [
      {
        "name": "string"
      }
    ]
  }
]
</code></pre>

This structure contains the `person`object, which has the property `ID` of type `string`.\
The `customFields` is an array that stores objects with the properties `key` and `value`, representing the custom fields of the `person`.\
Finally, the array `tags` contains objects with the property `name`, which indicates the tags associated with the person.

### Ticket

#### Create Ticket

Possibilities to create tickets through the builder SDK, as an alternative to magic forms.

**Component Structure - Example:**

{% code lineNumbers="true" %}

```typescript
const forms = []

forms.push({ key: "EMAIL", value: email })
forms.push({ key: "REGISTRATION", value: registration })
forms.push({ key: "CPF/CNPJ", value: document })
forms.push({ key: "NAME", value: fullName })
forms.push({ key: "PROPERTY_ADDRESS", value: address })
forms.push({ key: "PHONE", value: phone })

if (proof) {
  forms.push({ key: "PROPERTY_DOCUMENT", value: proof })
}

forms.push({ key: "IDENTITY", value: documentImage })
forms.push({ key: "SELFIE", value: customerImage })
forms.push({ key: "PROPERTY_WATER_BILL", value: billImage })

if (paidBillImage) {
  forms.push({ key: "RECENT_PAYMENT_PROOF", value: paidBillImage })
}

forms.push({ key: "STATE_YOUR_RELATIONSHIP_WITH_PROPERTY", value: relation })

const res = await sdk.ticket.create(
  organizationID,
  projectID,
  departmentID,
  description,
  attendanceTypeIDs,
  forms,
  formID,
  2
)
```

{% endcode %}

In the code, the constant `forms` is an array that starts empty and receives objects through the `push`method.\
Each object has the properties `key` and `value`, for example, `{ key: "EMAIL", value: email }`, adding the field "EMAIL" with its respective value.\
The `if` is used to include optional fields, such as `{ key: "PROPERTY_DOCUMENT", value: proof }`, only when the variable `proof` is defined.

The constant `res` stores the return of the `create` of the `ticket` object of the `sdk`function, which receives several parameters (`organizationID`, `projectID`, `departmentID`, `description`, `attendanceTypeIDs`, `forms`, `formID`, `2`) and creates a new ticket in the system with the provided data.

### Contact Center

#### Skipping the magic form when being redirected to the human agent:

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.skipForm()
```

{% endcode %}

#### Skipping the group, subgroup, specialty, subspecialty, area and subarea:&#x20;

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.skipQuestion()
```

{% endcode %}

#### Skipping the custom service hours:

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.skipAttendanceGroupOpeningHour()
```

{% endcode %}

The `await` indicates that each of these calls is **asynchronous**, that is, the code waits for their execution before proceeding.\
Each method is responsible for **skipping a specific step** of the flow:

* **`skipForm()`** → skips the magic form, sending the service directly to the human.
* **`skipQuestion()`** → ignores the categorization questions (group, subgroup, specialty, area, etc.).
* **`skipAttendanceGroupOpeningHour()`** → skips the verification of custom service hours.

Thus, the flow automatically proceeds to the next step, making the process faster and avoiding that the user needs to fill out or select information already known by the system.

#### Assigning information to the service when being redirected to the human agent:

**Key - Value**\
**Keys available for use:**

* `CPF_CNPJ`
* `NAME`

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.setFormItem("CPF_CNPJ", cpf)
```

{% endcode %}

The function `setFormItem("CPF_CNPJ", cpf)` is used to set an item of the form during the service. The `await` command indicates that the call is asynchronous, that is, the code will wait for the operation to complete before proceeding.

&#x20;has the property `sdk` contains the `contactCenter`object, responsible for operations related to human service. In the example above, the field `"CPF_CNPJ"` is set with the value stored in the variable `cpf`, showing this information in the agent's queue.

#### Getting session variables:

{% code lineNumbers="true" %}

```typescript
await sdk.session.getMetadataWebchat()
```

{% endcode %}

The function `getMetadataWebchat()` is used to obtain the metadata of the current Webchat channel session. The `await` command indicates that the call is asynchronous, that is, the code will wait for the data to be returned before continuing execution.&#x20;

has the property `sdk` contains the `session`, responsible for storing and providing information related to the active session. As a result, the contextual information of the ongoing service in the Webchat is returned.

**Example of use case:**

{% code lineNumbers="true" %}

```typescript
const metadataWebchat = sdk.session.getMetadataWebchat();

phoneParam = metadataWebchat.browser.queryParams["phone"];
```

{% endcode %}

On the first line, the function `getMetadataWebchat()` is used to capture the Webchat session metadata, storing the result in the constant `metadataWebchat`. On the second line, the value associated with the key `"phone"` is accessed from `metadataWebchat.browser.queryParams` and stored in the constant `phoneParam`.

#### Getting information by name:

The functions below perform asynchronous calls to fetch specific information within the `contactCenter`object, present in the main object `sdk`.

In all cases, the passed parameter is a string representing the **entity name** you want to locate.

* **Gets the Department by name:**

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.getDepartmentByName(departmentName)
```

{% endcode %}

* **Gets the Attendance Group by name:**&#x20;

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.getAttendanceGroupByName(groupName)
```

{% endcode %}

* **Gets the Group Specialization by name:**

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.getGroupSpecializationByName(specializationName)
```

{% endcode %}

* **Gets the Subspecialization by name:**

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.getSubSpecializationByName(subSpecializationName)
```

{% endcode %}

* **Gets the Area by name:**

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.getAreaByName(areaName)
```

{% endcode %}

* **Gets the Subarea by name:**

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.getSubAreaByName(subAreaName)
```

{% endcode %}

In all methods, the `await` indicates that the code execution will wait for the asynchronous call to return before proceeding. The **expected return** is an object containing the information of the located entity.

#### Setting Service Information

The functions below are used to **set the identifiers (ID)** of the entities related to a service within the `contactCenter`object, present in the main object `sdk`object.\
Each function receives a parameter that represents the **ID of the entity** that will be associated with the service.

* **Sets the department of the service:**

```typescript
await sdk.contactCenter.setDepartmentID(departmentID)
```

* **Sets the attendance group:**

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.setAttendanceGroupID(attendanceGroupID)
```

{% endcode %}

* **Sets the group's specialization for the attendance:**

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.setAttendanceGroupSpecializationID(groupSpecializationID)
```

{% endcode %}

* **Sets the attendance subspecialization:**

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.setSubspecializationID(subSpecializationID)
```

{% endcode %}

* **Sets the service area:**

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.setAreaID(areaID)
```

{% endcode %}

* Sets the service subarea:

{% code lineNumbers="true" %}

```typescript
await sdk.contactCenter.setSubareaID(subAreaID)
```

{% endcode %}

All functions use the `await` to await the asynchronous execution of the call. These definitions are used to correctly categorize and route the service within the Contact Center framework.;

### ChatBot

#### Adding Additional Information:

{% code lineNumbers="true" %}

```typescript
await sdk.chatbot.addInfo(key, value)
```

{% endcode %}

The function `addInfo(key, value)` adds custom information to the chatbot session. The parameter `key` represents the identifying key of the information, and `value` the value associated with that key. The call is made asynchronously, awaiting execution using `await`.

### Marketing

#### Obtaining information (metadatas) from single notifications and WhatsApp campaigns:

The functions below are used to retrieve additional data (metadata) related to WhatsApp campaigns and notifications by accessing the object `mkt` inside the `sdk`.\
Both perform asynchronous calls, awaiting the return using `await`.

{% code lineNumbers="true" %}

```typescript
await sdk.mkt.getWhatsappNotificationMetadatas()
```

{% endcode %}

Returns the metadata of single notifications sent via WhatsApp.

{% code lineNumbers="true" %}

```typescript
wait sdk.mkt.getWhatsappMktCampaignTargetAudienceMetadatas()
```

{% endcode %}

Returns the metadata of the target audience of a WhatsApp marketing campaign.

These functions allow access to additional information about the active session or campaign, useful for monitoring and analyzing the performance of communications via WhatsApp.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://portal.tatodesk.com/tato-docs-en/technical-documentation/sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
