# Introduction

## Tiledesk Developers Hub

Welcome to the Tiledesk Documentation, where you'll find guides and community support to help you start working as quickly as possible!

## Widget JS API

Use our powerful Tiledesk Widget JavaScript library for client side to automate some of your Tiledesk activities and create custom integrations with your own systems. These JS APIs allow you to interact with the widget UI.

## Chatbot API

You can use Tiledesk as platform, by creating your own Bot with API endpoint that describe within this document. These are few examples that show how Tiledesk platform will accept the request and give response, from API Endpoint for Bot uses.

## API Reference

Tiledesk is a headless support API that enables rapid experience-first all business development.

### REST API

An Tiledesk RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. You can use it to retrieve and update information from your own Tiledesk account, or to integrate Tiledesk into your own product. It's completely up to you and your custom use case.

### Webhook API

This Webhooks API allows you to subscribe to changes happening in the accounts of any Tiledesk. Webhooks are a powerful API resource that you can use to automate much of your use cases and improve your productivity.

Unlike the API resources, which represent static data that you can create, update and retrieve as needed, webhooks represent dynamic resources. You can configure them to automatically notify you when a customer has taken a particular action, such as making a purchase or replying to a conversation.

## Mobile SDKs

### Android

Bring real customer service to your mobile apps with ready-to-use chat widgets. In this documentation will cover embedding a mobile chat window in an Android application using the Android SDK.

### IOS

Get started on integrating the Tiledesk iOS SDK into your native iOS app using all functionality.

## Architecture

Tiledesk is the first open source live chat platform. Understand the Tiledesk architecture and all the components.

## Installation and configuration

Install Tiledesk on your server using Docker, Kubernetes or from source code and configure it (email, channel, etc.)


# Community

Join the Tiledesk community.

* Star on GitHub. Star [Tiledesk repositories](https://github.com/tiledesk) on GitHub and help others discover the platform.
* Share your Feedback. Discuss new ideas, suggestions by creating a post in our [Feedback Board](https://feedback.tiledesk.com/).
* Explore our Public Roadmap. Stay updated on our latest developments and contribute your thoughts about our [Public Roadmap](https://feedback.tiledesk.com/roadmap).
* Share your Projects. Publish your work on our [Chatbots and Conversational Apps Community](https://tiledesk.com/community/) and get recognized for it.
* Join our Affiliate Program. Start earninig rewards for your referrals by participating in our [Affiliate Program](https://tiledesk.com/affiliate/).
* Participate on the Forums. To discuss Tiledesk development with Tiledesk team and community join our [Discourse forum](https://tiledesk.discourse.group).
* Squash Bugs. Join Tiledesk’s passionate community to help us manage issues and squash bugs for Tiledesk Design Studio, Server, Widget, Web Chat and iOS and Android clients.
* Write Documentation. You don’t have to be a developer to contribute to Tiledesk. You can create new or update old Tiledesk Docs articles or tutorials directly through GitHub.
* Suggest a Blog Post. Write or suggest a blog post on your Tiledesk story, tell us about how it improved your team’s communication and we’ll share it with the community.
* Create Tutorial Videos. Tiledesk has a passionate community of content creators on [YouTube](https://www.youtube.com/@tiledesk) sharing tutorials on configuring, installing, customizing and developing for Tiledesk.
* Come Meet Us. Come say hi at a local meetup or conference, tell us how you customized it to suit your needs and improved your team’s communication.
* Start using Tiledesk. You can sign-up to our Free Forever [Cloud](https://panel.tiledesk.com/v3/dashboard/#/signup?su=37) version or install [On-Premise](https://tiledesk.com/install).
* Check our Website. Visit [Tiledesk.com](https://tiledesk.com) and our [Blog](https://tiledesk.com/blog/) for the latest news.


# Ask for Support

Please refer to this document to understand how the Tiledesk team and the Tiledesk Community provides support for the free plans and the open source edition of Tiledesk software.

## Urgent issues? Paid subscriptions

If you think your issue is urgent, then you have two choices:

* Subscribe for a paid plan on the [Cloud edition](https://tiledesk.com/pricing-live-chat/)
* Get a support package for the [Enterprise Edition](https://tiledesk.com/tiledesk-live-chat-on-premise/)

## I need Help but it's not so urgent

Use [our forum](https://tiledesk.discourse.group/)

Patiently wait for an engineer to consider helping you.

If you opt for community's help instead of paid support, please notice that:

1. When opening an issue, create a small, isolated, simple, reproduction of the issue using an online code editor (like replit, codepen, codesandbox etc.) if possible and a GitHub repository if not. The process may help you discover the underlying issue (or realize that it’s not an issue with the project). It will also make it easier for maintainers to help you resolve the problem.
2. Your question must be well-documented and you should provide the minimum code required to reproduce the problem. When possible always provide a running example to that gives evidence of the issue.
3. We do this in our spare time. Please respect our team.
4. Just because it is urgent for you does mean that it is urgent for the whole Tiledesk product or community
5. Please answer their questions patiently and help them try and understand your problem
6. Being rude to them will not help you at all
7. Please note that posting the same question in several channels will not help you
8. Don't open a bug yet. When you ask in the channels or forums then devs or other community helpers will tell you if you really need to open an issue. Frequently if there really is a problem you won't be the first one to experience it, so always check the forum carefully for duplicates. Use lots of different search terms and make sure you check closed Issues as well (see below).


# Public Roadmap and Changelog

The [Tiledesk Roadmap](https://feedback.tiledesk.com/roadmap) is publicly accessible, allowing our community to stay informed about upcoming features that will enhance Tiledesk as a product.

## Tiledesk Changelog

The [Tiledesk Changelog](https://feedback.tiledesk.com/changelog) provides an overview of the most recent key features that have been released.

### Detailed Changelogs for Main Components

* [Tiledesk Design Studio Full Changelog](https://github.com/Tiledesk/design-studio/blob/master/CHANGELOG.md)
* [Tiledesk Server Full Changelog](https://github.com/Tiledesk/tiledesk-server/blob/master/CHANGELOG.md)
* [Tiledesk Dashboard Full Changelog](https://github.com/Tiledesk/tiledesk-dashboard/blob/master/CHANGELOG.md)
* [Chat21 Ionic Full Changelog](https://github.com/Tiledesk/chat21-ionic/blob/master/CHANGELOG.md)
* [Chat21 Web Widget Full Changelog](https://github.com/Tiledesk/chat21-web-widget/blob/master/CHANGELOG.md)


# Tutorials

In this section we list all developer tutorials available for the Tiledesk platform.

Having all the tutorials listed in a single page is a good way to get a global vision of all the amazing things that you can do with Tiledesk.

## Connect Telegram Channel Tutorial

![Telegram integration](https://user-images.githubusercontent.com/45603238/175036688-f26d0efe-3150-425b-bab2-6ca07b63adf6.png)

This integration allows you to connect your company's Telegram bot to your Tiledesk account, thus creating a tunnel between the two platforms. Therefore customers can reach your support simply by writing to your Telegram bot and these messages will be delivered to the Tiledesk webchat, along with messages from other channels.

[Telegram integration Tutorial](/apps/telegram-integration)

## Custom Authentication Tutorial

![](https://user-images.githubusercontent.com/32564846/171562770-2c161497-ad36-4490-87d8-4e1fcdd203b7.png)

This tutorial will guide you to a deep look of Tiledesk custom (and secure) [JWT authentication](https://developer.tiledesk.com/apis/authentication) for your end-users. This tutorial is a fully-functional, full-stack application (backend+frontend) deployed on replit with nodeJS (backend) and HTML+Javascript (frontend).

[Custom authentication Tuturial](/apis/authentication/jwt-auth-tutorial)

To get a taste of the final result you can find the live web application up and running at this url:

<https://tiledesk-html-site.tiledesk.repl.co/custom-authentication-example.html>

## Hide Widget tutorial

A very simple tutorial to hide the widget when no agent is available. Good to learn the basics of Widget SDK (and some Tiledesk APIs too).

[Widget - Hide widget](/widget/tutorials/hide-widget)

## Conversation-embedded apps, Quick start

A quick start, introductory tutorial to *conversation-embedded* apps. You will learn how to implement a basic conversation-embedded application. It's a skeleton App that will show you the basic principles, architecture and APIs involved in the development of a simple conversation-embedded application.

[Widget - Payment App Tutorial](/widget/widget-app-introduction/widget-app-payment)

![Conversation-embedded apps - Quick start](https://user-images.githubusercontent.com/32564846/165598879-26373df7-d254-4174-bf2a-73638999de15.png)

## Conversation-embedded apps, *prechat form* during chat

Do you want a more customizable *prechat form*? Do you want the user to play with your chatbot and ask his personal data only when needed (i.e. during human handoff)? With this tutorial you'll learn how to setup a minimum and fully functional prechat form that appears in the conversation only when the user is bored with your chatbot and would like to chat with a human!

[Prechat form App Tutorial](/widget/widget-app-introduction/widget-app-prechat-form)

![In-conversation Prechat form](https://user-images.githubusercontent.com/32564846/165599748-fbc56e72-de48-4347-9a17-0712a2d29d89.png)

## External Chatbots Tutorials

* [External Chatbot - Hello World tutorial](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/tutorials/chatbot/connect-your-own-chatbot.md)
* [External Chatbot - Chatbot to Human handoff](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/tutorials/chatbot/agent-handoff.md)
* [External Chatbot - Send Text Buttons](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/tutorials/chatbot/buttons-media-actions-more.md)
* [External Chatbot - Advanced Tutorials](https://github.com/Tiledesk/tiledesk-docs/blob/master/external-chatbot/external-chatbot-tutorials/README.md)
* [External Chatbot - Introduction](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/tutorials/chatbot/dialogflow/introduction-dialgoflow-external.md)
* [External Chatbot - Tutorial 1 - Dialogflow as external chatbot](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/tutorials/chatbot/dialogflow/dialogflow-as-external-chatbot-integration.md)
* [External Chatbot - Tutorial 2 - Buttons and images](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/tutorials/chatbot/dialogflow/dialogflow-tutorial-2-micro-language-integration.md)
* [External Chatbot - Tutorial 3 - Automatic human handoff with fallback intent](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/tutorials/chatbot/dialogflow/dialogflow-tutorial-3-automatic-human-handoff.md)
* [External Chatbot - Tutorial 4 - Explicit Human handoff with user intent](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/tutorials/chatbot/dialogflow/dialogflow-tutorial-4-explicit-human-handoff.md)
* [External Chatbot - Tutorial 5 - Gracefully handling operating hours during handoff](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/tutorials/chatbot/dialogflow/dialogflow-tutorial-5-graceful-human-handoff.md)
* [External Chatbot - Generate Dialogflow Google Credentials file](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/tutorials/chatbot/dialogflow/generate-dialgoflow-google-credentials-file.md)
* [External Chatbot - Rasa Tutorial 1 - Rasa as external chatbot](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/tutorials/chatbot/rasa/rasa-as-external-chatbot-integration.md)

## Resolution Bot Tutorials

* [Resolution bot - Quickstart](https://github.com/Tiledesk/tiledesk-docs/blob/master/native-chatbot/quickstart.md)
* [Resolution bot - Rich messages](https://github.com/Tiledesk/tiledesk-docs/blob/master/native-chatbot/rich-messages.md)
* [Resolution bot - Chatbot chooser (multilanguage)](https://github.com/Tiledesk/tiledesk-docs/blob/master/native-chatbot/lang-chooser-chatbot.md)
* [Resolution bot - Department chooser](https://github.com/Tiledesk/tiledesk-docs/blob/master/native-chatbot/department-chooser-chatbot.md)
* [Resolution bot - Fallback to Knowledge-Base](https://github.com/Tiledesk/tiledesk-docs/blob/master/native-chatbot/fallback-to-knowledge-base.md)

## REST APIs Tutorials

* [REST API](/apis/tutorials/rest-api)
* [REST API - Sending and receiving messages with Tiledesk APIs](/apis/tutorials/rest-api/sending-and-receiving-messages)

## Webhooks Tutorials

This section proposes a set of tutorial to show some common tasks you can address using this feature.

The main purpose of webhooks is call a user-defined action (in the form of an HTTP endpoint) when specific Tiledesk events occur.

The first tutorial [Custom Request assignment](https://developer.tiledesk.com/apis/tutorials/webhooks/custom-assignment-pooled) addresses an custom assignment every time a new request is moved to a Department's pooled routing schema.

The second tutorial [Request transcript on close](https://developer.tiledesk.com/apis/tutorials/webhooks/get-transcript-on-close) shows how you can get your chat transcript on each closing operation (i.e. for the purpose of sending it to your remote CRM to synchronize conversations)

* [Webhooks - Custom Request assignment](/apis/tutorials/webhooks/custom-assignment-pooled)
* [Webhooks - Request transcript on close](/apis/tutorials/webhooks/get-transcript-on-close)


# Widget SDK

## Tiledesk Widget

**Widget SDK ver 6.0**

![](https://user-images.githubusercontent.com/47848430/151355859-f94be6a7-3098-43a2-924c-d411e10d5815.png)

Are you interested in the v4 version? [Click here](/widget/advanced/old-versions/web-sdk-v4).

This guide will show you how to get started as quickly as possible with the Widget SDK from Tiledesk. The Widget SDK will give businesses and developers the flexibility to build and customize a chat experience that meet their specific design/brand requirements.

## How to install

To chat with your visitors embed the widget on your site. Copy the following script and insert it in the HTML source between the HEAD tags:

```html
    <script type="application/javascript">
        var PROJECT_ID = "<<TILEDESK_PROJECT_ID>>"
        window.tiledeskSettings=
        {
            projectid: PROJECT_ID
        };
        (function(d, s, id) {
            var w=window; var d=document; var i=function(){i.c(arguments);}; 
            i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i; 
            var js, fjs=d.getElementsByTagName(s)[0]; 
            if (d.getElementById(id)) return; 
            js=d.createElement(s); 
            js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document,'script','tiledesk-jssdk'));
    </script>
```

To get your TILEDESK\_PROJECT\_ID go to the Tiledesk Dashboard and click on the Widget item of the menu:

![Tiledesk Dashboard](https://user-images.githubusercontent.com/47848430/150099187-a7697396-bc63-44d1-bcfc-d375da7a1b4b.png)

### Install with visitor basic information

Website visitors are generally leads (visitors if they have not communicated via the Messenger) whereas logged in users are Tiledesk users already logged in onces. The main difference is the amount of information you know about them. You can pass basic information throught tiledeskSettings object. An example is provided below.

```html
    <script type="application/javascript">
        var PROJECT_ID = "<<TILEDESK_PROJECT_ID>>"
        const USER_FULLNAME = "James Smith";
        const USER_EMAIL = james.smith@gmail.com"
        window.tiledeskSettings=
        {
            projectid: PROJECT_ID,
            userFullname: USER_FULLNAME,
            userEmail: USER_EMAIL
        };
        (function(d, s, id) {
            var w=window; var d=document; var i=function(){i.c(arguments);}; 
            i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i; 
            var js, fjs=d.getElementsByTagName(s)[0]; 
            if (d.getElementById(id)) return; 
            js=d.createElement(s); 
            js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document,'script','tiledesk-jssdk'));
    </script>
```

### Install with custom position

Sometimes you may want to show Tiledesk Widget on left or right side of your website. Moreover, you may also want to get more/less distance between widget and website margin. The following example shows a widget aligned on left side and with custom margin from X and Y axis.

```html
    <script type="application/javascript">
        var PROJECT_ID = "<<TILEDESK_PROJECT_ID>>"
        
        window.tiledeskSettings=
        {
            projectid: PROJECT_ID,
            align: 'left',
            marginX: '200px',
            marginY: '150px'
        };
        (function(d, s, id) {
            var w=window; var d=document; var i=function(){i.c(arguments);}; 
            i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i; 
            var js, fjs=d.getElementsByTagName(s)[0]; 
            if (d.getElementById(id)) return; 
            js=d.createElement(s); 
            js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document,'script','tiledesk-jssdk'));
    </script>   
```

![Custom position of the widget: property explanation](https://user-images.githubusercontent.com/47848430/151353935-8ee4711d-0bc3-4044-ba67-039adfb0a4b2.png)

## Enabling authenticated visitors in the Chat widget

You can configure your widget to authenticate visitors using the Javascript API and JWT token. More info [Widget Authentication](/widget/auth)


# Javascript API: Methods

Tiledesk provides a Tiledesk JavaScript object that responds to a few methods. These allow you to update widget without a page refresh and interact with the messenger window.

## Open the widget

This will open the widget:

```javascript
window.Tiledesk('open');
```

## Minimize the widget

This will minimize the widget:

```javascript
window.Tiledesk('close');
```

## Hide the widget

This will hide the widget:

```javascript
window.Tiledesk('hide');
```

## Show the widget

This will show the widget:

```javascript
window.Tiledesk('show');
```

## Dispose the widget

This will clear the widget html elements from the DOM:

```javascript
window.Tiledesk('dispose');
```

## Reinitialize the widget

If your app is characterized by very few page refreshes (ie., content is swapped out on the client side but no page refresh happens, Angular, React, jQuery, etc..) and lots of asynchronous JS, you'll need to update Tiledesk when your user's data changes. A reInit call simulates a page refresh, causing Tiledesk to reload the widget and all the configurations.

```javascript
window.Tiledesk('reInit');
```

## Restart the widget

This method allow you to restart widget with the same user's data without make a new authentication. This also mantein all the configurations.

```javascript
window.Tiledesk('restart');
```

## Signin with anonymously

This method make a signin anonymously

```javascript
window.Tiledesk('signInAnonymous');
```

## Signin with JWT Custom Token

This method make a signin using a JWT Custom Token as described [here](/widget/auth).

```javascript
window.Tiledesk('signInWithCustomToken', customJwt);
```

## Make a logout

This will logout the widget:

```javascript
window.Tiledesk('logout');
```

## Show callout

This will show the widget callout if it is not open:

```javascript
window.Tiledesk('showCallout');
```

## Show or hide the PreChatForm

This parameter configures the PreChatForm visibility:

```javascript
window.Tiledesk('setPreChatForm', true|false);
```

## Set custom PreChatForm Json

This method allow you to customize preChatFormJson property, and change preChatForm structure if preChatForm is still active (ensure preChatForm value is set to true, otherwize use window\.Tiledesk('setPreChatForm', true) method before call setPreChatFormJson ). This method accept an Array (see [docs](https://developer.tiledesk.com/widget/advanced/prechat-form-json) for more detail about customize it):

```javascript
window.Tiledesk('setPreChatFormJson', customFormArray);
```

## Get custom PreChatForm Json

This method allow you to get current preChatForm Json array used in the preChatForm component when is active (check preChatForm value is set to true):

```javascript
window.Tiledesk('setPreChatFormJson', customFormArray);
```

## Set new value to Widget parameter

You can change a value to the Tiledesk Widget parameter. Pass an object in the form of key/value, where key represent che name of the property you want to modify, and value is the new value you want to set:

```javascript
window.Tiledesk('setParameter', {key: string, value: string});
```

## Set new value to Widget attribute parameter

You can change a value to the Tiledesk Widget attribute parameter. Pass an object in the form of key/value, where key represent che name of the property you want to modify, and value is the new value you want to set:

```javascript
window.Tiledesk('setAttributeParameter', {key: string, value: string});
```

## Start a new conversation

You can programatically start a new conversation:

```javascript
window.Tiledesk('startConversation');
```

## Open a conversation from a specif ID

You can programatically open an already existing conversation by id in the form of *'support-group-'+\<project\_id>+'-'+uuid*

```javascript
window.Tiledesk('openConversationById', conversation_id);
```

## Clear site data

You can programatically clear saved session data :

```javascript
window.Tiledesk('clearStorage');
```


# Javascript API: Attributes

## Configuration with tiledeskSettings

You can customize the widget passing the following parameters to **window\.tiledeskSettings** object.

**Javascript API:**

### Visual Attributes

These set of attributes modify the general widget behaviour

| Attributes             | Type    | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| ---------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **projectid**          | string  | The Tiledesk project id. Find your Tiledesk ProjectID in the Tiledesk Dashboard under the Widget menu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| **departmentID**       | string  | To skip departments selection, you can set the department ID upon which the widget must start the new conversation (See the turorial [here](https://developer.tiledesk.com/widget/advanced/preset-department))                                                                                                                                                                                                                                                                                                                                                                                                                              |
| **welcomeTitle**       | string  | The welcome title to show on the widget home page                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| **welcomeMsg**         | string  | Set the widget welcome message                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| **widgetTitle**        | string  | Set the widget title label shown in the widget header. . The default value is '*Tiledesk*'                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| **calloutTitle**       | string  | The title of the callout window                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| **calloutMsg**         | string  | The message of the callout window                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| **calloutTimer**       | integer | Proactively open the chat windows to increase the customer engagement. Permitted values: -1 (Disabled), 0 (Immediatly) or a positive integer value (e.g. 5 (After 5 seconds), 10 (After 10 seconds))                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| **logoChat**           | string  | The url of the logo to show on the widget home page                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| **lang**               | string  | An ISO 639-two-letter-code. With this configuration it is possible to force the widget lang. The widget will try to get the browser lang, if it is not possible it will use the default "en" lang                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| **recipientId**        | string  | Enable the widget to open a specific conversation                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| **userFullname**       | string  | Current user fullname. Set this parameter to specify the visitor fullname                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| **userEmail**          | string  | Current user email address. Set this parameter to specify the visitor email address                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| **persistence**        | string  | You can specify how the Authentication state persists when using the Tiledesk JS SDK. This includes the ability to specify whether a signed in user should be indefinitely persisted until explicit sign out or cleared when the window is closed. Permitted values: local, session. Default value : local. Local value indicates that the state will be persisted even when the browser window is closed. An explicit sign out is needed to clear that state. Session value indicates that the state will only persist in the current session or tab, and will be cleared when the tab or window in which the user authenticated is closed |
| **singleConversation** | boolean | This property if true, allow you to transform widget from multi conversation channel to a single conversation channel (See more [here](https://developer.tiledesk.com/widget/advanced/singleConversation-mode))                                                                                                                                                                                                                                                                                                                                                                                                                             |
| **typingLocation**     | string  | Set the location of the typing indicator between 'header' or 'content' locations. Default alue:'content'. Permitted values: 'content', 'header'                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |

<br>

### Style Attributes

These set of attributes modify the Widget style (i.e theme color, page position, etc.)

| Attributes               | Type             | Description                                                                                                                                                                                                                                                                                                  |
| ------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **align**                | string           | Make the chat available on the Right or on the Left of the screen. Permitted values: 'right', 'left'. Default value is right.                                                                                                                                                                                |
| **marginX**              | string           | Set the side margin, left or right depending on the align property. Default value : "20px"                                                                                                                                                                                                                   |
| **marginY**              | string           | Set the distance from the page bottom margin. Default value : "20px"                                                                                                                                                                                                                                         |
| **mobileMarginX**        | string           | Set the side margin, left or right depending on the align property on mobile. Default value : "0px". (See example [here](https://developer.tiledesk.com/widget/tutorials/widget-mobile))                                                                                                                     |
| **mobileMarginY**        | string           | Set the distance from the page bottom margin on mobile. Default value : "0px". (See example [here](https://developer.tiledesk.com/widget/tutorials/widget-mobile))                                                                                                                                           |
| **size**                 | string           | Set the size of the widget to 'min, 'max', 'top' dimension. Default value : "min".                                                                                                                                                                                                                           |
| **themeColor**           | string           | Allows you to change the main widget's color (color of the header, color of the launcher button, other minor elements). Permitted values: Hex color codes(e.g. #87BC65) and RGB color codes (e.g. rgb(135, 188, 101))                                                                                        |
| **themeColorOpacity**    | number \[0..100] | Allows you to change opacity of the theme color in the widget's backgrounds (color of the header, color of the home). Permitted values: numbers from 0 to 100. Default value: 50                                                                                                                             |
| **themeForegroundColor** | string           | Allows you to change text and icons' color. Permitted values: Hex color codes (e.g. #425635) and RGB color codes (e.g. rgb(66, 86, 53))                                                                                                                                                                      |
| **launcherWidth**        | string           | Allow you to change launcher width dimension. Default value: "60px"                                                                                                                                                                                                                                          |
| **launcherHeight**       | string           | Allows you to change launcher height dimension. Default value: "60px"                                                                                                                                                                                                                                        |
| **baloonImage**          | string           | Allows you to change baloon image with custom image URL. Minimun size: 60x60px. Allowed image format: \*.jpg, \*.jpeg, \*.jfif, \*.JPG, \*.JPE.                                                                                                                                                              |
| **baloonShape**          | string           | Allows you to change baloon shape with custom dimension. Permitted values: string with **four values** (e.g. '10px 10px 10px 10px'), **three values** (e.g. '15px 50px 30px'), **two values** (e.g. '15px 50px'), **one values** (e.g. '15px'), **percentage dimension** (e.g. '10%'). Default value: "50%". |
| **fullscreenMode**       | boolean          | If it is true, the chat window is open in fullscreen mode. Default value: false                                                                                                                                                                                                                              |

<br>

### General settings attributes

General settings for the widget

| Attributes                             | Type    | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| -------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **allowTranscriptDownload**            | boolean | Allows the user to download the chat transcript. The download button appears when the chat is closed by the operator. Default value: false                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| **allowReopen**                        | boolean | Allows you to continue writing in a conversation even if it was archived by an agent or the user himself. Default value: false                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| **hideHeaderCloseButton**              | boolean | Hide the close button in the widget header. The default value is false.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| **hideHeaderConversationOptionsMenu**  | boolean | Enable you to show/hide options menu in a conversation header. Default value: false                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| **hideCloseConversationOptionMenu**    | boolean | Enable you to show/hide 'Close chat' menu option in converation header top-right menu. Default value: false                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| **hideRestartConversationOptionsMenu** | boolean | Enable you to show/hide 'Restart chat' menu option in converation header top-right menu. Default value: false                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| **hideSettings**                       | boolean | Enable you to show/hide options menu in home component. Default value: false                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| **openExternalLinkButton**             | boolean | Enable you to open or not a link in an action button externally. Default value: true                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| **showWaitTime**                       | boolean | Show the expected response time from your agents in the home widget window. Default value: true.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| **dynamicWaitTimeReply**               | boolean | Enable you to decide whether or not to share the average response time of his team. Default value: true                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| **showAvailableAgents**                | boolean | Show the available agents with avatar in the home widget window. Default value: true.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| **showLogoutOption**                   | boolean | Show the logout options in the home widget window. Default value: false.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| **showAttachmentButton**               | boolean | Enable you to show/hide attachment button in the footer of a conversation. Default value: true                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| **showAllConversations**               | boolean | Enable you to show/hide the list of all conversations. Default value: true                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| **soundEnabled**                       | boolean | Enable you to allow or not sound when new message arrived. Default value: true                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| **open**                               | boolean | Set the status of the widget: true(open) or false (close). If it is \**true* the Widget suddenly opens right after loading. Default value: false                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| **isLogEnabled**                       | boolean | Enable the widget log. The default value is false.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| **logLevel**                           | string  | Allows you to change the level of the log. Value type: string. Permitted values: ‘ERR’ < ‘WARN’ < ‘INFO’ < ‘DEBUG’. Default value: ‘ERROR’                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| **startFromHome**                      | boolean | If false when loaded the widget starts directly with a new conversation. If true the widget shows the home component. Default value: true                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| **autoStart**                          |         | boolean                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| **startHidden**                        | boolean | Set if the widget starts in hidden mode. Default value : false                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| **preChatForm**                        | boolean | You can require customers to enter information like name and email before sending a chat message by enabling the Pre-Chat form. Default value: false.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| **preChatFormJson**                    | Array   | You can customize the information you request from customers in the pre-chat form before start a new conversation. ([See docs](https://developer.tiledesk.com/widget/advanced/prechat-form-json))                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| **customAttributes**                   | Object  | You can add customAttributes to widget as a key-value object. It is required to use *" "* for each key-value parameter. *'userFullname'* and *'userEmail'* special key allow you to set user info from external. See example above [here](https://developer.tiledesk.com/widget/attributes#example-3.-widget-with-custom-attributes) for more detail                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| **nativeRating**                       | boolean | Allow you to show or not widget rating page. Default value: true                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| **showInfoMessage**                    | string  | You can show/hide an info message in a conversion by specifying a comma separated list of keys. The keys in question are: **'MEMBER\_JOINED\_GROUP'** to manage the information of when an agent is added to your conversion; **'MEMBER\_LEFT\_GROUP'** to manage the information of when an agent left the conversation; **'CHAT\_CLOSED'** to manage the information of when a chat is closed; **'CHAT\_REOPENED'** to manage the information of when a chat already archived is subsequently reopened; **'TOUCHING\_OPERATOR'** to manage the information of when a conversation is assigned to an agent; **'LEAD\_UPDATED'** to manage an update of the widget user's name and email . Ex: *'MEMBER\_JOINED\_GROUP,CHAT\_CLOSED'*: allows you to see information about the joining of an agent within a conversation and when the current chat is archived. Default value: *'MEMBER\_JOINED\_GROUP'* |
| **restartConversation**                | boolean | This property if true, only when singleConversation is enabled, allow you to start always a new conversation at each page refresh or widget restart.Default value: false                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| **participants**                       | boolean | This property if true allow you to talk only with specif user passed as a comma separated list of ids. Ex: 'ID\_user1,ID\_user2'                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| **fileUploadAccept**                   | string  | This define which file types is allowed to be upload by the user as an attachment. It takes as its value a comma-separated list of one or more file types. See more [here](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept#unique_file_type_specifiers). Default value: 'image/\*,.pdf,.txt'                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |

<br>

### Message Style Attributes

These set of attributes modify the Widget style for messages (i.e. message background color, text color, buttons color etc.)

| Attributes                       | Type   | Description                                                                                                                                                                                                                                          |
| -------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **bubbleSentBackground**\*       | string | Allow you to change the bubble sent message background color. Permitted values: Hex color codes (e.g. #2a6ac1) and RGB color codes (e.g. rgb(42, 106, 193))                                                                                          |
| **bubbleSentTextColor**\*        | string | Allow you to change the bubble sent message text color. Permitted values: Hex color codes (e.g. #ffffff) and RGB color codes (e.g. rgb(255, 255, 255))                                                                                               |
| **bubbleReceivedBackground**     | string | Allow you to change the bubble received message background color. Permitted values: Hex color codes (e.g. #f7f7f7) and RGB color codes (e.g. rgb(247, 247, 247))                                                                                     |
| **bubbleReceivedTextColor**      | string | Allow you to change the bubble received message text color. Permitted values: Hex color codes (e.g. #1a1a1a) and RGB color codes (e.g. rgb(26, 26, 26))                                                                                              |
| **fontSize**                     | string | allow you to change the font size of bubble messages. Permitted values: medium \|xx-small\| x-small \| small \| large \| x-large \| xx-large \| smaller \| larger \| *length* \|%. Default value : "1.4em"                                           |
| **buttonFontSize**               | string | Allow you to change the font size of all the attachment buttons of a message. Permitted values: medium \|xx-small\| x-small \| small \| large \| x-large \| xx-large \| smaller \| larger \| *length* \|%. Value type: string. Default value: "15px" |
| **buttonBackgroundColor**        | string | Allow you to change the background color of all the attachment buttons of a message. Permitted values: Hex color codes (e.g. #1a1a1a) and RGB color codes (e.g. rgb(26, 26, 26))                                                                     |
| **buttonTextColor**\*            | string | Allow you to change the text color of all the attachment buttons of a message. Permitted values: Hex color codes (e.g. #1a1a1a) and RGB color codes (e.g. rgb(26, 26, 26))                                                                           |
| **buttonHoverBackgroundColor**\* | string | Allow you to change the background color of all the attachment buttons of a message when when you mouse over them. Permitted values: Hex color codes (e.g. #1a1a1a) and RGB color codes (e.g. rgb(26, 26, 26))                                       |
| **buttonHoverTextColor**         | string | Allow you to change the text color of all the attachment buttons of a message when when you mouse over them. Permitted values: Hex color codes (e.g. #1a1a1a) and RGB color codes (e.g. rgb(26, 26, 26))                                             |

\*These properties if not provided will automatically be calculate starting from **themeColor** value

<br>

### Widget visibility

These set of attributes can manage the visibility of the widget on mobile and desktop platforms

| Attributes                          | Type    | Description                                                                                                                                                                                                                                                                                                     |
| ----------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **displayOnDesktop**\*              | boolean | Allow you to display/hide widget on desktop. Default value: true                                                                                                                                                                                                                                                |
| **onPageChangeVisibilityDesktop**\* | string  | Allow to decide the widget status (opened or closed) when the page is loaded or changed on web browser. You can always open the widget, always close the widget or restore the last status of it (if closed, stay close; if opened, open it).Permitted values: 'open' , 'close', 'last'. Default value: 'close' |
| **displayOnMobile**                 | boolean | Allow you to display/hide widget on mobile. Default value: true                                                                                                                                                                                                                                                 |
| **onPageChangeVisibilityMobile**    | string  | Allow to decide the widget status (opened or closed) when the page is loaded or changed on web browser. You can always open the widget, always close the widget or restore the last status of it (if closed, stay close; if opened, open it).Permitted values: 'open' , 'close', 'last'. Default value: 'close' |

<br>

![Message style attributes helper schema](https://user-images.githubusercontent.com/47848430/151520122-bc7cec71-6724-4ad3-8282-9425198be816.png)

### Social channels Attributes

#### *(available only in **window\.tiledeskSettings** object)*

These set of attributes allow the owner to be reachable in their own social media channels (whatsapp businness, facebook messanger page, telegram). Buttons, when available, will be shown at the bottom of the home page, as displayed below.

![Social channels position](https://user-images.githubusercontent.com/47848430/208400033-6b3bf329-0864-4cbc-b217-116e8adeb208.png)

| Attributes             | Type    | Description                                                                                                       |
| ---------------------- | ------- | ----------------------------------------------------------------------------------------------------------------- |
| **whatsappNumber**     | boolean | This property allows the user of the widget to start a conversation on your official whatsapp business account    |
| **messangerPageTitle** | boolean | This property allows the user of the widget to start a conversation on your official Facebook Page with Messanger |
| **telegramUsername**   | boolean | This property allows the user of the widget to start a conversation on your official Telegram account             |

### Ready-only properties

| Attributes  | Type   | Description                                                                                                                                                                                                                                                     |
| ----------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **isShown** | string | This property returns the visibility of the whole widget including the widget ballon. If true the widget is visible otherwise (false) the widget is hidden. Use *window\.tiledesk.show()* and *window\.tiledesk.hide()* methods to change the widget visibility |

<br>

## Configuration using URL parameters

You can also pass the above configurations as a Url parameter with the **tiledesk\_** prefix. For example:

```
https://widget.tiledesk.com/v6/assets/twp/index.html?tiledesk_projectid=<YOUR_PROJECT_ID>&tiledesk_isOpen=true&tiledesk_align=right&project_name=Assistente%20Virtuale
```

## Examples

### Example 1. Widget with user fullname and email

```html
<script type="application/javascript">
  window.tiledeskSettings = 
    {
      projectid: "6480a7f683b1e1001370a6b1",
      userFullname: "Andrea Leo",
      userEmail: "andrea.leo@tiledesk.com"
    };
    (function(d, s, id) {
        var w=window; var d=document; var i=function(){i.c(arguments);}; 
        i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i; 
        var js, fjs=d.getElementsByTagName(s)[0]; 
        if (d.getElementById(id)) return; 
        js=d.createElement(s); 
        js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document,'script','tiledesk-jssdk'));
</script>
```

### Example 2. Widget with preChatForm and left alignment:

```html
<script type="application/javascript">
  window.tiledeskSettings = 
    {
      projectid: "6480a7f683b1e1001370a6b1",
      preChatForm: true,
      align: 'left'
    };
    (function(d, s, id) {
        var w=window; var d=document; var i=function(){i.c(arguments);}; 
        i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i; 
        var js, fjs=d.getElementsByTagName(s)[0]; 
        if (d.getElementById(id)) return; 
        js=d.createElement(s); 
        js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document,'script','tiledesk-jssdk'));
</script>
```

### Example 3. Widget with custom attributes:

Widget allow you to pass some custom attributes as key-value object in window\.tiledeksSettings object or as a Url parameter with the **tiledesk\_customAttributes** prefix.

```html
<script type="application/javascript">
  window.tiledeskSettings = 
    {
      projectid: "6480a7f683b1e1001370a6b1",
      align: 'left',
      customAttributes: { 
        "user_country": "Italy", 
        "user_code": "E001"
      }
    };
    (function(d, s, id) {
        var w=window; var d=document; var i=function(){i.c(arguments);}; 
        i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i; 
        var js, fjs=d.getElementsByTagName(s)[0]; 
        if (d.getElementById(id)) return; 
        js=d.createElement(s); 
        js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document,'script','tiledesk-jssdk'));
</script>
```

**customAttributes** is shown in conversation detail as payload key under attributes accordion as shown above

![customAttributes location](https://user-images.githubusercontent.com/47848430/166652826-a37e1d97-1e92-43bf-8f9a-6d7cd06b5e30.png)

Set *'userFullname'* or *'userEmail'* special key to manage user information from external (e.g. from your mobile app after an internal login). Above example of how to set it:

```html
<script type="application/javascript">
  window.tiledeskSettings = 
    {
        projectid: "6480a7f683b1e1001370a6b1",
        align: 'left',
        customAttributes: { 
          "userFullname": "Andrea Leo", 
          "userEmail": "andrea.leo@tiledesk.com"
        }
    };
    (function(d, s, id) {
        var w=window; var d=document; var i=function(){i.c(arguments);}; 
        i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i; 
        var js, fjs=d.getElementsByTagName(s)[0]; 
        if (d.getElementById(id)) return; 
        js=d.createElement(s); 
        js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document,'script','tiledesk-jssdk'));
</script>
```


# Javascript API: Listeners/Events

These event will triggers only when Tiledesk Widget fired some event in a specific situation. Once it's up, you'll be able to do something you need in the fanction handler.

```javascript
window.Tiledesk(event_name, handler)
```

Register an event handler to an event type.

## Available events:

| event\_name                        | description                                                                                                     |
| ---------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| **onLoadParams**                   | Fired when the parameters are loaded\*.                                                                         |
| **onInit**                         | Fired when the widget is initialized                                                                            |
| **onAuthStateChanged**             | The event is generated when the user logs in or logs out                                                        |
| **onOpen**                         | Fired when the widget is open                                                                                   |
| **onClose**                        | Fired when the widget is closed                                                                                 |
| **onBeforeMessageSend**            | Fired before the message sending.                                                                               |
| **onAfterMessageSend**             | This event is generated after the message has been sent.                                                        |
| **onOpenEyeCatcher**               | Fired when the callout box is open                                                                              |
| **onClosedEyeCatcher**             | Fired when the callout box is closed                                                                            |
| **onCloseMessagePreview**          | Fired when the user click on close button in message preview while new message is received and widget is closed |
| **onNewConversationComponentInit** | Fired just after a new conversation is initialized                                                              |
| **onBeforeDepartmentsFormRender**  | Fired just before rendering Departments in the Departments view                                                 |
| **onMessageCreated**               | Fired when the widget receive a message                                                                         |
| **onNewConversation**              | Fired when the widget start a new conversation                                                                  |
| **onConversationUpdated**          | Fired when the widget receive a conversation update                                                             |

\*This event will be fired before the tiledesk parameters is loaded. Use this event to change at runtime your Tiledesk settings.

## Initial events lifecycle:

onLoadParams -> onInit -> onAuthStateChanged

The handler will have the signature function(event\_data).

event\_data is a Javascript CustomEvent. More info about CustomEvent [here](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent)

Arguments:

| Parameter   | Type     | Required | Description                                       |
| ----------- | -------- | -------- | ------------------------------------------------- |
| event\_name | String   | YES      | Event name to bind to                             |
| handler     | Function | YES      | Function with the signature function(event\_data) |

## Important payload of event\_data:

| Parameter                | Type   | Description                      |
| ------------------------ | ------ | -------------------------------- |
| detail.default\_settings | Object | the constructor default settings |

**Ex. Logging of widget events**

```
<script type="application/javascript">    
    window.Tiledesk('onBeforeMessageSend', function(event_data) {
      var message =  event_data.detail.message;
      console.log("onBeforeMessageSend called ", message);
    });
    window.Tiledesk('onAfterMessageSend', function(event_data) {
      var message =  event_data.detail.message;
      console.log("onAfterMessageSend called ", message);
    });
</script>
```

**Ex. Widget with visitor fullname and email from localStorage**

```
<script type="application/javascript">    
    //set fullname to localstorage
    localStorage.setItem("user_fullname", "Andrea from localStorage");
    localStorage.setItem("user_email", "andrea.leo@f21.it");

    window.Tiledesk('onLoadParams', function(event_data) {
        window.tiledeskSettings.userFullname = localStorage.getItem("user_fullname");
        window.tiledeskSettings.userEmail = localStorage.getItem("user_email");
    }); 
</script>
```

**Ex. Widget with welcome message with current date**

```
<script type="application/javascript">    
    window.Tiledesk('onLoadParams', function(event_data) {
        window.tiledeskSettings.welcomeMsg = " Hello at: " + new Date().toLocaleString();
    });
</script>
```

## onBeforeMessageSend

This event will be fired before the message sending. Use this event to add user information or custom attributes to your chat message.

Important payload of event\_data:

| Parameter      | Type   | Description                    |
| -------------- | ------ | ------------------------------ |
| detail.message | Object | the message that is being sent |

**Ex. Programmatic setting custom user metadata**

```
<script type="application/javascript">    
    window.Tiledesk('onBeforeMessageSend', function(event_data) {
        var message =  event_data.detail.message;
        message.attributes.userCompany = "Frontiere21";
    });
</script>
```

**Ex. Add a custom attribute (page title) to the message.**

```
<script type="application/javascript">    
    window.Tiledesk('onBeforeMessageSend', function(event_data) {
        var message = event_data.detail.message;
        message.attributes.pagetitle = document.title;
    });
</script>
```

## onAfterMessageSend

This event is generated after the message has been sent.

Important payload of event\_data:

| Parameter      | Type   | Description               |
| -------------- | ------ | ------------------------- |
| detail.message | Object | the message that was sent |

**Ex:**

```
<script type="application/javascript">    
    window.Tiledesk('onAfterMessageSend', function(event_data) {
        var message =  event_data.detail.message;
        console.log("onAfterMessageSend called ", message);
    });
</script>
```

## onAuthStateChanged

This event is generated when the authentication state changed (Ex: user sign-in, user logout, etc.) Important payload of event\_data:

| Parameter | Type   | Description    |
| --------- | ------ | -------------- |
| detail    | Object | the auth event |

**Auth Event description:**

| Parameter             | Type    | Description                                                                         |
| --------------------- | ------- | ----------------------------------------------------------------------------------- |
| **event**             | string  | Possible values: 'online' when user is logged in, 'offline' when user is logged out |
| **isLogged**          | boolean | Possible values: true if the user is logged, false if not logged                    |
| **user\_id**          | string  | The current user identifier                                                         |
| **global**            | object  | An object with all the widget global parameters                                     |
| **default\_settings** | object  | The initial widget config parameters (window\.tiledeskSettings)                     |
| **appConfigs**        | object  | The remote widget config parameters obtained from the remote Tiledesk server        |

**Ex. :**

```
<script type="application/javascript">    
    window.Tiledesk('onAuthStateChanged', function (event_data) {
        console.log("onAuthStateChanged ----> ", event_data.detail.event);
        if (!event_data.detail.isLogged) {
            console.log("NOT logged");                      
            window.tiledesk.signInWithCustomToken("JWT CHANGE IT");                
        } else {
            console.log("logged in");
        }
    });
</script>
```

## onBeforeDepartmentsFormRender

This event is generated before rendering the Departments selection View. Use this event if you want to filter the default Departments list based on some conditions.

Important payload of event\_data:

| Parameter          | Type   | Description                          |
| ------------------ | ------ | ------------------------------------ |
| detail.departments | Object | the array of the default Departments |

**Ex. :**

In the following example Departments are filtered based on the current widget language. Actually a Department doesn't provide a specific "language" field. In this example Department language is put in the Department description field. Attention you can modify the departments array only by reference.

```
<script type="application/javascript">
    window.Tiledesk('onBeforeDepartmentsFormRender', function(event_data) {
        var departments = event_data.detail.departments;
        var lang = window.tiledesk.angularcomponent.component.g.lang;
        if (lang && lang === 'en') {
            var new_deps = departments.filter(function(dep) {
                if (dep.description && dep.description.includes('English')) {
                     return dep;
                }
            });
        } else {
            var new_deps = departments.filter(function(dep) {
                if (dep.description && dep.description.includes('French')){
                    return dep;
                }
            });
        }
        
        //modify the department array by reference
        
        departments.length=0;  //empty the array
        console.log("new_deps",new_deps);
        new_deps.forEach(function(d) { //populate the department array
            departments.push(d);
        });
            
    });
</script>
```

## onNewConversationComponentInit

This event is generated as soon as a new conversation view is rendered. Use this event if you want to execute some actions on a Conversation start.

Important payload of event\_data:

| Parameter        | Type   | Description                                     |
| ---------------- | ------ | ----------------------------------------------- |
| detail.newConvId | Object | the id of the conversation that fired the event |

**Ex. :**

In the following example a hidden message is sent as soon as a conversation starts. Sending a hidden message is useful to fire a bot welcome message, if one is invited in the conversation.

```
<script type="application/javascript">    
    window.Tiledesk('onNewConversationComponentInit', function(event_data) {
        const message = 'hello';
        const recipientId = event_data.detail.newConvId;
        const recipientFullname = 'Owner';
        const type = 'text';
        const metadata = {};
        const attributes = {test:'test attributes', subtype: 'info'};
        window.tiledesk.sendSupportMessage(
            message,
            recipientId,
            recipientFullname,
            type,
            metadata,
            attributes
        )
    });
}
</script>
```

## onMessageCreated

This event is generated when the widget receive a message.

Important payload of event\_data:

| Parameter | Type   | Description                   |
| --------- | ------ | ----------------------------- |
| detail    | Object | the message that was received |

**Ex. :**

```
<script type="application/javascript">    
    window.Tiledesk('onMessageCreated', function(event_data) {
        var message = event_data.detail;
        console.log("TRIGGER onMessageCreated -> ", message);
    });
</script>
```

## onConversationUpdated

This event is generated when the widget receive a conversation update.

Important payload of event\_data:

| Parameter | Type   | Description                        |
| --------- | ------ | ---------------------------------- |
| detail    | Object | the conversation that was received |

Example:

```
<script type="application/javascript">    
    var now = Date.now();
    window.Tiledesk('onConversationUpdated', function(event_data) {
        var dateConvUpdate = event_data.detail.conversation.timestamp
        console.log(" TRIGGER onConversationUpdated -> ", event_data.detail.conversation);
        console.log("now-> ", now);
        console.log("dateConvUpdate-> ", dateConvUpdate);
        if(now < dateConvUpdate){
            console.log(" New conversation!!!");
        }
    });
</script>
```


# Widget Authentication

## Enabling authenticated visitors

Require Widget Javascript API v4

### Overview

You can configure your widget to authenticate visitors using the Javascript API and JWT token.

When you configure the Chat widget to use authenticated visitors, you get the following benefits:

* Ability to have higher confidence and security that the visitor/customer you or your agents are talking to is the real deal
* Support for cross device/browser identification. The visitor can be viewed as the same person if or when they choose to use a different device or browser when the custom ID is specified in the authentication call.

To configure your widget for visitor authentication, you need to [Generate a Project Shared Secret](/apis/authentication#generating-a-project-shared-secret). Only Chat administrators can configure visitor authentication settings. Once you have generated the shared secret, use it to create a JWT token that you'll add to your Web Widget snippet.

### Creating a JWT token

To create a JWT token:

1\) Construct a server-side payload of data for the JWT token. Your token needs to be dynamically generated from the server-side on page load. Please follow this guide to [Create a JWT Token](/apis/authentication).

2\) Set the Tiledesk widget property **autoStart** to **false**.

3\) Use the **window\.Tiledesk('signInWithCustomToken', JWT)** Javascript API to provide a function which supplies a fresh JWT every time it is invoked. Below is a code example:

```
window.Tiledesk("signInWithCustomToken", "<JWT JWT_TOKEN_HERE_GENERATED_SERVER_SIDE>");
```

ATTENTION: the token passed with signInWithCustomToken must starts with the string "JWT ".

Example:

```
window.Tiledesk("signInWithCustomToken","JWT 12345678...");
```

4\) Use the **onAuthStateChanged** event to check if user is logged in and then show widget

```
window.Tiledesk('onAuthStateChanged', function(event_data) {
    console.log("onAuthStateChanged FIRED-->", event_data);
    if(event_data.detail.isLogged){
        window.Tiledesk('show')
    }
});
```

See a complete example [here](https://www.w3schools.com/code/tryit.asp?filename=GU3DPFHYTP8E).

## About the agent experience with authenticated visitors

A few things are updated in the Chat dashboard when an agent starts chatting with an authenticated visitor.

First, the agent will be able to tell the visitor is authenticated by the authenticated checkmark overlay on the visitor's avatar.

![image](https://user-images.githubusercontent.com/9378770/150633296-5bb21335-2b5d-4be9-a5d2-d62b0f488e7e.png)


# Widget for Android with WebView

This example shows how to integrate the Tiledesk Widget via a WebView for Android.

Attention the Tiledesk Widget is compatible with Android 13+

## Integrate Widget for Android with WebView

### Permissions

Don't forget to give permission in your manifest.xml adding the following:

```
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
```

## **Method 1:** load Tiledesk widget from embedding url

### Activity

```
package com.tiledesk.tiledeskwidgetintegrationexample;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

public class TiledeskActivity extends AppCompatActivity {


    public static final int REQUEST_SELECT_FILE = 100;
    public ValueCallback<Uri[]> uploadMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tiledesk);

        WebView myWebView = (WebView) findViewById(R.id.tiledesk);

        
        myWebView.setWebChromeClient(new FileChooserWebChromeClient(this) {
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.d("TiledeskActivity", consoleMessage.message() + " -- From line "
                        + consoleMessage.lineNumber() + " of "
                        + consoleMessage.sourceId());
                return super.onConsoleMessage(consoleMessage);
            }
        });

        // Enable JavaScript
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

    
        // Enable DOM storage API (localStorage/sessionStorage)
        webSettings.setDomStorageEnabled(true);

        //allow to snap photos
        webSettings.setAllowFileAccess(true);

        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        //Inject widget load URL
        myWebView.loadUrl("https://widget.tiledesk.com/v6/assets/twp/index.html?tiledesk_projectid=<CHANGE_IT>&tiledesk_fullscreenMode=true&tiledesk_hideHeaderCloseButton=true&tiledesk_open=true");

    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SELECT_FILE) {
            if (uploadMessage == null) return;
            uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
            uploadMessage = null;
        }
    }


    public class FileChooserWebChromeClient extends WebChromeClient {

        private Activity myActivity;

        public FileChooserWebChromeClient(TiledeskActivity myActivity) {
            this.myActivity = myActivity;
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            uploadMessage = filePathCallback;

            Intent intent = fileChooserParams.createIntent();
            try {
                myActivity.startActivityForResult(intent, REQUEST_SELECT_FILE);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(myActivity, "Cannot open file chooser", Toast.LENGTH_LONG).show();
                return false;
            }

            return true;
        }
    }

}
```

### Layout

```
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TiledeskActivity">

    <WebView
        android:id="@+id/tiledesk"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
```

## **Method 2:** load Tiledesk widget from custom html file that integrate tiledesk script

### HTML code

Consider an \*.html file into assets that contains basic html code with script tag able to integrate tilesk widget inside your webview

```html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

    <script type="application/javascript">
      window.tiledeskSettings=
      {
          projectid: "<CHANGE_IT>",
          fullscreenMode: true,
          open:true,
      };
      (function(d, s, id) {
        var w=window; var d=document; var i=function(){i.c(arguments);};
        i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i;
        var js, fjs=d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js=d.createElement(s);
        js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
        fjs.parentNode.insertBefore(js, fjs);
      }(document,'script','tiledesk-jssdk'));

      window.addEventListener('load', (event)=> {
        document.dispatchEvent(new Event('mousemove'))
      })

    </script>
</head>
</html>
```

### Activity

```
package com.tiledesk.tiledeskwidgetintegrationexample;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

public class TiledeskInjectActivity extends AppCompatActivity {


    public static final int REQUEST_SELECT_FILE = 100;
    public ValueCallback<Uri[]> uploadMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tiledesk);

        WebView myWebView = (WebView) findViewById(R.id.tiledesk);

        
        myWebView.setWebChromeClient(new FileChooserWebChromeClient(this) {
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.d("TiledeskInjectActivity", consoleMessage.message() + " -- From line "
                        + consoleMessage.lineNumber() + " of "
                        + consoleMessage.sourceId());
                return super.onConsoleMessage(consoleMessage);
            }
        });

        // Enable JavaScript
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

    
        // Enable DOM storage API (localStorage/sessionStorage)
        webSettings.setDomStorageEnabled(true);

        //allow to snap photos
        webSettings.setAllowFileAccess(true);

        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        //Inject widget load URL
        myWebView.loadUrl("file:///android_asset/index.html");

    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SELECT_FILE) {
            if (uploadMessage == null) return;
            uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
            uploadMessage = null;
        }
    }


    public class FileChooserWebChromeClient extends WebChromeClient {

        private Activity myActivity;

        public FileChooserWebChromeClient(TiledeskInjectActivity myActivity) {
            this.myActivity = myActivity;
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            uploadMessage = filePathCallback;

            Intent intent = fileChooserParams.createIntent();
            try {
                myActivity.startActivityForResult(intent, REQUEST_SELECT_FILE);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(myActivity, "Cannot open file chooser", Toast.LENGTH_LONG).show();
                return false;
            }

            return true;
        }
    }

}
```

Find [here](/widget/web-sdk) other widget parameters to customize your experience.

### Layout

```
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TiledeskInjectActivity">

    <WebView
        android:id="@+id/tiledesk"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
```

## Example

You can find here a complete [Tiledesk Widget example for Android](https://github.com/Tiledesk/tiledesk-android-widget-example).


# Widget for iOS with WKWebView

This example shows how to integrate the Tiledesk Widget for iOS

## Controller

```
//
//  WebViewViewController.swift
//  Tiledesk
//

import UIKit
import WebKit

class WebViewViewController: UIViewController, WKUIDelegate {

    @IBOutlet weak var webView: WKWebView!
    @IBAction func actionClosing(_ sender: UIBarButtonItem) {
        dismiss(animated: true, completion: nil)
    }

    override func loadView() {

        let image = UIImage(named: "ic_navigation_bar")!
        let nav = self.navigationController?.navigationBar
        let tintColor = UIColor(red: 51, green: 71, blue: 94, alpha: 1)
        nav?.setupNavigationBar(barStyleBlack: true, tintColor: tintColor, image: image)


        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }



    override func viewDidLoad() {
        super.viewDidLoad()
        let url = "https://widget.tiledesk.com/v6/assets/twp/blank.html?tiledesk_projectid=<CHANGE_IT>&tiledesk_fullscreenMode=true&tiledesk_hideHeaderCloseButton=true&tiledesk_open=true"
        let myURL = URL(string:url)
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
```

Find [here](/widget/web-sdk) other widget parameters to customize your experience.

## Web View Controller

Create a Web View Controller in your Story Board and add a WebView as below:

![](/files/-LkZT1Acumur8-pemJUB)


# Widget for Flutter with WebView

This example shows how to integrate the Tiledesk Widget via a WebView for Flutter.

## Integrate Widget for Flutter with WebView

This guide will use the package [webview\_flutter](https://pub.dev/packages/webview_flutter) to implement a Webview, but other similar packages should work with minimal changes to the code.

## Implementation

```dart
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';

class Webview extends StatefulWidget {
  const WebView();

  @override
  ConsumerState<WebView> createState() => _WebViewState();
}

class _WebViewState extends State<WebView> {
  late final _controller = WebViewController();

  @override
  void initState() {
    super.initState();
    unawaited(_initializeController());
  }

  @override
  Widget build(BuildContext context) {
    return ColoredBox(
      color: Colors.white,
      child: WebViewWidget(controller: _controller),
    );
  }

  Future<void> _initializeController() async {
    // disable javascript dialog
    await _controller.setOnJavaScriptAlertDialog((request) async {
      return;
    });
    switch (_controller.platform) {
      case final AndroidWebViewController controller:
        await controller.setOnShowFileSelector((params) {
          // implement your logic to show a file picker
          // attachment upload will not work on android unless this is setup
        });
      case final WebKitWebViewController _:
        break;
    }

    await _controller.setJavaScriptMode(JavaScriptMode.unrestricted);

    return _loadRequest();
  }
  
  Future<void> _loadRequest() async {
    final navigationDelegate = NavigationDelegate(
      onPageFinished: (url) {
        // this is necessary to trigger the widget to show without the need for
        //the user to interact with the webview
        _controller.runJavaScript('''
document.dispatchEvent(new Event('mousemove'));
''');
      }
      onNavigationRequest: (request) {
        // intercept url navigation
        // this may be useful to display attachments like PDFs in a custom widget

        // if(request.url.endsWith('.pdf')) {
        //   Navigator.of(context).push(MyPdfViewer());
        //   return NavigationDecision.prevent;
        // }

        return NavigationDecision.navigate;
      },
    );
    await _controller.setNavigationDelegate(navigationDelegate);

    return _controller.loadHtmlString(
      '''
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

    <script type="application/javascript">
      window.tiledeskSettings= 
      {
          projectid: "<<TILEDESK_PROJECT_ID>>",
          fullscreenMode: true,
          open:true,
      };
      (function(d, s, id) { 
        var w=window; var d=document; var i=function(){i.c(arguments);};
        i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i;                    
        var js, fjs=d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js=d.createElement(s); 
        js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
        fjs.parentNode.insertBefore(js, fjs);
      }(document,'script','tiledesk-jssdk'));
    </script>
  </head>
</html>''',
      baseUrl: 'https://widget.tiledesk.com',
    );
  }
}

```

Find [here](https://developer.tiledesk.com/widget/web-sdk) other widget parameters to customize your experience.


# Widget for React with WebView

This example shows how to integrate the Tiledesk Widget via a WebView for React Native Expo or React Native CLI project

## Integrate Widget for React Native Expo project with WebView

### Prerequisites

Make sure you have installed react-native-webview via Expo command:

```shell
npx expo install react-native-webview
```

### **Method 1:** load Tiledesk widget from embedding url

Consider an \*.html file into assets that contains basic html code with script tag able to integrate tilesk widget insede your webview

```html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

    <script type="application/javascript">
      window.tiledeskSettings=
      {
          projectid: "<CHANGE_IT>",
          fullscreenMode: true,
          open:true,
      };
      (function(d, s, id) {
        var w=window; var d=document; var i=function(){i.c(arguments);};
        i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i;
        var js, fjs=d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js=d.createElement(s);
        js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
        fjs.parentNode.insertBefore(js, fjs);
      }(document,'script','tiledesk-jssdk'));

      window.addEventListener('load', (event)=> {
        document.dispatchEvent(new Event('mousemove'))
      })

    </script>
</head>
</html>
```

Add a webview to the file and set the source as the url of the local html file

```dart
import React from 'react';
import { StyleSheet, View } from 'react-native';
import { WebView } from 'react-native-webview';


const WebViewScreen = () => {
 return (
   <View style={styles.container}>
     <WebView
       originWhitelist={['*']}
       source={require('../../assets/widget.html')}
       style={{ flex: 1 }}
     />
   </View>
 );
};


const styles = StyleSheet.create({
 container: {
   flex: 1,
 },
});


export default WebViewScreen;
```

### **Method 2:** load Tiledesk widget from embedding script

Add a webview to the file and set the source as html code

```dart
import React from 'react';
import { StyleSheet, View } from 'react-native';
import { WebView } from 'react-native-webview';


const WebViewScreen = () => {
 const htmlContent = `
   <!DOCTYPE html>
   <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">


        <script type="application/javascript">
          window.tiledeskSettings=
          {
              projectid: "<CHANGE_IT>",
              fullscreenMode: true,
              open:true,
          };
          (function(d, s, id) {
            var w=window; var d=document; var i=function(){i.c(arguments);};
            i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i;
            var js, fjs=d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js=d.createElement(s);
            js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
            fjs.parentNode.insertBefore(js, fjs);
          }(document,'script','tiledesk-jssdk'));


          window.addEventListener('load', (event)=> {
            document.dispatchEvent(new Event('mousemove'))
          })
        </script>
    </head>
    <body>
    </body>
   </html>
 `;


 return (
   <View style={styles.container}>
     <WebView
       originWhitelist={['*']}
       source={{ html: htmlContent }}
       style={{ flex: 1 }}
     />
   </View>
 );
};


const styles = StyleSheet.create({
 container: {
   flex: 1,
 },
});


export default WebViewScreen;
```

## Integrate Widget for React Native CLI project with WebView

### Prerequisites

Make sure you have installed react-native-webview via Expo command:

```shell
npx expo install react-native-webview
```

### Implementation

Consider an \*.html file into assets that contains basic html code with script tag able to integrate tiledesk widget inside your webview ex. *“widget.html”*

```html
<!DOCTYPE html>
<html>
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

      <script type="application/javascript">
        window.tiledeskSettings=
        {
            projectid: "<CHANGE_IT>",
            fullscreenMode: true,
            open:true,
        };
        (function(d, s, id) {
          var w=window; var d=document; var i=function(){i.c(arguments);};
          i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i;
          var js, fjs=d.getElementsByTagName(s)[0];
          if (d.getElementById(id)) return;
          js=d.createElement(s);
          js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
          fjs.parentNode.insertBefore(js, fjs);
        }(document,'script','tiledesk-jssdk'));

        window.addEventListener('load', (event)=> {
          document.dispatchEvent(new Event('mousemove'))
        })

      </script>
  </head>
</html>
```

Add the **widget.html** file to the correct project directory.

**For Android**: Place the file in android/app/src/main/assets/.\
**For iOS**: Place the file in ios/\<AppName>/widget.html. If the assets folder does not exist (on Android), you can create it manually.

Add webview to App.tsx

```dart
import React from 'react';
import { SafeAreaView, StyleSheet } from 'react-native';
import { WebView } from 'react-native-webview';


import { Platform } from 'react-native';


const App = () => {
 const localFile = Platform.OS === 'ios' ? require('./widget.html') : 'file:///android_asset/widget.html';


 return (
   <SafeAreaView style={styles.container}>
     <WebView
       originWhitelist={['*']}
       source={Platform.OS === 'ios' ? localFile : { uri: localFile }}
       style={styles.webview}
     />
   </SafeAreaView>
 );
};


const styles = StyleSheet.create({
 container: {
   flex: 1,
 },
 webview: {
   flex: 1,
 },
});


export default App;
```

## Example

You can find here a complete [Tiledesk Widget example for React Native EXPO project example](https://github.com/Tiledesk/tiledesk-widget-react-native-expo) or [Tiledesk Widget example for React Native CLI project example](https://github.com/Tiledesk/tiledesk-widget-react-native-cli)


# Widget for Wix Website platform

This example shows how to integrate the Tiledesk Widget via a custom HTML code using [Wix website platform](https://manage.wix.com/)

### Prerequisites

Due to [security update](https://support.wix.com/en/article/updates-to-iframes-and-custom-elements) in wix, some elements in widget installation snippet code could be blocked. But, no warries. We already found a smart solution with some additional work.

What you have to do, before adding custom code to your website with wix, is to create an html page that can host the Tiledesk Widget installation snippet code like the one below:

```html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

    <script type="application/javascript">
      window.tiledeskSettings=
      {
          projectid: "<CHANGE_IT>",
          fullscreenMode: true,
          open:true,
      };
      (function(d, s, id) {
        var w=window; var d=document; var i=function(){i.c(arguments);};
        i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i;
        var js, fjs=d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js=d.createElement(s);
        js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
        fjs.parentNode.insertBefore(js, fjs);
      }(document,'script','tiledesk-jssdk'));

      window.addEventListener('load', (event)=> {
        document.dispatchEvent(new Event('mousemove'))
      })

    </script>
</head>
</html>
```

Now take notes of this url (for this tutorial we'll named it as **https\://\<my-server-hosting-page-url>** ). We have to use it soon.

### Installation

From your wix website panel, follow this steps:

1. After completing the basic configuration of your site, navidate to "Settings." You can usually find this option in the top menu or sidebar.
2. Scroll down and click on *Custom code* setting option in **Developer and integrations** section.
3. Add your custom code by click on *+Add custom code* ![](https://a.storyblok.com/f/156985/975x505/2a40158e0d/wix-custom-code.png/m/)
4. From the modal window that appears, place an iframe HTML element in the text box. The iframe src property has to link to a public https page hosted on your server. Code example could be:

```html
<iframe src="https://<my-server-hosting-page-url>" width="100%" height="600" style="border:none;"></iframe>
```

Set a name, the pages where the code has to be active and set the embedded code to 'pin to screen' (to make it stick in the right bottom corner)

5. Apply the changes and the Tiledesk live chat widget on your Wix website should works fine.

That's it! Your Wix website is now equipped with the Tiledesk live chat widget, allowing you to engage with visitors in real-time and provide excellent customer support.

Many thanks to Frank Huisman from Duo Criativo agency for the collaboration on writing this tutorial


# Tutorials


# Hide widget

In this tutorial we will show to you a simple tutorial of how to hide widget if no agent is still available. Steps to make them is very easy:

1. Start widget in hidden mode setting startHidden boolean property to true
2. Get widget settings using Tiledesk APIs
3. Use the function window\.Tiledesk(‘show’) to show the widget ONLY if some agent is available.

Here is the full code example

```html
<html>
    <head>
        <script type="application/javascript">
            var PROJECT_ID = "<<TILEDESK_PROJECT_ID>>"
            window.tiledeskSettings=
            {
                projectid: PROJECT_ID,
                startHidden: true
            };
            (function(d, s, id) {
                var w=window; var d=document; var i=function(){i.c(arguments);}; 
                i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i; 
                var js, fjs=d.getElementsByTagName(s)[0]; 
                if (d.getElementById(id)) return; 
                js=d.createElement(s); 
                js.id=id; js.async=true; js.src="https://widget.tiledesk.com/6/launch.js";
                fjs.parentNode.insertBefore(js, fjs);
            }(document,'script','tiledesk-jssdk'));

            getWidgetSettings((err, result) => {
                    const users_available = result['user_available']
                    let availability = true;
                    if (!users_available || users_available.length == 0) {
                        document.getElementById('available').innerHTML = "No one is available, widget will stay hidden!";
                    }
                    else {
                        document.getElementById('available').innerHTML = "Someone is available, showing widget...";
                        window.Tiledesk('show');
                    }
                });

                function getWidgetSettings(callback) {
                    const options = {
                        url: `https://api.tiledesk.com/v3/${projectId}/widgets`, // PROJECT ID IS ALSO USED HERE TO GET PROJECT SETTINGS
                        method: 'GET'
                    };
                    let xmlhttp = new XMLHttpRequest();
                    xmlhttp.open(options.method, options.url, true);
                    xmlhttp.onreadystatechange = function() {
                        if (callback && xmlhttp.readyState == 4 && xmlhttp.status == 200 && xmlhttp.responseText) {
                            try {
                                const json = JSON.parse(xmlhttp.responseText);
                                callback(null, json);
                            }
                            catch (err) {
                                callback(err, null);
                            }
                        }
                    };
                    xmlhttp.send(null);
                }
        </script>
    </head>
    <body>
        This Tiledesk example will hide the widget if no agent is available
        <div>
            <b>Agents available:</b> <span id='available'>loading availability...</span>
        </div>
    </body>
</html>
```

View result [here](https://andreasponziello.w3spaces.com/tiledesk-widget-hidden-on-unavailability-example.html)


# Show/Hide widget programmatically

In this tutorial we will show to you how to manage visualization of widget programmatically using *hide/show* parameters and *open/close* method. Furthermore, we add a subscription to **onClose** tiledesk event to manage close button and hide it on click.

First of all you have to set **startHidden** property to true in window\.tiledeskSettings to not show widget when it starts.

```java
window.tiledeskSettings= {
    projectid: "<<TILEDESK_PROJECT_ID>>",
    startHidden: true
};
```

Then you have to handle click event of the openWidget and closeWidget buttons in order to programmatically show and hide widget.

```java
// programmatically open the widget
function openWidget() {
    window.Tiledesk('show');
    window.Tiledesk('open');
}

// programmatically close the widget
function closeWidget() {
    window.Tiledesk('close');
    window.Tiledesk('hide');
}
```

Finally, to complete, you can optionally subscribe to 'onClose' tiledesk event and use hide method to hide widget when user click on close up right corner icon.

```java
//subscribe to onClose Tiledesk event and then hide widget 
window.Tiledesk('onClose', function(event_data) {
    window.Tiledesk('hide')
});
```

The entire sample code is presented below.

```html
<script type="application/javascript">
        window.tiledeskSettings= 
        {
            projectid: "6480a7f683b1e1001370a6b1",
            startHidden: true
        };
        (function(d, s, id) { 
            var w=window; var d=document; var i=function(){i.c(arguments);};
            i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i;                    
            var js, fjs=d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js=d.createElement(s); 
            js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document,'script','tiledesk-jssdk'));

        
        // programmatically open the widget
        function openWidget() {
          window.Tiledesk('show');
          window.Tiledesk('open');
        }

        // programmatically close the widget
        function closeWidget() {
          window.Tiledesk('close');
          window.Tiledesk('hide');
        }

        //subscribe to onClose Tiledesk event and then hide widget 
        window.Tiledesk('onClose', function(event_data) {
           window.Tiledesk('hide')
        });
</script>
```

On this page [here](https://replit.com/@tiledesk/Tiledesk-HTML-Site#index.html) you can view the entire code and run it to better understand the results


# Force widget loading without user interaction

In this tutorial we will show to you how to force the loading of Tiledesk Widget on your website.\
By default widget is not loaded. It will always appear after 5 seconds unless one of the below listed event triggers an earlier start. This prevent your website to load tiledesk resources and improve the entire performance loading. Only once your website is loaded and user move/scroll mouse, tiledesk starts load widget source.

Steps to make them is very easy:

1. Copy and paste the basic widget script code
2. Use the window event listener to hook 'load' event
3. Manually fire one of the following event listed:
   * scroll
   * mousedown
   * mousemove
   * touchstart
   * keydown

Here is the full code example

```html
<html>
    <head>
        <script type="application/javascript">
            var PROJECT_ID = "<<TILEDESK_PROJECT_ID>>"
            window.tiledeskSettings=
            {
                projectid: PROJECT_ID,
            };
            (function(d, s, id) {
                var w=window; var d=document; var i=function(){i.c(arguments);}; 
                i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i; 
                var js, fjs=d.getElementsByTagName(s)[0]; 
                if (d.getElementById(id)) return; 
                js=d.createElement(s); 
                js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
                fjs.parentNode.insertBefore(js, fjs);
            }(document,'script','tiledesk-jssdk'));

            /** listen to 'load' window event **/
            window.addEventListener('load', (event)=> {
                document.dispatchEvent(new Event('mousemove'))
            })

        </script>
    </head>
    <body>
        This Tiledesk example will force the loading of the widget 
    </body>
</html>
```

## Force the loading only on mobile platform

If you only want to force the loading of the widget on mobile you can add a funtion to detect the platform where the widget is currently running on.

```html
<html>
    <head>
        <script type="application/javascript">
            var PROJECT_ID = "<<TILEDESK_PROJECT_ID>>"
            window.tiledeskSettings=
            {
                projectid: PROJECT_ID,
            };
            (function(d, s, id) {
                var w=window; var d=document; var i=function(){i.c(arguments);}; 
                i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i; 
                var js, fjs=d.getElementsByTagName(s)[0]; 
                if (d.getElementById(id)) return; 
                js=d.createElement(s); 
                js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
                fjs.parentNode.insertBefore(js, fjs);
            }(document,'script','tiledesk-jssdk'));

            let isMobile = detectIfIsMobile(window)
            if(isMobile){
                window.addEventListener('load', (event)=> {
                    document.dispatchEvent(new Event('mousemove'))
                })
            }

            /** check current platform **/
            function detectIfIsMobile(windowContext) {
                let isMobile = false;
                if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|mobile|CriOS/i.test(windowContext.navigator.userAgent))
                    isMobile = true
                else
                    isMobile = false
                return isMobile;
            } 

        </script>
    </head>
    <body>
        This Tiledesk example will force the loading of the widget <b>only on MOBILE PLATFORM</b>
    </body>
</html>
```


# Mobile positioning

In this tutorial we will show to you how to better and simply position Tiledesk Widget on your website when in served on mobile browser Steps to make them is very easy:

1. Copy and paste the basic widget script code
2. Set **mobileMarginX** and **mobileMarginY** property inside window\.tiledeskSettings
3. Use the function window\.Tiledesk(‘show’) to show the widget ONLY if some agent is available.

Here is the full code example

```html
<html>
    <head>
        <script type="application/javascript">
            var PROJECT_ID = "<<TILEDESK_PROJECT_ID>>"
            window.tiledeskSettings=
            {
                projectid: PROJECT_ID,
                startHidden: true,
                mobileMarginX: "20px",
                mobileMarginY: "10px"
            };
            (function(d, s, id) {
                var w=window; var d=document; var i=function(){i.c(arguments);}; 
                i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i; 
                var js, fjs=d.getElementsByTagName(s)[0]; 
                if (d.getElementById(id)) return; 
                js=d.createElement(s); 
                js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
                fjs.parentNode.insertBefore(js, fjs);
            }(document,'script','tiledesk-jssdk'));

        </script>
    </head>
    <body>
        This Tiledesk example will hide the widget if no agent is available
        <div>
            <b>Agents available:</b> <span id='available'>loading availability...</span>
        </div>
    </body>
</html>
```

Here is in detail what exactly **mobileMarginX** and **mobileMarginY** do

![Mobile positioning](https://user-images.githubusercontent.com/47848430/226629891-bf97c1f5-dd3b-48be-ba70-07a2e5bcdbbf.png)


# Custom size (width/height)

In this tutorial we will show to you how to better and simply change the Tiledesk Widget size on your website

Steps to make them is very easy:

1. Copy and paste the basic widget script code
2. Subscribe to **onInit** Tiledesk event
3. Add custom stylesheet to override the default values

Here is the full code example

```html
<html>
    <head>
        <script type="application/javascript">
            var PROJECT_ID = "<<TILEDESK_PROJECT_ID>>"
            window.tiledeskSettings=
            {
                projectid: PROJECT_ID,
                startHidden: true,
            };
            (function(d, s, id) {
                var w=window; var d=document; var i=function(){i.c(arguments);}; 
                i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i; 
                var js, fjs=d.getElementsByTagName(s)[0]; 
                if (d.getElementById(id)) return; 
                js=d.createElement(s); 
                js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
                fjs.parentNode.insertBefore(js, fjs);
            }(document,'script','tiledesk-jssdk'));

            window.Tiledesk('onInit', function (event_data) {
                //var tiledeskDiv = document.getElementById("tiledeskdiv")

                var head = document.getElementsByTagName('head')[0];
                var style = document.createElement('style');
                style.id = 'customStyle';
                style.type = 'text/css';

                style.innerHTML += '#tiledeskdiv { height: 800px; width: 400px; }\n';

                head.appendChild(style);
            })

        </script>
    </head>
    <body>
        This Tiledesk example will change the widget size in height and width as you want
        <div>
            <b>Agents available:</b> <span id='available'>loading availability...</span>
        </div>
    </body>
</html>
```

View result [here](https://tiledesk-html-site-tiledesk.replit.app/widget/customDimension.html)


# Installing widget on selected pages

This tutorial guides you through setting up the Tiledesk live chat widget to display only on selected pages of your website. By leveraging a custom script, you can include or exclude the widget based on the page's URL. The script checks the current URL and decides whether to load the Tiledesk widget based on defined conditions, and it includes functions for login, logout, and custom authentication.

## Step 1: Define Included/Excluded Pages

The script checks the current URL to decide if the widget should be loaded. Here’s how you can set up exclusions:

```javascript
const projectId = "63b711fa2ef2e4001a5e4977";
let attributes = {};

if (
  (window.location.href.indexOf('/cds') >= 0) ||
  (window.location.href.indexOf('%2Fcds') >= 0) ||
  (window.location.href.indexOf('/dashboard') >= 0) ||
  (window.location.href.indexOf('%2Fdashboard') >= 0)
) {
  // Pages to exclude: do not start the widget
} else if (
  ((window.location.href.indexOf('/login') >= 0) || 
   (window.location.href.indexOf('%2Flogin') >= 0) || 
   (window.location.href.indexOf('/signup') >= 0) || 
   (window.location.href.indexOf('%signup') >= 0)
  ) && screen.width < 800
) {
  // Also exclude these pages on mobile devices
} else {
  // startWidget()
}
```

In this code, replace /cds, /dashboard, /login, etc., with the specific paths on your domain where you want to exclude or include the widget.

## Step 2: Define the startWidget Function

The startWidget function loads the Tiledesk widget with the desired configuration, setting up the project ID and auto-start behavior.

```javascript
function startWidget(){
    window.tiledeskSettings = {
        projectid: projectId,
        autoStart: true
    };

    (function (d, s, id) {
        var w = window; var d = document; var i = function () { i.c(arguments); };
        i.q = []; i.c = function (args) { i.q.push(args); }; w.Tiledesk = i;
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s);
        js.id = id; js.async = true; js.src = "https://widget.tiledesk.com/v6/launch.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'tiledesk-jssdk'));
}
```

## Step 3: Additional Control Functions

The following functions provide additional control over the widget’s behavior:

* tiledesk\_widget\_hide(): Hides the widget.
* tiledesk\_widget\_show(): Shows the widget.
* tiledesk\_widget\_login(attribute): Logs in the user with a custom attribute.
* tiledesk\_widget\_logout(): Logs out the user and signs in anonymously.

These functions help manage the widget's state on different pages.

## Step 4: Custom Authentication

The customAuth function sends user data to a custom authentication URL, receiving a JWT token that is used to sign in the user with Tiledesk.

```javascript
function customAuth(callback) {
    const storedUser = localStorage.getItem('user');
    let user = storedUser ? JSON.parse(storedUser) : null;
    if (!user) {
        callback(null);
        return;
    }
    const remote_support_project_userId = projectId + "_" + user._id;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "https://tiledesk-custom-jwt-authentication.replit.app/tiledeskauth", true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.onreadystatechange = function () {
        if (callback && xmlhttp.readyState == 4 && xmlhttp.status == 200 && xmlhttp.responseText) {
            callback(xmlhttp.responseText);
        }
    };
    xmlhttp.send("id=" + remote_support_project_userId + "&firstname=" + user.firstname + "&lastname=" + user.lastname + "&email=" + user.email);
}
```

## Step 5: Testing and Verification

1. Verify Included/Excluded Pages: Visit the included pages to confirm the widget appears, and the excluded pages to ensure it remains hidden.
2. Test Login/Logout: Confirm that login and logout behaviors are working as expected, especially for the custom authentication flow.

This script provides granular control over where the Tiledesk widget appears, enhancing the user experience by excluding it from specific pages and enabling custom authentication.


# Custom widget style

In this tutorial we will show to you a simple tutorial of how to override the default style of the widget icon, and how to add a simple animation on hover event on the same element

You can use this example to override and change every element of the widget and customize it as you want. Simply remember to subsribe to 'onInit' navite Tiledesk event and append style to the and of the already loaded files

Here is a preview of the custom launcher icon override

![Custom launcher icon](https://raw.githubusercontent.com/gab-95/images-host/refs/heads/main/453939446-a14920a4-1c51-4b40-ba5e-a456aa740abd.png)

Here is the full code example

```html
<html>
    <head>
        <script type="application/javascript">
            var PROJECT_ID = "<<TILEDESK_PROJECT_ID>>"
            window.tiledeskSettings =
            {
                projectid: PROJECT_ID,
            };
            (function (d, s, id) {
                var w = window; var d = document; var i = function () {i.c(arguments);};
                i.q = []; i.c = function (args) {i.q.push(args);}; w.Tiledesk = i;
                var js, fjs = d.getElementsByTagName(s)[0];
                if (d.getElementById(id)) return;
                js = d.createElement(s);
                js.id = id; js.async = true; js.src = "https://widget.tiledesk.com/v6/launch.js";
                fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'tiledesk-jssdk'));

            window.Tiledesk('onInit', function (event_data) {
                var iframeTiledesk = document.getElementById("tiledeskiframe");

                var style = iframeTiledesk.contentWindow.document.createElement('style');
                style.type = 'text/css';
                style.innerHTML = '.message_innerhtml.marked { font-size: 17!important;}\n';

                //add custom stype to launcher-button (image + border + background-image)
                style.innerHTML += '#c21-launcher-button > div > svg { display: none !important; }\n';
                style.innerHTML += '#c21-launcher-button .launcher-button { background-image: url("https://panel.tiledesk.com/v3/dashboard/assets/img/avatar_bot_tiledesk.svg"); background-repeat: no-repeat;}\n';
                style.innerHTML += '#c21-launcher-button { padding: 6px;background-color:unset !important;     border: 1px solid rgb(182, 20, 22);}\n';

                //add custom animation to launcher button on hover
                style.innerHTML += '#c21-launcher-button .launcher-button:hover { animation: fade-in 1.2s ease-in both;}'
                style.innerHTML += '@-webkit-keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } } @keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } }'

                iframeTiledesk.contentWindow.document.getElementsByTagName('head')[0].appendChild(style);

            })

        </script>
    </head>

    <body>
        This Tiledesk example will change the default style of widget launcher icon and add a simple animation hovering it
    </body> 

</html>
```


# Custom attributes

In this tutorial we will show you how to easily initialize custom attributes in the Tiledesk Widget and use them inside your chatbot flow. We will explain how to define these attributes so they appear in the “System defined” → payload section of your chatbot blocks, how to trigger their initialization when needed, and finally how to dynamically update their values when a specific event occurs (in our example, a button click).

The steps to achieve this are very simple:

1. Copy and paste the basic Tiledesk Widget script.
2. Define your initial custom attributes inside the customAttributes field of window\.tiledeskSettings.
3. Listen for the event you want to use as a trigger (in this example, a button click).
4. Update the custom attributes by using the setAttributeParameter method.

Here is the full code example

```html
<html>

    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>replit</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    </head>

    <body>
        Hello Tiledesk Widget example page. Tutorial available in Tiledesk
        <a href="https://developer.tiledesk.com/widget/tutorials" target="_blank">developer zone</a>

        <h2><b>Here an example to update custom attributes.</b></h2>
        <h5>
            Steps:
            <ol>
            <li>Open the widget</li>
            <li>Start a new conversation (the printed custom attributes should be the initial ones)</li>
            <li>Click the "Update attributes" button"</li>
            <li>Start again a new conversation (the new printed custom attributes should be the updated ones)</li>
            </ol>
        </h5>
        <br><br>
        <h3>Click the button to update the custom attributes</h3> <button id="myButton">Update attibutes</button>
        
        <script type="application/javascript">
            var PROJECT_ID = "<<TILEDESK_PROJECT_ID>>"
            let payload =  {
                "city": "California",
                "name": "William",
            }
            window.tiledeskSettings =
            {
                projectid: PROJECT_ID,
                customAttributes: payload
            };
            (function (d, s, id) {
            var w = window; var d = document; var i = function () {i.c(arguments);};
            i.q = []; i.c = function (args) {i.q.push(args);}; w.Tiledesk = i;
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s);
            js.id = id; js.async = true; js.src = "https://widget.tiledesk.com/v6/launch.js";
            fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'tiledesk-jssdk'));

            document.getElementById("myButton").addEventListener("click", function () {
                //Update payload object
                let updatedPayload = {
                    ...payload,
                    "surname": "Smith"
                };

                // Send to widget
                window.Tiledesk('setAttributeParameter', {
                    key: 'payload',
                    value: updatedPayload
                });
            });

        </script>
    </body>

</html>
```

The screen below highlights how to read your defined or updated customAttributes inside the chatbot flow. As shown, the customAttributes JSON data is stored in the **payload** variable under System Defined section.

![Custom Attributes chatbot flow](https://github.com/gab-95/images-host/blob/74c4e40d286f068d5ecb8d309a23555b8bd548c6/custom-attributes-bot.png?raw=true)

View result [here](https://tiledesk-html-site-tiledesk.replit.app/widget/custom-attributes_dynamic.html)


# Conversation Embedded Apps

## Embedding Apps

![Embedded App example](https://user-images.githubusercontent.com/32564846/161718340-b89817b5-a3d3-45f2-a55e-a0d6b3fc99d5.png)

Applications (aka Apps) displayed in the conversation flow are a very useful tool. They allow to achieve two main objectives:

1. Enhancement of the UI. They enhance the interactive and functional power of a conversation
2. Data isolation. They totally isolate the data flow from the conversation

**Enhancement of the UI** is obviuous. You can, for example, play an entire video game in the conversation flow, without ever leaving the conversation in the chat. You can also complete a complex input form, that through a chatbot is difficult to fill. There are many use cases where an app running in the conversation increases the end-user perceived interactive power.

**Data isolation** is less obvious but probably more important. In Tilesk, the conversational app is an entire web application running on his own web server on the HTTPS protocol. This means that data exchanged with the app is unkonwn by Tiledesk and is exchanged directly between the app and his own backend. This pertains to **privacy** and **security**. Imagine for example that a user should pay for a cart. The chatbot can provide to the user a payment-app where the user is asked about his credit card and these data are directly exchanged with the payment backend, never with Tiledesk. No info about the transaction is stored into the conversation. Through an app only the actors interested in the interaction are involved.

## Conversation-embedded app anatomy

An App is just a message of type *frame*. See the [Widget JSON protocol](https://developer.tiledesk.com/widget/advanced/widget-json-protocol#message-with-content-in-iframe) to see the details.

!['frame' type message](https://user-images.githubusercontent.com/32564846/161697596-3567a083-7ec7-47f1-bde0-933c7bec6e1b.png)

### Embed App with microlanguage

In addition to using the widget JSON protocol, you can better use the [microlanguage](https://docs.tiledesk.com/knowledge-base/response-bot-images-buttons-videos-and-more/) to render the App in the chatbot's reply without knowing weird JSON specifications.

```
tdFrame:APPLICATION_ENDPOINT
```

For example:

```
tdFrame:https://tiledesk-conversational-app.tiledesk.repl.co/chatbot
```

### App height

You can also specify the App height in the conversation, using the followinf format:

```
tdFrame,hHEIGHT:APPLICATION_ENDPOINT
```

For example:

```
tdFrame,h310:https://tiledesk-conversational-app.tiledesk.repl.co/apps/creditcard
```

![Set App's height with microlanguage](https://user-images.githubusercontent.com/32564846/161760857-2dd0b10b-789e-4c4a-ad79-4e520a5fe7b6.png)

With Tiledesk displaying an app to the end-user means to simply send him a message.

## App status

It's worth to understand that an app is totally under your control. You are totally responsable of the app data, app features, app Tiledesk and Third party's APIs usage and ...app status!

The "app status" is the status of your app in the conversation workflow. Suppose for example that you embedded an App in the conversation to allow users to pay for a cart using their credit card. Wath you want is an App "active" only when the user has to pay, while the app should be in a sort of "inactive" status when the user stopped or terminated his payment.

To manage the app status there is a simple way. You can use the *messageId* that comes in the webhook of you application to uniquely identify your application. Consider that in the most frequent use case there is a strict corrispondence between the App and the message where it is displayed into.

![Use the messageId as App's unique reference on your backend](https://user-images.githubusercontent.com/32564846/162071545-99326eca-de53-4931-95bc-35cb20a78427.png)

The basic principle is that you can use the unique messageId to uniquely identify the app in the conversation flow and use this same messageId as a unique-id in your Database to save data relative to that app instance, including his status.

## App > Tiledesk APIs interaction

Your App can always use *Tiledesk APIs* to communicate with your project, for example to send messages back to your conversation whenever it wants.

How? With each webhook payload you receive a **token** that you can use to talk with the conversation where (as a message) the App is hosted into. Just use this token in Tiledesk APIs to call any (allowed) [REST method](https://developer.tiledesk.com/apis/rest-api) you want...

### Send messages to end-users

...but specially the [SendSupportMessage()](https://tiledesk.github.io/tiledesk-nodejs-libs/TiledeskClient.html#sendSupportMessage) method. This is a special method that allows the user to send messages to the conversation where the token belongs to.

![Send messages to the conversation](https://user-images.githubusercontent.com/32564846/162134720-84f37b1f-b52d-473d-aaa0-908d9563a0e6.png)

As you can see in the picture sending messages from the App back to the conversation can be very useful. You can for example notify in a graceful and useful manner the end of an operation packed with some useful data.

It's now time to face a **Tutorial example**, the [Credit Card payment App tutorial](/widget/widget-app-introduction/widget-app-payment).


# Payment App Tutorial

## Introduction

During a conversation is sometimes useful providing the user with a method to complete a task through a payment.

![image](https://user-images.githubusercontent.com/32564846/161642865-d7c9f00a-49fb-4a0c-b6a5-54014694e45b.png)

Using an app is a secure way to accomplish this task. Using the app the end-user doesn't send any "sensible" payment information as a message in the conversation. He directly interacts with the payment system on the HTTPS protocol, leaving out from Tiledesk informations that Tiledesk absolutely doesn't want :)

In this tutorial we'll only build a skeleton application, useful enough to show the basic principles of building a widget app with Tiledesk.

We'll cover three basic needs.

1. Create and render an app to be shown and used in the conversation
2. Mark the app as "Terminated" changing his UI behaviour on the task end, avoiding further user interaction
3. Interact with the current conversation, i.e. sending a message, directly from the app code

Let's start.

## Create and render an app

### Create a new Project

To use Tiledesk APIs or integrate your own chatbots is mandatory to signup a new user on [Tiledesk](https://tiledesk.com/). Then go to the console, available on the following link <https://panel.tiledesk.com/v3/dashboard>

After signup please follow the proposed wizard to create your first Tiledesk project

We choosed "Widget Embedded App" as Project name:

![image](https://user-images.githubusercontent.com/32564846/162209056-dd4217ba-293c-47f6-99c2-bbccc1c3126b.png)

As soon as you create the project you will be redirected to the project home (for this tutorial you can jump the last step, relative to the widget installation).

### Create a simple chatbot

As first step we will create a simple chatbot. We'll use the chatbot so it can send back a conversation-embedded Application to the end-user who started the chat, asking him to pay for his order using his credit card info. The Application will implement the (fake) payment-logic and will reply to the user with a message showing the payment operation relevant info.

Select the chatbot icon on the left menu, then press the "ADD BOT" button:

![image](https://user-images.githubusercontent.com/32564846/162210700-42c5b927-a7c1-4a34-914e-ef2faf7591b2.png)

Choose "Resolution bot" as type:

![image](https://user-images.githubusercontent.com/32564846/160479723-f95ef4e5-47a0-4e70-af02-3f36403847bb.png)

Set "Shopper" (or whatever you prefer) as the chatbot name and leave the other settings with their default value. Press "CREATE BOT":

![image](https://user-images.githubusercontent.com/32564846/162211018-cc29be2a-8770-4bde-841c-048b73b278fd.png)

When asked, choose "Activate bot". In this manner the new chatbot is immediatly available as soon as someone starts a new conversation.

![image](https://user-images.githubusercontent.com/32564846/162211365-7b705564-9fcc-4616-b0ea-a9404b37f947.png)

Now, in the Shopper chatbot intents list, select the "start" intent:

![image](https://user-images.githubusercontent.com/32564846/162285884-80b5d7f3-a64e-470f-b3d0-5ab3d2fb0acb.png)

Then modify the start intent, adding a *Quick reply* button using the chatbot microlanguage (simply use an asterisk followed by a space and the quick reply text), as this:

![image](https://user-images.githubusercontent.com/32564846/162286307-7a3872d0-d1ec-4305-9f01-f43eee1caac5.png)

Now save the answer and go back to the intents list. Add a new answer (+ *New answer* button).

Configure the new answer as the following:

**Intent**: "payment" **Questions**: "I want to pay" **Answer**: "Showing Paying app (placeholder)..."

Do not forget to activate the webhook switch on the bottom "Enable webhook call for this intent". This will forward the webhook reply to the backend logic that we'll add later in the tutorial.

![image](https://user-images.githubusercontent.com/32564846/162287813-5739c1ec-036f-4735-add0-e3566e7bc306.png)

### Create the backend on Replit

To develop our app logic, we'll need a web application endpoint where all the chatbot's requests will be forwarded. We'll use the [Repl.it](https://repl.it) service to fast create our own NodeJS web application endpoint.

#### Develop your application logic. Let's fork!

We simply fork the tutorial application, available at this url:

<https://replit.com/@tiledesk/tiledesk-conversational-app#index.js>

Use the fork button and choose a name for your app:

![image](https://user-images.githubusercontent.com/32564846/162422896-78a544ad-0da9-4f0b-b390-4abb0d2d7dea.png)

Once forked go on your replit application and do a little customization. You should set the APP\_ENDPOINT environment var using the option on the left menù, as shown in the figure. You must add to the **replit App endpoint** - in our case *<https://tiledesk-conversational-app.tiledesk.repl.co>* - the */apps/creditcard* suffix to build the full APP\_ENDPOINT functional to our integration, exactly as shown in the picture.

![Setup the APP\_ENDPOINT](https://user-images.githubusercontent.com/32564846/199575979-e20ed2ad-d1b8-4e9e-9c7f-a08a98bad9fe.png)

Now press the *Run* button in the top bar. You application starts, as you can see in the log panel.

Now you must connect this application to your *Shopper* chatbot. Go on the Shopper bot in Tiledesk Console, enable [Fullfilment](https://developer.tiledesk.com/resolution-bot/home#fulfillment) and put there the API\_ENDPOINT url of your chatbot using the previuos *Replit App endpoint* followed by the */bot* suffix:

*<https://tiledesk-conversational-app.tiledesk.repl.co/bot>*

![](https://user-images.githubusercontent.com/32564846/162305135-9a063e33-eaf0-49d4-8ae1-3b9dc3e4075a.png)

And press the UPDATE BOT button. Now we are ready to see the embedded App in action with our chatbot.

### Let's run

To run the example simply choose the "Simulate visitor" button on top of the console of your project.

The widget "test page" will open. These are the main steps involved in the interaction:

1. Start a conversation.
2. The chatbot will greet you.
3. Press the "I want to pay" Quick reply button. It will decode the "payment" intent you already built.
4. The intent is connected to the API\_ENDPOINT you setup previously and the reply is dynamically generated by the /bot method
5. The reply sends back to the widget a message containing a "frame" with the API url of the application
6. The user interacts with the application, setting his name
7. The App gets the user data and disables further user interaction
8. The App sends a message back to the user containing his name (got from the app form)
9. The interaction ends.

You can try a "live" tutorial [here](https://tiledesk-html-site.tiledesk.repl.co/conversation-embedded-app.html). You can get the source code directly from the replit app.

If you have any problems do not esitate to write us on our [Community forum](https://tiledesk.discourse.group/)!

See you on our next tutorial!

Do you have suggestions on this article? Please send us your feedback writing an email to <info@tiledesk.com>


# Prechat form App Tutorial

## Introduction

![Prechat form in conversation](https://user-images.githubusercontent.com/32564846/165312900-4a7588c8-a408-44d8-a3a8-77ecd99af280.png)

The widget's [native prechat form](https://developer.tiledesk.com/widget/advanced/prechat-form-json) is very userful to ask some data before starting a conversation. But sometimes you want let the end-user play around with your chatbot freely, avoiding asking him unuseful sensitive data. Just ask data only when necessary, i.e. just before talking with a human agent!

We'll discuss here exactly this use case. We'll build a chatbot, placing it in front of a department. When the user asks for an agent a form appears in the conversation flow that will ask the user some personal info (i.e. email, fullname, telephone). As soon the user fills out the form the chatbot will handoff the conversation to a human agent that can read the user data from the conversation panel.

Moreover with this use case you will be free to create your own form, without all the limitations of the widget's native form. In effect your form will be a complete web application shown as an iframe into the widget. You can implement whatever computation or your favourite user interaction. From your app you will be able to talk to Tiledesk using APIs or send messages back into the same conversation where the app is hosted into.

In this tutorial we'll cover three basic features:

1. Render the prechat form exactly when the chatbot-human handover occurs
2. Mark the prechat form as "Terminated" changing his UI as soon as the task ends, avoiding further user interaction
3. Ask the prechat form only once to the same user, avoiding asking the same data on each chatbot-human handoff
4. Interact with the current conversation sending a message back to the user indicating a successfull operation

Let's start.

## Create and render an app

### Create a new Project

To use Tiledesk APIs or integrate your own chatbots is mandatory to signup a new user on [Tiledesk](https://tiledesk.com/). Then go to the console, available on the following link <https://panel.tiledesk.com/v3/dashboard>

After signup please follow the proposed wizard to create your first Tiledesk project.

We choosed "Widget Prechat App" as Project name:

![Create your project](https://user-images.githubusercontent.com/32564846/164986208-86d3223c-ace2-4332-acb5-62b6ed11328b.png)

As soon as you create the project you will be redirected to the project home (for this tutorial you can jump the last step, relative to the widget installation).

### Create a simple chatbot

As first step we will create a simple chatbot. We'll put the chatbot in front fo a Department so it will absorb all the initial support requests. When unsatisfied by the chatbot replies the user will ask for human. The chatbot, instead of suddenly deflect the conversation to the human will instead open a conversation-embedded Application asking the user to fill it with some data (i.e. his email, fullname). As soon as the form is completed the conversation will be switched to a human agent.

The Prechat form application will interact with Tiledesk request-context through APis, filling the context with the info got from the prechat form panel.

Select the chatbot icon on the left menu, then press the "ADD BOT" button:

![Chatbot creation](https://user-images.githubusercontent.com/32564846/162210700-42c5b927-a7c1-4a34-914e-ef2faf7591b2.png)

Choose "Resolution bot" as chatbot type:

![Chatbot creation](https://user-images.githubusercontent.com/32564846/160479723-f95ef4e5-47a0-4e70-af02-3f36403847bb.png)

Set "Helpbot" (or whatever you prefer) as the chatbot name and leave the other settings with their default value. Press "CREATE BOT":

![Chatbot creation](https://user-images.githubusercontent.com/32564846/164986414-e37ede39-8ce6-4bb3-9482-4bc15dd79626.png)

When asked, choose "Activate bot". In this manner the new chatbot is immediatly available as soon as someone starts a new conversation.

![Activate chatbot](https://user-images.githubusercontent.com/32564846/162211365-7b705564-9fcc-4616-b0ea-a9404b37f947.png)

Now, in the *Helpbot* chatbot intents list, select the "start" intent:

![Select the start intent](https://user-images.githubusercontent.com/32564846/162285884-80b5d7f3-a64e-470f-b3d0-5ab3d2fb0acb.png)

Then modify the start intent, adding a [Quick reply](https://developer.tiledesk.com/widget/advanced/widget-json-protocol#quick-replies) button using the chatbot [microlanguage](https://developer.tiledesk.com/resolution-bot/rich-messages#microlanguage) (simply use an *asterisk* followed by a *space* and the quick reply text), as this:

![Add a quick reply to the Start intent](https://user-images.githubusercontent.com/32564846/165066393-4ad37f90-3766-4bc3-94c1-e2d60a088697.png)

Now save the answer and go back to the intents list. Add a new answer (+ *New answer* button).

Configure the new answer as the following:

* Intent: "agent\_handoff"
* Questions: "I want an agent"
* Answer: "Prechat form (placeholder)..."

Do not forget to activate the webhook switch on the bottom "Enable webhook call for this intent". This will forward the reply to the programmatic backend logic that we'll add later in the tutorial.

![Agent handoff intent](https://user-images.githubusercontent.com/32564846/165396321-f81834b8-476c-4f78-952a-be2853c07aeb.png)

### Create the backend on Replit

To develop our app logic, we'll need a web application endpoint where all the chatbot's requests will be forwarded. We'll use the [Repl.it](https://repl.it) service to fast create our own NodeJS web application endpoint.

#### Develop your application logic. Let's fork!

We need tp simply fork the tutorial application, available at this url:

<https://replit.com/@tiledesk/tiledesk-prechatform-widget-app#index.js>

Fork the app.

Once forked press the *Run* button in the top bar. You application starts, as you can see in the log panel.

Connect your application to our chatbot. Go on *Helpbot* in Tiledesk Console, enable [Fullfilment](https://developer.tiledesk.com/resolution-bot/home#fulfillment) and put there the /bot API\_ENDPOINT url that you will build by joining the *replit app endpoint* (see next figure) with the */bot* method.

![replit app endpoint](https://user-images.githubusercontent.com/32564846/165266643-7d3b5b09-c137-4f59-93da-50f998435cec.png)

In our case the url is the following:

*<https://tiledesk-prechatform-widget-app.tiledesk.repl.co/bot>*

![image](https://user-images.githubusercontent.com/32564846/165267374-dc64e254-6299-4d49-b196-38c3b58898c6.png)

And press the UPDATE BOT button. Now we are ready to see the prechatform App in action with our chatbot.

### Let's run

To run the example simply choose the "Simulate visitor" button on top of the console of your project.

The widget "test page" will open. These are the main steps involved in the interaction:

1. Start a conversation.
2. The chatbot will greet you.
3. Press the "I need agent" Quick reply button. It will decode the "agent\_handoff" intent you already built.
4. The intent is connected to the *fulfillment endpoint* you setup previously and the reply is dynamically generated by the */bot* method
5. The reply sends back to the widget a message containing a "frame" with the *prechat form application*
6. The user fills in the form, setting his name, email, telephone number, and accepting Privacy policy
7. The App gets the user data and disables further user interaction
8. The App sends a message back to the user containing his name (got from the form)
9. The interaction ends.

![From chatbot to human agent through a Prechat Form](https://user-images.githubusercontent.com/32564846/165395959-34de2716-0103-48e4-b856-1003546c9bd6.png)

You can try a "live" tutorial [here](https://tiledesk-html-site.tiledesk.repl.co/conversation-embedded-prechat-form-app.html). You can get the source code directly from the replit app.

If you have any problems do not esitate to write us on our [Community forum](https://tiledesk.discourse.group/)!

See you on our next tutorial!

Do you have suggestions on this article? Please send us your feedback writing an email to <info@tiledesk.com>


# Advanced


# Preset the Widget on a specific Department

Departments are very useful to separate support actions into “domains” of competences.

This domains can be served by humans, chatbots or can be served in a hybrid fashion, mixing chatbots with humans handoff.

Tiledesk has a very easy way to handle departments.

Just go into the Departments section, create your own departments, configure these departments to be served by chatbots, humans or hybrid way:

![deps-705x371](https://user-images.githubusercontent.com/9378770/92229538-f2495f80-eea9-11ea-9331-33dc8a8f6c3d.png)

Now simply open the widget in the test page and the departments are shown to the guests of your site every time they will start a new conversation:

![widgt-438x705](https://user-images.githubusercontent.com/9378770/92229579-ff664e80-eea9-11ea-9c2f-d797cc7d2d7b.png)

## The problem

But, if you embed the widget in your “pricing” page, you probably don’t want all the new conversations in the page to be constrained choosing a department different by the “Pricing” one.

## Solution

In this case, to skip departments selection, you can simply slightly modify the widget code in the page, setting the department ID upon which the widget must start the new conversation. Just add this line of code:

```
departmentID: 'ID-OF-DEPARTMENT'
```

In the position shown by the following picture:

![snippet-dep-450x165](https://user-images.githubusercontent.com/9378770/92229706-2de42980-eeaa-11ea-8166-62a838cd4c5e.png)

You can always find the department id in the url of the “Modify Department” view, as shown in the following picture:

![edit-dep-705x304](https://user-images.githubusercontent.com/9378770/92229729-363c6480-eeaa-11ea-9709-26a6b14a7c51.png)

If the widget finds this property set, he will always skip the Department selection view, moving the user directly into a conversation in the preset department.


# Authentication Flow

## Anonymous authentication

![image](https://user-images.githubusercontent.com/9378770/91860033-6ea22f80-ec6b-11ea-9bfe-c90c446685d3.png)

## Custom authentication

![image](https://user-images.githubusercontent.com/9378770/91860102-87aae080-ec6b-11ea-8b67-18140e53d2e6.png)

## Authentication refresh

![image](https://user-images.githubusercontent.com/9378770/91860117-8d082b00-ec6b-11ea-921e-1b9aeba54718.png)


# Widget protocol specs

This document describes the raw JSON protocol specifications used by external chatbots (and by Tiledesk itself) to send messages to the widget. You can use this protocol from an [external chatbot](https://developer.tiledesk.com/external-chatbot/integrate-your-chatbot) to customize messages for your end-users. The JSON protocol allows you to discover what kind of content the widget supports, building enhanced chatbot replies for increased user experience that go beyond simple text messages, adding images, special buttons and interaction.

New features are costantly added to Tiledesk widget so take a constant reference to this section to keep yourself updated with all the supported widget messages, controls and media that can be rendered in widget messages.

### Resources

For a live demo of all the supported features described in this document you can refer to this external chatbot project on *repl.it* that you can use as a showcase of all the wideget features

[External-bot widget demo on Repl.it](https://repl.it/@andreasponziell/tiledesk-widget-protocol-example#index.js)

You can also see a live demo of this chatbot on this tiledesk live page:

[Live demo](https://widget.tiledesk.com/v4/assets/twp/index.html?project_name=Widget+showcase+demo\&tiledesk_projectid=5f8474e99c9f0200125b01c0)

## Text message

Sending a text to the widget (from your chatbot, or your generic chat client) really needs a minimal JSON. For example, if you want to send the "Hello" message use the following:

### JSON

```
{
    text: "Hello"
}
```

You can also specify some options:

**type** field: optional. the value 'text' is the default one. Use this field to change the message type (e.g. '[image](#message-with-image)').

**senderFullname** field: optional, because Tiledesk knows who he is talking to. But this field is useful to set if you want to change the sender name for some reason.

## Quick replies

![Quick replies](https://user-images.githubusercontent.com/32564846/95662490-abe5c100-0b37-11eb-8621-bfb7f324845c.png)

*Quick Replies* (generally sent by chatbots) allow users to quickly reply with a proposed, pre-build option. Pressing the button simply sends the text contained in the button label to the recipient (most of the time the chatbot) on the other side.

### JSON

```
{
    type: "text",
    text: "Hello with buttons",
    attributes: {
        attachment: {
            type:"template",
            buttons: [
                {
                    type: "text",
                    value: "REPLY ONE"
                },
                {
                    type: "text",
                    value: "REPLY TWO"
                }
            ]
        }
    }
}
```

## URL buttons

![URL Buttons](https://user-images.githubusercontent.com/32564846/95662652-c9675a80-0b38-11eb-8bf7-a489dfb7e9ce.png)

The URL button opens a link in a new browser tab, the same page hosting the widget or inside the widget itself.

A *target* option is used to specify where to open the URL content. It can have the *blank*, *parent* or *self* values. If a value is not specified it defaults to "blank".

Buttons of this type have a **small arrow** icon to help the user understand that tapping on a URL button will open a new window.

The *self* button is special because it opens the URL content directly inside a special frame of the widget itself. It as a slightly different arrow, pointing to the right orizzontally.

![Self buttons](https://user-images.githubusercontent.com/32564846/140601014-e3967820-7dce-492a-b4f0-353dfbd57188.png)

"self" buttons open the URL content in the "Widget frame" mode. In this mode the URL content appears into the same widget’s frame with a special header, showing the button title, a button to go back to the conversation and another button to open the content into a full browser window.

![Widget frame](https://user-images.githubusercontent.com/32564846/140600868-c3093864-d02d-4c72-ba09-acb2b767e7d8.png)

You can obtain the best results with "self" option if the content you are displaying plays good with the "responsive" mode, because of the small dimension of the widget makes it act with mobile-device-like responsiveness.

### "blank" mode JSON

```
{
    type: "text",
    text: "Hello with buttons (blank)",
    attributes: {
        attachment: {
            type:"template",
            buttons: [
                {
                    type: "url",
                    value: "SITE 1",
                    link: "http://www.tiledesk.com",
                    target: "blank"
                }
            ]
        }
    }
}
```

### "parent" mode JSON

```
{
    type: "text",
    text: "Hello with buttons (parent)",
    attributes: {
        attachment: {
            type:"template",
            buttons: [
                {
                    type: "url",
                    value: "SITE 2",
                    link: "http://www.ietf.org",
                    target: "parent"
                }
            ]
        }
    }
}
```

### "self" (Widget frame) mode JSON

```
{
    type: "text",
    text: "Hello with buttons (self)",
    attributes: {
        attachment: {
            type:"template",
            buttons: [
                {
                    type: "url",
                    value: "Dante",
                    link: "https://en.m.wikipedia.org/wiki/Dante_Alighieri",
                    target: "self"
                }
            ]
        }
    }
}
```

## Action buttons

When a user presses an action button, an “action” message is sent to the chatbot. Your chatbot will receive the "action" field value that you can use to execute some specific actions. Upon receiving the action value, the chatbot can simply reply with a related-to-the-action reply message. If the **show\_echo** option is set to true the widget will also show in the chat the message in the **value** field, giving evidence to the user that a real message was sent to the chatbot.

### JSON

```
{
    type: "text",
    text: "Hello with buttons",
    attributes: {
        attachment: {
            type:"template",
            buttons: [
                {
                    type: "action",
                    value: "EXECUTE AN ACTION",
                    action: "my-action-name",
                    show_echo: true
                }
            ]
        }
    }
}
```

#### Action message (replied by the Widget)

This format is used by Tiledesk chat clients (e.g. Web Widget) to send a message that contains an action for the backend. The message can be hidden or not on the widget, it doesn’t affect the message behaviour. The backend that receives messages with the “action” field set in the attributes section can choose to take a corresponding action, then optionally reply to the same message. A button with an action message has the same aspect as the standard reply button, but with a different, longest and evident animation.

**JSON**

```
{
    type: "text",
    text: "This is an action for the backend",
    attributes: {
        action: "my-action-name"
    }
}
```

## Image attachment

If you want to send an image from your external chatbot you should embed the image http source in the reply JSON schema shown below.

**type** field must be set to **image**

**text** field is optional

**metadata.src** field is mandatory and must point to a valid image

**metadata.width** and **metadata.height** fields are optional. If set they will reduce the image size accordingly in the reply message.

### JSON

```
{
    type: "image",
    text: "Hello with image",
    metadata: {
        src: "http://www.tiledesk.com/logo.jpg",
        width: 200,
        height: 200
    }
}
```

## File attachment

If you want to send a generic document from your backend to the Tiledesk Widget you should embed the document file http source in the reply JSON schema shown below.

**type** field must be set to **file**

**text** field is optional

**metadata.src** field is mandatory. It must be a valid *http url* containing the document **binary file**

**metadata.name** field is optional. It's the file name

**metadata.type** field is mandatory. It must be a valid http *content-type* value representing the binary type of the document

### JSON

```
{
    type: "file",
    text: "My document is sent as attachment",
    metadata: {
    name: "sales-report.pdf",
        src: "http://www.mywebsite.com/sales-report.pdf",
    type: "application/pdf"
    }
}
```

## iframe content messages

You can send content to the web widget that can be easily embeddable into an HTML *iframe*. For example you can send a youtube video, an external map, and also a mini HTML5 video game!

**type** must be set to 'frame'

**text** is optional.

**metadata.src** is mandatory and must point to a valid http content embaddable into an HTML5 iframe

**metadata.width** and **metadata.height** are optional. If set, they will reduce the iframe size accordingly in the reply message.

### JSON

```
{
    type: "frame",
    text: "This is a video!",
    metadata: {
        src: "https://www.youtube.com/embed/H1WfFkp4puw"
    }
}
```

## Disable the reply textbox

You can temporarily disable the user input textbox. This feature is useful, for example, when you provide a set of reply buttons and you want the user to press one of these buttons to continue the conversation.

**attributes.disableInputMessage** if true the reply textbox is disabled

**attributes.inputMessagePlaceholder** if set the reply textbox placeholder is replaced by this text. Used only when *attributes.disableInputMessage* is *true*

### JSON

To disable the reply textbox set the above properties in the attributes section, as in the following example:

```
{
    type: "text",
    text: "Do you agree? Please press one of the buttons to proceed",
    attributes: {
        disableInputMessage: true,
        inputMessagePlaceholder: 'Press a button to continue',
        attachment: {
            type:"template",
            buttons: [
                {
                    type: "text",
                    value: "Yes, I do"
                },
                {
                    type: "text",
                    value: "No, I do not"
                }
            ]
        }
    }
}
```

In the following image, the input textbox is disabled, until the next message arrives.

![image](https://user-images.githubusercontent.com/32564846/144202116-3035b6e0-ba89-4fbb-b15c-fa24ec7825bb.png)

## Update user metadata

Sometimes, while interacting with the chatbot, you can ask the user to update his info like his fullname. In this case the widget provides special attributes to update his user info, so he can send new messages with the correct user fullname. You can update user's fullname and email using the following message's properties:

**attributes.updateUserFullname**: Use this attribute to update the Widget's new user *full name*

**attributes.updateUserEmail**: Use this attribute to update the Widget's new user *email*

### JSON example

```
    {
        text: "Thanks Andrea, we got your data and will take care of it!",
        attributes: {
            "updateUserEmail": "andrea@tiledesk.com",
            "updateUserFullname": "Andrea"
        }
    }
```

Once the Widget's receives a message with these attributes it will use the updated fullname and/or email in all subsequest messages.

## Hidden messages

Sometimes it's useful to send messages hidden to end-users. For example, if some message should trigger a chatbot message without the user see the actual "question" that triggered that reply.

To hide messages to the widget you can use "info" messages. All info messages are hidden to the end-users, but keep in mind that info messages are always visible in teammate chat, as in the following example.

![Info messages always visible in teamate chat](https://user-images.githubusercontent.com/32564846/154105533-ab9dd3ca-4b55-4d3f-83d8-902eec6f71ce.png)

**attributes.subtype** set to "info". Hides the message to the end-user channels (Widget, whatsapp, Telegram, Facebook etc.)

### JSON

Triggers a chatbot to start a conversation. This message is hidden in the end-users channels:

```
{
    type: "text",
    text: "start",
    attributes: {
        subtype: "info"
    }
}
```

## Splitted messages

It's a common trend to break long chatbot messages in multiple messages. This can happen on the server side, but there are some issues with this approach, like sometimes unwished unordered messages in the conversation, client "live" reordering (this happens because Tiledesk cannot assure that "very timestamp near" messages arrival order is preserved in the long "message delivery chain".

In this cases the "Widget side" splitting is a preferrable approach. You can send all the messages in a single "packet" to the Widget, specifing the "delay" between them. It will be the Tiledesk Widget to render the messages in the exact order, preserving the exact timing between the messages.

Let's look at an example:

Suppose you want to send these messages as a unique chatbot message, but splitted in multiple messages:

![image](https://user-images.githubusercontent.com/32564846/169641648-4271e7bf-0e20-4356-ab58-e61391ee25f7.png)

### JSON

You have to send a single message like the following:

```
{
	"text": "Hello 👋. I'm a bot 🤖 I'm beautiful Do you need help I can really help you with joy!",
	"attributes": {
		"commands": [{
			"type": "message",
			"message": {
				"text": "Hello 👋. I'm a bot 🤖",
				"type": "text"
			}
		}, {
			"type": "wait",
			"time": 500
		}, {
			"type": "message",
			"message": {
				"text": "I'm beautiful",
				"type": "text"
			}
		}, {
			"type": "wait",
			"time": 1000
		}, {
			"type": "message",
			"message": {
				"text": "Do you need help?",
				"type": "text"
			}
		}, {
			"type": "wait",
			"time": 2000
		}, {
			"type": "message",
			"message": {
				"text": "I can really help you with joy!",
				"type": "text",
				"attributes": {
					"attachment": {
						"type": "template",
						"buttons": [{
							"type": "url",
							"value": "Get Help",
							"link": "https://gethelp.tiledesk.com/articles/install-widget-on-your-website/",
							"target": "self"
						}, {
							"type": "url",
							"value": "Wikipedia",
							"link": "https://it.m.wikipedia.org/wiki/E_Street_Band",
							"target": "self"
						}]
					}
				}
			}
		}]
	}
}
```

As you can see from the example above, the effective message is splitted in the *attributes.commands* section of the message JSON payload.

The commands are alternated. Each command has a "type" property.

* type: 'message' is an effective message. It carries an effective complete 'message' - *message* property, json payload, look at the example above - the real message (a splitted piece of the orginal one) you wish to display.
* type: 'wait', it specifies a delay - *time* property, a number, milliseconds, look at the example above - for the next message to display

Hope you enjoy to split messages like Tiledesk does! :)

## HTML messagees

The widget is able to receive messages containing html tags and render them within the conversation. To do this, server-side the developer should value the **type** field of the message object with '**html**' and insert in the **text** field the HTML code that you want to show on the widget.

Furthermore, the widget is currently capable of supporting link buttons as well.

Below is a practical example of an HTML message and its rendering inside the widget.

![Html message preview example](https://user-images.githubusercontent.com/47848430/173019659-69e0e537-54ee-4d5b-8049-56ebd03abe7e.png)

### JSON

Below we present an example of message json object with html message type

```html
{
    "attributes": {},
    "recipient_fullname: ...
    ...
    ...
    "type": "html",
    "text": `<html>
                <head>
                    <style>

                        .text-html {
                            font-size: 14px;
                        }

                        .button-html {
                            font-size: 10px !important;
                        }
                    </style>

                </head>
                <body>
                
                    <div>
                        <p class="text-html"><b>This is an HTML message type example</b> </p>
                        <p class="text-html"> Place any html tag to be loaded here...  </p>
                    </div>
                    <br><br>
                    <div><p class="text-html"> Button example below 👇🏻</p></div>
                    <button type="button" class="button-html url" onclick="window.open('https://www.tiledesk.com', '_blank')">Button 1</button>
                    <button type="button" class="button-html url" onclick="window.open('https://developer.tiledesk.com/widget/web-sdk', '_blank')">Button 2</button>
                    <button type="button" class="button-html url " onclick="window.open('https://developer.tiledesk.com/widget/advanced', '_blank')">Button 3</button>
                    <br><br>
                    <div><p class="text-html"> Image example below 👇🏻</p></div>
                    <div class="img-container">
                        <img src="https://tiledesk.com/wp-content/uploads/2020/08/tiledesk-logo_x4_vpadding.png" width="200px">
                    </div>
                </body>
            </html>`,
    ...
    ...
}
```

As specified in the example presented, it is also possible, like a normal HTML page, to specify the style inside the **`<style></style>`** tag.

The widget inside renders three types of styles, assigned respectively to the css classes *text-html*, *button-html* and *image-container*.

The example shows an override of these css classes in order to customize the style of the elements as desired.


# Prechat Form JSON specs

## Prechat Form JSON specs

![image](https://user-images.githubusercontent.com/32564846/140908272-673f6e7b-2395-4b5f-a850-7ec233b7be7e.png)

## Table of contents

* [Introduction](#introduction)
* [Default prechat form](#default-prechat-form)
* [Custom Prechat Form](#custom-prechat-form)
  * [Inspect filled-in user data](#inspect-filled-in-user-data)
* [Examples](#examples)
  * [Example 1: ask the telephone number](#example-1-ask-the-telephone-number)
  * [Example 2: accepting Privacy and ToS](#example-2-accepting-privacy-and-tos)
  * [Example 3: ask the first message](#example-3-ask-the-first-message)
* [Control types](#control-types)
  * [Text](#text)
  * [Textarea](#textarea)
  * [Checkbox](#checkbox)
  * [Static](#static)
* [Format specification](#format-specification)
  * [name attribute](#name-attribute)
    * [Reserved-names](#reserved-names)
  * [type attribute](#type-attribute)
  * [mandatory attribute](#mandatory-attribute)
  * [value attribute](#value-attribute)
  * [regex attribute](#regex-attribute)
  * [label attribute](#label-attribute)
  * [errorLabel attribute](#errorLabel-attribute)
  * [rows attribute](#rows-attribute)

### Introduction

![image](https://user-images.githubusercontent.com/32564846/140908024-29213c65-3af3-406b-b521-7a695abc01ec.png)

The *Prechat Form* is used to collect some end-user data before starting a conversation. Generally this info are asked to guests users, because of authenticated users already providing some "certified" information into a custom JWT. The info collected by the Prechat Form will be used either by Agents, by the Tiledesk platform itself or by developers trough APIs.

The prechat form is asked just once to the user, on the first conversation. Once filled and submitted the form data is saved in the browser Local Storage database. If the user wants to fill the prechat form again after the first submission he must "logout" from the widget. This will also change his anonymous user ID.

To logout and reset the widget status, press the option menu (gear icon) in the bottom left corner of the widget home screen and click "logout".

### Default Prechat Form

To activate the prechat form, got to the Tiledesk Dashboard, then Settings > Widget > Prechat form (section). Open this section and activate the form through the provided switch:

![image](https://user-images.githubusercontent.com/32564846/140116717-e34fa56b-90ff-4171-a332-b8ac63ee9f78.png)

If you activate the Prechat Form and no custom format is specified, the default form is shown before starting any conversation. The default form asks the basic info necessary to interact with a Guest user: *email* and a *fullname*.

For the default prechat form, *useremail* and *fullname* are required fields.

### Custom Prechat Form

The prechat form provides customization, so if email is not enough you can ask a telephone number or you can make the user agree to your terms and conditions before proceeding with a conversation. Custom forms use a special (and easy) JSON syntax to customize the form fields. You can specify the fields type choosing the right "control type" (i.e. text/textarea, checkbox, static text etc.). You can also provide some options, useful to validate the field, show a custom validation error or make the field mandatory or not. Multilanguage for labels is also supported.

#### Inspect filled-in user data

Once you fill the custom prechat form, the operator can find the filled-in user data in the dedicated section of the conversation detail. Suppose the user fills the custom form of [Example 2](#example-2-accepting-privacy-and-tos) as in the following picture:

![image](https://user-images.githubusercontent.com/32564846/140916378-cae22b99-3aa0-403a-94fb-c9ab61e94226.png)

The operator can see the filled-in form data looking at the "Prechat form section" of the conversation detail, as in the following picture:

![image](https://user-images.githubusercontent.com/32564846/140917336-413a6158-13ad-428e-a994-98b919ea4c11.png)

### Examples

To understand how prechat form works we can start with some examples.

These examples will show how to accomplish some common tasks with the prechat form. We will start asking the user's telephone number. In the second example we'll propose to read & accept a Privacy Policy and finally, in the third example, a form will ask the user to fill the first question in order to proceed to a new conversation.

#### Example 1: ask the telephone number

In this first example we'll show you how to ask the user telephone number in addition to email and fullname. To customize the prechat form, first sign in the Tiledesk dashboard using your credentials, then choose a project (if you have more then one). Move to the widget section, scroll down to the prechat form section and enable the prechat form using the switch.

![image](https://user-images.githubusercontent.com/32564846/135799563-92771635-3f48-49a3-9aee-901b5ea9db38.png)

Now activate the custom form editor using the switch, as in the following figure:

![image](https://user-images.githubusercontent.com/32564846/135799722-be9f5d06-1370-43cd-9053-e546926a6df3.png)

You will see the JSON source for an already provided example.

Please replace the provided JSON with the following code:

```
[
    {
        "name": "userFullname",
        "type": "text",
        "mandatory": true,
        "label": {
            "en": "Your name",
            "it": "Il tuo nome"
        }
    },
    {
        "name": "userEmail",
        "type": "text",
        "mandatory": true,
        "regex": "/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/",
        "label": {
            "en": "Your email",
            "it": "La tua email"
        },
        "errorLabel": {
            "en": "Invalid email address",
            "it": "Indirizzo email non valido"
        }
    },
    {
        "name": "tel",
        "mandatory": true,
        "label": {
            "en": "Your phone number",
            "it": "Il tuo numero di telefono"
        }
    }
]
```

Now save the pasted source pressing the `UPDATE WIDGET` button.

On the top bar, press the green button to open the widget. Now Start a conversation.

![image](https://user-images.githubusercontent.com/32564846/135870494-0a129267-f4e0-431d-9275-e6433452f7e4.png)

> **NOTE**: If you don't see the prechat form after starting a conversation, don't panic. You probably already submitted the prechat form. Open the option menu (gear icon) in the bottom left corner of the widget home screen and select "logout". On the next conversation start the form will appear again.

We just added a phone number text field to the basic form. As you can guess, the form JSON is an array of "controls". Each control has some attributes that allow to fine tuning the control itself. In this case the first two elements (controls) of the array are a "name" textfield and an "email" textfield. We just focus on the added one, the phone number. The phone number is *mandatory* (mandatory attributes set to true) and we set a couple of multilanguage labels, to show you how multi-language is supported using the languages iso codes (en, it) of the desired languages (English and Italian in this example, respectively).

> **Reserved fields names**: While choosing the controls "name" attribute, keep in mind that there are some reserved Tiledesk names: userEmail, userFullname and firstMessage. We discuss about those fields [here](#name)

#### Example 2: accepting Privacy and ToS

In this example we'll add an option for the user to proceed in the conversation only if "You accept our Terms and Conditions and Privacy Policy". We will add a couple of controls: 1. Static text to show the notice, 2. Checkbox to declare acceptance. We can modify the JSON for the *Example 1*, adding the new controls:

Please replace the provided JSON with the following code:

```
[
    {
        "name": "userFullname",
        "type": "text",
        "mandatory": true,
        "label": {
            "en": "Your name",
            "it": "Il tuo nome"
        }
    },
    {
        "name": "userEmail",
        "type": "text",
        "mandatory": true,
        "regex": "/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/",
        "label": {
            "en": "Your email",
            "it": "La tua email"
        },
        "errorLabel": {
            "en": "Invalid email address",
            "it": "Indirizzo email non valido"
        }
    },
    {
        "name": "tel",
        "mandatory": true,
        "label": {
            "en": "Your phone number",
            "it": "Il tuo numero di telefono"
        }
    },
    {
        "type": "static",
        "label": "Before proceeding in the conversation please agree to our <a href='https://tiledesk.com/termsofservice/' target='_blank'>Terms</a> and <a href='https://tiledesk.com/privacy.html' target='_blank'>Privacy Policy</a>"
    },
    {
        "type": "checkbox",
        "name": "acceptedTermsPrivacy",
        "label": {
            "en": "I agree",
            "it": "Accetto"
        },
        "mandatory": "true"
    }
]
```

Now save the pasted source pressing the `UPDATE WIDGET` button.

On the top bar, press the green button to open the widget. Now Start a conversation.

![image](https://user-images.githubusercontent.com/32564846/140267086-2745f13f-9b0a-4a67-8712-7d99a4aab43a.png)

As you can see the new controls are shown on the footer. If you try to proceed without accepting, the form will block you.

![image](https://user-images.githubusercontent.com/32564846/140267290-2a6b7b23-82b0-492a-a83c-b3c18daafaa4.png)

Now check the option to accept the Terms of use and proceed with the conversation 😅

#### Example 3: ask the first message

In this example we'll add an option for the user to write the first message before starting a conversation. This option is extremely useful when you don't have a chatbot and you want your agents get in contact with a great first message from the end-user, that exactly describes the problem. Note that with this special field (that uses for the "name" property the reserved value "firstMessage") the widget instantly sends the message to Tiledesk. We will add a new textarea control with *firstMessage* as the value of the *name* property. This will tell Tiledesk to use this value as the first message of the conversation. We can modify the JSON for the *Example 1*, adding the new textarea control:

```
[
    {
        "name": "userFullname",
        "type": "text",
        "mandatory": true,
        "label": {
            "en": "Your name",
            "it": "Il tuo nome"
        }
    },
    {
        "name": "userEmail",
        "type": "text",
        "mandatory": true,
        "regex": "/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/",
        "label": {
            "en": "Your email",
            "it": "La tua email"
        },
        "errorLabel": {
            "en": "Invalid email address",
            "it": "Indirizzo email non valido"
        }
    },
    {
        "name": "firstMessage",
        "rows": 5,
        "type": "textarea",
        "mandatory": true,
        "label": {
            "default": "Your message for the support team"
        }
    }
]
```

Now save the pasted source pressing the `UPDATE WIDGET` button.

On the top bar, press the green button to open the widget. Now Start a conversation.

![image](https://user-images.githubusercontent.com/32564846/140522941-3138cfe1-03d8-4f9e-b65f-93b64e44932c.png)

You can see the new control, "Your message for the support team", shown as the last one. It's a mandatory field, you must fill it or the form will block you.

As soon as you fill the form, the new conversation starts, with the first message appearing as the first one of the conversation. The agent (or the chatbot) will receive it and happily reply 😎

![image](https://user-images.githubusercontent.com/32564846/140512666-328e7214-32a9-458a-813b-465acbf506e3.png)

### Control types

Here follows a list and a description for all the control types actually supported by the Tiledesk prechat form.

### Text

This is the default control, it's a simple text field. When *type* is omitted a Textfield control is rendered. You can provide a regex to validate the field.

![image](https://user-images.githubusercontent.com/32564846/140146075-79b748e5-fe09-490a-96e5-9935cf73c977.png)

Example:

```
[
  {
    "name": "userFullname",
    "type": "text",
    "mandatory": true,
    "label": {
        "default": "Your name",
        "en": "Your name",
        "it": "Il tuo nome"
    },
    "regex": "/^[a-zA-Z\\s]*$/",
    "errorLabel": {
        "default": "Incorrect name, only letters and spaces are allowed",
        "en": "Incorrect name, only letters and spaces are allowed",
        "it": "Nome errato, sono permesse solo lettere e spazi"
    }
  }
]
```

### Text - Format specification

#### *name* attribute

*mandatory*

Example:

```
name: “phone”
```

**Reserved names**

While choosing the controls "name" attribute, keep in mind that there are three reserved Tiledesk names:

1. *userEmail* It's the email used by Tiledesk to send automated messages.
2. *userFullname* When available it is used to identify the user by his fullname around Tiledesk.
3. *firstMessage* When provided, this value is used as the first message sent by the Widget as soon as the conversation starts.

#### *type* attribute

*optional*, *case insensitive*

For *Textfield* use **text** value.

#### *mandatory* attribute

*optional*, *boolean*

This property denotes if is mandatory to have a value for this control.

“mandatory”: true | false

Default is *false*

If true filling some text is mandatory.

#### *value* attribute

*optional*

The pre-defined value for the field.

#### *regex* attribute

*optional*

If set, the field value will be validated with this regex.

Example:

```
"regex" : "/^[a-zA-Z\\s]*$/"
```

#### *label* attribute

*optional*

This is the control's label. Multilanguage is supported. Simply add the language's ISO code as in the following example to add languages. If no supported language is found, the "default" label value will be used.

```
"label": {
  "default": "Your name",
  "en": "Your name",
  "it": "Il tuo nome"
}
```

If *label* attribute is not configured, the “name” attribute is used as the control's label. If the *label*'s property value is a *string* (not a JSON object with ISO language value) the translation is searched in Tiledesk translations using the label's string property as the key for the translation.

Ex. label as string "email" will use the Tiledesk translation key "email".

```
"label": "email"
```

#### *errorLabel* attribute

*optional*

If available the errorLabel will be displayed if the regex doesn't match. If not set the standard message is displayed.

```
errorLabel: {
  "en": "Pattern not valid. Insert only 10-digits number",
  "it": "Campo non valido. Insersci solo un numero di dieci cifre"
}
```

### Textarea

Textarea is a multi-line text input. Use "textarea" value for "type" property to render a Textarea. You can provide a regex to validate the textarea input text. Use the optional property "rows" to render a specific number of initial rows.

![image](https://user-images.githubusercontent.com/32564846/140148740-d1ab3cdb-173a-4727-9470-df1b89f71be4.png)

Example:

```
[
  {
    "name": "firstMessage",
    "type": "textarea",
    "label": {
      "default": "Your message"
    },
    "mandatory": true,
    "rows": 5
  }
]
```

### Textarea - Format specification

#### *name* attribute

*mandatory*

Example:

```
name: “description”
```

**Reserved names**

While choosing the controls "name" attribute, keep in mind that there are three reserved Tiledesk names:

1. *userEmail* It's the email used by Tiledesk to send automated messages.
2. *userFullname* When available it is used to identify the user by his fullname around Tiledesk.
3. *firstMessage* When provided, this value is used as the first message sent by the Widget as soon as the conversation starts.

#### *type* attribute

*optional*, *case insensitive*

For *Textarea* use **textarea** value.

#### *mandatory* attribute

*optional*, *boolean*

This property denotes if is mandatory to have a value for this control.

“mandatory”: true | false

Default is *false*

If true filling some text is mandatory.

#### *value* attribute

*optional*

The pre-defined value for the field.

#### *regex* attribute

*optional*

If set, the field value will be validated with this regex.

Example:

```
"regex" : "/^[a-zA-Z\\s]*$/"
```

#### *label* attribute

*optional*

This is the control's label. Multilanguage is supported. Simply add the language's ISO code as in the following example to add languages. If no supported language is found, the "default" label value will be used.

```
"label": {
  "default": "Your name",
  "en": "Your name",
  "it": "Il tuo nome"
}
```

If *label* attribute is not configured, the “name” attribute is used as the control's label. If the *label*'s property value is a *string* (not a JSON object with ISO language value) the translation is searched in Tiledesk translations using the label's string property as the key for the translation.

Ex. label as string "email" will use the Tiledesk translation key "email".

```
"label": "description"
```

#### *errorLabel* attribute

*optional*

If available the errorLabel will be displayed if the regex doesn't match. If not set the standard message is displayed.

```
errorLabel: {
  "en": "Pattern not valid. Insert only 10-digits number",
  "it": "Campo non valido. Insersci solo un numero di dieci cifre"
}
```

#### *rows* attribute

*optional*

'rows' property specifies the initial number of rows of the Textarea control.

```
{
    "name": "firstMessage",
    "type": "textarea",
    "rows": 5
}
```

### Checkbox

Checkbox represents an HTML checkbox. Use "checkbox" value for "type" property to render a Checkbox. It can only assume two values, 'checked' and 'unchecked'. Use "checkbox" value for "type" property to render a Checkbox.

![image](https://user-images.githubusercontent.com/32564846/140150681-4a5b349a-1638-4340-9c32-f3270797aea6.png)

Example:

```
[
  {
    "name": "acceptPrivacy",
    "type": "checkbox",
    "label": {
      "default": "Accept our privacy policy before contacting support"
    },
    "mandatory": true
  }
]
```

### Checkbox - Format specification

#### *name* attribute

*mandatory*

Example:

```
name: “accept”
```

**Reserved names**

While choosing the controls "name" attribute, keep in mind that there are three reserved Tiledesk names:

1. *userEmail* It's the email used by Tiledesk to send automated messages.
2. *userFullname* When available it is used to identify the user by his fullname around Tiledesk.
3. *firstMessage* When provided, this value is used as the first message sent by the Widget as soon as the conversation starts.

#### *type* attribute

*optional*, *case insensitive*

For *Checkbox* use **checkbox** value.

#### *mandatory* attribute

*optional*, *boolean*

This property denotes if is mandatory to have a value for this control.

“mandatory”: true | false

Default is *false*

In the case of *checkbox* this means that checking the box is mandatory.

#### *value* attribute

*optional*

The pre-defined value for the field.

#### *label* attribute

*optional*

This is the control's label. Multilanguage is supported. Simply add the language's ISO code as in the following example to add languages. If no supported language is found, the "default" label value will be used.

```
"label": {
  "default": "Your name",
  "en": "Your name",
  "it": "Il tuo nome"
}
```

If *label* attribute is not configured, the “name” attribute is used as the control's label. If the *label*'s property value is a *string* (not a JSON object with ISO language value) the translation is searched in Tiledesk translations using the label's string property as the key for the translation.

Ex. label as string "email" will use the Tiledesk translation key "email".

```
"label": "accept"
```

### Static

Static type is simple text. Use "static" value for "type" property to render a Static block of text. You can use simple text or HTML to render more complex pieces of text.

![image](https://user-images.githubusercontent.com/32564846/140153649-cb801282-dde3-422d-8b40-0fd1ad826135.png)

Example:

```
[
  {
    "type": "static",
    "label": {
      "default": "Accept the <a href='https://site.com/terms/' target='_blank'>Terms</a> before contacting support",
      "en": "Accept the <a href='https://site.com/en/terms/' target='_blank'>Terms</a> before contacting support",
      "it": "Accetta i <a href='https://site.com/it/terms/' target='_blank'>Termini</a> prima di contattare il supporto"
    }
  }
]
```

### Static - Format specification

#### *type* attribute

*optional*, *case insensitive*

For *Static* use **static** value.

#### *label* attribute

*optional*

This is the control's label. Multilanguage is supported. Simply add the language's ISO code as in the following example to add languages. If no supported language is found, the "default" label value will be used.

```
"label": {
  "default": "Your name",
  "en": "Your name",
  "it": "Il tuo nome"
}
```

If *label* attribute is not configured, the “name” attribute is used as the control's label. If the *label*'s property value is a *string* (not a JSON object with ISO language value) the translation is searched in Tiledesk translations using the label's string property as the key for the translation.

Ex. label as string "email" will use the Tiledesk translation key "email".

```
"label": "terms"
```


# Prevent multiple conversations

![](https://user-images.githubusercontent.com/47848430/179253313-86628998-8a0b-4127-b7a1-7fd1ac6140be.png)

A new feature in Tiledesk widget settings will prevent your customers from starting a new conversation if they already have one open. This change makes conversations more of a continuous thread, preventing customers from reaching out to your team multiple times, which saves your team time and effort. This feature is named as **Single Conversation**

## Overview

Tiledesk Widget can handle only one conversation at a time by properly setting the singleConversation property. In fact, just set **singleConversation** to **true** (see how to do this [here](https://developer.tiledesk.com/widget/installation/attributes)) to be able to show the widget user only one conversation at a time. This option disables the possibility of viewing the home with the list of open conversations and those already archived as image below highlight.

![singleConversation](https://user-images.githubusercontent.com/47848430/179259137-42b932b1-1312-44c7-83c6-9534d39905bf.png)

Once the user has been authenticated, the widget proceeds with the normal initialization flow of a new conversation only if the user has no active conversation previously, otherwise, the widget will load the most recent active conversation

## How to set *singleConversation* mode

As with the other widget setting parameters, **singleConversation** mode can be enabled in various ways: as a url parameter or as a property of tiledeskSettings.

### Set property from **tiledeskSettings**

You can passing the parameters to **window\.tiledeskSettings** object as shown in the example below

```html
<script type="application/javascript">
    window.tiledeskSettings = 
        {
            projectid: "<YOUR_PROJECT_ID>",
            singleConverstion: true
        };
    (function(d, s, id) {
        var w=window; var d=document; var i=function(){i.c(arguments);}; 
        i.q=[]; i.c=function(args){i.q.push(args);}; w.Tiledesk=i; 
        var js, fjs=d.getElementsByTagName(s)[0]; 
        if (d.getElementById(id)) return; 
        js=d.createElement(s); 
        js.id=id; js.async=true; js.src="https://widget.tiledesk.com/v6/launch.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document,'script','tiledesk-jssdk'));
</script>
```

The above script can start widget with the single conversation mode, immediately

### Set property from **URL**

You can pass the a tiledesk widget property as a Url parameter with the **tiledesk\_** prefix. For example, in this case:

```
https://widget.tiledesk.com/6/assets/twp/index.html?tiledesk_projectid=<YOUR_PROJECT_ID>&tiledesk_singleConversation=true
```

## Make a Sign Out

In this mode, the user can still logout from the system by using the menu at the top right corner in the conversation header, as shown in the figure below.

![](https://user-images.githubusercontent.com/47848430/179550749-cef51928-5d64-4f13-b70b-54f99ff7feeb.png)

Once you have make a sign out, widget restarts itself and create a new user. New initialization flow of a new conversation starts and new user can starts to chat again!!


# Old versions


# Web SDK v4

#### Web SDK ver 4.0

This guide will show you how to get started as quickly as possible with the Web SDK from TileDesk. The Web SDK will give businesses and developers the flexibility to build and customize a chat experience that meet their specific design/brand requirements.

## Install the Web HTML Widget

To chat with your visitors embed the widget on your site. Copy the following script and insert it in the HTML source between the HEAD tags:

```
    <script type="application/javascript">
        window.tiledeskSettings = 
            {
                projectid: "YOUR_TILEDESK_PROJECT_ID"
            };
            (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id; 
            js.src = "https://widget.tiledesk.com/v4/launch.js";
            fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'tiledesk-jssdk'));
    </script>
```

To get your TILEDESK\_PROJECT\_ID go to the TileDesk Dashboard and click on the Widget item of the menu:

![](https://raw.githubusercontent.com/chat21/chat21-web-widget/master/docs/tiledesk-dashboard-widget-screenshots.png)

### Configuration

Widget version 4.0 supports remote configuration of most parameters directly from the Widget menu of the Dashboard.

You can customize the widget passing the following parameters to window\.tiledeskSettings object.

* **projectid**. The TileDesk project id. Find your TileDesk ProjectID in the TileDesk Dashboard under the Widget menu.
* **preChatForm**: You can require customers to enter information like name and email before sending a chat message by enabling the Pre-Chat form. Permitted values: true, false. The default value is false.
* **align**: Make the chat available on the Right or on the Left of the screen. Permitted values: 'right', 'left'. Default value is right.
* **calloutTimer**: Proactively open the chat windows to increase the customer engagement. Permitted values: -1 (Disabled), 0 (Immediatly) or a positive integer value. For exmaple: 5 (After 5 seconds), 10 (After 10 seconds).
* **calloutTitle** : The title of the callout window.
* **calloutMsg** : The message of the callout window.
* **userFullname**: Current user fullname. Set this parameter to specify the visitor fullname.
* **userEmail**: Current user email address. Set this parameter to specify the visitor email address.
* **wellcomeTitle**: The welcome title to show on the widget home page.
* **wellcomeMsg**: Set the widget welcome message. Value type : string
* **widgetTitle**: Set the widget title label shown in the widget header. Value type : string. The default value is Tiledesk.
* **startFromHome**: If false when loaded the widget starts directly with a new conversation. If true the widget shows the home componenent. The default value is true.
* **logoChat**: The url of the logo to show on the widget home page.
* **lang** : With this configuration it is possible to force the widget lang. The widget will try to get the browser lang, if it is not possible it will use the default "en" lang
* **hideHeaderCloseButton**: Hide the close button in the widget header. Permitted values: true, false. The default value is false.
* **isOpen**: Read-only property. Set this property true in the script to automatically open the widget as soon as it is loaded. Permitted values: true, false. Default value : false.
* **fullscreenMode**: if it is true, the chat window is open in fullscreen mode. Permitted values: true, false. Default value : false
* **themeColor**: allows you to change the main widget's color (color of the header, color of the launcher button, other minor elements). Permitted values: Hex color codes, e.g. #87BC65 and RGB color codes, e.g. rgb(135,188,101)
* **themeForegroundColor**: allows you to change text and icons' color. Permitted values: Hex color codes, e.g. #425635 and RGB color codes, e.g. rgb(66,86,53)
* **departmentID:** to skip departments selection, you can set the department ID upon which the widget must start the new conversation. See the turorial [here](/widget/advanced/preset-department).
* **isShown:** Read only property. This property returns the visibility of the whole widget including the widget ballon. If true the widget is visible otherwise (false) the widget is hidden. Use *window\.tiledesk.show()* and *window\.tiledesk.hide()* methods to change the widget visibility.
* **allowTranscriptDownload**: allows the user to download the chat transcript. The download button appears when the chat is closed by the operator. Permittet values: true, false. Default value: false
* **marginX**: Set the side margin, left or right depending on the align property. Value type: string. Default value : "20px"
* **marginY**: Set the distance from the page bottom margin. Value type: string. Default value : "20px"
* **autoStart**: Set if the widget performs an automatic anonymous authentication at the startup. Default value : true
* **startHidden**: Set if the widget starts in hidden mode. Default value : false
* **persistence**: You can specify how the Authentication state persists when using the Tiledesk JS SDK. This includes the ability to specify whether a signed in user should be indefinitely persisted until explicit sign out or cleared when the window is closed. Permittet values: local, session. Default value : local. Local value indicates that the state will be persisted even when the browser window is closed. An explicit sign out is needed to clear that state. Session value indicates that the state will only persist in the current session or tab, and will be cleared when the tab or window in which the user authenticated is closed.
* **showWaitTime**: Show the expected response time from your agents in the home widget window. Value type : boolean. The default value is true.
* **showAvailableAgents**: Show the available agents with avatar in the home widget window. Value type : boolean. The default value is true.
* **showLogoutOption**: Show the logout options in the home widget window. Value type : boolean. The default value is true.
* **isLogEnabled**: Enable the widget log. Value type: boolean. The default value is false.

#### Example 1. Widget with user fullname and email

```
<script type="application/javascript">
      window.tiledeskSettings = 
          {
              projectid: "5b55e806c93dde00143163dd",
              userFullname: "Andrea Leo",
              userEmail: "andrea.leo@f21.it"
          };

      (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id; //js.async=!0;
        js.src = "https://widget.tiledesk.com/v4/launch.js";
        fjs.parentNode.insertBefore(js, fjs);
      }(document, 'script', 'tiledesk-jssdk'));
    </script>
```

#### Example 2. Widget with preChatForm and left alignment:

```
<script type="application/javascript">
  window.tiledeskSettings = 
    {
      projectid: "5b55e806c93dde00143163dd",
      preChatForm: true,
      align: 'left'
    };
    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id; 
      js.src = "https://widget.tiledesk.com/v4/launch.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'tiledesk-jssdk'));
</script>
```

### Configuration using URL parameters

You can also pass the above configurations as a Url parameter with the **tiledesk\_** prefix. For example:

```
https://widget.tiledesk.com/v4/index.html?tiledesk_isOpen=true&tiledesk_align=right
```

## Methods

### Open the widget

This will open the widget:

```
window.tiledesk.open();
```

### Minimize the widget

This will minimize the widget:

```
window.tiledesk.close();
```

### Hide the widget

This will hide the widget:

```
window.tiledesk.hide();
```

### Show the widget

This will show the widget:

```
window.tiledesk.show();
```

### Reinitialize the widget

If your app is characterized by very few page refreshes (ie., content is swapped out on the client side but no page refresh happens, Angular, React, jQuery, etc..) and lots of asynchronous JS, you'll need to update Tiledesk when your user's data changes. A reInit call simulates a page refresh, causing Tiledesk to reload the widget and all the configurations.

```
window.tiledesk.reInit();
```

### Signin with JWT Custom Token

This method make a signin using a JWT Custom Token as described [here](/widget/auth).

```
window.tiledesk.signInWithCustomToken(customJwt);
```

### Make a logout

This will logout the widget:

```
window.tiledesk.logout();
```

### Show or hide the PreChatForm

This parameter configures the PreChatForm visibility:

```
window.tiledesk.setPreChatForm(true|false);
```

### Send a message to a support conversation

This method sends a message to the current support conversation:

```
const recipientId = window.tiledesk.angularcomponent.component.g.activeConversation
const message = 'hello';
const type = 'text';
const metadata = {};
const attributes = {};
window.tiledesk.sendSupportMessage(
    message,
    recipientId,
    type,
    metadata,
    attributes
)
```

## Events

### tileDeskAsyncInit

The function tileDeskAsyncInit is called when the basic apis of the widget are loaded. Inside the tileDeskAsyncInit function the object window\.tiledesk is defined and can be used.

### window\.tiledesk.on(event\_name, handler)

Register an event handler to an event type.

Available events:

| event\_name                    | description                                                     |
| ------------------------------ | --------------------------------------------------------------- |
| onLoadParams                   | Fired when the parameters are loaded.                           |
| onInit                         | Fired when the widget is initialized                            |
| onAuthStateChanged             | The event is generated when the user logs in or logs out        |
| onOpen                         | Fired when the widget is open                                   |
| onClose                        | Fired when the widget is closed                                 |
| onBeforeMessageSend            | Fired before the message sending.                               |
| onAfterMessageSend             | This event is generated after the message has been sent.        |
| onOpenEyeCatcher               | Fired when the callout box is open                              |
| onClosedEyeCatcher             | Fired when the callout box is closed                            |
| onNewConversationComponentInit | Fired just after a new conversation is initialized              |
| onBeforeDepartmentsFormRender  | Fired just before rendering Departments in the Departments view |
| onMessageCreated               | Fired when the widget receive a message                         |
| onConversationUpdated          | Fired when the widget receive a conversation update             |

Initial events lifecycle:

onLoadParams -> onInit -> onAuthStateChanged

The handler will have the signature function(event\_data).

event\_data is a Javascript CustomEvent. More info about CustomEvent [here](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent)

Arguments:

| Parameter   | Type     | Required | Description                                       |
| ----------- | -------- | -------- | ------------------------------------------------- |
| event\_name | String   | YES      | Event name to bind to                             |
| handler     | Function | YES      | Function with the signature function(event\_data) |

#### Example 3. Logging of widget events

```
 <script type="application/javascript">    
      window.tileDeskAsyncInit = function() {
       window.tiledesk.on('onBeforeMessageSend', function(event_data) {
         var message =  event_data.detail;
         console.log("onBeforeMessageSend called ", message);
       });
       window.tiledesk.on('onAfterMessageSend', function(event_data) {
         var message =  event_data.detail;
         console.log("onAfterMessageSend called ", message);
       });
      }
</script>
```

[Full example here](https://github.com/chat21/chat21-web-widget/blob/master/src/test.html)

### Load Parameters event

This event will be fired before the tiledesk parameters is loaded. Use this event to change at runtime your TileDesk settings.

Important payload of event\_data:

| Parameter                | Type   | Description                      |
| ------------------------ | ------ | -------------------------------- |
| detail.default\_settings | Object | the constructor default settings |

#### Example 4. Widget with visitor fullname and email from localStorage

```
<script type="application/javascript">    
    //set fullname to localstorage
    localStorage.setItem("user_fullname", "Andrea from localStorage");
    localStorage.setItem("user_email", "andrea.leo@f21.it");

      window.tileDeskAsyncInit = function() {
       window.tiledesk.on('onLoadParams', function(event_data) {
          window.tiledeskSettings.userFullname = localStorage.getItem("user_fullname");
          window.tiledeskSettings.userEmail = localStorage.getItem("user_email");
       });
      }
</script>
```

[Full example here](https://github.com/chat21/chat21-web-widget/blob/master/src/test.html)

#### Example 5. Widget with welcome message with current date

```
<script type="application/javascript">    
      window.tileDeskAsyncInit = function() {
       window.tiledesk.on('onLoadParams', function(event_data) {
         window.tiledeskSettings.wellcomeMsg = " Hello at: " + new Date().toLocaleString();
       });
      }
</script>
```

### Before sending messsage

This event will be fired before the message sending. Use this event to add user information or custom attributes to your chat message.

Important payload of event\_data:

| Parameter | Type   | Description                    |
| --------- | ------ | ------------------------------ |
| detail    | Object | the message that is being sent |

Example. Programmatic setting custom user metadata

```
 <script type="application/javascript">    
      window.tileDeskAsyncInit = function() {
       window.tiledesk.on('onBeforeMessageSend', function(event_data) {
         var message =  event_data.detail;
         message.attributes.userCompany = "Frontiere21";
       });
      }
</script>
```

[Full example here](https://github.com/chat21/chat21-web-widget/blob/master/src/test.html)

Example. Add a custom attribute (page title) to the message.

```
 <script type="application/javascript">    
      window.tileDeskAsyncInit = function() {
       window.tiledesk.on('onBeforeMessageSend', function(event_data) {
         var message =  event_data.detail;
         message.attributes.pagetitle = document.title;
       });
      }
</script>
```

[Full example here](https://github.com/chat21/chat21-web-widget/blob/master/src/test.html)

### After messsage sent

This event is generated after the message has been sent.

Important payload of event\_data:

| Parameter | Type   | Description               |
| --------- | ------ | ------------------------- |
| detail    | Object | the message that was sent |

Example:

```
 <script type="application/javascript">    
      window.tileDeskAsyncInit = function() {
        window.tiledesk.on('onAfterMessageSend', function(event_data) {
          var message =  event_data.detail;
          console.log("onAfterMessageSend called ", message);
       });
      }
</script>
```

### onAuthStateChanged

This event is generated when the authentication state changed (Ex: user sign-in, user logout, etc.) Important payload of event\_data:

| Parameter | Type   | Description    |
| --------- | ------ | -------------- |
| detail    | Object | the auth event |

Auth Event description:

| Parameter         | Type    | Description                                                                                                                                     |
| ----------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| event             | number  | Possible values: 0 if wasn't logged( with autoStart false), 200 already logged, 201 new login, 400 error, -2 from reinit method, -1 from logout |
| isLogged          | boolean | Possible values: true if the user is logged, false if not logged                                                                                |
| user\_id          | string  | The current user identifier                                                                                                                     |
| global            | object  | An object with all the widget global parameters                                                                                                 |
| default\_settings | object  | The initial widget config parameters (window\.tiledeskSettings)                                                                                 |
| appConfigs        | object  | The remote widget config parameters obtained from the remote Tiledesk server                                                                    |

Example:

```
 <script type="application/javascript">    
      window.tileDeskAsyncInit = function() {
      window.tiledesk.on('onAuthStateChanged', function (event_data) {

            console.log("onAuthStateChanged ----> ", event_data.detail.event);
            if (!event_data.detail.isLogged) {
                console.log("NOT logged");                      
                window.tiledesk.signInWithCustomToken("JWT CHANGE IT");                
            } else {
              console.log("logged in");
            }
        });
      }
</script>
```

### onBeforeDepartmentsFormRender

This event is generated before rendering the Departments selection View. Use this event if you want to filter the default Departments list based on some conditions.

Important payload of event\_data:

| Parameter          | Type   | Description                          |
| ------------------ | ------ | ------------------------------------ |
| detail.departments | Object | the array of the default Departments |

Example:

In the following example Departments are filtered based on the current widget language. Actually a Deparment doesn't provide a specific "language" field. In this example Department language is put in the Department description field. A next update will provide specific Department "tags" (or "lables") that will be used to save specific informations into the Department resources.

```
<script type="application/javascript">
window.tileDeskAsyncInit = function() {
  window.tiledesk.on('onBeforeDepartmentsFormRender', function(event_data) {
    var departments = event_data.detail.departments;
    var lang = window.tiledesk.angularcomponent.component.g.lang;
    if (lang && lang === 'en') {
      return departments.filter(function(dep) {
        if (dep.description.includes('English')) {
            return dep;
        }
      });
    } else {
      return departments.filter(function(dep) {
        if (dep.description.includes('French')){
            return dep;
        }
      });
    }
  });
}
</script>
```

### onNewConversationComponentInit

This event is generated as soon as a new conversation view is rendered. Use this event if you want to execute some actions on a Conversation start.

Important payload of event\_data:

| Parameter        | Type   | Description                                     |
| ---------------- | ------ | ----------------------------------------------- |
| detail.newConvId | Object | the id of the conversation that fired the event |

Example:

In the following example a hidden message is sent as soon as a conversation starts. Sending a hidden message is useful to fire a bot welcome message, if one is invited in the conversation.

```
<script type="application/javascript">    
window.tileDeskAsyncInit = function() {
    window.tiledesk.on('onNewConversationComponentInit', function(event_data) {
    const message = 'hello';
    const recipientId = event_data.detail.newConvId;
    const type = 'text';
    const metadata = {};
    const attributes = {test:'test attributes', subtype: 'info'};
    window.tiledesk.sendSupportMessage(
        message,
        recipientId,
        type,
        metadata,
        attributes
    )
    });
}
</script>
```

### onMessageCreated

This event is generated when the widget receive a message.

Important payload of event\_data:

| Parameter | Type   | Description                   |
| --------- | ------ | ----------------------------- |
| detail    | Object | the message that was received |

Example:

```
 <script type="application/javascript">    
      window.tileDeskAsyncInit = function() {
       window.tiledesk.on('onMessageCreated', function(event_data) {
              var message = event_data.detail;
              console.log(" TRIGGER onMessageCreated -> ", message);
        });
      }
</script>
```

### onConversationUpdated

This event is generated when the widget receive a conversation update.

Important payload of event\_data:

| Parameter | Type   | Description                        |
| --------- | ------ | ---------------------------------- |
| detail    | Object | the conversation that was received |

Example:

```
 <script type="application/javascript">    
      window.tileDeskAsyncInit = function() {
       var now = Date.now();
       window.tiledesk.on('onConversationUpdated', function(event_data) {
          var dateConvUpdate = event_data.detail.conversation.timestamp
          console.log(" TRIGGER onConversationUpdated -> ", event_data.detail.conversation);
          console.log("now-> ", now);
          console.log("dateConvUpdate-> ", dateConvUpdate);
          if(now < dateConvUpdate){
            console.log(" New conversation!!!");
          }
        });
      }
</script>
```

## Enabling authenticated visitors in the Chat widget

You can configure your widget to authenticate visitors using the Javascript API and JWT token. More info [Widget Authentication](/widget/auth)


# Accessibility statement doc

**Document type:** Consolidated alignment statement and implementation inventory\
**Language:** English\
**Last update:** 2026-05-12

This document describes **capabilities and patterns that are present** in the product engineering. It is **not** a legal certificate, VPAT, or third-party audit report.

***

## 1. Purpose and scope

This statement describes how the Tiledesk chat widget product line positions its user interface engineering relative to internationally recognised accessibility norms. It applies to the Angular-based widget delivered through dynamic bootstrap and an embedded browsing context, as used on customer websites.

The scope is the interactive widget experience (launcher, conversations, forms, media, and related overlays) as implemented in this codebase.

This statement may be shared with customers, integrators, or accessibility specialists as **context** for how the widget is built and maintained. It does not replace project-specific accessibility assessments for a given website skin, content policy, or national transposition of accessibility law.

***

## 2. Reference frameworks (informative)

Accessibility work on this product is informed by the following technical and regulatory reference layers, which organisations commonly use when specifying digital accessibility for public-sector procurement and enterprise risk management:

| Reference                                                                                                                    | Role in product engineering                                                                                                                                  |
| ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **W3C Web Content Accessibility Guidelines (WCAG) 2.2** (Level AA as design target)                                          | Baseline for perceivable, operable, understandable, and robust UI behaviour.                                                                                 |
| **W3C Accessible Rich Internet Applications (WAI-ARIA) 1.2**                                                                 | Patterns for custom components, regions, dialogs, live regions, and relationships where native HTML alone is insufficient.                                   |
| **ETSI EN 301 549** (European accessibility standard for ICT products and services, including WCAG 2.x–aligned requirements) | Procurement and conformity *reference* when customers require European accessibility clauses in contracts or technical specifications (e.g. chapters 9, 11). |

Formal conformity claims for a specific deployment remain the responsibility of the deploying organisation and are typically supported by independent evaluation against the applicable version of WCAG and any regional transposition of EN 301 549.

***

## 3. Engineering posture (state of the art)

The widget is implemented as a focused single-page application within an iframe, with a parent-page bootstrap script responsible for embedding. Engineering attention is directed toward:

* **Semantic controls and naming:** Primary navigation and chrome actions use native `button` elements where the interaction model is activational; icon-only controls are paired with translatable `aria-label` (or equivalent) text from the product’s translation maps.
* **Structured regions and bypass:** Conversation views use landmark-style regions (for example `role="region"`) and skip affordances so keyboard users can move efficiently to the message composer.
* **Modal and overlay semantics:** Key flows such as customer satisfaction rating, department selection, and pre-chat entry use dialog semantics (`role="dialog"`, `aria-modal`, labelling) consistent with WAI-ARIA dialog guidance, with focus management support via Angular CDK where applied.
* **Forms and errors:** Dynamic form fields support programmatic association of labels, required state, invalid state, and error descriptions via ARIA relationships; error content uses live semantics where appropriate for time-sensitive feedback.
* **Rich content:** Components for audio playback, carousels, and image preview follow patterns that expose control state and mark decorative graphics appropriately for assistive technologies.
* **Motion and perception:** Stylesheets include reduced-motion handling so that users who prefer less animation receive a calmer visual experience.
* **Embedding context:** The host iframe is given a descriptive title in the bootstrap layer so that the embedded application is identifiable in browsing contexts that surface frame titles.

Testing and quality assurance combine static template review, build verification, diagnostics, manual keyboard walk-through, screen reader smoke tests, and reduced-motion verification, in line with common industry practice for complex widgets.

***

## 4. Document metadata

| Field                 | Value                                                                                                                                           |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| Product               | Tiledesk Web Widget                                                                                                                             |
| Package               | `@chat21/chat21-web-widget`                                                                                                                     |
| Version               | 5.1.33                                                                                                                                          |
| Stack                 | Angular 18.2.x (NgModule bootstrap), Angular CDK 17 (`A11yModule`), iframe-hosted (`launch.js`)                                                 |
| Standards orientation | WCAG 2.2 Level AA, WAI-ARIA 1.2 Authoring Practices, EN 301 549 v3.2.1 (informative reference for ICT accessibility chapters aligned with WCAG) |
| Document language     | English                                                                                                                                         |

***

## 5. Accessibility engineering coverage (summary)

The table below is the **engineering self-assessment summary** used internally to track breadth of accessibility work across product areas. Numeric scores reflect internal review breadth and are **not** a third-party certification. Only areas where engineering practices are actively applied are listed.

| Area                            | Score (0–5) | Conformance level targeted                            |
| ------------------------------- | ----------- | ----------------------------------------------------- |
| Semantic HTML                   | 4.5         | WCAG 2.2 AA                                           |
| Keyboard accessibility          | 4.5         | WCAG 2.2 AA                                           |
| ARIA compliance                 | 4.5         | WAI-ARIA 1.2                                          |
| Forms accessibility             | 5.0         | WCAG 2.2 AA                                           |
| Dialog / Modal accessibility    | 4.5         | WAI-ARIA 1.2 (focus trap via Angular CDK)             |
| Live regions / SR announcements | 4.0         | WCAG 4.1.3                                            |
| Reduced motion / animations     | 5.0         | WCAG 2.3.3 / 2.2.2                                    |
| Internationalization            | 4.5         | WCAG 3.1.1 / 3.1.2                                    |
| Iframe integration              | 4.5         | WCAG 2.4.1 / 4.1.2                                    |
| **Overall self-assessment**     | **4.5 / 5** | **WCAG 2.2 AA — engineering-oriented implementation** |

***

## 6. Project overview

| Topic                            | Detail                                                                                                                                                                                                                                          |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bootstrap mode**               | NgModule (`AppModule`) via `platformBrowserDynamic().bootstrapModule(AppModule)` (`src/main.ts`). The compiled bundle is injected into a same-origin iframe by `src/launch.js`, which builds and styles `#tiledesk-container` in the host page. |
| **Standalone components**        | Not used; components are declared in `AppModule` (`src/app/app.module.ts`).                                                                                                                                                                     |
| **Routing**                      | Not used at runtime: navigation between `home`, `list-conversations`, `conversation`, `selection-department`, `prechat-form`, `star-rating-widget`, `error-alert` is driven by template flags inside `AppComponent`.                            |
| **i18n**                         | `@ngx-translate/core` 16 with JSON dictionaries in `src/assets/i18n/{en,it,es,fr}.json` plus an optional remote dictionary. Active language is propagated to `<html lang>` in the widget document.                                              |
| **Accessibility libraries used** | `@angular/cdk/a11y` (`A11yModule`) — focus trap support for modals where integrated.                                                                                                                                                            |

***

## 7. Component inventory and accessibility highlights

The widget exposes 30+ components. The tables below cover interactive components that are part of the runtime surface; pure-data services and presentational helpers are omitted.

### 7.1 Shell components

| Component                    | Selector                   | Role / landmark  | Accessibility highlights                                                      |
| ---------------------------- | -------------------------- | ---------------- | ----------------------------------------------------------------------------- |
| `AppComponent`               | `chat-root`                | Application root | `:focus-visible` ring scoped to `chat-root`; `prefers-reduced-motion` honored |
| `LauncherButtonComponent`    | `chat-launcher-button`     | `<button>`       | `type="button"`, `aria-label` from `BUTTON_OPEN_CHAT`, focus-visible          |
| `EyeeyeCatcherCardComponent` | `chat-eyeeye-catcher-card` | Buttons          | All clickable areas are real `<button type="button">` with `aria-label`       |
| `LastMessageComponent`       | `chat-last-message`        | Buttons          | Preview activator is `<button>` with `aria-label`; close is a real button     |

### 7.2 Home / list / department views

| Component                       | Role / landmark                                    | Highlights                                                                                                            |
| ------------------------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `HomeComponent`                 | `role="region"` + `aria-label`                     | `<h1>` welcome, `<p>` intro; close/maximize/minimize/center are buttons; social channels labelled                     |
| `HomeConversationsComponent`    | `role="list"` + `role="listitem"`                  | "Show all conversations" and "Start new conversation" are buttons with `aria-label`; archived badge uses `role="img"` |
| `ListAllConversationsComponent` | `role="region"`                                    | `<h2>` title; back is a button; dead `altIconTitle` SVG markup removed                                                |
| `ListConversationsComponent`    | List items                                         | Each item activates a button; counters/badges marked `aria-hidden="true"`                                             |
| `SelectionDepartmentComponent`  | `role="dialog"` `aria-modal="true"` `cdkTrapFocus` | `<h2>` title, Escape closes, options are real buttons                                                                 |

### 7.3 Conversation surface

| Component                            | Role / landmark                                    | Highlights                                                                                                                                                                                                        |
| ------------------------------------ | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ConversationComponent`              | `role="region"`                                    | Visible-on-focus skip link → composer (WCAG 2.4.1); scroll-to-bottom is a button with `aria-label`                                                                                                                |
| `ConversationHeaderComponent`        | `<button>` toolbar                                 | Each control is `<button type="button">` with `aria-label`; options popover uses `aria-expanded`/`aria-haspopup="true"`/`aria-controls`; popover items are real buttons grouped under `role="group"` (Esc closes) |
| `ConversationContentComponent`       | `role="log"` `aria-live="polite"`                  | Each message wrapped in `role="article"`; carousel slides expose `role="group"` + `aria-roledescription="slide"`                                                                                                  |
| `ConversationFooterComponent`        | Form-like region                                   | Attachment/emoji/send/record are buttons; emoji panel is `role="dialog"`; alert area is `role="alert"` `aria-live="assertive"`                                                                                    |
| `ConversationAudioRecorderComponent` | Buttons                                            | Record toggle uses `aria-pressed`; play/pause/delete/send all labelled                                                                                                                                            |
| `ConversationPreviewComponent`       | `role="dialog"` `aria-modal="true"` `cdkTrapFocus` | `aria-labelledby` via `LABEL_PREVIEW`; Esc closes; close/send are buttons                                                                                                                                         |
| `ConversationInternalFrameComponent` | Panel                                              | Iframe has `title`, `sandbox`, `referrerpolicy`, `loading="lazy"`; spinner `aria-hidden`                                                                                                                          |
| `MenuOptionsComponent`               | `role="group"` popover                             | Sound toggle uses `aria-pressed`; Esc closes; toggle button advertises `aria-expanded`/`aria-haspopup="true"`                                                                                                     |

### 7.4 Form components

| Component                  | Highlights                                                                                                                       |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `PrechatFormComponent`     | `role="dialog"` `aria-modal="true"` `cdkTrapFocus`; `<h2>` title; Escape closes                                                  |
| `FormBuilderComponent`     | Submit button is `type="button"`; native form semantics                                                                          |
| `FormTextComponent`        | `<label for>` ↔ `<input id>`; `aria-required`, `aria-invalid`, `aria-describedby` to error `role="alert"`; `:focus-visible` ring |
| `FormTextareaComponent`    | Same pattern as `FormText`, plus `aria-multiline`                                                                                |
| `FormCheckboxComponent`    | Native `<input type="checkbox">` linked to `<label>`; ARIA validation states wired                                               |
| `FormRadioButtonComponent` | Native `<input type="radio">`                                                                                                    |
| `FormSelectComponent`      | Native `<select>`                                                                                                                |
| `FormLabelComponent`       | Pure label slot                                                                                                                  |

### 7.5 Message bubble components

| Component                                                                                  | Highlights                                                                                                                                                                                          |
| ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `BubbleMessageComponent`                                                                   | Class-based selector replacing former duplicated `id="bubble-message"`; carries translation map down                                                                                                |
| `TextComponent`                                                                            | Root is `<div>`; markdown rendered through `marked` pipe; CSS targets the `.message_innerhtml` wrapper                                                                                              |
| `HtmlComponent`                                                                            | Class-based wrapper; sanitizer-aware                                                                                                                                                                |
| `ImageComponent`                                                                           | Wrapped in `<button>` with `aria-label`; lightbox is a `role="dialog"` iframe with close button, Escape support and focus restoration                                                               |
| `FrameComponent`                                                                           | Iframe hardened: dynamic `title`, `sandbox`, `referrerpolicy`, `loading="lazy"`                                                                                                                     |
| `AudioComponent`                                                                           | Play/pause buttons labelled via `BUTTON_PLAY_AUDIO` / `BUTTON_PAUSE_AUDIO`                                                                                                                          |
| `CarouselComponent`                                                                        | Wrapper exposes `role="region"` `aria-roledescription="carousel"` `aria-label`; each card is `role="group"` `aria-roledescription="slide"` `aria-label="Slide N of M"`; arrows and CTAs are buttons |
| `ActionButtonComponent`, `LinkButtonComponent`, `TextButtonComponent`                      | Real `<button>` / `<a>` with `aria-label`                                                                                                                                                           |
| `ReturnReceiptComponent`, `LikeUnlikeComponent`, `AvatarComponent`, `InfoMessageComponent` | Decorative iconography flagged `aria-hidden="true"`; semantic content carries text alternatives                                                                                                     |

### 7.6 Modals

| Component                   | Highlights                                                                                                                                                 |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ConfirmCloseComponent`     | `role="dialog"` `aria-modal="true"` `cdkTrapFocus` `aria-labelledby="confirm-close-title"`; `<h2>` heading; Escape closes; cancel/confirm are real buttons |
| `ErrorAlertComponent`       | Provides translatable error messages                                                                                                                       |
| `StarRatingWidgetComponent` | Stars exposed as buttons; comment area is a labelled textarea                                                                                              |

***

## 8. WCAG 2.2 compliance checklist (implemented patterns)

The following table lists **success criteria for which the widget implements supporting patterns** that were reviewed in the engineering statement. Each row documents what **is present** in the product line.

| Success Criterion                 | Level             | Status | Evidence                                                                                                                |
| --------------------------------- | ----------------- | ------ | ----------------------------------------------------------------------------------------------------------------------- |
| 1.1.1 Non-text Content            | A                 | Pass   | All informational icons carry `aria-label`/`alt`; decorative SVGs use `aria-hidden="true"` and `focusable="false"`      |
| 1.3.1 Info and Relationships      | A                 | Pass   | `<h1>`/`<h2>` headings, `role="log"`, `role="article"`, `role="list"`, programmatic `<label for>` ↔ `<input id>`        |
| 1.3.2 Meaningful Sequence         | A                 | Pass   | Tab order follows reading order; high `tabindex` values removed                                                         |
| 1.4.3 Contrast (Minimum)          | AA                | Pass   | Default theme passes 4.5:1; custom palettes remain integrator-validated                                                 |
| 1.4.4 Resize Text                 | AA                | Pass   | Layout is em-based; honours user font scaling                                                                           |
| 1.4.10 Reflow                     | AA                | Pass   | Responsive layout; no horizontal scrolling at 320 CSS pixels                                                            |
| 1.4.11 Non-text Contrast          | AA                | Pass   | Focus ring is `2px solid #1a73e8`, ≥ 3:1 against widget backgrounds                                                     |
| 1.4.12 Text Spacing               | AA                | Pass   | No critical fixed line-height/letter-spacing overrides                                                                  |
| 1.4.13 Content on Hover or Focus  | AA                | Pass   | Tooltips use `:hover`/`:focus`, dismissable, persistent; no time-based dismissal                                        |
| 2.1.1 Keyboard                    | A                 | Pass   | Every actionable element is reachable and operable from keyboard (real buttons, native form controls)                   |
| 2.1.2 No Keyboard Trap            | A                 | Pass   | `cdkTrapFocus` traps only inside dialogs; Esc and dialog-close return focus                                             |
| 2.1.4 Character Key Shortcuts     | A                 | Pass   | The widget does not bind single-character shortcuts globally                                                            |
| 2.2.2 Pause, Stop, Hide           | A                 | Pass   | Animations are decorative and short; reduced-motion media query disables them entirely                                  |
| 2.3.3 Animation from Interactions | AAA (informative) | Pass   | `prefers-reduced-motion: reduce` neutralises animations and transitions inside `chat-root`                              |
| 2.4.1 Bypass Blocks               | A                 | Pass   | Skip link in conversation surface jumps focus to the message composer                                                   |
| 2.4.3 Focus Order                 | A                 | Pass   | Logical order: header → log → composer → footer; high `tabindex` removed                                                |
| 2.4.7 Focus Visible               | AA                | Pass   | Global `outline: none` removed; `:focus-visible` rule scoped to `chat-root`                                             |
| 2.4.11 Focus Not Obscured (Min)   | AA                | Pass   | Sticky header/footer leave the active control visible; verified with launcher button                                    |
| 2.5.7 Dragging Movements          | AA                | Pass   | Carousel can be operated by next/previous arrow buttons in addition to drag                                             |
| 2.5.8 Target Size (Minimum)       | AA                | Pass   | All primary controls ≥ 24×24 CSS px                                                                                     |
| 3.1.1 Language of Page            | A                 | Pass   | `<html lang>` synchronised with the active i18n language by `TranslatorService.syncDocumentLang`                        |
| 3.2.1 On Focus                    | A                 | Pass   | No context change on focus                                                                                              |
| 3.2.2 On Input                    | A                 | Pass   | No context change on input; the user always confirms                                                                    |
| 3.2.6 Consistent Help             | A                 | Pass   | Help / contact entry points (`menu-options`) are consistent across views                                                |
| 3.3.1 Error Identification        | A                 | Pass   | Form errors are announced with `role="alert"` and `aria-invalid`                                                        |
| 3.3.2 Labels or Instructions      | A                 | Pass   | All form fields have programmatic labels and placeholder is not the only label                                          |
| 3.3.3 Error Suggestion            | AA                | Pass   | Localised strings (`LABEL_ERROR_FIELD_NAME`, `LABEL_ERROR_FIELD_EMAIL`, `LABEL_ERROR_FIELD_REQUIRED`) explain the issue |
| 3.3.7 Redundant Entry             | A                 | Pass   | Pre-chat form data is persisted and re-applied across reopen                                                            |
| 4.1.2 Name, Role, Value           | A                 | Pass   | All custom controls converted to native HTML or carry valid ARIA                                                        |
| 4.1.3 Status Messages             | AA                | Pass   | Conversation log uses `role="log"`/`aria-live="polite"`; emoji-blocked alert uses `role="alert"`                        |

***

## 9. Implemented accessibility practices (inventory)

This section inventories **concrete engineering practices** present in the codebase.

### 9.1 Modal dialogs

* `@angular/cdk/a11y` (`A11yModule`) imported in `AppModule`.
* `cdkTrapFocus` + `cdkTrapFocusAutoCapture="true"` on dialog surfaces including `ConversationPreviewComponent`, `ConfirmCloseComponent`, `SelectionDepartmentComponent`, `PrechatFormComponent`.
* `@HostListener('keydown.escape')` on dialog components to close on Escape and emit the close event.
* `<h2>` heading in confirm-close dialog wired through `aria-labelledby="confirm-close-title"`.
* Native `<dialog>` with `showModal()` where used for confirm-close so the browser enforces focus behaviour in addition to CDK.

### 9.2 Image lightbox

* Image trigger as `<button type="button">` with `aria-label`.
* Lightbox iframe content with `role="dialog"`, `aria-modal="true"` and explicit `aria-label`.
* Close control as `<button>` with `aria-label` and focus-visible outline.
* Auto-focus on close button when opened; focus restored on close; Escape and backdrop close.
* Document `lang` inherited; transitions disabled under `prefers-reduced-motion`.

### 9.3 Skip link and landmarks

* Visible-on-focus skip link in `ConversationComponent` (`.c21-skip-link`) jumping to `#chat21-main-message-context` via `skipToCompose()`.
* `role="region"` + `aria-label` on `HomeComponent`, `ListAllConversationsComponent`, `ConversationComponent`.
* `<h1>` for home welcome title; `<p>` for intro; `<h2>` for list-all-conversations title.

### 9.4 Internationalization and document language

`TranslatorService` updates `document.documentElement.lang` when a translation bundle loads (widget iframe document only).

| Key                    | Purpose                                                          |
| ---------------------- | ---------------------------------------------------------------- |
| `CAROUSEL_LABEL`       | `aria-label` of the carousel container                           |
| `CAROUSEL_SLIDE_LABEL` | Template for `aria-label="Slide {current} of {total}"` per slide |
| `SKIP_TO_COMPOSER`     | Text of the skip link                                            |

### 9.5 Reduced motion

A media-query block in `src/app/sass/animations.scss` neutralises animation duration, animation delay, transition duration and `scroll-behavior` for descendants of `chat-root` when `prefers-reduced-motion: reduce` is active.

### 9.6 Menu pattern

Popover menus in `conversation-header` and `chat-menu-options` are modelled as a `role="group"` of native `<button>` elements: trigger exposes `aria-expanded`, `aria-haspopup="true"`, `aria-controls`; popover has `aria-label`; sound toggle uses `aria-pressed`; Escape closes the group.

### 9.7 Carousel

* Wrapper: `role="region"`, `aria-roledescription="carousel"`, localised `aria-label`.
* Each card: `role="group"`, `aria-roledescription="slide"`, `aria-label="Slide N of M"` (localisable).
* Arrow controls: `<button type="button">` with `aria-label` from `CAROUSEL_PREVIOUS` / `CAROUSEL_NEXT`.
* Card CTAs: `<button>` with `aria-label`.
* Images carry meaningful `alt`; placeholder uses `alt=""`.

### 9.8 Forms

`form-text`, `form-textarea`, `form-checkbox` expose pairing between labels, inputs, and error regions (`aria-describedby`, `aria-invalid`, `role="alert"` on errors).

### 9.9 Iframes

`FrameComponent` and `ConversationInternalFrameComponent` declare `title`, `sandbox`, `referrerpolicy`, and `loading="lazy"` on embedded frames.

### 9.10 Focus visibility

`app.component.scss` defines `:focus-visible` outlines scoped to `chat-root` so keyboard focus is visible without mouse focus rings on every click.

***

## 10. Testing methodology

| Layer                        | Activity                                                                                                                                                                                           |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Static review                | Templates (`*.component.html`), styles (`*.component.scss`), and component classes reviewed against WCAG 2.2, WAI-ARIA 1.2, and EN 301 549 as informative reference.                               |
| Build verification           | `ng build` and Angular template type-checking.                                                                                                                                                     |
| Diagnostics                  | TypeScript and Angular template diagnostics on modified files.                                                                                                                                     |
| Manual keyboard walk-through | Tab / Shift+Tab / Enter / Space / Esc through launcher → home → conversation → composer (skip link), menu popovers, confirm-close, prechat, department selection, image lightbox, carousel arrows. |
| Screen reader smoke test     | NVDA, VoiceOver — headings, log announcements, dialog labels, button labels in the active language.                                                                                                |
| Reduced-motion smoke test    | With `prefers-reduced-motion: reduce`, animations and transitions inside `chat-root` are neutralised.                                                                                              |

***

## 11. Primary source locations (reference)

The following paths are primary locations for verifying the practices above:

```
src/app/app.module.ts
src/app/app.component.html
src/app/app.component.scss
src/app/sass/animations.scss
src/app/providers/translator.service.ts
src/app/providers/brand.service.ts
src/app/utils/utils-resources.ts
src/app/utils/globals.ts
src/app/component/home/home.component.html
src/app/component/home/home.component.scss
src/app/component/home-conversations/home-conversations.component.html
src/app/component/list-all-conversations/list-all-conversations.component.html
src/app/component/list-all-conversations/list-all-conversations.component.scss
src/app/component/selection-department/selection-department.component.html
src/app/component/selection-department/selection-department.component.ts
src/app/component/conversation-detail/conversation/conversation.component.html
src/app/component/conversation-detail/conversation/conversation.component.scss
src/app/component/conversation-detail/conversation/conversation.component.ts
src/app/component/conversation-detail/conversation-header/conversation-header.component.html
src/app/component/conversation-detail/conversation-content/conversation-content.component.html
src/app/component/conversation-detail/conversation-footer/conversation-footer.component.html
src/app/component/conversation-detail/conversation-footer/conversation-footer.component.ts
src/app/component/conversation-detail/conversation-preview/conversation-preview.component.html
src/app/component/conversation-detail/conversation-preview/conversation-preview.component.ts
src/app/component/conversation-detail/conversation-internal-frame/conversation-internal-frame.component.html
src/app/component/conversation-detail/conversation-audio-recorder/conversation-audio-recorder.component.html
src/app/component/conversation-detail/conversation-audio-recorder/conversation-audio-recorder.component.ts
src/app/component/menu-options/menu-options.component.html
src/app/component/eyeeye-catcher-card/eyeeye-catcher-card.component.html
src/app/component/eyeeye-catcher-card/eyeeye-catcher-card.component.scss
src/app/component/last-message/last-message.component.html
src/app/component/last-message/last-message.component.scss
src/app/component/launcher-button/launcher-button.component.html
src/app/component/send-button/send-button.component.html
src/app/component/star-rating-widget/star-rating-widget.component.html
src/app/component/form/prechat-form/prechat-form.component.html
src/app/component/form/prechat-form/prechat-form.component.ts
src/app/component/form/form-builder/form-builder.component.html
src/app/component/form/inputs/form-text/*
src/app/component/form/inputs/form-textarea/*
src/app/component/form/inputs/form-checkbox/*
src/app/component/message/bubble-message/bubble-message.component.html
src/app/component/message/text/text.component.html
src/app/component/message/text/text.component.scss
src/app/component/message/html/html.component.html
src/app/component/message/html/html.component.scss
src/app/component/message/image/image.component.html
src/app/component/message/image/image.component.scss
src/app/component/message/image/image.component.ts
src/app/component/message/audio/audio.component.html
src/app/component/message/audio/audio.component.ts
src/app/component/message/frame/frame.component.html
src/app/component/message/frame/frame.component.ts
src/app/component/message/buttons/action-button/action-button.component.html
src/app/component/message/carousel/carousel.component.html
src/app/component/message/carousel/carousel.component.scss
src/app/component/message/carousel/carousel.component.ts
src/app/modals/confirm-close/confirm-close.component.html
src/app/modals/confirm-close/confirm-close.component.scss
src/app/modals/confirm-close/confirm-close.component.ts
src/assets/i18n/en.json
src/assets/i18n/it.json
src/assets/i18n/es.json
src/assets/i18n/fr.json
```

***

## 12. References

| Resource                     | URL                                                                         |
| ---------------------------- | --------------------------------------------------------------------------- |
| WCAG 2.2                     | <https://www.w3.org/TR/WCAG22/>                                             |
| WAI-ARIA Authoring Practices | <https://www.w3.org/WAI/ARIA/apg/>                                          |
| EN 301 549 v3.2.1            | ETSI publication — accessibility requirements for ICT products and services |
| Angular CDK Accessibility    | <https://material.angular.dev/cdk/a11y/overview>                            |
| MDN Accessibility            | <https://developer.mozilla.org/en-US/docs/Web/Accessibility>                |

***

## 13. Continuous alignment

Tiledesk continues, day by day, to track evolving accessibility standards and platform behaviour across browsers and assistive technologies. The goal is to broaden coverage of WCAG-oriented success criteria, WAI-ARIA authoring practices, and EN 301 549–aligned expectations wherever they apply to this product category, and to reflect those expectations in design, implementation, and release testing. Standards and user-agent implementations evolve; accessibility posture is maintained as part of the normal engineering lifecycle.

***

## 14. Contact and feedback

For accessibility questions or updates for a custom deployment, contact the maintainers of this repository: <https://github.com/Tiledesk/chat21-web-widget>. Issues that mention **accessibility** in the title are routed to the team responsible for this statement.


# REST APIs


# Introduction

Tiledesk is a live chat solution that helps businesses increase sales conversion by engaging important leads on their websites. It is our goal to help many of these businesses use the Tiledesk API (the "API") to automate and enhance their customer support with Tiledesk.

## The API

This is the documentation for the Tiledesk REST API. Read the contents of this page carefully to understand how to be a good API citizen.

Endpoints are documented with the HTTP method for the request and a partial resource identifier. Example:

**GET /v3/{project\_id}**

Your Project ID (this appears as project\_id in your code) is a unique code assigned to your project when you create it in Tiledesk. There are a few ways you can find your Project ID.

The easiest way to find your Project ID is to check the URL of any page you have open in Tiledesk. It's the code that comes after /project/ in the URL. So for example, if we check the URL below you can see that the Project ID is *5c88a82990996000173cd4d1*.

![](/files/hOQhgM9Bi8yGdkJEaHhP)

Your Project ID is also available on the top of the Project Setting page of your dashboard.

To use the API prepend <https://api.tiledesk.com> to the resource identifier to get the full endpoint URL:

[https://api.tiledesk.com/v3/{project\_id}](https://api.tiledesk.com/v3/%7Bproject_id%7D)

The examples in the docs are cURL statements. You can run the statements on a command line to try out different API requests. In Windows, you'll need to modify some of the examples in the docs to make them work.

## Security and Authentication

This API is an SSL-only API. You must be a Tiledesk user to make API requests.

Tiledesk supports the following user roles:

* Guest: Any unknown visitor to your site who’s not logged in.
* User: A user is a signed-in visitor using JWT token o converted from guest type.
* Agent: Agents are your organization’s team members who will log into the dashboard and respond to your customer’s chats
* Admin: It's an agent with special permissions
* Owner: It's the project creator.

See here the [Authentication REST API](/apis/rest-api/authentication).

Tiledesk supports two authentication methods:

* Basic Authentication
* JWT Authentication

### Basic authentication

Use the following authentication format with your email address and password:

**{email\_address}:{password}**

#### Example

```
curl -v -X GET -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5ab0f32757066e0014bfd718/departments
```

### JWT authentication

Use the sign-in method to get a valid JWT token:

```
curl -v -X POST -H 'Content-Type:application/json' -d '{"email":"<YOUR_EMAIL>","password":"<YOUR_PASSWORD>"}' https://api.tiledesk.com/v3/auth/signin
```

Example

```
curl -v -X POST -H 'Content-Type:application/json' -d '{"email":"andrea.leo@f21.it","password":"123456"}' https://api.tiledesk.com/v3/auth/signin
```

Example: How to use JWT token

```
curl -v -X GET -H 'Authorization: JWT <JWT_TOKEN>' https://api.tiledesk.com/v3/5ab0f32757066e0014bfd718/departments
```

#### Rate Limiting

This API is rate limited. We only allow a certain number of requests per minute. We reserve the right to adjust the rate limit for given endpoints in order to provide a high quality of service for all clients. As an API consumer, you should expect to be able to make at least 200 requests per minute.

If the rate limit is exceeded, Tiledesk will respond with a HTTP 429 Too Many Requests response code and a body that details the reason for the rate limiter kicking in.

#### Request Format

This is a JSON-only API. You must supply a *Content-Type: application/json* header on PUT and POST requests. Sometimes you have to set an Accept: application/json header on a specific request. You may get a text/plain response in case of an error such as a bad request. You should treat this as an error you need to take action on.

#### Response Format

Tiledesk responds to successful requests with HTTP status codes in the 200 or 300 range. When you create or update a resource, Tiledesk renders the resulting JSON representation in the response body. Time stamps use UTC time and their format is **ISO8601**.

We respond to unsuccessful requests with HTTP status codes in the 400 range. The response may be "text/plain" content type for API level error messages (such as when trying to call the API without SSL). If you see a response from a known endpoint that looks like plain text, you probably made a syntax error in your REST call. If you ever experience responses with status codes in the 500 range, Tiledesk may be experiencing internal issues or having a scheduled maintenance (during which we send a 503 Service Unavailable status code). Please check the status page in such cases for any known issues.

When building an API client, we recommend treating any 500 status codes as a warning or temporary state. However, if the status persists and we don't have a publicly announced maintenance or service disruption, contact us at *<info@frontiere21.it>*.

## APIs

Below the apis:

* [Authentication](/apis/rest-api/authentication)
* [Requests](/apis/rest-api/requests)
* [Leads](/apis/rest-api/leads)
* [Messages](/apis/rest-api/messages)
* [Activities](/apis/rest-api/activities)
* [Projects](/apis/rest-api/projects)
* [Team](/apis/rest-api/team)
* [ChatBot](https://github.com/Tiledesk/tiledesk-docs/tree/782fa84dbf0a19a68076756029cbb9a33ce2b6f1/apis/rest-api/bots/README.md)
* [Management](https://github.com/Tiledesk/tiledesk-docs/tree/782fa84dbf0a19a68076756029cbb9a33ce2b6f1/apis/rest-api/management-api/README.md)

### Legal notices

Restrictions and responsibilities Your use and access to the API is expressly conditioned on your compliance with the policies, restrictions, and other provisions related to the API set forth in our API Restrictions and Responsibilities and the other documentation we provide you. You must also comply with the restrictions set forth in the Terms of Service and the Privacy Policy that apply to your use of the Tiledesk Service, in all uses of the API. If Tiledesk believes that you have or attempted to violate any term, condition or the spirit of these policies or agreements, your right to access and use the API may be temporarily or permanently revoked.

Change Policy Tiledesk may modify the attributes and resources available to the API and our policies related to access and use of the API from time to time without advance notice. Tiledesk will use commercially reasonable efforts to notify you of any modifications to the API or policies through notifications or posts on the Tiledesk Website. Modification of the API may have an adverse effect on Tiledesk Applications, including but not limited to changing the manner in which Tiledesk Applications communicate with the API and display or transmit Your Data. Tiledesk will not be liable to you or any third party for such modifications or any adverse effects resulting from such modifications.


# Authentication

## Authentication with email and password

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/auth/signin`

Allows to authenticate an agent using email and password.

#### Headers

| Name         | Type   | Description                  |
| ------------ | ------ | ---------------------------- |
| Content-Type | string | use "application/json" value |

#### Request Body

| Name     | Type   | Description            |
| -------- | ------ | ---------------------- |
| email    | string | the user email address |
| password | string | the user password      |

{% tabs %}
{% tab title="200 " %}

```
{
   "success":true,
   "token":"JWT  XYZ",
   "user":{
      "_id":"5ab11c6b83dc240014d46095",
      "email":"andrea.leo@f21.it"
   }
```

{% endtab %}
{% endtabs %}

## Anonymous authentication for a user

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/auth/signinAnonymously`

Allows a user to authenticate anonymously on the system.

#### Headers

| Name         | Type   | Description                  |
| ------------ | ------ | ---------------------------- |
| Content-Type | string | use "application/json" value |

#### Request Body

| Name        | Type   | Description                           |
| ----------- | ------ | ------------------------------------- |
| id\_project | string | the project to which the user belongs |
| firstname   | string | the user firstname                    |
| lastname    | string | the user password                     |
| email       | string | the user email                        |
| attributes  | object | the user custom attributes            |

{% tabs %}
{% tab title="200 " %}

```
{
   "success":true,
   "token":"JWT XYZ",
   "user":{
      "_id":"5e25944ecf6bcc00178e75fa",
      "email":"a0fe493b-a19b-44a0-99ce-414c65fc20b0@tiledesk.com",
      "emailverified":false,
      "createdAt":"2020-01-20T11:51:42.115Z",
      "updatedAt":"2020-01-20T11:51:42.115Z",
      "__v":0
   }
}
```

{% endtab %}
{% endtabs %}

## Custom authentication for a user

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/auth/signinWithCustomToken`

Allows to authenticate with a custom JWT token.

#### Headers

| Name          | Type   | Description                     |
| ------------- | ------ | ------------------------------- |
| Authorization | string | Custom JWT Authorization token. |

{% tabs %}
{% tab title="200 " %}

```
{
   "success":true,
   "token":"JWT eyJ0eXYZ",
   "user": {
     "_id":"123456",
     "firstname":"Andrea",
     "lastname":"Leo",
     "email":"andrea.l@test.it",
     "code":"123456",
     "sub":"userexternal",
     "aud":"https://tiledesk.com/projects/5ec688ed13400f0012c2edd1",
     "iat":1598865103,
     "exp":1598865223
  }
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl 'https://api.tiledesk.com/v3/auth/signinWithCustomToken' \
  -X 'POST' \
  -H 'authorization: JWT eyJ0eXAiOiJKVXYZZ....ZZZZZ'
```

You can find here [How to Generate a Custom Authentication Token](/apis/authentication)


# Requests

Requests are the means through which your end users (customers) communicate with agents in Tiledesk. Requests can originate from a number of channels, including email, chat, Facebook, Whatsapp or the API. All requests have a core set of properties. Commonly when a request is created via email channel it is also called a ticket in the Tiledesk platform. Instead when a request is created by a chat channel it is also called conversation.

## The Request model

| Key                 | Type    | Description                                                                                                                                                                                                                                                                                                                                                                                                              |
| ------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| id                  | String  | The unique identifier for the request which is given by                                                                                                                                                                                                                                                                                                                                                                  |
| request\_id         | String  | A unique identifier for the request which is given to Tiledesk. Follow this pattern 'support-group-UUID'. It is an external Id, so you must uniquely generate this id and pass it to Tiledesk. For example you can generate this id like this: 'support-group-af4b54df-3237-4db5-9351' (using [uuid](https://www.npmjs.com/package/uuid) or other UUID generator) or using timestamp like this 'support-group-TIMESTAMP' |
| first\_text         | String  | the request first text.                                                                                                                                                                                                                                                                                                                                                                                                  |
| department          | Object  | the [Department model](/apis/rest-api/management-api/departments#the-department-model) selected for the request.                                                                                                                                                                                                                                                                                                         |
| lead                | Object  | the [Lead model](/apis/rest-api/leads#the-lead-model) involved in this request.                                                                                                                                                                                                                                                                                                                                          |
| requester           | Object  | contains information about the user originated the request. This is a [Team model](/apis/rest-api/team#the-team-model).                                                                                                                                                                                                                                                                                                  |
| participants        | Array   | The list of the identifier of the teammates or bots who participated in the request.                                                                                                                                                                                                                                                                                                                                     |
| participatingAgents | Array   | The list of the teammates who participated in the request.                                                                                                                                                                                                                                                                                                                                                               |
| participatingBots   | Array   | The list of the bots who participated in the request.                                                                                                                                                                                                                                                                                                                                                                    |
| hasBot              | Boolean | Indicates whether a bot is participating in the conversation.                                                                                                                                                                                                                                                                                                                                                            |
| status              | Number  | The request status: TEMPORARY : 50, UNSERVED : 100, ABANDONED : 150, SERVED : 200, CLOSED : 1000                                                                                                                                                                                                                                                                                                                         |
| sourcePage          | String  | The request source page.                                                                                                                                                                                                                                                                                                                                                                                                 |
| language            | String  | The request language.                                                                                                                                                                                                                                                                                                                                                                                                    |
| userAgent           | String  | The user agent.                                                                                                                                                                                                                                                                                                                                                                                                          |
| tags                | Array   | A list of tags objects associated with the request.                                                                                                                                                                                                                                                                                                                                                                      |
| notes               | Array   | A list of notes objects associated with the request.                                                                                                                                                                                                                                                                                                                                                                     |
| rating              | Number  | The request rating. From 0 to 5.                                                                                                                                                                                                                                                                                                                                                                                         |
| rating\_message     | String  | The rating message.                                                                                                                                                                                                                                                                                                                                                                                                      |
| waiting\_time       | Number  | Wait time is calculated as duration between the first visitor message in the chat and the first agent message.                                                                                                                                                                                                                                                                                                           |
| transcript          | String  | The chat transcript.                                                                                                                                                                                                                                                                                                                                                                                                     |
| attributes          | Object  | The custom attributes which are set for the request.                                                                                                                                                                                                                                                                                                                                                                     |
| channel             | Object  | The channel of the conversation.                                                                                                                                                                                                                                                                                                                                                                                         |
| createdAt           | String  | The time (ISO-8601 date string) when the request was created.                                                                                                                                                                                                                                                                                                                                                            |
| first\_response\_at | String  | The time (ISO-8601 date string) when the first answer is given by bot or an agent                                                                                                                                                                                                                                                                                                                                        |
| updatedAt           | String  | The time (ISO-8601 date string) when the request was updated.                                                                                                                                                                                                                                                                                                                                                            |
| assigned\_at        | String  | The time (ISO-8601 date string) when the request was assigned to an agent or bot.                                                                                                                                                                                                                                                                                                                                        |
| first\_response\_at | String  | The time (ISO-8601 date string) when the agent or the bot replies the first time.                                                                                                                                                                                                                                                                                                                                        |
| closed\_at          | String  | The time (ISO-8601 date string) when the request was closed.                                                                                                                                                                                                                                                                                                                                                             |
| closed\_by          | String  | The unique identifier of the user who closed the request.                                                                                                                                                                                                                                                                                                                                                                |
| createdBy           | String  | The unique identifier of the row creator                                                                                                                                                                                                                                                                                                                                                                                 |
| preflight           | Boolean | If true the request has been proactively created by the system and the user has not yet sent a message                                                                                                                                                                                                                                                                                                                   |
| priority            | String  | Define the priority of the request. Available values: normal (default), low, hight, urgent.                                                                                                                                                                                                                                                                                                                              |
| location            | Object  | Define the location of the request obtained by a geo search based on the ip address of the client.                                                                                                                                                                                                                                                                                                                       |
| ticket\_id          | String  | It is the number that uniquely identifies the request within the project.                                                                                                                                                                                                                                                                                                                                                |
| snapshot            | Object  | The snapshot object containing context information (like department, lead, requester, agents, availableAgentsCount) when the the request was created.                                                                                                                                                                                                                                                                    |
| id\_project         | String  | The unique identifier of the project                                                                                                                                                                                                                                                                                                                                                                                     |

You can use the API to get the request information.

## Get all requests

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/requests`

Allows an account to list all the requests for the project.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Query Parameters

| Name                 | Type    | Description                                                                                                                                                                                                                                                                                                            |
| -------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| sortField            | string  | <p>what field to sort the results by.</p><p><em>default field is createdAt</em></p>                                                                                                                                                                                                                                    |
| direction            | string  | <p>sort direction: 1 (asc) or -1 (desc). Return the results in ascending (1) or descending (-1) order.</p><p><em>defaults to desc (-1)</em></p>                                                                                                                                                                        |
| page                 | number  | what page of results to fetch. defaults to first page.                                                                                                                                                                                                                                                                 |
| limit                | number  | <p>specify the maximum number of results to be returned.</p><p><em>default is 40 rows</em></p>                                                                                                                                                                                                                         |
| full\_text           | string  | make a fulltext search query                                                                                                                                                                                                                                                                                           |
| status               | string  | filter by request status. Values: 100 for unserved requests, 150 for abandoned requests, 1000 for closed requests, "all" to retrieve all statuses. Default value is status < 1000 so it returns all the opened requests. You can also search for multiple statuses separating the statuses with a comma (i.e. 100,200) |
| start\_date          | string  | filter by date interval. Use the format DD/MM/YYYY to define the start of the interval (i.e. 01/09/2024)                                                                                                                                                                                                               |
| end\_date            | string  | filter by date interval. Use the format DD/MM/YYYY to define the end of the interval (i.e. 30/09/2024)                                                                                                                                                                                                                 |
| start\_date\_time    | string  | filter by date/time interval. Use the format DD/MM/YYYY HH:mm:ss to define the start of the interval. Please encode the query parameter like the example (07/10/2025 12:10:09 -> encoded 07%2F10%2F2025%2012%3A10%3A09)                                                                                                |
| end\_date\_time      | string  | filter by date/time interval. Use the format DD/MM/YYYY HH:mm:ss to define the end of the interval. Please encode the query parameter like the example (07/10/2025 23:10:09 -> encoded 07%2F10%2F2025%2023%3A10%3A09)                                                                                                  |
| ticket\_id           | string  | filter by ticket id                                                                                                                                                                                                                                                                                                    |
| dept\_id             | string  | filter by department id                                                                                                                                                                                                                                                                                                |
| lead                 | string  | filter by lead id                                                                                                                                                                                                                                                                                                      |
| hasBot               | boolean | filter by the hasBot field. If hasBot is true, the service returns all requests served by the chatbot, If hasBot is false, the service returns all requests served by a human agent.                                                                                                                                   |
| tags                 | string  | filter by tag                                                                                                                                                                                                                                                                                                          |
| channel              | string  | filter by channel name. The channel name can be: "chat21" for chat messages, "email" for inboud ticket email, "form" for ticket created using the Dashboard UI, "whatsapp" for Whatsapp channel, "telegram" for Telegram Channel, "messenger" for Facebook Messenger Channel                                           |
| snap\_lead\_email    | string  | filter by the field email of the lead                                                                                                                                                                                                                                                                                  |
| snap\_lead\_lead\_id | string  | filter by the field lead\_id of the lead                                                                                                                                                                                                                                                                               |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 " %}

```
{
   "perPage":40,
   "count":179,
   "requests":[
      {
            "_id":"5c81593adf767b0017d1aa67",
            "updatedAt":"2019-03-07T17:48:05.934Z",
            "createdAt":"2019-03-07T17:47:38.405Z",
            "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
            "requester_id":"5c81593adf767b0017d1aa66",
            "first_text":"first text message",
            "department":"5c34ba232c62730016da250e",
            "sourcePage":"https://www.tiledesk.com",
            "language":"it",
            "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
            "id_project":"5b55e806c93dde00143163dd",
            "createdBy":"5c81593adf767b0017d1aa66",
            "__v":2,
            "waiting_time":21709,
            "agents":[
               {
                  "__v":0,
                  "createdBy":"5aaa99024c3b110014b478f0",
                  "user_available":true,
                  "role":"admin",
                  "id_user":"5ab0f3fa57066e0014bfd71e",
                  "id_project":"5b55e806c93dde00143163dd",
                  "createdAt":"2018-10-03T14:40:19.521Z",
                  "updatedAt":"2019-03-07T17:47:38.405Z",
                  "_id":"5bb4d4d39214830015742b00"
               }
            ],
            "tags":[
            ],
            "notes":[
               {
                  "_id":"5e6ba903261616001752b9f4",
                  "text":"note 1",
                  "createdBy":"5aaa99024c3b110014b478f0",
                  "updatedAt":"2020-03-13T15:38:43.880Z",
                  "createdAt":"2020-03-13T15:38:43.880Z"
               }
            ],
            "participants":[
               "5aaa99024c3b110014b478f0"
            ],
            "status":200,
            "lead":{..}
         }
      ...
   ]
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/requests
```

## Get a request by request\_id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id`

Fetches a request by his or her request\_id

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier.                             |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "department":"5c34ba232c62730016da250e",
   "sourcePage":"https://www.tiledesk.com",
   "language":"it",
   "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5c81593adf767b0017d1aa66",
   "__v":2,
   "waiting_time":21709,
   "agents":[
      {
         "__v":0,
         "createdBy":"5aaa99024c3b110014b478f0",
         "user_available":true,
         "role":"admin",
         "id_user":"5ab0f3fa57066e0014bfd71e",
         "id_project":"5b55e806c93dde00143163dd",
         "createdAt":"2018-10-03T14:40:19.521Z",
         "updatedAt":"2019-03-07T17:47:38.405Z",
         "_id":"5bb4d4d39214830015742b00"
      }
   ],
   "tags":[
   ],
   "notes":[
      {
         "_id":"5e6ba903261616001752b9f4",
         "text":"note 1",
         "createdBy":"5aaa99024c3b110014b478f0",
         "updatedAt":"2020-03-13T15:38:43.880Z",
         "createdAt":"2020-03-13T15:38:43.880Z"
      }
   ],
   "participants":[
      "5aaa99024c3b110014b478f0"
   ],
   "status":200,
   "lead":{..}
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X GET -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/requests/support-group-L_OG76RYhR0XFiMf2PK
```

## Close a request by request\_id

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/close`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "department":"5c34ba232c62730016da250e",
   "sourcePage":"https://www.tiledesk.com",
   "language":"it",
   "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5c81593adf767b0017d1aa66",
   "__v":2,
   "waiting_time":21709,
   "agents":[
      {
         "__v":0,
         "createdBy":"5aaa99024c3b110014b478f0",
         "user_available":true,
         "role":"admin",
         "id_user":"5ab0f3fa57066e0014bfd71e",
         "id_project":"5b55e806c93dde00143163dd",
         "createdAt":"2018-10-03T14:40:19.521Z",
         "updatedAt":"2019-03-07T17:47:38.405Z",
         "_id":"5bb4d4d39214830015742b00"
      }
   ],
   "tags":[
   ],
   "participants":[
      "5aaa99024c3b110014b478f0"
   ],
   "status":1000,
   "lead":{..}
}
```

{% endtab %}
{% endtabs %}

## Reopen a request by request\_id

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/reopen`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "department":"5c34ba232c62730016da250e",
   "sourcePage":"https://www.tiledesk.com",
   "language":"it",
   "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5c81593adf767b0017d1aa66",
   "__v":2,
   "waiting_time":21709,
   "agents":[
      {
         "__v":0,
         "createdBy":"5aaa99024c3b110014b478f0",
         "user_available":true,
         "role":"admin",
         "id_user":"5ab0f3fa57066e0014bfd71e",
         "id_project":"5b55e806c93dde00143163dd",
         "createdAt":"2018-10-03T14:40:19.521Z",
         "updatedAt":"2019-03-07T17:47:38.405Z",
         "_id":"5bb4d4d39214830015742b00"
      }
   ],
   "tags":[
   ],
   "participants":[
      "5aaa99024c3b110014b478f0"
   ],
   "status":100,
   "lead":{..}
}
```

{% endtab %}
{% endtabs %}

## Route a request to a department

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/departments`

Routes a request to a department.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name         | Type    | Description                                                                          |
| ------------ | ------- | ------------------------------------------------------------------------------------ |
| departmentid | string  | the department identifier                                                            |
| nobot        | boolean | Optional. Default is false. If nobot is true the bot is excluded from the assignment |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "department":"5c34ba232c62730016da250e",
   "sourcePage":"https://www.tiledesk.com",
   "language":"it",
   "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5c81593adf767b0017d1aa66",
   "__v":2,
   "waiting_time":21709,
   "agents":[
      {
         "__v":0,
         "createdBy":"5aaa99024c3b110014b478f0",
         "user_available":true,
         "role":"admin",
         "id_user":"5ab0f3fa57066e0014bfd71e",
         "id_project":"5b55e806c93dde00143163dd",
         "createdAt":"2018-10-03T14:40:19.521Z",
         "updatedAt":"2019-03-07T17:47:38.405Z",
         "_id":"5bb4d4d39214830015742b00"
      }
   ],
   "tags":[
   ],
   "participants":[
      "5aaa99024c3b110014b478f0"
   ],
   "status":100,
   "lead":{..}
}
```

{% endtab %}
{% endtabs %}

## Update a request by request\_id

<mark style="color:purple;">`PATCH`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name            | Type   | Description                |
| --------------- | ------ | -------------------------- |
| first\_text     | string | the request first text     |
| lead            | string | the lead identifier        |
| status          | number | the request status         |
| tags            | array  | the request tags           |
| rating          | number | the request rating         |
| rating\_message | string | the request rating message |
| language        | string | the request language       |
| sourcePage      | string | the request source page    |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "department":"5c34ba232c62730016da250e",
   "sourcePage":"https://www.tiledesk.com",
   "language":"it",
   "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5c81593adf767b0017d1aa66",
   "__v":2,
   "waiting_time":21709,
   "agents":[
      {
         "__v":0,
         "createdBy":"5aaa99024c3b110014b478f0",
         "user_available":true,
         "role":"admin",
         "id_user":"5ab0f3fa57066e0014bfd71e",
         "id_project":"5b55e806c93dde00143163dd",
         "createdAt":"2018-10-03T14:40:19.521Z",
         "updatedAt":"2019-03-07T17:47:38.405Z",
         "_id":"5bb4d4d39214830015742b00"
      }
   ],
   "tags":[
   ],
   "participants":[
      "5aaa99024c3b110014b478f0"
   ],
   "status":100,
   "lead":{..}
}
```

{% endtab %}
{% endtabs %}

## Add a participant to a request

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/participants`

Add a participant (agent or bot) to a request.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name   | Type   | Description                               |
| ------ | ------ | ----------------------------------------- |
| member | string | the participant (agent or bot) identifier |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "department":"5c34ba232c62730016da250e",
   "sourcePage":"https://www.tiledesk.com",
   "language":"it",
   "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5c81593adf767b0017d1aa66",
   "__v":2,
   "waiting_time":21709,
   "agents":[
      {
         "__v":0,
         "createdBy":"5aaa99024c3b110014b478f0",
         "user_available":true,
         "role":"admin",
         "id_user":"5ab0f3fa57066e0014bfd71e",
         "id_project":"5b55e806c93dde00143163dd",
         "createdAt":"2018-10-03T14:40:19.521Z",
         "updatedAt":"2019-03-07T17:47:38.405Z",
         "_id":"5bb4d4d39214830015742b00"
      }
   ],
   "tags":[
   ],
   "participants":[
      "5aaa99024c3b110014b478f0"
   ],
   "status":100,
   "lead":{..}
}
```

{% endtab %}
{% endtabs %}

## Set the request participants

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/participants`

Set the request participants (agent or bot).

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name | Type  | Description                                       |
| ---- | ----- | ------------------------------------------------- |
|      | array | the participants (agent or bot) identifiers array |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "department":"5c34ba232c62730016da250e",
   "sourcePage":"https://www.tiledesk.com",
   "language":"it",
   "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5c81593adf767b0017d1aa66",
   "__v":2,
   "waiting_time":21709,
   "agents":[
      {
         "__v":0,
         "createdBy":"5aaa99024c3b110014b478f0",
         "user_available":true,
         "role":"admin",
         "id_user":"5ab0f3fa57066e0014bfd71e",
         "id_project":"5b55e806c93dde00143163dd",
         "createdAt":"2018-10-03T14:40:19.521Z",
         "updatedAt":"2019-03-07T17:47:38.405Z",
         "_id":"5bb4d4d39214830015742b00"
      }
   ],
   "tags":[
   ],
   "participants":[
      "5aaa99024c3b110014b478f0"
   ],
   "status":100,
   "lead":{..}
}
```

{% endtab %}
{% endtabs %}

## Delete a participant from the request

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/participants/:participantid`

Delete a participant (agent or bot) from the request.

#### Path Parameters

| Name          | Type   | Description                                                                              |
| ------------- | ------ | ---------------------------------------------------------------------------------------- |
| participantid | string | the participant (agent or bot) identifier                                                |
| request\_id   | string | the request\_id field. It's the external request identifier                              |
| project\_id   | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "department":"5c34ba232c62730016da250e",
   "sourcePage":"https://www.tiledesk.com",
   "language":"it",
   "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5c81593adf767b0017d1aa66",
   "__v":2,
   "waiting_time":21709,
   "agents":[
      {
         "__v":0,
         "createdBy":"5aaa99024c3b110014b478f0",
         "user_available":true,
         "role":"admin",
         "id_user":"5ab0f3fa57066e0014bfd71e",
         "id_project":"5b55e806c93dde00143163dd",
         "createdAt":"2018-10-03T14:40:19.521Z",
         "updatedAt":"2019-03-07T17:47:38.405Z",
         "_id":"5bb4d4d39214830015742b00"
      }
   ],
   "tags":[
   ],
   "participants":[
      "5aaa99024c3b110014b478f0"
   ],
   "status":100,
   "lead":{..}
}
```

{% endtab %}
{% endtabs %}

## Update the request attributes

<mark style="color:purple;">`PATCH`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/attributes`

Update the request custom attributes.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name | Type   | Description            |
| ---- | ------ | ---------------------- |
|      | object | the request attributes |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "department":"5c34ba232c62730016da250e",
   "sourcePage":"https://www.tiledesk.com",
   "language":"it",
   "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5c81593adf767b0017d1aa66",
   "__v":2,
   "waiting_time":21709,
   "agents":[
      {
         "__v":0,
         "createdBy":"5aaa99024c3b110014b478f0",
         "user_available":true,
         "role":"admin",
         "id_user":"5ab0f3fa57066e0014bfd71e",
         "id_project":"5b55e806c93dde00143163dd",
         "createdAt":"2018-10-03T14:40:19.521Z",
         "updatedAt":"2019-03-07T17:47:38.405Z",
         "_id":"5bb4d4d39214830015742b00"
      }
   ],
   "tags":[
   ],
   "participants":[
      "5aaa99024c3b110014b478f0"
   ],
   "status":100,
   "lead":{..}
}
```

{% endtab %}
{% endtabs %}

## Add a note to a request

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/notes`

Add a participant (agent or bot) to a request.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name | Type   | Description      |
| ---- | ------ | ---------------- |
| text | string | the note content |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "department":"5c34ba232c62730016da250e",
   ...
   "tags":[
   ],
   "notes":[
      {
         "_id":"5e6ba903261616001752b9f4",
         "text":"note 1",
         "createdBy":"5aaa99024c3b110014b478f0",
         "updatedAt":"2020-03-13T15:38:43.880Z",
         "createdAt":"2020-03-13T15:38:43.880Z"
      }
   ],
   "participants":[
      "5aaa99024c3b110014b478f0"
   ],
   "status":100,
   "lead":{..}
}
```

{% endtab %}
{% endtabs %}

## Delete a note

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/notes/:noteid`

Add a participant (agent or bot) to a request.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| noteid      | string | the note identifier                                                                      |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
  ..
   "notes":[
   ],
   "participants":[
      "5aaa99024c3b110014b478f0"
   ],
   "status":100,
   "lead":{..}
}
```

{% endtab %}
{% endtabs %}

## Get a request history by request\_id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/history`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier.                             |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 " %}

```
..
```

{% endtab %}
{% endtabs %}

## Delete a request by request\_id

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id`

Only the project owner can delete a request.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

{% tabs %}
{% tab title="200 " %}

```
{
  ...
}
```

{% endtab %}
{% endtabs %}

## Rate a request by request\_id

<mark style="color:purple;">`PATCH`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/rating`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: guest |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name          | Type   | Description                  |
| ------------- | ------ | ---------------------------- |
| rate          | number | the request rate from 0 to 5 |
| rate\_message | string | the rate message             |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "department":"5c34ba232c62730016da250e",
   "sourcePage":"https://www.tiledesk.com",
   "language":"it",
   "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5c81593adf767b0017d1aa66",
   "__v":2,
   "waiting_time":21709,
   "rate":5,
   "rating_message":"great work"
   "agents":[
      {
         "__v":0,
         "createdBy":"5aaa99024c3b110014b478f0",
         "user_available":true,
         "role":"admin",
         "id_user":"5ab0f3fa57066e0014bfd71e",
         "id_project":"5b55e806c93dde00143163dd",
         "createdAt":"2018-10-03T14:40:19.521Z",
         "updatedAt":"2019-03-07T17:47:38.405Z",
         "_id":"5bb4d4d39214830015742b00"
      }
   ],
   "tags":[
   ],
   "participants":[
      "5aaa99024c3b110014b478f0"
   ],
   "status":100,
   "lead":{..}
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X PATCH -H 'Content-Type:application/json' -u andrea.leo@f21.it:123456 -d '{"rating":5, "rating_message":"Very good"}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/requests/support-group-5b55e806c93dde00143163dd/rating
```

## Add a follower to a request

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/followers`

Add a follower (agent) to a request.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name   | Type   | Description                     |
| ------ | ------ | ------------------------------- |
| member | string | the teammate (agent) identifier |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",   
   "followers":["62dfbbbf6b07df3ecbb130f4"],
   ....
}
```

{% endtab %}
{% endtabs %}

## Set the request followers

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/followers`

Set the request followers (agent).

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name | Type  | Description                             |
| ---- | ----- | --------------------------------------- |
|      | array | the followers (agent) identifiers array |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "followers":["62dfbbbf6b07df3ecbb130f4"],
   ....
}
```

{% endtab %}
{% endtabs %}

## Delete a follower from the request

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/followers/:followerid`

Delete a follower (agent) from the request.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| follower    | string | the teammate (agent) identifier                                                          |
| request\_id | string | the request\_id field. It's the external request identifier                              |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "followers":[],
   ....
}
```

{% endtab %}
{% endtabs %}

## Create a request

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/`

This method should be used for mass importing of messages. After this endpoint, use [Insert multiple messages REST API](https://developer.tiledesk.com/apis/rest-api/messages#insert-multiple-messages). For common cases, use [Send message REST API](https://developer.tiledesk.com/apis/rest-api/messages#send-a-message)

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: guest |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name        | Type   | Description                                                      |
| ----------- | ------ | ---------------------------------------------------------------- |
| first\_text | string | the request first text                                           |
| request\_id | string | the request identifier. If not specified an auto id is generated |
| language    | string | the request language                                             |
| sourcePage  | string | the request source page                                          |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5c81593adf767b0017d1aa67",
   "updatedAt":"2019-03-07T17:48:05.934Z",
   "createdAt":"2019-03-07T17:47:38.405Z",
   "request_id":"support-group-L_OG76RYhR0XFiMf2PK",
   "requester_id":"5c81593adf767b0017d1aa66",
   "first_text":"first text message",
   "department":"5c34ba232c62730016da250e",
   "sourcePage":"https://www.tiledesk.com",
   "language":"it",
   "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5c81593adf767b0017d1aa66",
   "__v":2,
   "waiting_time":21709,
   "agents":[
      {
         "__v":0,
         "createdBy":"5aaa99024c3b110014b478f0",
         "user_available":true,
         "role":"admin",
         "id_user":"5ab0f3fa57066e0014bfd71e",
         "id_project":"5b55e806c93dde00143163dd",
         "createdAt":"2018-10-03T14:40:19.521Z",
         "updatedAt":"2019-03-07T17:47:38.405Z",
         "_id":"5bb4d4d39214830015742b00"
      }
   ],
   "tags":[
   ],
   "participants":[
      "5aaa99024c3b110014b478f0"
   ],
   "status":100,
   "lead":{..}
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X POST -H 'Content-Type:application/json' -u andrea.leo@f21.it:123456 -d '{"sender":"bb0d809b-b093-419b-8b48-11a192cc3619", "first_text":"1"}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/requests/
```

## Get all chatbot parameters of a request

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/chatbot/parameters`

Allows to obtain all the parameters set by the chatbot during the conversation.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| request\_id | string | the request\_id field. It's the external request identifier                              |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: guest |
| Content-Type  | string | use "application/json" value                                |

{% tabs %}
{% tab title="200 " %}

```
{
    "user_email": "giovanni@test.com",
    "user_name": "Giovanni"
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u giovanni@tiledesk.com:password https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/requests/support-group-63ad512e70d5ed0012ad6286-82c16d3b10dc4abba2326a5d7611b022/chatbot/parameters
```


# Leads

You can use the API to get or set lead information.

## The Lead Model

Our Lead API is a central place to gather all information and take actions on your contacts (leads), such as fetching, searching, creating, updating, and deleting.

| Key         | Type   | Description                                                                     |
| ----------- | ------ | ------------------------------------------------------------------------------- |
| id          | String | The unique identifier for the lead which is given by Tiledesk.                  |
| lead\_id    | String | A unique identifier for the lead which is given to Tiledesk.It's an external id |
| fullname    | String | The lead name and surname.                                                      |
| attributes  | Object | The custom attributes which are set for the lead.                               |
| createdAt   | String | The time (ISO-8601 date string) when the lead was created.                      |
| updatedAt   | String | The time (ISO-8601 date string) when the lead was updated.                      |
| createdBy   | String | The unique identifier of the row creator                                        |
| id\_project | String | The unique identifier of the project                                            |

## Get all leads

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/leads`

Allows an account to list all the leads.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Query Parameters

| Name      | Type   | Description                                                                                                          |
| --------- | ------ | -------------------------------------------------------------------------------------------------------------------- |
| sortField | string | what field to sort the results by.                                                                                   |
| direction | string | <p>sort direction: 1 or -1. Return the results in ascending or descending order.</p><p><em>defaults to desc</em></p> |
| email     | string | search a lead by the email address                                                                                   |
| page      | number | what page of results to fetch. defaults to first page.                                                               |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 " %}

```
{
   "perPage":40,
   "count":179,
   "leads":[
      {
         "_id":"5c81593adf767b0017d1aa66",
         "updatedAt":"2019-03-07T17:47:38.393Z",
         "createdAt":"2019-03-07T17:47:38.393Z",
         "lead_id":"SRbb2PfbSFcgICv9VQBcURZeloh1",
         "fullname":"Guest",
         "attributes":{
         ...
         },
         "id_project":"5b55e806c93dde00143163dd",
         "createdBy":"system",
         "__v":0
      },
      {
         "_id":"5c81565edf767b0017d1aa35",
         "updatedAt":"2019-03-07T17:35:26.132Z",
         "createdAt":"2019-03-07T17:35:26.132Z",
         "lead_id":"WTteQpKpGZN1aElfFYCP9YPaaLN2",
         "fullname":"Guest",
         "attributes":{
          ...
         },
         "id_project":"5b55e806c93dde00143163dd",
         "createdBy":"system",
         "__v":0
      },
      ...
   ]
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/leads
```

## Get a lead by id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/leads/:id`

Fetches a lead by his or her Lead ID

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| id          | string | the lead identifier                                                                      |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

{% tabs %}
{% tab title="200 " %}

```
{  
         "_id":"5c81593adf767b0017d1aa66",
         "updatedAt":"2019-03-07T17:47:38.393Z",
         "createdAt":"2019-03-07T17:47:38.393Z",
         "lead_id":"SRbb2PfbSFcgICv9VQBcURZeloh1",
         "fullname":"Guest",
         "attributes":{ ... },
         "id_project":"5b55e806c93dde00143163dd",
         "createdBy":"system",
         "__v":0
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/leads/5c81593adf767b0017d1aa66
```

## Create a new lead

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/leads`

Allows to add more leads.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name       | Type   | Description                 |
| ---------- | ------ | --------------------------- |
| email      | string | the lead email address      |
| lead\_id   | string | the external id of the lead |
| fullname   | string | The lead fullname           |
| attributes | object | The lead custom attributes  |

{% tabs %}
{% tab title="200 " %}

```
{  
         "_id":"5c81593adf767b0017d1aa66",
         "updatedAt":"2019-03-07T17:47:38.393Z",
         "createdAt":"2019-03-07T17:47:38.393Z",
         "lead_id":"SRbb2PfbSFcgICv9VQBcURZeloh1",
         "fullname":"Guest",
         "attributes":{ ... },
         "id_project":"5b55e806c93dde00143163dd",
         "createdBy":"system",
         "__v":0
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X POST -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d '{"fullname":"andrea", "lead_id":"123456"}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/leads
```

## Update a lead by id

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/leads/:id`

Allows to update a lead.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The id is the lead indentifier.                                                          |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name          | Type   | Description                |
| ------------- | ------ | -------------------------- |
| email         | string | the lead email address     |
| fullname      | string | The lead fullname          |
| attributes    | object | The lead custom attributes |
| phone         | string | The lead phone             |
| company       | string | The lead company           |
| note          | string | Notes                      |
| streetAddress | string | The lead address           |
| city          | string | The lead city              |
| region        | string | The lead region            |
| zipcode       | string | The lead zipcode           |
| country       | string | The lead country           |
| tags          | array  | The lead tags              |

{% tabs %}
{% tab title="200 " %}

```
{  
         "_id":"5c81593adf767b0017d1aa66",
         "updatedAt":"2019-03-07T17:47:38.393Z",
         "createdAt":"2019-03-07T17:47:38.393Z",
         "lead_id":"SRbb2PfbSFcgICv9VQBcURZeloh1",
         "fullname":"Guest",
         "attributes":{ ... },
         "id_project":"5b55e806c93dde00143163dd",
         "createdBy":"system",
         "__v":0
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X PUT -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d '{"fullanem":"andrea", "lead_id":"123456"}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/leads/5c81593adf767b0017d1aa66
```

## Delete a lead by id

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/leads/:id`

Allows to delete a lead.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The id is the lead indentifier.                                                          |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 " %}

```
{  
         "_id":"5c81593adf767b0017d1aa66",
         "updatedAt":"2019-03-07T17:47:38.393Z",
         "createdAt":"2019-03-07T17:47:38.393Z",
         "lead_id":"SRbb2PfbSFcgICv9VQBcURZeloh1",
         "fullname":"Guest",
         "attributes":{ ... },
         "id_project":"5b55e806c93dde00143163dd",
         "createdBy":"system",
         "__v":0
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X DELETE -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/leads/5c81593adf767b0017d1aa66
```


# Messages

## Messages

You can use the API to get the message information.

The Message model

| Key            | Type   | Description                                                                                                                   |
| -------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------- |
| id             | String | The unique identifier for the message which is given by Tiledesk.                                                             |
| sender         | String | A unique identifier of the sender. It can be: the user identifier, a bot identifier or the system user                        |
| senderFullname | String | The sender fullname. It can be: the user fullname, the bot name or an alias                                                   |
| recipient      | String | A unique identifier of the recipient. It can be: the request\_id field (external id) of the request                           |
| status         | Number | The message status: FAILED : -100, SENDING : 0, SENT : 100, DELIVERED : 150, RECEIVED : 200, RETURN\_RECEIPT: 250, SEEN : 300 |
| text           | String | The message text.                                                                                                             |
| type           | String | The message type. Accepted values: text (default), image                                                                      |
| metadata       | Object | The message metadata.                                                                                                         |
| attributes     | Object | The custom attributes which are set for the message.                                                                          |
| createdAt      | String | The time (ISO-8601 date string) when the message was created.                                                                 |
| updatedAt      | String | The time (ISO-8601 date string) when the message was updated.                                                                 |
| createdBy      | String | The unique identifier of the row creator                                                                                      |
| id\_project    | String | The unique identifier of the project                                                                                          |

## Send a message

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/messages`

Allows to send a message. This method also creates a new conversation (request) if it didn’t exist at the time of the call.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| request\_id | string | The request identifier. Must follow this pattern 'support-group-UUID'                    |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name         | Type   | Description                                                                                                                                                                                                                                                                                         |
| ------------ | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| text         | string | the message text                                                                                                                                                                                                                                                                                    |
| departmentid | string | The selected department identifier. Accepted only on the first message.                                                                                                                                                                                                                             |
| sourcePage   | string | The source page of the request. Accepted only on the first message.                                                                                                                                                                                                                                 |
| language     | string | The language of the request. Accepted only on the first message.                                                                                                                                                                                                                                    |
| userAgent    | string | The userAgent string of the request. Accepted only on the first message.                                                                                                                                                                                                                            |
| attributes   | object | it's the message custom attributes. Example: attributes = {"custom\_attribute1": "value1"}. You can also use [attributes](#attributes) to enable advanced features.                                                                                                                                 |
| type         | string | it's the message type. "text" value for textual message and "image" for sending image message(you must set metadata field). Available values: text (default) and image.                                                                                                                             |
| metadata     | object | it's the image properties: src is the absolute source path of the image, width is the image width, height is the image height. Width and height are optional. Example: metadata = { "src": "<https://www.tiledesk.com/wp-content/uploads/2018/03/tiledesk-logo.png>", "width": 200, "height": 200 } |

{% tabs %}
{% tab title="200 " %}

```
 {
      "_id":"5c81593adf767b0017d1aa68",
      "updatedAt":"2019-03-07T17:47:38.411Z",
      "createdAt":"2019-03-07T17:47:38.411Z",
      "sender":"SRbb2PfbSFcgICv9VQBcURZeloh1",
      "senderFullname":"Guest",
      "recipient":"support-group-L_OG76RYhR0XFiMf2PK",
      "text":"hello from api",
      "id_project":"5b55e806c93dde00143163dd",
      "createdBy":"SRbb2PfbSFcgICv9VQBcURZeloh1",
      "__v":0,
      "status":200
   }
```

{% endtab %}
{% endtabs %}

Example sending text message:

```
curl -v -X POST -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d '{"text":"hello from api"}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/requests/support-group-1234/messages
```

Example sending image:

```
curl -v -X POST -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d '{"text":"Alternative text from api", "type":"image", "metadata": {"src": "https://tiledesk.com/tiledesk-logo-x1.png", "width": 200, "height": 200}}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/requests/support-group-1234/messages
```

## Attributes

When you send a message you can use the following attributes to activate advanced features:

* attributes.clienttimestamp: use this property to force the message timestamp in milliseconds. This parameter is used by the clients (widgets and chat agents) to perform a client side reordering of messages based on the value of the timestamp field. This property doesn’t guarantees the order of arrival, but only the ordering or reordering on the client side.
* attributes.attachment: use this property to set the response additional reply componenst as quick replies, buttons, links etc. (see: <https://developer.tiledesk.com/widget/advanced/widget-json-protocol>)
* attributes.subtype.info: If “true” it hides the message to the end-user channels (Widget, whatsapp, Telegram, Facebook etc.)
* attributes.microlanguage: set this property to true to enable the microlanguage pre-processor. You can find more info here: [Chatbot buttons, images, video](https://docs.tiledesk.com/knowledge-base/response-bot-images-buttons-videos-and-more/) and [microlanguage example](https://developer.tiledesk.com/external-chatbot/buttons-media-actions-more#microlanguage)
* attributes.disableInputMessage: if true it disables the input message, until the next message arrival
* attributes.inputMessagePlaceholder: if set, it modify the default input text placeholder
* attributes.updateUserEmail and attributes.updateUserFullname: If set, the back forward user fullname and email to the widget. Useful if you set user fullname or email in a webhook or external service.

## Advanced features

Tiledesk uses Chat21 as messaging engine. When you send a message to Tiledesk using the REST API, Tiledesk will forward the call to the Chat21 REST API. You can see how the Chat21 REST Api works here: <https://github.com/chat21/chat21-cloud-functions/blob/master/docs/api.md#send-a-message>

You can enable special message features following this paragraph: <https://github.com/chat21/chat21-cloud-functions/blob/master/docs/api.md#message-attributes>

## Get the messages of a request by id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/messages`

Fetches the messages by his or her request\_id

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier.                             |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
[
   {
      "_id":"5c81593adf767b0017d1aa68",
      "updatedAt":"2019-03-07T17:47:38.411Z",
      "createdAt":"2019-03-07T17:47:38.411Z",
      "sender":"SRbb2PfbSFcgICv9VQBcURZeloh1",
      "senderFullname":"Guest",
      "recipient":"support-group-L_OG76RYhR0XFiMf2PK",
      "text":"test56",
      "id_project":"5b55e806c93dde00143163dd",
      "createdBy":"SRbb2PfbSFcgICv9VQBcURZeloh1",
      "__v":0,
      "status":200
   },
   {
      "_id":"5c81593adf767b0017d1aa69",
      "updatedAt":"2019-03-07T17:47:38.625Z",
      "createdAt":"2019-03-07T17:47:38.625Z",
      "sender":"system",
      "senderFullname":"Bot",
      "recipient":"support-group-L_OG76RYhR0XFiMf2PK",
      "text":"La stiamo mettendo in contatto con un operatore. Attenda...",
      "id_project":"5b55e806c93dde00143163dd",
      "createdBy":"system",
      "__v":0,
      "status":200
   },
  ...
]
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X GET -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/requests/support-group-L_OG76RYhR0XFiMf2PK/messages
```

## Get the message by request id and message id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/messages/:message_id`

Fetche the message by his or her id

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| request\_id | string | the request\_id field. It's the external request identifier.                             |
| message\_id | string | the message identifier                                                                   |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
   {
      "_id":"5c81593adf767b0017d1aa68",
      "updatedAt":"2019-03-07T17:47:38.411Z",
      "createdAt":"2019-03-07T17:47:38.411Z",
      "sender":"SRbb2PfbSFcgICv9VQBcURZeloh1",
      "senderFullname":"Guest",
      "recipient":"support-group-L_OG76RYhR0XFiMf2PK",
      "text":"test56",
      "id_project":"5b55e806c93dde00143163dd",
      "createdBy":"SRbb2PfbSFcgICv9VQBcURZeloh1",
      "__v":0,
      "status":200
   }
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X GET -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/requests/support-group-L_OG76RYhR0XFiMf2PK/messages/5c81593adf767b0017d1aa68
```

## Insert multiple messages

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/requests/:request_id/messages/multi`

This method should be used for mass importing of messages. For common cases, use Send message REST API

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| request\_id | string | The request identifier. Must follow this pattern 'support-group-UUID'                    |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name       | Type   | Description                                                                                                                                                                                                                                                                                         |
| ---------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| text       | string | the message text                                                                                                                                                                                                                                                                                    |
| attributes | object | it's the message custom attributes. Example: attributes = {"custom\_attribute1": "value1"}. You can also use [attributes](#attributes) to enable advanced features.                                                                                                                                 |
| type       | string | it's the message type. "text" value for textual message and "image" for sending image message(you must set metadata field). Available values: text (default) and image.                                                                                                                             |
| metadata   | object | it's the image properties: src is the absolute source path of the image, width is the image width, height is the image height. Width and height are optional. Example: metadata = { "src": "<https://www.tiledesk.com/wp-content/uploads/2018/03/tiledesk-logo.png>", "width": 200, "height": 200 } |

{% tabs %}
{% tab title="200 " %}

```
 {
      "_id":"5c81593adf767b0017d1aa68",
      "updatedAt":"2019-03-07T17:47:38.411Z",
      "createdAt":"2019-03-07T17:47:38.411Z",
      "sender":"SRbb2PfbSFcgICv9VQBcURZeloh1",
      "senderFullname":"Guest",
      "recipient":"support-group-L_OG76RYhR0XFiMf2PK",
      "text":"hello from api",
      "id_project":"5b55e806c93dde00143163dd",
      "createdBy":"SRbb2PfbSFcgICv9VQBcURZeloh1",
      "__v":0,
      "status":200
   }
```

{% endtab %}
{% endtabs %}

Example of inserting multiple messages:

```
curl -v -X POST -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d '[{"sender":"bb0d809b-b093-419b-8b48-11a192cc3619","text":"1"},{"sender":"bb0d809b-b093-419b-8b48-11a192cc3619", "text":"2"}]' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/requests/support-group-1234/messages/multi
```


# Activities

You can use the API to get the activity data.

## Get all activities

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/activities`

Allows an admin to list all the activities for the project.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Query Parameters

| Name       | Type   | Description                                                                                                          |
| ---------- | ------ | -------------------------------------------------------------------------------------------------------------------- |
| agent\_id  | string | The agent identifier.                                                                                                |
| activities | string | A comma separeted list of events to filter the results. Ex: "PROJECT\_USER\_DELETE,PROJECT\_USER\_INVITE"            |
| sortField  | string | what field to sort the results by.                                                                                   |
| direction  | string | <p>sort direction: 1 or -1. Return the results in ascending or descending order.</p><p><em>defaults to desc</em></p> |
| page       | string | what page of results to fetch. defaults to first page.                                                               |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
{
   "perPage":40,
   "count":1,
   "activities":[
      {
         "_id":"5cbf2eec5bf27612afc0c309",
         "updatedAt":"2019-04-23T15:27:40.619Z",
         "createdAt":"2019-04-23T15:27:40.619Z",
         "actor":{
            "type":"user",
            "id":"5ac7521787f6b50014e0b592",
            "name":"Nico Lanzilotto"
         },
         "verb":"PROJECT_USER_INVITE",
         "actionObj":{
            "email":"tizio@asd.it",
            "role":"agent",
            "id_project":"5ad5bd52c975820014ba900a",
            "project_name":"Tiledesk"
         },
         "target":{
            "type":"pendinginvitation",
            "id":"5cbf2eec5bf27612afc0c308",
            "object":{
               "_id":"5cbf2eec5bf27612afc0c308",
               "createdBy":"5ac7521787f6b50014e0b592",
               "id_project":"5ad5bd52c975820014ba900a",
               "role":"agent",
               "email":"tizio@asd.it",
               "createdAt":"2019-04-23T15:27:40.519Z",
               "updatedAt":"2019-04-23T15:27:40.519Z",
               "__v":0
            }
         },
         "id_project":"5ad5bd52c975820014ba900a",
         "__v":0
      }
   ]
}
```

{% endtab %}
{% endtabs %}


# Projects

The Project model

| Key                  | Type    | Description                                                       |
| -------------------- | ------- | ----------------------------------------------------------------- |
| id                   | String  | The unique identifier for the project which is given by Tiledesk. |
| name                 | String  | The project name.                                                 |
| activeOperatingHours | Boolena | Determine if the operating hours option is enabled                |
| operatingHours       | Object  | The operating hours settings.                                     |
| settings             | Object  | The project settings                                              |
| widget               | Object  | The widget settings.                                              |
| profile              | Object  | The project profile object                                        |
| status               | Number  | The project status. Permitted values: 100 active, 0 disabled      |
| createdAt            | String  | The time (ISO-8601 date string) when the project was created.     |
| updatedAt            | String  | The time (ISO-8601 date string) when the project was updated.     |
| createdBy            | String  | The unique identifier of the row creator                          |

## Get a list of projects the user belongs

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/projects/`

#### Headers

| Name          | Type   | Description                                                |
| ------------- | ------ | ---------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: user |

{% tabs %}
{% tab title="200 " %}

```
[
{
      "_id":"5acdc6d86fb82500141d56c9",
      "updatedAt":"2019-01-31T18:09:53.417Z",
      "createdAt":"2018-04-11T08:27:04.509Z",
      "id_project":{
         "versions":30,
         "_id":"5acba41a213ae3001451b723",
         "updatedAt":"2019-01-29T12:01:06.793Z",
         "createdAt":"2018-04-09T17:34:18.064Z",
         "name":"conversational landing page",
         "createdBy":"5aabade839db7d001477d3d5",
         "__v":0,
         "profile":{
            "name":"free",
            "trialDays":30,
            "agents":0,
            "type":"free"
         },
         "channels":[
            {
               "name":"chat21"
            }
         ],
         "trialExpired":true,
         "trialDaysLeft":680,
         "isActiveSubscription":false,
         "id":"5acba41a213ae3001451b723"
      },
      "id_user":"5aaa99024c3b110014b478f0",
      "role":"admin",
      "createdBy":"5aabade839db7d001477d3d5",
      "__v":0,
      "user_available":true,
      "id":"5acdc6d86fb82500141d56c9"
   },
...
]
```

{% endtab %}
{% endtabs %}

## Get the project detail

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/projects/:project_id`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 " %}

```
{
   "versions":30,
   "_id":"5df2240cecd41b00173a06bb",
   "name":"000000",
   "activeOperatingHours":true,
   "createdBy":"5aaa99024c3b110014b478f0",
   "profile":{
      "name":"free",
      "trialDays":30,
      "agents":0,
      "type":"free"
   },
   "channels":[
      {
         "name":"chat21"
      }
   ],
   "createdAt":"2019-12-12T11:27:08.548Z",
   "updatedAt":"2020-01-08T10:53:12.844Z",
   "__v":0,
   "operatingHours":"{\"0\":[{\"start\":\"09:00\",\"end\":\"13:00\"},{\"start\":\"14:00\",\"end\":\"18:00\"}],\"1\":[{\"start\":\"09:00\",\"end\":\"13:00\"},{\"start\":\"14:00\",\"end\":\"18:00\"}],\"tzname\":\"Europe/Rome\"}",
   "trialExpired":false,
   "trialDaysLeft":-4,
   "isActiveSubscription":false,
   "id":"5df2240cecd41b00173a06bb"
}
```

{% endtab %}
{% endtabs %}

## Return the available agents

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/projects/:project_id/users/availables`

Return the available agents evaluating the general operating hours of the project and agents chat load (with Smart Assignment enabled)

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Query Parameters

| Name | Type    | Description                                                                                              |
| ---- | ------- | -------------------------------------------------------------------------------------------------------- |
| raw  | Boolean | If true only agents status is considered (the general operating hours of the project are not considered) |

#### Headers

| Name          | Type   | Description                                                |
| ------------- | ------ | ---------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: user |

{% tabs %}
{% tab title="200 " %}

```
[
   {
      "id":"5aaa99024c3b110014b478f0",
      "firstname":"Andrea"
   },
   {
      "id":"5de9200d6722370017731969",
      "firstname":"Nuovopre"
   }
]
```

{% endtab %}
{% endtabs %}

## Return if the project is open regarding operating hours

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/projects/:project_id/isopen`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: guest |

{% tabs %}
{% tab title="200 " %}

```
   {"isopen":false}
```

{% endtab %}
{% endtabs %}

## Update the project (Widget Settings)

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/projects/:project_id/availables`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                |
| ------------- | ------ | ---------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: user |

#### Request Body

| Name   | Type   | Description                                                                  |
| ------ | ------ | ---------------------------------------------------------------------------- |
| widget | Object | The object containing the widget configuration parameters (See curl example) |

{% tabs %}
{% tab title="200 " %}

```
{
   "widget": {
      "logoChat": "https://your_site_url.com/your-logo.png",
      "themeColor": "#76528B",
      "themeForegroundColor": "#CBCE91",
      "themeColorOpacity": 0,
      "align": "right",
      "displayOnDesktop": true,
      "displayOnMobile": true,
      "onPageChangeVisibilityDesktop": "open",
      "onPageChangeVisibilityMobile": "last",
      "singleConversation": false,
      "baloonImage": "https://your_site_url.com/your-baloon-logo.png",
      "poweredBy": "<a tabindex=\"-1\" target=\"_blank\" href=\"https://your_site_url.com\"><img src=\"https://your_site_url.com/your-logo.png\"/><span>Powered by YourCompany</span></a>"
   }
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X PUT -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456 -d '{"widget": {"logoChat": "https://your_site_url.com/your-logo.png","themeColor": "#76528B","themeForegroundColor": "#CBCE91","themeColorOpacity": 0,"align": "right","displayOnDesktop": true,"displayOnMobile": true,"onPageChangeVisibilityDesktop": "open","onPageChangeVisibilityMobile": "last","singleConversation": false,"baloonImage": "https://your_site_url.com/your-baloon-logo.png","poweredBy": "<a tabindex=\"-1\" target=\"_blank\" href=\"https://your_site_url.com\"><img src=\"https://your_site_url.com/your-logo.png\"/><span>Powered by YourCompany</span></a>"}}' https://tiledesk-server-pre.herokuapp.com/projects/62c3f10152dc7400352bab0d'
```


# Team

A teammate is a special user who represents a Tiledesk user invited to a project with a specific role. When you work with teammates very often you will not use the user\_id of the Tiledesk user but rather the specific id of your teammate in the project. In the Tiledesk API the temamate is named project\_user. For example, if you want to know your project\_user in a specific project, all you have to do is call this API: [Get a teammate by id](#get-a-teammate-by-id).

## The Team Model

| Key                        | Type    | Description                                                                                                |
| -------------------------- | ------- | ---------------------------------------------------------------------------------------------------------- |
| id                         | String  | The unique identifier for the teammate which is given by Tiledesk.                                         |
| role                       | String  | The teammate role. Values: owner, agent, admin, user, guest                                                |
| user\_available            | Boolean | Dermine if the teammate is available or unavailable to accept requests                                     |
| id\_user                   | Object  | The user object referenced by the teammate                                                                 |
| max\_served\_chat          | Number  | Number of chats that agent is allowed to take at one time (Only Enterprise)                                |
| number\_assigned\_requests | Number  | Number of active request for the teammate (Only Enterprise)                                                |
| status                     | String  | The status of a teammate. Can be "active" or "disabled"                                                    |
| isBusy                     | Boolean | Determine if the teammate is busy (Only Enterprise)                                                        |
| profileStatus              | String  | It is an alias associated to the teammate availability. For example: inactive, to the toilet, on the phone |
| attributes                 | Object  | The custom attributes which are set for the teammate.                                                      |
| tags                       | Array   | A list of tags objects associated with the teammate.                                                       |
| settings                   | Object  | The setting configurations of the teammate.                                                                |
| presence                   | Object  | The presence info of the teammate.                                                                         |
| isAuthenticated            | Boolean | Returns true if is strongly authenticated (custom-auth or email/password), false otherwise (anonymous).    |
| isBusy                     | Boolean | Returns true if is teammate is busy, false otherwise. See Tiledesk Smart Assignment for more info.         |
| createdAt                  | String  | The time (ISO-8601 date string) when the teammate was created.                                             |
| updatedAt                  | String  | The time (ISO-8601 date string) when the teammate was updated.                                             |
| createdBy                  | String  | The unique identifier of the row creator                                                                   |
| id\_project                | String  | The unique identifier of the project                                                                       |
| trashed                    | Boolean | True if the teammate has been removed from the project                                                     |

### The Presence model

Presence lets you track the online and offline status of the teammates in real-time (if you use Tiledesk [Websocket](/apis/realtime-api) or [Webhook](/apis/webhooks)) and store the information state. Possible values: online, offline. Attention: an agent passes from online to offline only when he closed all Tiledesk messaging apps (eg Agent web chat in all tabs and mobile apps).

### Agent availability

The field **user\_available** determines if the teammate is available or unavailable to accept requests. Attention: Agent availability changes only when the agent explicitly changes from the UI from available to unavailable. If an agent is available and logs out, the agent remains available as he may have decided to serve chats from another channel (eg. Tiledesk mobile app).

## Get the team

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/project_users`

Return the team members and availability. Use the optional query parameter `trashed=true` to include trashed teammates in the response.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Query Parameters

| Name    | Type   | Description                                                                                                                              |
| ------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| trashed | string | Optional. Set to `true` to include trashed teammates in the response. When `false` or omitted, trashed teammates are excluded (default). |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 List of teammates. Without trashed (default): only active." %}

```
[
   {
      "_id":"5df2240cecd41b00173a06bc",
      "id_project":"5df2240cecd41b00173a06bb",
      "id_user":{
         "_id":"5aaa99024c3b110014b478f0",
         "email":"andrea.leo@frontiere21.it",
         "firstname":"Andrea",
         "lastname":"Leo",
         "emailverified":true,
         "__v":0,
         "resetpswrequestid":""
      },
      "role":"owner",
      "user_available":true,
      "trashed":false,
      "createdBy":"5aaa99024c3b110014b478f0",
      "createdAt":"2019-12-12T11:27:08.581Z",
      "updatedAt":"2019-12-12T11:27:08.581Z",
      "__v":0
   },
   {
      "_id":"5df34ab80bc923001792e274",
      "id_project":"5df2240cecd41b00173a06bb",
      "id_user":{
         "_id":"5de9200d6722370017731969",
         "email":"nuovopre@f21test.it",
         "firstname":"Nuovopre",
         "lastname":"Pre",
         "emailverified":false,
         "createdAt":"2019-12-05T15:19:41.296Z",
         "updatedAt":"2019-12-05T15:19:41.296Z",
         "__v":0
      },
      "role":"admin",
      "user_available":true,
      "trashed":false,
      "createdBy":"5aaa99024c3b110014b478f0",
      "createdAt":"2019-12-13T08:24:24.586Z",
      "updatedAt":"2020-01-04T09:45:26.331Z",
      "__v":0
   }
]
```

{% endtab %}
{% endtabs %}

Example (default, exclude trashed):

```
curl -v -X GET \
  -u user@example.com:password \
  https://api.tiledesk.com/v3/5df2240cecd41b00173a06bb/project_users
```

Example (include trashed teammates):

```
curl -v -X GET \
  -u user@example.com:password \
  "https://api.tiledesk.com/v3/5df2240cecd41b00173a06bb/project_users?trashed=true"
```

## Get a teammate by id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/project_users/:project_user_id`

#### Path Parameters

| Name              | Type   | Description                                                                              |
| ----------------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id       | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| project\_user\_id | string | The teammate identifier.                                                                 |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 " %}

```
   {
      "_id":"5df2240cecd41b00173a06bc",
      "id_project":"5df2240cecd41b00173a06bb",
      "id_user":{
         "_id":"5aaa99024c3b110014b478f0",
         "email":"andrea.leo@frontiere21.it",
         "firstname":"Andrea",
         "lastname":"Leo",
         "emailverified":true,
         "__v":0,
         "resetpswrequestid":""
      },
      "role":"owner",
      "user_available":true,
      "createdBy":"5aaa99024c3b110014b478f0",
      "createdAt":"2019-12-12T11:27:08.581Z",
      "updatedAt":"2019-12-12T11:27:08.581Z",
      "__v":0
   }
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X GET \
  -u user@example.com:password \
  https://api.tiledesk.com/v3/5df2240cecd41b00173a06bb/project_users/5df2240cecd41b00173a06bc
```

## Get a teammate by user id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/project_users/users/:user_id`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| user\_id    | string | The user identifier.                                                                     |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 " %}

```
   {
      "_id":"5df2240cecd41b00173a06bc",
      "id_project":"5df2240cecd41b00173a06bb",
      "id_user":{
         "_id":"5aaa99024c3b110014b478f0",
         "email":"andrea.leo@frontiere21.it",
         "firstname":"Andrea",
         "lastname":"Leo",
         "emailverified":true,
         "__v":0,
         "resetpswrequestid":""
      },
      "role":"owner",
      "user_available":true,
      "createdBy":"5aaa99024c3b110014b478f0",
      "createdAt":"2019-12-12T11:27:08.581Z",
      "updatedAt":"2019-12-12T11:27:08.581Z",
      "__v":0
   }
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X GET \
  -u user@example.com:password \
  https://api.tiledesk.com/v3/5df2240cecd41b00173a06bb/project_users/users/5aaa99024c3b110014b478f0
```

## Invite an agent

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/project_users/invite`

Invite an agent to a project.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name            | Type    | Description                                                        |
| --------------- | ------- | ------------------------------------------------------------------ |
| email           | string  | the agent email address                                            |
| role            | string  | the agent role. Accepted values: agent, admin                      |
| firstname       | string  | the firstname of the agent                                         |
| lastname        | string  | the lastname of the agent                                          |
| user\_available | boolean | the initial agent status. Available (true) or unavailable (false). |

{% tabs %}
{% tab title="200 Teammate invited successfully" %}

```
{
  "_id": "5df34ab80bc923001792e274",
  "id_project": "5df2240cecd41b00173a06bb",
  "id_user": {
    "_id": "5de9200d6722370017731969",
    "email": "nuovopre@f21test.it",
    "firstname": "Nuovopre",
    "lastname": "Pre",
    "emailverified": false,
    "createdAt": "2019-12-05T15:19:41.296Z",
    "updatedAt": "2019-12-05T15:19:41.296Z",
    "__v": 0
  },
  "role": "admin",
  "user_available": true,
  "createdBy": "5aaa99024c3b110014b478f0",
  "createdAt": "2019-12-13T08:24:24.586Z",
  "updatedAt": "2019-12-13T08:24:24.586Z",
  "__v": 0
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X POST \
  -H 'Content-Type: application/json' \
  -u user@example.com:password \
  -d '{"email":"agent@example.com","role":"agent","firstname":"Mario","lastname":"Rossi","user_available":true}' \
  https://api.tiledesk.com/v3/5df2240cecd41b00173a06bb/project_users/invite
```

## Update the current logged teammate

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/project_users/`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name              | Type    | Description                                                                                                 |
| ----------------- | ------- | ----------------------------------------------------------------------------------------------------------- |
| role              | string  | The teammate role. Permitted values: admin, agent.                                                          |
| user\_available   | boolean | <p>The teammate availability. True for available, false for unavailable.</p><p><em>Default is true</em></p> |
| max\_served\_chat | number  | The number of concurrent chats the teammate can take at once.                                               |
| attributes        | object  | The teammate custom attributes                                                                              |
| settings          | object  | The teammate settings object                                                                                |

{% tabs %}
{% tab title="200 Updated teammate" %}

```
{
  "_id": "5df2240cecd41b00173a06bc",
  "id_project": "5df2240cecd41b00173a06bb",
  "id_user": {
    "_id": "5aaa99024c3b110014b478f0",
    "email": "andrea.leo@frontiere21.it",
    "firstname": "Andrea",
    "lastname": "Leo",
    "emailverified": true,
    "__v": 0,
    "resetpswrequestid": ""
  },
  "role": "admin",
  "user_available": false,
  "createdBy": "5aaa99024c3b110014b478f0",
  "createdAt": "2019-12-12T11:27:08.581Z",
  "updatedAt": "2020-01-04T09:50:00.000Z",
  "__v": 0
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X PUT \
  -H 'Content-Type: application/json' \
  -u user@example.com:password \
  -d '{"user_available":false,"role":"admin"}' \
  https://api.tiledesk.com/v3/5df2240cecd41b00173a06bb/project_users/
```

## Update a teammate by id

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/project_users/:project_user_id`

It requires admin role

#### Path Parameters

| Name              | Type   | Description                                                                              |
| ----------------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id       | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| project\_user\_id | string | The teammate identifier.                                                                 |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name              | Type    | Description                                                                                                 |
| ----------------- | ------- | ----------------------------------------------------------------------------------------------------------- |
| role              | string  | The teammate role. Permitted values: admin, agent.                                                          |
| user\_available   | boolean | <p>The teammate availability. True for available, false for unavailable.</p><p><em>Default is true</em></p> |
| max\_served\_chat | number  | The number of concurrent chats the teammate can take at once.                                               |
| attributes        | object  | The teammate custom attributes                                                                              |
| settings          | object  | The teammate settings object                                                                                |

{% tabs %}
{% tab title="200 Updated teammate" %}

```
{
  "_id": "5df34ab80bc923001792e274",
  "id_project": "5df2240cecd41b00173a06bb",
  "id_user": {
    "_id": "5de9200d6722370017731969",
    "email": "nuovopre@f21test.it",
    "firstname": "Nuovopre",
    "lastname": "Pre",
    "emailverified": false,
    "createdAt": "2019-12-05T15:19:41.296Z",
    "updatedAt": "2019-12-05T15:19:41.296Z",
    "__v": 0
  },
  "role": "agent",
  "user_available": true,
  "createdBy": "5aaa99024c3b110014b478f0",
  "createdAt": "2019-12-13T08:24:24.586Z",
  "updatedAt": "2020-01-04T09:55:00.000Z",
  "__v": 0
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X PUT \
  -H 'Content-Type: application/json' \
  -u user@example.com:password \
  -d '{"role":"agent","user_available":true}' \
  https://api.tiledesk.com/v3/5df2240cecd41b00173a06bb/project_users/5df34ab80bc923001792e274
```

## Remove a teammate from the project

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/project_users/:project_user_id`

Remove an agent from a project. The type of removal is controlled by query parameters:

* **soft** (`soft=true`): Soft delete (ghost delete). The teammate is marked as trashed and can be restored later. Data is preserved.
* **hard** (`hard=true`): Hard delete. The teammate is permanently removed from the database. **Warning:** statistics referring to this teammate will be lost.
* **Disable** (no `soft` or `hard`): The teammate is disabled but remains visible on the dashboard and can be re-enabled. Sets `status: "disabled"` and `user_available: false`.

#### Path Parameters

| Name              | Type   | Description                                                                              |
| ----------------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id       | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| project\_user\_id | string | The teammate identifier.                                                                 |

#### Query Parameters

| Name | Type   | Description                                                                                                                            |
| ---- | ------ | -------------------------------------------------------------------------------------------------------------------------------------- |
| soft | string | Set to `true` for soft delete (ghost delete). The teammate is marked as trashed and can be restored.                                   |
| hard | string | Set to `true` for hard delete. Permanently removes the teammate from the database; statistics referring to this teammate will be lost. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 Returns the updated or removed project\_user. For soft delete: trashed is true; for disable: status is "disabled" and user\_available is false; for hard delete: the deleted project\_user object." %}

```
{
  "_id": "5df34ab80bc923001792e274",
  "id_project": "5df2240cecd41b00173a06bb",
  "id_user": {
    "_id": "5de9200d6722370017731969",
    "firstname": "Nuovopre",
    "lastname": "Pre"
  },
  "role": "admin",
  "user_available": false,
  "status": "disabled",
  "trashed": false,
  "createdBy": "5aaa99024c3b110014b478f0",
  "createdAt": "2019-12-13T08:24:24.586Z",
  "updatedAt": "2020-01-04T10:00:00.000Z",
  "__v": 0
}
```

{% endtab %}

{% tab title="404 Project user not found" %}

```
{
  "success": false,
  "error": "Project user not found with id 5df34ab80bc923001792e274"
}
```

{% endtab %}

{% tab title="500 Server error" %}

```
{
  "success": false,
  "msg": "Error deleting Project User with id ..."
}
```

{% endtab %}
{% endtabs %}

Example (soft delete - can be restored):

```
curl -v -X DELETE \
  -u user@example.com:password \
  "https://api.tiledesk.com/v3/5df2240cecd41b00173a06bb/project_users/5df34ab80bc923001792e274?soft=true"
```

Example (hard delete - permanent, statistics lost):

```
curl -v -X DELETE \
  -u user@example.com:password \
  "https://api.tiledesk.com/v3/5df2240cecd41b00173a06bb/project_users/5df34ab80bc923001792e274?hard=true"
```

Example (disable - remains visible, can be re-enabled):

```
curl -v -X DELETE \
  -u user@example.com:password \
  https://api.tiledesk.com/v3/5df2240cecd41b00173a06bb/project_users/5df34ab80bc923001792e274
```

## Restore a trashed teammate

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/project_users/:project_user_id/restore`

Restore a teammate that was previously soft-deleted (trashed). Sets `trashed: false` and `status: "active"`. The teammate must be in trashed state; if not, the API returns 400.

#### Path Parameters

| Name              | Type   | Description                                                                              |
| ----------------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id       | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| project\_user\_id | string | The teammate identifier (project\_user id) to restore.                                   |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minimum role: admin |

{% tabs %}
{% tab title="200 Teammate restored successfully" %}

```
{
  "_id": "5df34ab80bc923001792e274",
  "id_project": "5df2240cecd41b00173a06bb",
  "id_user": {
    "_id": "5de9200d6722370017731969",
    "email": "nuovopre@f21test.it",
    "firstname": "Nuovopre",
    "lastname": "Pre",
    "emailverified": false,
    "createdAt": "2019-12-05T15:19:41.296Z",
    "updatedAt": "2019-12-05T15:19:41.296Z",
    "__v": 0
  },
  "role": "admin",
  "user_available": true,
  "status": "active",
  "trashed": false,
  "createdBy": "5aaa99024c3b110014b478f0",
  "createdAt": "2019-12-13T08:24:24.586Z",
  "updatedAt": "2020-01-04T10:05:00.000Z",
  "__v": 0
}
```

{% endtab %}

{% tab title="400 Teammate is not trashed and cannot be restored" %}

```
{
  "success": false,
  "error": "Project user is not trashed, cannot restore"
}
```

{% endtab %}

{% tab title="404 Teammate not found" %}

```
{
  "success": false,
  "error": "Project user not found with id ..."
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X PUT \
  -u user@example.com:password \
  https://api.tiledesk.com/v3/5df2240cecd41b00173a06bb/project_users/5df34ab80bc923001792e274/restore
```


# User

You can use the API to get or set user information.

The Model

| Key           | Type    | Description                                                    |
| ------------- | ------- | -------------------------------------------------------------- |
| id            | String  | The unique identifier for the user which is given by Tiledesk. |
| email         | String  | The user email.                                                |
| password      | String  | The user password.                                             |
| firstname     | String  | The user firstname.                                            |
| lastname      | String  | The user lastname.                                             |
| emailverified | Boolean | Determine if the user has a email validated.                   |
| status        | Number  | User status. Permitted values: 100 active, 0 disabled          |
| createdAt     | String  | The time (ISO-8601 date string) when the user was created.     |
| updatedAt     | String  | The time (ISO-8601 date string) when the user was updated.     |
| createdBy     | String  | The unique identifier of the row creator                       |
| id\_project   | String  | The unique identifier of the project                           |

## Get the current authenticated user

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/users`

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
...
```

{% endtab %}
{% endtabs %}

## Update the current authenticated user

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/users/`

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name       | Type   | Description                |
| ---------- | ------ | -------------------------- |
| firstname  | string | The user firstname         |
| lastname   | string | The user lastname          |
| attributes | object | The user custom attributes |

{% tabs %}
{% tab title="200 " %}

```
...
```

{% endtab %}
{% endtabs %}


# Analytics

You can use the API to get the analytics data.

## Get the average waiting response time

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/requests/waiting`

This is calculated over the last 30 days.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}

## Get the average waiting response time of the last day

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/requests/waiting/day/last`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}

## Get the conversations count of the last 30 days

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/requests/count`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}

## Get the conversations count aggregated by the status field of the last 30 days

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/requests/aggregate/status`

With this endpoint you can get how many assigned, unassigned and archived conversations do you have.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}

## Get the conversations count aggregated by days

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/requests/aggregate/day`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}

## Get the conversations count aggregated by months

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/requests/aggregate/month`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}

## Get the conversations count aggregated by weeks

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/requests/aggregate/week`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}

## Get the conversations count aggregated by hours

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/requests/aggregate/hours`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}

## Get the median conversations length

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/requests/duration`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}

## Get the median conversations length calculated over the last 30 days

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/requests/duration`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}

## Get the average customers rating of the conversations (Customer satisfaction)

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/requests/satisfaction`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}

## Get the number of the conversations handled by a bot

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/requests/hasBot/count`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}

## Get the total number of the messages sent and received during the last 30 days

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/messages/count`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}

## Get the total number of the messages sent and received aggregated by days during the last 30 days

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/analytics/messages/aggregate/day`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: admin |

{% tabs %}
{% tab title="200 " %}

```
....
```

{% endtab %}
{% endtabs %}


# Canned responses

You can use the API to get or set canned response information.

The Canned respose model

| Key         | Type   | Description                                                              |
| ----------- | ------ | ------------------------------------------------------------------------ |
| id          | String | The unique identifier for the canned respose which is given by Tiledesk. |
| title       | String | The canned respose title.                                                |
| text        | String | The canned respose content                                               |
| attributes  | Object | The custom attributes which are set for the canned respose.              |
| createdAt   | String | The time (ISO-8601 date string) when the canned respose was created.     |
| updatedAt   | String | The time (ISO-8601 date string) when the canned respose was updated.     |
| createdBy   | String | The unique identifier of the row creator                                 |
| id\_project | String | The unique identifier of the project                                     |

## Get all canned responses

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/canned`

Allows an account to list all the canned responses.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Query Parameters

| Name      | Type   | Description                                                                                                                   |
| --------- | ------ | ----------------------------------------------------------------------------------------------------------------------------- |
| sortField | string | <p>what field to sort the results by.</p><p><em>Default field is createdAt</em></p>                                           |
| direction | string | <p>sort direction: 1 or -1. Return the results in ascending (1) or descending (-1) order.</p><p><em>defaults to desc</em></p> |
| page      | number | what page of results to fetch. defaults to first page.                                                                        |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 " %}

```
[
   {
      "status":100,
      "_id":"5e67c1c89d86fa001755ed90",
      "title":"howcanhelpyou",
      "text":"Hi $recipient_name my name is $agent_name how can I help you?",
      "id_project":"5e5d40b2bd0a9b00179ff3cd",
      "createdBy":"5e09d16d4d36110017506d7f",
      "createdAt":"2020-03-10T16:35:20.458Z",
      "updatedAt":"2020-03-10T16:35:20.458Z",
      "__v":0
   },
   ...
]
```

{% endtab %}
{% endtabs %}

## Get a canned respose by id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/canned/:id`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| id          | string | the canned identifier                                                                    |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

{% tabs %}
{% tab title="200 " %}

```
{
      "status":100,
      "_id":"5e67c1c89d86fa001755ed90",
      "title":"howcanhelpyou",
      "text":"Hi $recipient_name my name is $agent_name how can I help you?",
      "id_project":"5e5d40b2bd0a9b00179ff3cd",
      "createdBy":"5e09d16d4d36110017506d7f",
      "createdAt":"2020-03-10T16:35:20.458Z",
      "updatedAt":"2020-03-10T16:35:20.458Z",
      "__v":0
   }
```

{% endtab %}
{% endtabs %}

## Create a new canned response

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/canned`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name       | Type   | Description                           |
| ---------- | ------ | ------------------------------------- |
| title      | string | the canned response title             |
| text       | string | the canned response content           |
| attributes | object | The canned response custom attributes |

{% tabs %}
{% tab title="200 " %}

```
{
      "status":100,
      "_id":"5e67c1c89d86fa001755ed90",
      "title":"howcanhelpyou",
      "text":"Hi $recipient_name my name is $agent_name how can I help you?",
      "id_project":"5e5d40b2bd0a9b00179ff3cd",
      "createdBy":"5e09d16d4d36110017506d7f",
      "createdAt":"2020-03-10T16:35:20.458Z",
      "updatedAt":"2020-03-10T16:35:20.458Z",
      "__v":0
   }
```

{% endtab %}
{% endtabs %}

## Update a canned response by id

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/canned/:id`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The id is the canned response indentifier.                                               |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name       | Type   | Description                           |
| ---------- | ------ | ------------------------------------- |
| title      | string | the canned response title             |
| text       | string | the canned response content           |
| attributes | object | The canned response custom attributes |

{% tabs %}
{% tab title="200 " %}

```
{
      "status":100,
      "_id":"5e67c1c89d86fa001755ed90",
      "title":"howcanhelpyou",
      "text":"Hi $recipient_name my name is $agent_name how can I help you?",
      "id_project":"5e5d40b2bd0a9b00179ff3cd",
      "createdBy":"5e09d16d4d36110017506d7f",
      "createdAt":"2020-03-10T16:35:20.458Z",
      "updatedAt":"2020-03-10T16:35:20.458Z",
      "__v":0
   }
```

{% endtab %}
{% endtabs %}

## Delete a canned response by id

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/canned/:id`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The id is the canned response indentifier.                                               |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |

{% tabs %}
{% tab title="200 " %}

```
{
      "status":100,
      "_id":"5e67c1c89d86fa001755ed90",
      "title":"howcanhelpyou",
      "text":"Hi $recipient_name my name is $agent_name how can I help you?",
      "id_project":"5e5d40b2bd0a9b00179ff3cd",
      "createdBy":"5e09d16d4d36110017506d7f",
      "createdAt":"2020-03-10T16:35:20.458Z",
      "updatedAt":"2020-03-10T16:35:20.458Z",
      "__v":0
   }
```

{% endtab %}
{% endtabs %}


# Tags

You can use the API to get or set tags.

The Tag model

| Key         | Type   | Description                                                   |
| ----------- | ------ | ------------------------------------------------------------- |
| id          | String | The unique identifier for the tag which is given by Tiledesk. |
| tag         | String | The tag name.                                                 |
| color       | String | The tag hexadecimal color                                     |
| attributes  | Object | The custom attributes which are set for the tag.              |
| createdAt   | String | The time (ISO-8601 date string) when the tag was created.     |
| updatedAt   | String | The time (ISO-8601 date string) when the tag was updated.     |
| createdBy   | String | The unique identifier of the row creator                      |
| id\_project | String | The unique identifier of the project                          |

## Get all tags

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/tags`

Allows an account to list all the tags.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Query Parameters

| Name      | Type   | Description                                                                                                                   |
| --------- | ------ | ----------------------------------------------------------------------------------------------------------------------------- |
| sortField | string | <p>what field to sort the results by.</p><p><em>Default field is createdAt</em></p>                                           |
| direction | string | <p>sort direction: 1 or -1. Return the results in ascending (1) or descending (-1) order.</p><p><em>defaults to desc</em></p> |
| page      | number | what page of results to fetch. defaults to first page.                                                                        |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
[
   {
      "_id":"5e67b8bafb930c0017aa4e42",
      "tag":"tag1",
      "color":"#66C549",
      "id_project":"5e5d40b2bd0a9b00179ff3cd",
      "createdBy":"5e09d16d4d36110017506d7f",
      "createdAt":"2020-03-10T15:56:42.374Z",
      "updatedAt":"2020-03-10T15:56:42.374Z",
      "__v":0
   },
   {
      "_id":"5e67b737fb930c0017aa4e40",
      "tag":"important",
      "color":"#43B1F2",
      "id_project":"5e5d40b2bd0a9b00179ff3cd",
      "createdBy":"5e09d16d4d36110017506d7f",
      "createdAt":"2020-03-10T15:50:15.759Z",
      "updatedAt":"2020-03-10T15:50:15.759Z",
      "__v":0
   },
```

{% endtab %}
{% endtabs %}

## Get a tag by id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/tags/:id`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| id          | string | the tag identifier                                                                       |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

{% tabs %}
{% tab title="200 " %}

```
  {
      "_id":"5e67b737fb930c0017aa4e40",
      "tag":"important",
      "color":"#43B1F2",
      "id_project":"5e5d40b2bd0a9b00179ff3cd",
      "createdBy":"5e09d16d4d36110017506d7f",
      "createdAt":"2020-03-10T15:50:15.759Z",
      "updatedAt":"2020-03-10T15:50:15.759Z",
      "__v":0
   }
```

{% endtab %}
{% endtabs %}

## Create a new tag

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/tags`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name       | Type   | Description               |
| ---------- | ------ | ------------------------- |
| tag        | string | the tag name              |
| color      | string | the tag color             |
| attributes | object | The tag custom attributes |

{% tabs %}
{% tab title="200 " %}

```
  {
      "_id":"5e67b737fb930c0017aa4e40",
      "tag":"important",
      "color":"#43B1F2",
      "id_project":"5e5d40b2bd0a9b00179ff3cd",
      "createdBy":"5e09d16d4d36110017506d7f",
      "createdAt":"2020-03-10T15:50:15.759Z",
      "updatedAt":"2020-03-10T15:50:15.759Z",
      "__v":0
   }
```

{% endtab %}
{% endtabs %}

## Update a tag by id

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/tags/:id`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The id is the tag indentifier.                                                           |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name       | Type   | Description               |
| ---------- | ------ | ------------------------- |
| tag        | string | the tag name              |
| color      | string | the tag color             |
| attributes | object | The tag custom attributes |

{% tabs %}
{% tab title="200 " %}

```
  {
      "_id":"5e67b737fb930c0017aa4e40",
      "tag":"important",
      "color":"#43B1F2",
      "id_project":"5e5d40b2bd0a9b00179ff3cd",
      "createdBy":"5e09d16d4d36110017506d7f",
      "createdAt":"2020-03-10T15:50:15.759Z",
      "updatedAt":"2020-03-10T15:50:15.759Z",
      "__v":0
   }
```

{% endtab %}
{% endtabs %}

## Delete a tag by id

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/tags/:id`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The id is the tag indentifier.                                                           |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
...
```

{% endtab %}
{% endtabs %}


# Events

You can use the API to get or set event information.

## The Event Model

| Key           | Type   | Description                                                                                     |
| ------------- | ------ | ----------------------------------------------------------------------------------------------- |
| id            | String | The unique identifier for the event which is given by Tiledesk.                                 |
| name          | String | The event name. You can find the standard Tiledesk events [here](/apis/webhooks#webhook-events) |
| project\_user | Object | The user who creates the event.                                                                 |
| attributes    | Object | The custom attributes which are set for the event.                                              |
| createdAt     | String | The time (ISO-8601 date string) when the event was created.                                     |
| updatedAt     | String | The time (ISO-8601 date string) when the event was updated.                                     |
| createdBy     | String | The unique identifier of the row creator                                                        |
| id\_project   | String | The unique identifier of the project                                                            |

## Get all events

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/events`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Query Parameters

| Name      | Type   | Description                                                                                                          |
| --------- | ------ | -------------------------------------------------------------------------------------------------------------------- |
| sortField | string | what field to sort the results by.                                                                                   |
| direction | string | <p>sort direction: 1 or -1. Return the results in ascending or descending order.</p><p><em>defaults to desc</em></p> |
| page      | number | what page of results to fetch. defaults to first page.                                                               |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
{
   ...
}
```

{% endtab %}
{% endtabs %}

## Get a event by id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/events/:id`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| id          | string | the event identifier                                                                     |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

{% tabs %}
{% tab title="200 " %}

```
{  
        ..
}
```

{% endtab %}
{% endtabs %}

## Fire a new custom event and save it

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/events`

With this endpoint you can fire a custom event. You event name should be

`event.emit.EVENT_NAME`

to correctly identify your custom event. You can find the standard Tiledesk events here

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name       | Type   | Description                 |
| ---------- | ------ | --------------------------- |
| name       | string | the event name              |
| attributes | object | The event custom attributes |

{% tabs %}
{% tab title="200 " %}

```
{  
        ..
}
```

{% endtab %}
{% endtabs %}


# Jwt

## List the jwt tokens of a user

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/jwt/history`

#### Query Parameters

| Name      | Type   | Description                                                                                                          |
| --------- | ------ | -------------------------------------------------------------------------------------------------------------------- |
| sortField | string | what field to sort the results by.                                                                                   |
| direction | string | <p>sort direction: 1 or -1. Return the results in ascending or descending order.</p><p><em>defaults to desc</em></p> |
| page      | number | what page of results to fetch. defaults to first page.                                                               |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
..
```

{% endtab %}
{% endtabs %}

## Revoke a jwt token by JTI (JWT identifier)

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/jwt/history/:jti`

#### Path Parameters

| Name | Type   | Description                        |
| ---- | ------ | ---------------------------------- |
| jti  | string | The JTI Json Web Token identifier. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
..
```

{% endtab %}
{% endtabs %}

## Revoke a jwt token by id

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/jwt/history/id/:id`

#### Path Parameters

| Name | Type   | Description        |
| ---- | ------ | ------------------ |
| id   | string | The JWT identifier |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
..
```

{% endtab %}
{% endtabs %}


# Labels

## Labels

You can use the API to get or set label information.

## The Model

The API tag is used to implement internationalization and multilingual for the widget and chatbots.

| Key         | Type   | Description                                                     |
| ----------- | ------ | --------------------------------------------------------------- |
| id          | String | The unique identifier for the label which is given by Tiledesk. |
| data        | Object | The label data model.                                           |
| attributes  | Object | The custom attributes which are set for the label.              |
| createdAt   | String | The time (ISO-8601 date string) when the label was created.     |
| updatedAt   | String | The time (ISO-8601 date string) when the label was updated.     |
| createdBy   | String | The unique identifier of the row creator                        |
| id\_project | String | The unique identifier of the project                            |

### Label Data Model

| Key      | Type    | Description                                                    |
| -------- | ------- | -------------------------------------------------------------- |
| lang     | String  | The language identifier                                        |
| data     | Object  | The translation labels data                                    |
| category | String  | The label data category                                        |
| default  | Boolean | Determines if this translation is the default for the project. |

## Get all labels for the project\_id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/labels`

Allows an account to list all the labels.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
TODO
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/labels
```

## Get a all the labels for the provided language

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/labels/:id`

Fetches the labels by the provided language

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| id          | string | the language iso identifier(Ex. EN, IT, ES, etc.)                                        |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

{% tabs %}
{% tab title="200 " %}

```
TODO
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/labels/EN
```

## Create or update a label

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/labels`

Allows to add or update labels.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name    | Type    | Description                             |
| ------- | ------- | --------------------------------------- |
| lang    | string  | the language identifier                 |
| data    | object  | the data object                         |
| default | boolean | Dermine if this is the default language |

{% tabs %}
{% tab title="200 " %}

```
TODO
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X POST -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d '{"lang":"andrea", "data":{OBJECT}}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/labels
```

## Make a language as default for the project

<mark style="color:purple;">`PATCH`</mark> `https://api.tiledesk.com/v3/:project_id/labels/:lang/default`

Make a language as default for the project

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| lang        | string | The language identifier                                                                  |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

{% tabs %}
{% tab title="200 " %}

```
TODO
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X PATCH -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456   https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/labels/EN/default
```

## Delete a label by language identifier

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/labels/:lang`

Allows to delete a label by language identifier.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| lang        | string | The lang indentifier.                                                                    |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
TODO
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X DELETE -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/labels/EN
```

## Delete all the labels of the project

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/labels/`

Allows to delete all the labels of the project

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
TODO
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X DELETE -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/labels/
```

## Get all predefined labels

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/labels/default`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
TODO
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/labels/default
```

## Get all the standard pre-translated labels

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/labels/default`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
TODO
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/labels/default
```

## Get the standard pre-translated label by language id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/labels/default/lang`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
TODO
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/labels/default/EN
```

## Create a label clone from a pre-traslated language

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/labels/default/clone`

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name | Type   | Description             |
| ---- | ------ | ----------------------- |
| lang | string | the language identifier |

{% tabs %}
{% tab title="200 " %}

```
TODO
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X POST -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/labels/default/clone
```


# Files

You can use the API to download and upload binary files. The API supports three types of file uploads: chat files (with automatic expiration), project assets, and user/bot avatars.

## File Upload Types

* **Chat files**: Files uploaded during conversations. These have automatic expiration (default: 30 days).
* **Assets**: Project assets that can be used across the platform. These have no expiration by default, but can be set via query parameter. Images automatically generate thumbnails.
* **Avatars**: User profile photos or bot avatars. These have no expiration and are stored in a fixed path structure.

## Upload a project asset

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/files/assets`

Uploads a file as a project asset. Assets have no expiration by default, but can be set via query parameter.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Query Parameters

| Name       | Type   | Description                                                                                                 |
| ---------- | ------ | ----------------------------------------------------------------------------------------------------------- |
| expiration | number | Optional. Expiration time in seconds. If provided and greater than 0, the file will expire after this time. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minimum role: admin |
| Content-Type  | string | Use "multipart/form-data" value                             |

#### Request Body

| Name | Type   | Description                                                                                                         |
| ---- | ------ | ------------------------------------------------------------------------------------------------------------------- |
| file | binary | The binary file to upload. Must match allowed extensions for assets. Images will automatically generate thumbnails. |

{% tabs %}
{% tab title="201 File uploaded successfully" %}

```
{
  "message": "File uploaded successfully",
  "filename": "uploads/projects/5ebd890292befe0019054973/files/uuid/logo.png",
  "thumbnail": "uploads/projects/5ebd890292befe0019054973/files/uuid/thumbnails_200_200-logo.png"
}
```

{% endtab %}

{% tab title="400 Bad request - Invalid file or upload error" %}

```
{
  "success": false,
  "error": "Error message"
  "code": "Error code" // code is not always returned
}
```

{% endtab %}

{% tab title="403 Forbidden - File extension not allowed or content verification failed" %}

```
{
  "success": false,
  "error": "File extension .exe is not allowed"
}
```

{% endtab %}

{% tab title="413 File too large" %}

```
{
  "success": false,
  "error": "File too large",
  "code": "LIMIT_FILE_SIZE"
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X POST \
  -H 'Content-Type: multipart/form-data' \
  -u user@example.com:password \
  -F file=@logo.png \
  https://api.tiledesk.com/v3/files/assets?expiration=86400
```

## Upload a chat file

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/files/chat`

Uploads a file for use in chat conversations. The file will automatically expire after a configured time (default: 30 days).

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                             |
| ------------- | ------ | --------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. |
| Content-Type  | string | Use "multipart/form-data" value         |

#### Request Body

| Name | Type   | Description                |
| ---- | ------ | -------------------------- |
| file | binary | The binary file to upload. |

{% tabs %}
{% tab title="201 File uploaded successfully" %}

```
{
  "message": "File uploaded successfully",
  "filename": "uploads/projects/5ebd890292befe0019054973/files/uuid/document.pdf"
}
```

{% endtab %}

{% tab title="400 Bad request - Invalid file or upload error" %}

```
{
  "success": false,
  "error": "Error message",
  "code": "Error code"
}
```

{% endtab %}

{% tab title="403 Forbidden - File extension not allowed or content verification failed" %}

```
{
  "success": false,
  "error": "File extension .exe is not allowed"
}
```

{% endtab %}

{% tab title="413 File too large" %}

```
{
  "success": false,
  "error": "File too large",
  "code": "LIMIT_FILE_SIZE"
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X POST \
  -H 'Content-Type: multipart/form-data' \
  -u user@example.com:password \
  -F file=@document.pdf \
  https://api.tiledesk.com/v3/files/chat
```

## Upload user profile photo or bot avatar

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/files/users/photo`

Uploads a profile photo for a user or avatar for a bot. Only image files are allowed (`.png`, `.jpg`, `.jpeg`, `.gif`). The file is stored in a fixed path structure: `uploads/users/{user_id|bot_id}/images/photo.jpg`. Automatically generates a 200x200 thumbnail. Requires agent role or bot/subscription authentication.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Query Parameters

| Name    | Type   | Description                                                                                                                             |
| ------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| bot\_id | string | Optional. If provided, uploads the avatar for the specified bot. The authenticated user must be an admin or owner of the bot's project. |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minimum role: agent |
| Content-Type  | string | Use "multipart/form-data" value                             |

#### Request Body

| Name | Type   | Description                                                               |
| ---- | ------ | ------------------------------------------------------------------------- |
| file | binary | The image file to upload. Must be one of: `.png`, `.jpg`, `.jpeg`, `.gif` |

{% tabs %}
{% tab title="201 Image uploaded successfully" %}

```
{
  "message": "Image uploaded successfully",
  "filename": "uploads/users/5ebd890292befe0019054973/images/photo.jpg",
  "thumbnail": "uploads/users/5ebd890292befe0019054973/images/thumbnails_200_200-photo.jpg"
}
```

{% endtab %}

{% tab title="400 Bad request - No file uploaded or invalid file" %}

```
{
  "success": false,
  "error": "No file uploaded"
}
```

{% endtab %}

{% tab title="401 Unauthorized - User doesn" %}

```
{
  "success": false,
  "error": "You don't belong to the chatbot's project"
}
```

{% endtab %}

{% tab title="403 Forbidden - Insufficient permissions or file extension not allowed" %}

```
{
  "success": false,
  "error": "You don't have the role required to modify the chatbot"
}
```

{% endtab %}

{% tab title="404 Chatbot not found" %}

```
{
  "success": false,
  "error": "Chatbot not found"
}
```

{% endtab %}

{% tab title="413 File too large" %}

```
{
  "success": false,
  "error": "File too large",
  "code": "LIMIT_FILE_SIZE"
}
```

{% endtab %}
{% endtabs %}

Example (user photo):

```
curl -v -X POST \
  -H 'Content-Type: multipart/form-data' \
  -u user@example.com:password \
  -F file=@photo.jpg \
  https://api.tiledesk.com/v3/files/users/photo
```

Example (bot avatar):

```
curl -v -X POST \
  -H 'Content-Type: multipart/form-data' \
  -u user@example.com:password \
  -F file=@bot_avatar.png \
  https://api.tiledesk.com/v3/files/users/photo?bot_id=65c5f3599faf2d04cd7da528
```

## Get the binary file as stream by filename path

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/files`

Retrieves a file as a stream by its path. The file is returned with appropriate Content-Type headers. If the file is not found in the primary storage, the system automatically falls back to a secondary storage service.

#### Query Parameters

| Name           | Type    | Description                                                                                                      |
| -------------- | ------- | ---------------------------------------------------------------------------------------------------------------- |
| path           | string  | The file path (URL encoded). Example: `uploads/projects/5ebd890292befe0019054973/files/uuid/document.pdf`        |
| as\_attachment | boolean | Optional. If set, the file will be returned with Content-Disposition header set to attachment, forcing download. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 File stream" %}

```
<binary content>
```

{% endtab %}

{% tab title="404 File not found" %}

```
{
  "success": false,
  "error": "File not found."
}
```

{% endtab %}

{% tab title="500 Error getting file" %}

```
{
  "success": false,
  "error": "Error getting file."
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X GET \
  -u user@example.com:password \
  "https://api.tiledesk.com/v3/files?path=uploads%2Fprojects%2F5ebd890292befe0019054973%2Ffiles%2Fuuid%2Fdocument.pdf"
```

Example (as attachment):

```
curl -v -X GET \
  -u user@example.com:password \
  "https://api.tiledesk.com/v3/files?path=uploads%2Fprojects%2F5ebd890292befe0019054973%2Ffiles%2Fuuid%2Fdocument.pdf&as_attachment=true"
```

## Download the binary file by filename path

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/files/download`

Downloads a file by its path. The file is returned with Content-Disposition header set to attachment, forcing download with the original filename.

#### Query Parameters

| Name | Type   | Description                                                                                               |
| ---- | ------ | --------------------------------------------------------------------------------------------------------- |
| path | string | The file path (URL encoded). Example: `uploads/projects/5ebd890292befe0019054973/files/uuid/document.pdf` |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 File download" %}

```
<binary content>
```

{% endtab %}

{% tab title="404 File not found" %}

```
{
  "success": false,
  "error": "File not found."
}
```

{% endtab %}

{% tab title="500 Error getting file" %}

```
{
  "success": false,
  "error": "Error getting file."
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X GET \
  -u user@example.com:password \
  "https://api.tiledesk.com/v3/files/download?path=uploads%2Fprojects%2F5ebd890292befe0019054973%2Ffiles%2Fuuid%2Fdocument.pdf"
```

## Delete a file

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/files`

Deletes a file by its path. If the file is an image, the associated thumbnail (if exists) will also be deleted automatically. The system checks both primary and fallback storage services.

#### Query Parameters

| Name | Type   | Description                                                                                                                                                        |
| ---- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| path | string | The file path (URL encoded). Example: `uploads/users/65c5f3599faf2d04cd7da528/images/photo.jpg` or `uploads/projects/65c5f3599faf2d04cd7da528/files/uuid/logo.png` |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 File deleted successfully" %}

```
{
  "message": "File deleted successfully",
  "filename": "uploads/users/65c5f3599faf2d04cd7da528/images/photo.jpg"
}
```

{% endtab %}

{% tab title="400 Bad request - Path parameter missing or invalid" %}

```
{
  "success": false,
  "error": "Path parameter is required"
}
```

{% endtab %}

{% tab title="404 File not found" %}

```
{
  "success": false,
  "error": "File not found."
}
```

{% endtab %}

{% tab title="500 Error deleting file" %}

```
{
  "success": false,
  "error": "Error deleting file."
}
```

{% endtab %}
{% endtabs %}

Example (delete user photo):

```
curl -v -X DELETE \
  -u user@example.com:password \
  "https://api.tiledesk.com/v3/files?path=uploads%2Fusers%2F65c5f3599faf2d04cd7da528%2Fimages%2Fphoto.jpg"
```

Example (delete project asset):

```
curl -v -X DELETE \
  -u user@example.com:password \
  "https://api.tiledesk.com/v3/files?path=uploads%2Fprojects%2F65c5f3599faf2d04cd7da528%2Ffiles%2Fuuid%2Flogo.png"
```

## Error Codes

* **400**: Bad request - Invalid file, missing parameters, or upload error
* **403**: Forbidden - File extension not allowed, content verification failed, or insufficient permissions
* **404**: Not found - File or resource not found
* **413**: Payload too large - File exceeds maximum upload size (configurable via `MAX_UPLOAD_FILE_SIZE` environment variable)
* **500**: Internal server error - Server error during file operations

## File Content Verification

All uploaded files are verified to ensure the file content matches the declared MIME type. This prevents security issues by detecting mismatched file types.

## Thumbnail Generation

Images uploaded as assets or user/bot avatars automatically generate 200x200 pixel thumbnails. Thumbnails are stored with the pattern `thumbnails_200_200-{original_filename}` and are automatically deleted when the main file is deleted.


# Segments

You can use the API to get or set segment information. A segment is a collection of contacts, defined by a specific set of attributes, used to filter them in a marketing campaign. User segmentation is the process of separating leads into distinct groups, or segments, based on shared characteristics. A company might segment leads based on language preferences, product version, geographical region.

## The Segment Model

| Key         | Type   | Description                                                       |
| ----------- | ------ | ----------------------------------------------------------------- |
| id          | String | The unique identifier for the segment which is given by Tiledesk. |
| name        | String | The segment name                                                  |
| match       | String | all or any                                                        |
| createdAt   | String | The time (ISO-8601 date string) when the segment was created.     |
| filters     | Array  |                                                                   |
| createdBy   | String | The unique identifier of the row creator                          |
| id\_project | String | The unique identifier of the project                              |

## Get all segments

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/segments`

Example

```
curl -v -X GET -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/segments
```

## Get a segment by id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/segments/:id`

Fetches a segment by his or her segment ID

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| id          | string | the segment identifier                                                                   |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

Example

```
curl -v -X GET -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/segments/5c81593adf767b0017d1aa66
```

## Create a new segment

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/segments`

Allows to add more segments.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name    | Type   | Description                        |
| ------- | ------ | ---------------------------------- |
| name    | string | The segment name                   |
| match   | string | The segment match type. All or Any |
| filters | array  | The segment filters                |

Example:

```
curl -v -X POST -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d '{ "name":"segment1", "filters": [{"field":"field1","operator":"=","value":"value1"}]}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/segments
```

## Update a segment by id

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/segments/:id`

Allows to update a segment.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The id is the segment indentifier.                                                       |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |
| Content-Type  | string | use "application/json" value                                |

#### Request Body

| Name    | Type   | Description                        |
| ------- | ------ | ---------------------------------- |
| name    | string | The segment name                   |
| match   | string | The segment match type. All or Any |
| filters | array  | The segment filters                |

## Delete a segment by id

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/segments/:id`

Allows to delete a segment.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The id is the segment indentifier.                                                       |

#### Headers

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT. Minumun role: agent |


# Chatbots

## The Bot model

| Key              | Type    | Description                                                   |
| ---------------- | ------- | ------------------------------------------------------------- |
| id               | String  | The unique identifier for the bot which is given by Tiledesk. |
| name             | String  | The bot name.                                                 |
| id\_project      | String  | The unique identifier of the project                          |
| type             | String  | The bot type. Permitted values: internal, external.           |
| secret           | String  | The bot secret token used for JWT authentication.             |
| createdBy        | String  | The unique identifier of the row creator                      |
| description      | String  | (Optional) The bot description.                               |
| url              | String  | (Optional) The bot external endpoint address                  |
| webhook\_url     | String  | (Optional)                                                    |
| webhook\_enabled | Boolean | (Optional)                                                    |
| trashed          | Boolean | (Optional) The bot status.                                    |
| attributes       | Object  | (Optional) The custom attributes which are set for the bot.   |
| language         | String  | (Optional) The bot language.                                  |
| createdAt        | String  | (Optional) The time when the bot was created.                 |
| public           | Boolean | (Optional) The sharing status of the bot. Default false.      |
| updatedAt        | String  | (Optional) The time when the bot was updated.                 |

## Get all bots

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/bots`

Allows an account to list all the bots of the project.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
[
   {
      "_id":"5be9b2ecc72a050015e14951",
      "updatedAt":"2018-11-12T17:05:50.616Z",
      "createdAt":"2018-11-12T17:05:48.544Z",
      "name":"bot1",
      "id_project":"5b55e806c93dde00143163dd",
      "trashed":false,
      "createdBy":"5ab0f3fa57066e0014bfd71e",
      "__v":0,
      "external":false
   },
   {
      "_id":"5ce265596438e40017e3610d",
      "updatedAt":"2019-05-20T08:29:14.524Z",
      "createdAt":"2019-05-20T08:29:13.286Z",
      "name":"bot2",
      "id_project":"5b55e806c93dde00143163dd",
      "trashed":false,
      "createdBy":"5ab0f3fa57066e0014bfd71e",
      "__v":0,
      "external":false
   }
]
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/bots
```

***

## Get a bot by id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/bots/:id`

Allows an account to get a bot of the project.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| id          | string | The bot identifier                                                                       |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
  {
      "_id":"5be9b2ecc72a050015e14951",
      "updatedAt":"2018-11-12T17:05:50.616Z",
      "createdAt":"2018-11-12T17:05:48.544Z",
      "name":"bot1",
      "id_project":"5b55e806c93dde00143163dd",
      "trashed":false,
      "createdBy":"5ab0f3fa57066e0014bfd71e",
      "__v":0,
      "external":false
   }
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/bots/5be9b2ecc72a050015e14951
```

***

## Export a bot in JSON format

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/bots/exportjson/:id`

Allows an accont to export the bot in json format

#### Path Parameters

| Name        | Type   | Description                                                                             |
| ----------- | ------ | --------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The bot identifier                                                                      |

#### Query Parameters

| Name        | Type    | Description                                                 |
| ----------- | ------- | ----------------------------------------------------------- |
| intentsOnly | boolean | (Optional) if TRUE will be exported only the intents (faqs) |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

{% tabs %}
{% tab title="200 " %}

```
  {"webhook_enabled":false,"language":"en","name":"bot1","intents":[{"webhook_enabled":false,"enabled":true,"question":"\start","answer":"Hello","intent_display_name":"start","language":"en"}]}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/bots/exportjson/5be9b2ecc72a050015e14951
```

***

## Create a new bot

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/bots`

Allows to add more bots.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name             | Type   | Description                                                                                                                                                                                                                                                                                                                                              |
| ---------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name             | string | The bot name                                                                                                                                                                                                                                                                                                                                             |
| description      | string | The bot description                                                                                                                                                                                                                                                                                                                                      |
| language         | string | The bot language with two-letter ISO 639-1 code.                                                                                                                                                                                                                                                                                                         |
| webhook\_enabled | string | Enable the webhook fullfillment endpoint                                                                                                                                                                                                                                                                                                                 |
| template         | string | If internal type is used you can specify the template used to create the faqs. Supported values : blank, handoff, example. Example is the default value. Blank is a basic chatbot with only start e defaultFallback intents. Handoff is like the basic chatbot with the Agent handoff intent. Example is a chatbot with a showcase of the main features. |
| type             | string | Supported type values are: "internal", "external". Default is "internal". With internal value the standard tiledesk bot engine is used. With external you can create your own chatbot engine specifing the url parameter.                                                                                                                                |
| url              | string | The external chatbot endpoint                                                                                                                                                                                                                                                                                                                            |

{% tabs %}
{% tab title="200 " %}

```
 {
      "_id":"5be9b2ecc72a050015e14951",
      "updatedAt":"2018-11-12T17:05:50.616Z",
      "createdAt":"2018-11-12T17:05:48.544Z",
      "name":"bot1",
      "id_project":"5b55e806c93dde00143163dd",
      "trashed":false,
      "createdBy":"5ab0f3fa57066e0014bfd71e",
      "__v":0,
      "external":false
   }
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X POST -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d '{"name":"bot1"}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/bots
```

***

## Fork a bot

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/bots/fork/:id`

Allows to fork an existing bot.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The bot identifier                                                                       |

#### Query Parameters

| Name      | Type   | Description                                                    |
| --------- | ------ | -------------------------------------------------------------- |
| public    | string | The sharing status of the bot. Permitted values: true \| false |
| projectid | string | The id of the project where wants to fork the bot              |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

{% tabs %}
{% tab title="200 " %}

```
{
   "message":"Chatbot forked successfully",
   "bot_id":"5ab0f3fa57066e0014bf777e"
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X PUT -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/bots/fork/5be9b2ecc72a050015e14951?public=false&projectid=5b55e806c93dde0014316e33
```

***

## Import whole bot from JSON

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/bots/importjson/:id`

Allows to import the bot informations and intents from a JSON file.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | the bot identifier (on which perform import) (is null with create option)                |

#### Query Parameters

| Name      | Type   | Description                                                                                                                                                                                                                     |
| --------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| create    | string | Allows to create a chatbot before importing Permitted values: true \| false \| null                                                                                                                                             |
| replace   | string | (BETA) Allows you to clean the chatbot (all its intents) before importing Permitted values: true \| false \| null                                                                                                               |
| overwrite | string | Choose whether to replace intents with the same intent\_display\_name with the imported ones. If false or null Old intents with the same intent\_display\_name will not be overwritten. Permitted values: true \| false \| null |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name       | Type | Description                       |
| ---------- | ---- | --------------------------------- |
| uploadFile | json | The JSON file that contains data. |

{% tabs %}
{% tab title="200 " %}

```
{
   "_id":"5be9b2ecc72a050015e14951",
   "updatedAt":"2018-11-12T17:05:50.616Z",
   "createdAt":"2018-11-12T17:05:48.544Z",
   "name":"bot1",
   "id_project":"5b55e806c93dde00143163dd",
   "trashed":false,
   "createdBy":"5ab0f3fa57066e0014bfd71e",
   "__v":0,
   "external":false
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X POST -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d "@path_to_file/bot.json" https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/bots/importjson/5be9b2ecc72a050015e14951
```

***

## Update a bot

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/bots/:id`

Allows to update a bot.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The bot identifier                                                                       |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name             | Type   | Description                                                                                                                                                                                                               |
| ---------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name             | string | The bot name                                                                                                                                                                                                              |
| url              | string | The bot external endpoint                                                                                                                                                                                                 |
| description      | string | The bot description                                                                                                                                                                                                       |
| language         | string | The bot language with two-letter ISO 639-1 code.                                                                                                                                                                          |
| webhook\_enabled | string | Enable the webhook fullfillment endpoint                                                                                                                                                                                  |
| type             | string | Supported type values are: "internal", "external". Default is "internal". With internal value the standard tiledesk bot engine is used. With external you can create your own chatbot engine specifing the url parameter. |

{% tabs %}
{% tab title="200 " %}

```
{
      "_id":"5be9b2ecc72a050015e14951",
      "updatedAt":"2018-11-12T17:05:50.616Z",
      "createdAt":"2018-11-12T17:05:48.544Z",
      "name":"bot1",
      "id_project":"5b55e806c93dde00143163dd",
      "trashed":false,
      "createdBy":"5ab0f3fa57066e0014bfd71e",
      "__v":0,
      "external":false
   }
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X PUT -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d '{"name":"bot1"}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/bots/5be9b2ecc72a050015e14951
```

***

## Delete a bot

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/bots/:id`

Allows to delete a bot.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The bot identifier                                                                       |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
{
      "_id":"5be9b2ecc72a050015e14951",
      "updatedAt":"2018-11-12T17:05:50.616Z",
      "createdAt":"2018-11-12T17:05:48.544Z",
      "name":"bot1",
      "id_project":"5b55e806c93dde00143163dd",
      "trashed":false,
      "createdBy":"5ab0f3fa57066e0014bfd71e",
      "__v":0,
      "external":false
   }
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X DELETE -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/bots/5be9b2ecc72a050015e14951
```


# Knowledge Bases


# Knowledge Base

Manage contents for your chatbot instant replies using our RAG engine. Populate your KBs using your own contents (URLs, sitemaps, pdfs, docx, text or FAQs). Our semantic engine will help you provide the best answers based on user questions using advanced Semantic indexing and the OpenAI generative AI. [More info](https://gethelp.tiledesk.com/categories/knowledge-base/)

### The Knowledge Base model

| Key               | Type    | Description                                                                                                      |
| ----------------- | ------- | ---------------------------------------------------------------------------------------------------------------- |
| id                | String  | The unique identifier for the knowledge base which is given by Tiledesk.                                         |
| name              | String  | The knowledge base name.                                                                                         |
| id\_project       | String  | The unique identifier of the project                                                                             |
| preview\_settings | Object  | The settings for the knowledge base preview                                                                      |
| default           | Boolean | Specifies if the knowledge base is the default one                                                               |
| hybrid            | Boolean | Specifies if the knowledge base is hybrid. Default is false (standard type)                                      |
| engine            | Object  | Specifies the configuration of the vector store system used by the knowledge base. A default engine is provided. |
| embedding         | Object  | Indicates which embeddings are used for vector-based search. A default embedding is present.                     |

## Get all knowledge bases

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/kb/namespace/all`

Allows to list all the knowledge bases of a project. Returns at least the default knowledge base.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
[
    {
        "default": true,
        "id_project": "63ad512e70d5ed0012ad6286",
        "id": "63ad512e70d5ed0012ad6286",
        "name": "Customer Support",
        "preview_settings": {
            "model": "gpt-3.5-turbo",
            "max_tokens": 128,
            "temperature": 0.7,
            "top_k": 4,
            "context": "You are an awesome AI Assistant."
        },
        "createdAt": "2024-06-20T13:49:04.006Z",
        "updatedAt": "2024-06-21T10:52:55.235Z"
    },
    {
        "default": false,
        "id_project": "63ad512e70d5ed0012ad6286",
        "id": "66755b6b9fee7f001357bc7f",
        "name": "Sales",
        "preview_settings": {
            "model": "gpt-3.5-turbo",
            "max_tokens": 128,
            "temperature": 0.7,
            "top_k": 4,
            "context": "You are an awesome AI Assistant."
        },
        "createdAt": "2024-06-21T10:52:27.111Z",
        "updatedAt": "2024-06-21T10:52:27.111Z"
    }
]
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u giovanni@tiledesk.com:password https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/namespace/all
```

***

## Create new knowledge base

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/kb/namespace`

Allows to create a new knowledge base for a project.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

#### Request Body

| Name | Type   | Description                     |
| ---- | ------ | ------------------------------- |
| name | string | The name of the knowledge base. |

{% tabs %}
{% tab title="200 " %}

```
{
    "default": false,
    "id_project": "63ad512e70d5ed0012ad6286",
    "id": "6675a1b3c08d0b00141c415b",
    "name": "Products",
    "preview_settings": {
        "model": "gpt-3.5-turbo",
        "max_tokens": 128,
        "temperature": 0.7,
        "top_k": 4,
        "context": "You are an awesome AI Assistant."
    },
    "createdAt": "2024-06-21T15:52:19.036Z",
    "updatedAt": "2024-06-21T15:52:19.036Z"
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u giovanni@tiledesk.com:password -d '{"name": "Products"}' https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/namespace
```

***

## Update a knowledge base

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/kb/namespace/:id`

Allows to update a knowledge base info and preview settings.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| id          | string | The unique identifier for the knowledge base                                             |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

#### Request Body

| Name              | Type   | Description                                      |
| ----------------- | ------ | ------------------------------------------------ |
| name              | string | The name of the knowledge base.                  |
| preview\_settings | object | The AI settings for the knowledge base settings. |

{% tabs %}
{% tab title="200 " %}

```
{
    "default": false,
    "id_project": "63ad512e70d5ed0012ad6286",
    "id": "6675a1b3c08d0b00141c415b",
    "name": "New Products",
    "preview_settings": {
        "model": "gpt-4o",
        "max_tokens": 256,
        "temperature": 0.5,
        "top_k": 5,
        "context": "Custom context."
    },
    "createdAt": "2024-06-21T15:52:19.036Z",
    "updatedAt": "2024-06-24T08:37:32.313Z"
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X PUT -u giovanni@tiledesk.com:password -d '{"name": "New Products", "preview_settings": { "model": "gpt-4o", "max_tokens": 256, "temperature": 0.5, "top_k": 5,"context": "Custom context." }}' 
https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/namespace/6675a1b3c08d0b00141c415b
```

***

## Delete a knowledge base

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/kb/namespace/:id`

Allows to delete the whole knowledge base or it's contents only.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| id          | string | The unique identifier for the knowledge base                                             |

#### Query Parameters

| Name           | Type    | Description                                          |
| -------------- | ------- | ---------------------------------------------------- |
| contents\_only | boolean | (Optional) if TRUE will be deleted only the contents |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
{
    "success": true,
    "message": "Namespace deleted succesfully"
}
```

{% endtab %}
{% endtabs %}

Example

```

curl -v -X DELETE -u giovanni@tiledesk.com:password -d https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/namespace/6675a1b3c08d0b00141c415b
```


# Contents

Manage contents of your Knowledge Bases.

### The Content model

| Key         | Type   | Description                                                                                                            |
| ----------- | ------ | ---------------------------------------------------------------------------------------------------------------------- |
| \_id        | String | The unique identifier for the contents which is given by Tiledesk.                                                     |
| name        | String | The content name.                                                                                                      |
| id\_project | String | The unique identifier of the project                                                                                   |
| type        | String | The type of the content. Supported types: url, text, pdf, docx, faq                                                    |
| source      | String | The content source.                                                                                                    |
| content     | String | The textual content of a source. Is empty if the type is not text                                                      |
| namespace   | String | The namespace id to which the content belongs                                                                          |
| status      | Number | The content status. Admissible status: -1 (not in queue), 100 (in queue), 200 (in indexing),300 (indexed), 400 (error) |

## Get all contents of a knowledge base

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/kb/`

Allows to list all the content of a knowledge base

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Query Parameters

| Name      | Type   | Description                                                                                       |
| --------- | ------ | ------------------------------------------------------------------------------------------------- |
| namespace | string | The Namespace Id is a unique code assigned to your knowledge base when you create it in Tiledesk. |
| status    | number | (Optional) To list all content in a determined indexing status.                                   |
| type      | string | (Optional) To list all content of a determined status.                                            |
| limit     | number | (Optional) Determines the number of contents returned (used for pagination).                      |
| page      | number | (Optional) Determines the number of the page (used for pagination).                               |
| sortField | string | (Optional) Determines the field on which to sort.                                                 |
| direction | number | (Optional) Determines the sorting direction. -1 (descending order), 1 (ascending order)           |
| search    | string | (Optional) The text to search for in the source field                                             |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
{
    "count": 2,
    "query": {
        "limit": 20,
        "sortField": "updatedAt",
        "direction": -1
    },
    "kbs": [
        {
            "_id": "667941c90d6bac990eb908da",
            "id_project": "63ad512e70d5ed0012ad6286",
            "source": "Return an item",
            "type": "text",
            "__v": 0,
            "content": "Return an item content sample",
            "createdAt": "2024-06-24T09:52:09.613Z",
            "name": "Return an item",
            "namespace": "63ad512e70d5ed0012ad6286",
            "status": 300,
            "updatedAt": "2024-06-24T09:52:11.698Z"
        },
        {
            "_id": "6679419c0d6bac990eb8452f",
            "id_project": "63ad512e70d5ed0012ad6286",
            "source": "Shipping information",
            "type": "text",
            "__v": 0,
            "content": "Shipping informazione content sample.",
            "createdAt": "2024-06-24T09:51:24.835Z",
            "name": "Shipping information",
            "namespace": "63ad512e70d5ed0012ad6286",
            "status": 300,
            "updatedAt": "2024-06-24T09:51:26.278Z"
        }
    ]
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u giovanni@tiledesk.com:password https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb?direction=-1&sortField=updatedAt&namespace=63ad512e70d5ed0012ad6286&limit=20
```

***

## Get content detail

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/kb/:content_id`

Allows to get the content detail

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| content\_id | string | The content Id is a unique code assigned to your content.                                |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
{
    "_id": "66794d310d6bac990ef72ed3",
    "id_project": "63ad512e70d5ed0012ad6286",
    "source": "Shipping information",
    "type": "text",
    "__v": 0,
    "content": "Shipping information content sample.",
    "createdAt": "2024-06-24T09:51:24.835Z",
    "name": "Shipping information",
    "namespace": "63ad512e70d5ed0012ad6286",
    "status": 300,
    "updatedAt": "2024-06-24T09:51:26.278Z"
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u giovanni@tiledesk.com:password https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/66794d310d6bac990ef72ed3
```

***

## Add a content to a knowledge base

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/kb/`

Allows to create and add a content to a specific knwoledge base

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

#### Request Body

| Name      | Type   | Description                                                                                                                                   |
| --------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
| name      | string | The name of the content                                                                                                                       |
| type      | string | The type of the content. It can be text, url, pdf, docx or faq.                                                                               |
| source    | string | The source name of a content. If the content type is url, pdf or docx the source field must be the resource's url.                            |
| content   | string | The content field of the content entity. Is empty if the type is url, pdf or docx. If the type is faq the content should be Question\nAnswer. |
| namespace | string | The namespace id to which the content belongs.                                                                                                |

{% tabs %}
{% tab title="200 " %}

```
{
    "lastErrorObject": {
        "n": 1,
        "updatedExisting": false,
        "upserted": "6679502d0d6bac990e06c2fb"
    },
    "value": {
        "_id": "6679502d0d6bac990e06c2fb",
        "id_project": "63ad512e70d5ed0012ad6286",
        "source": "https://eu.rtmv3.tiledesk.com/api/files?path=uploads/users/63ad512170d5ed0012ad6279/files/09d40382-3755-4d87-8cb5-e345b7fcf418/my_awesome_file.pdf",
        "type": "pdf",
        "__v": 0,
        "content": "",
        "createdAt": "2024-06-24T10:53:33.368Z",
        "name": "my_awesome_file.pdf",
        "namespace": "63ad512e70d5ed0012ad6286",
        "status": -1,
        "updatedAt": "2024-06-24T10:53:33.368Z"
    }
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X POST -u giovanni@tiledesk.com:password https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/ -d '{"type":"pdf","source":"https://eu.rtmv3.tiledesk.com/api/files?path=uploads/users/63ad512170d5ed0012ad6279/files/09d40382-3755-4d87-8cb5-e345b7fcf418/my_awesome_file.pdf","content":"","name":"my_awesome_file.pdf","namespace":"63ad512e70d5ed0012ad6286"}'
```

***

## Add multiple URL contents to a knowledge base

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/kb/multi`

Allows to add more than one content of type url to a specific knwoledge base in a single operation.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Query Parameters

| Name      | Type   | Description                                                                                       |
| --------- | ------ | ------------------------------------------------------------------------------------------------- |
| namespace | string | The Namespace Id is a unique code assigned to your knowledge base when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

#### Request Body

| Name | Type  | Description                                          |
| ---- | ----- | ---------------------------------------------------- |
| list | array | The array of URLs to be added to the knwoledge base. |

{% tabs %}
{% tab title="200 " %}

```
[
    {
        "_id": "667954840d6bac990e1dc383",
        "id_project": "63ad512e70d5ed0012ad6286",
        "source": "https://mysite.com/content_1",
        "type": "url",
        "content": "",
        "createdAt": "2024-06-24T11:12:04.080Z",
        "name": "https://mysite.com/content_1",
        "namespace": "63ad512e70d5ed0012ad6286",
        "status": -1,
        "updatedAt": "2024-06-24T11:12:04.080Z"
    },
    {
        "_id": "667954840d6bac990e1dc399",
        "id_project": "63ad512e70d5ed0012ad6286",
        "source": "https://mysite.com/content_2",
        "type": "url",
        "content": "",
        "createdAt": "2024-06-24T11:12:04.080Z",
        "name": "https://mysite.com/content_2",
        "namespace": "63ad512e70d5ed0012ad6286",
        "status": -1,
        "updatedAt": "2024-06-24T11:12:04.080Z"
    },
    {
        "_id": "667954840d6bac990e1dc3be",
        "id_project": "63ad512e70d5ed0012ad6286",
        "source": "https://mysite.com/content_3",
        "type": "url",
        "content": "",
        "createdAt": "2024-06-24T11:12:04.080Z",
        "name": "https://mysite.com/content_3",
        "namespace": "63ad512e70d5ed0012ad6286",
        "status": -1,
        "updatedAt": "2024-06-24T11:12:04.080Z"
    }
]
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X POST -u giovanni@tiledesk.com:password https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/multi?namespace=63ad512e70d5ed0012ad6286 -d '{"list": [ 'https://mysite.com/content_1', 'https://mysite.com/content_2', 'https://mysite.com/content_3']}'
```

***

## Convert a sitemap in a list of URLs

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/kb/sitemap`

Allows to convert a sitemap into a list of urls to be uploaded later in a single operation.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

#### Request Body

| Name | Type  | Description                                          |
| ---- | ----- | ---------------------------------------------------- |
| list | array | The array of URLs to be added to the knwoledge base. |

{% tabs %}
{% tab title="200 " %}

```
{
    "url": "https://gethelp.tiledesk.com/sitemap.xml",
    "sites": [
        "https://gethelp.tiledesk.com/articles/activities-log/",
        "https://gethelp.tiledesk.com/articles/define-the-operating-hours/",
        "https://gethelp.tiledesk.com/articles/how-do-invite-a-teammate/",
        "https://gethelp.tiledesk.com/articles/understanding-default-roles/",
        ...
    ],
    "errors": []
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X POST -u giovanni@tiledesk.com:password https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/sitemap -d '{"sitemap": "https://gethelp.tiledesk.com/sitemap.xml" }'
```

***

## Delete a content from the knowledge base

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/kb/:content_id`

Allows to delete a single content from the knowledge base.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| content\_id | string | The Content Id is a unique code assigned to your contnet when you create it.             |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
{
    "_id": "66794d950d6bac990ef90e3d",
    "id_project": "63ad512e70d5ed0012ad6286",
    "source": "Use a Voucher",
    "type": "text",
    "__v": 0,
    "content": "Use a Voucher content sample",
    "createdAt": "2024-06-24T10:42:29.798Z",
    "name": "Use a Voucher",
    "namespace": "63ad512e70d5ed0012ad6286",
    "status": 300,
    "updatedAt": "2024-06-24T10:42:31.202Z"
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X POST -u giovanni@tiledesk.com:password https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/66794d950d6bac990ef90e3d
```

***


# Question & Answer

Allows to query the knowledge base using a specific AI model.

### The Knowledge Base model

| Key               | Type    | Description                                                                                                      |
| ----------------- | ------- | ---------------------------------------------------------------------------------------------------------------- |
| id                | String  | The unique identifier for the knowledge base which is given by Tiledesk.                                         |
| name              | String  | The knowledge base name.                                                                                         |
| id\_project       | String  | The unique identifier of the project                                                                             |
| preview\_settings | Object  | The settings for the knowledge base preview                                                                      |
| default           | Boolean | Specifies if the knowledge base is the default one                                                               |
| hybrid            | Boolean | Specifies if the knowledge base is hybrid. Default is false (standard type)                                      |
| engine            | Object  | Specifies the configuration of the vector store system used by the knowledge base. A default engine is provided. |
| embedding         | Object  | Indicates which embeddings are used for vector-based search. A default embedding is present.                     |

## Ask the Knowledge Base

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/kb/qa`

Allows to query the knowledge base using a specific AI model.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

#### Request Body

| Name            | Type    | Description                                                                                                        |
| --------------- | ------- | ------------------------------------------------------------------------------------------------------------------ |
| question        | string  | The question submitted                                                                                             |
| namespace       | string  | The id of the Knowledge Base in which to search for the answer                                                     |
| llm             | string  | (Optional) The LLM to use to generate the response (Default: "openai")                                             |
| model           | string  | The model to use to generate the response (e.g. gpt-4o)                                                            |
| max\_tokens     | Number  | The maximum number of tokens that can be consumed to generate the response                                         |
| temperature     | Number  | Defines creativity in generating responses (low values ​​determine more specific and predictable responses)        |
| top\_k          | Number  | The number of nearby chunks to use to generate the response                                                        |
| engine          | Object  | (Optional) The engine configuration object to use for the vector store system if different from the Default Engine |
| embedding       | Object  | (Optional) The embedding object to use for the embedding generation if different from the Default Engine           |
| system\_context | string  | (Optional) The context to give to the AI ​​to shape its behavior in generating the response.                       |
| alpha           | Number  | (Optional) Defines the balance of hybrid search (0 = full-text focused, 1 = semantic/vector focused).              |
| chunks\_only    | Boolean | (Optional) Returns only the retrieved text chunks without generating a final answer.                               |
| stream          | Boolean | (Optional) Enables real-time streaming of the response as it is generated.                                         |
| citations       | Boolean | (Optional) Includes source references for the retrieved or generated content.                                      |
| tags            | Array   | (Optional) Filters or categorizes results based on associated tags.                                                |
| rereanking      | Boolean | (Optional) Applies a secondary ranking step to improve the relevance of retrieved results.                         |

{% tabs %}
{% tab title="200 " %}

```
{
    "answer": "To create an AI assistant using OpenAI, you can follow these steps:\n\n1. **Visit OpenAI**: Navigate to the OpenAI website.\n2. **Access the API Section**:\n   - Go to ‘Products’, then select ‘API’.\n   - Log in and select ‘API’.\n3. **Navigate to Assistant Creation**:\n   - Ensure you are on the Dashboard.\n   - Click on ‘Assistant’ from the left sidebar menu.\n4. **Create the Assistant**:\n   - Click the green ‘Create’ button in the top right corner.\n   - Name your assistant and provide context in the ‘Instructions’ section to fine-tune its responses.\n5. **Select the Model**:\n   - For this example, you can use GPT-4o.\n6. **Handle File Formats**:\n   - If uploading a CSV file, use a Code interpreter.\n   - For PDF or text files, use the File Search feature.\n7. **Integrate with Tiledesk**:\n   - Copy the assistant ID.\n   - Go to the Tiledesk dashboard, click on the block where the ChatGPT Assistant is placed.\n   - In the right-side menu, paste the assistant ID into the “Assign GPT Assistant” field.\n\nIf you need",
    "success": true,
    "namespace": "66a897133eaa7f0013632c5b",
    "id": "66b6268722af86ab6a739cb6",
    "ids": [
        "66b6268722af86ab6a739cb6"
    ],
    "source": "https://gethelp.tiledesk.com/articles/create-an-ai-assistant-in-openai/",
    "sources": [
        "https://gethelp.tiledesk.com/articles/create-an-ai-assistant-in-openai/"
    ],
    "content_chunks": null,
    "prompt_token_size": 1185,
    "error_message": null,
    "chat_history_dict": {
        "0": {
            "question": "how can i create an AI assistant?",
            "answer": "To create an AI assistant using OpenAI, you can follow these steps:\n\n1. **Visit OpenAI**: Navigate to the OpenAI website.\n2. **Access the API Section**:\n   - Go to ‘Products’, then select ‘API’.\n   - Log in and select ‘API’.\n3. **Navigate to Assistant Creation**:\n   - Ensure you are on the Dashboard.\n   - Click on ‘Assistant’ from the left sidebar menu.\n4. **Create the Assistant**:\n   - Click the green ‘Create’ button in the top right corner.\n   - Name your assistant and provide context in the ‘Instructions’ section to fine-tune its responses.\n5. **Select the Model**:\n   - For this example, you can use GPT-4o.\n6. **Handle File Formats**:\n   - If uploading a CSV file, use a Code interpreter.\n   - For PDF or text files, use the File Search feature.\n7. **Integrate with Tiledesk**:\n   - Copy the assistant ID.\n   - Go to the Tiledesk dashboard, click on the block where the ChatGPT Assistant is placed.\n   - In the right-side menu, paste the assistant ID into the “Assign GPT Assistant” field.\n\nIf you need"
        }
    }
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u giovanni@tiledesk.com:password -d {"question":"how can i create an AI assistant?","namespace":"66a897133eaa7f0013632c5b","model":"gpt-4o","temperature":0.7,"max_tokens":256,"top_k":4,"system_context":null} https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/qa
```

***


# Unanswered Questions

Stores questions that did not receive a satisfactory answer from the knowledge base, scoped by project and knowledge base (`namespace`). All routes require authentication; the namespace must belong to the current project.

### Unanswered question object

Defined by the Mongoose schema: `id_project`, `namespace`, and `question` are required; `timestamps: true` adds `createdAt` and `updatedAt`.

| Key          | Type   | Description                                              |
| ------------ | ------ | -------------------------------------------------------- |
| `_id`        | String | Unique identifier of the unanswered question document.   |
| `id_project` | String | Project identifier (set from the authenticated request). |
| `namespace`  | String | Knowledge base identifier (same as KB `id`).             |
| `question`   | String | The user question text.                                  |
| `createdAt`  | String | Creation time (ISO date).                                |
| `updatedAt`  | String | Last update time (ISO date)                              |

## Add an unanswered question

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/kb/unanswered`

Creates a new unanswered question for the given knowledge base namespace.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

#### Request Body

| Name      | Type   | Description                                                                      |
| --------- | ------ | -------------------------------------------------------------------------------- |
| namespace | string | (Required) Knowledge base id the question refers to. Must belong to the project. |
| question  | string | (Required) The question text to store.                                           |

{% tabs %}
{% tab title="200 Created document" %}

```
{
    "_id": "671a1b2c3d4e5f6789012345",
    "id_project": "63ad512e70d5ed0012ad6286",
    "namespace": "66a897133eaa7f0013632c5b",
    "question": "How do I reset my password?",
    "createdAt": "2025-10-24T12:00:00.000Z",
    "updatedAt": "2025-10-24T12:00:00.000Z"
}
```

{% endtab %}

{% tab title="400 Missing `namespace` or `question`" %}

```
{
    "success": false,
    "error": "Missing required parameters: namespace and question"
}
```

{% endtab %}

{% tab title="403 Namespace does not belong to the project" %}

```
{
    "success": false,
    "error": "Not allowed. The namespace does not belong to the current project."
}
```

{% endtab %}

{% tab title="500 Server error" %}

```
{
    "success": false,
    "error": "Error adding unanswered question"
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X POST -u user@example.com:password \
  -H "Content-Type: application/json" \
  -d '{"namespace":"66a897133eaa7f0013632c5b","question":"How do I reset my password?"}' \
  https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/unanswered
```

***

## Count unanswered questions

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/kb/unanswered/count/:namespace`

Returns the total number of unanswered questions for a namespace. In the API implementation, this route should be registered before the generic list route so that the path segment `count` is not interpreted as a namespace.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| namespace   | string | Knowledge base id.                                                                       |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
{
    "count": 42
}
```

{% endtab %}

{% tab title="400 Missing namespace" %}

```
{
    "success": false,
    "error": "Missing required parameter: namespace"
}
```

{% endtab %}

{% tab title="403 Namespace does not belong to the project" %}

```
{
    "success": false,
    "error": "Not allowed. The namespace does not belong to the current project."
}
```

{% endtab %}

{% tab title="500 Server error" %}

```
{
    "success": false,
    "error": "Error counting unanswered questions"
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u user@example.com:password \
  https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/unanswered/count/66a897133eaa7f0013632c5b
```

***

## List unanswered questions

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/kb/unanswered/:namespace`

Returns a paginated list of unanswered questions for a namespace. Default pagination: `page` 0, `limit` 20. Default sort: field `createdAt`, direction `-1` (descending). `direction` is numeric: `-1` for descending, `1` for ascending.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| namespace   | string | Knowledge base id.                                                                       |

#### Query Parameters

| Name      | Type    | Description                                                                           |
| --------- | ------- | ------------------------------------------------------------------------------------- |
| page      | integer | Page index (0-based). Default: `0`.                                                   |
| limit     | integer | Page size. Default: `20`.                                                             |
| sortField | string  | Field to sort by (any field on the document, e.g. `createdAt`). Default: `createdAt`. |
| direction | integer | Sort direction (`-1` or `1`). Default: `-1`.                                          |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
{
    "count": 2,
    "questions": [
        {
            "_id": "671a1b2c3d4e5f6789012345",
            "id_project": "63ad512e70d5ed0012ad6286",
            "namespace": "66a897133eaa7f0013632c5b",
            "question": "How do I reset my password?",
            "createdAt": "2025-10-24T12:00:00.000Z",
            "updatedAt": "2025-10-24T12:00:00.000Z"
        }
    ],
    "query": {
        "page": 0,
        "limit": 20,
        "sortField": "createdAt",
        "direction": -1
    }
}
```

{% endtab %}

{% tab title="400 Missing namespace" %}

```
{
    "success": false,
    "error": "Missing required parameter: namespace"
}
```

{% endtab %}

{% tab title="403 Namespace does not belong to the project" %}

```
{
    "success": false,
    "error": "Not allowed. The namespace does not belong to the current project."
}
```

{% endtab %}

{% tab title="500 Server error" %}

```
{
    "success": false,
    "error": "Error getting unanswered questions"
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u user@example.com:password \
  "https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/unanswered/66a897133eaa7f0013632c5b?page=0&limit=20&sortField=createdAt&direction=-1"
```

***

## Delete an unanswered question

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/kb/unanswered/:id`

Deletes a single unanswered question by its document id. The question must belong to the current project.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| id          | string | The unanswered question document id (`_id`).                                             |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
{
    "success": true,
    "message": "Question deleted successfully"
}
```

{% endtab %}

{% tab title="404 No document for this id and project" %}

```
{
    "success": false,
    "error": "Question not found"
}
```

{% endtab %}

{% tab title="500 Server error" %}

```
{
    "success": false,
    "error": "Error deleting unanswered question"
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X DELETE -u user@example.com:password \
  https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/unanswered/671a1b2c3d4e5f6789012345
```

***

## Delete all unanswered questions for a namespace

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/kb/unanswered/namespace/:namespace`

Removes every unanswered question stored for the given knowledge base namespace within the project.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| namespace   | string | Knowledge base id.                                                                       |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | Authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
{
    "success": true,
    "count": 15,
    "message": "All questions deleted successfully"
}
```

{% endtab %}

{% tab title="403 Namespace does not belong to the project" %}

```
{
    "success": false,
    "error": "Not allowed. The namespace does not belong to the current project."
}
```

{% endtab %}

{% tab title="500 Server error" %}

```
{
    "success": false,
    "error": "Error deleting unanswered questions"
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X DELETE -u user@example.com:password \
  https://api.tiledesk.com/v3/63ad512e70d5ed0012ad6286/kb/unanswered/namespace/66a897133eaa7f0013632c5b
```

***


# Management Api


# Departments

## The Department model

| Key         | Type    | Description                                                          |
| ----------- | ------- | -------------------------------------------------------------------- |
| id          | String  | The unique identifier for the department which is given by Tiledesk. |
| name        | String  | The department name.                                                 |
| id\_bot     | Array   | The bot identifier associated to the department                      |
| routing     | String  | The department routing type. Permitted values: 'assigned', 'pooled'  |
| id\_group   | String  | The group identifier associated to the department                    |
| default     | Boolean | Determines if it is the default department                           |
| status      | Number  | The request status: VISIBLE : 1, INVISIBLE : 0                       |
| attributes  | Object  | The custom attributes which are set for the department.              |
| createdAt   | String  | The time when the department was created.                            |
| updatedAt   | String  | The time when the department was updated.                            |
| createdBy   | String  | The unique identifier of the row creator                             |
| id\_project | String  | The unique identifier of the project                                 |
| groups      | Array   | The array of groups associated to the department                     |

## Get all active departments

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/departments`

Allows an account to list all the active departments of the project.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
[
   {
      "_id":"5b55e806c93dde00143163df",
      "updatedAt":"2019-08-02T08:08:22.292Z",
      "createdAt":"2018-07-23T14:36:54.410Z",
      "name":"Default Department",
      "id_project":"5b55e806c93dde00143163dd",
      "createdBy":"5aaa99024c3b110014b478f0",
      "online_msg":"Describe shortly your problem, you will be contacted by an agent..",
      "offline_msg":"",
      "__v":0,
      "id_bot":"5be9b2ecc72a050015e14951",
      "status":1,
      "default":true,
      "routing":"assigned"
   }
]
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/departments
```

## Get all departments (active or hidden)

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/departments/allstatus`

Allows an account to list all the departments of the project.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
[
   {
      "_id":"5b55e806c93dde00143163df",
      "updatedAt":"2019-08-02T08:08:22.292Z",
      "createdAt":"2018-07-23T14:36:54.410Z",
      "name":"Default Department",
      "id_project":"5b55e806c93dde00143163dd",
      "createdBy":"5aaa99024c3b110014b478f0",
      "online_msg":"Describe shortly your problem, you will be contacted by an agent..",
      "offline_msg":"",
      "__v":0,
      "id_bot":"5be9b2ecc72a050015e14951",
      "status":1,
      "default":true,
      "routing":"assigned"
   }
]
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/departments/allstatus
```

## Get a department by id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/departments`

Allows an account to get a department of the project.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |
| id          | string | The department identifier                                                                |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
   {
      "_id":"5b55e806c93dde00143163df",
      "updatedAt":"2019-08-02T08:08:22.292Z",
      "createdAt":"2018-07-23T14:36:54.410Z",
      "name":"Default Department",
      "id_project":"5b55e806c93dde00143163dd",
      "createdBy":"5aaa99024c3b110014b478f0",
      "online_msg":"Describe shortly your problem, you will be contacted by an agent..",
      "offline_msg":"",
      "__v":0,
      "id_bot":"5be9b2ecc72a050015e14951",
      "status":1,
      "default":true,
      "routing":"assigned"
   }
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/departments/5b55e806c93dde00143163df
```

## Create a new department

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/departments`

Allows to add more departments.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name      | Type   | Description                                                                                                                      |
| --------- | ------ | -------------------------------------------------------------------------------------------------------------------------------- |
| name      | string | The department name                                                                                                              |
| routing   | string | Optional. The department routing type. Permitted values: 'assigned', 'pooled' (default)                                          |
| id\_group | string | Optional. The group of users assigned to the department. If not provided the request will be routed through all available users. |
| id\_bot   | string | Optional. The bot assigned to the department, if any.                                                                            |

{% tabs %}
{% tab title="200 " %}

```
 {
      "_id":"5b55e806c93dde00143163df",
      "updatedAt":"2019-08-02T08:08:22.292Z",
      "createdAt":"2018-07-23T14:36:54.410Z",
      "name":"Default Department",
      "id_project":"5b55e806c93dde00143163dd",
      "createdBy":"5aaa99024c3b110014b478f0",
      "online_msg":"Describe shortly your problem, you will be contacted by an agent..",
      "offline_msg":"",
      "__v":0,
      "id_bot":"5be9b2ecc72a050015e14951",
      "status":1,
      "default":true,
      "routing":"assigned"
   }
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X POST -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d '{"name":"new department1", "routing":"pooled"}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/departments
```

## Update a department

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/departments/:id`

Allows to update a department.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The department identifier                                                                |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name      | Type   | Description                                                                                                                                                                              |
| --------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name      | string | The department name                                                                                                                                                                      |
| routing   | string | Optional. The department routing type. Permitted values: 'assigned', 'pooled' (default)                                                                                                  |
| id\_group | string | Optional. The group of users assigned to the department. If not provided the request will be routed through all available users.                                                         |
| groups    | array  | Optional. The groups assigned to the department with the id\_group and percentage for dynamic load distribution. If not provided the request will be routed through all available users. |
| id\_bot   | string | Optional. The bot assigned to the department, if any.                                                                                                                                    |

{% tabs %}
{% tab title="200 " %}

```
 {
      "_id":"5b55e806c93dde00143163df",
      "updatedAt":"2019-08-02T08:08:22.292Z",
      "createdAt":"2018-07-23T14:36:54.410Z",
      "name":"Default Department",
      "id_project":"5b55e806c93dde00143163dd",
      "createdBy":"5aaa99024c3b110014b478f0",
      "online_msg":"Describe shortly your problem, you will be contacted by an agent..",
      "offline_msg":"",
      "__v":0,
      "id_bot":"5be9b2ecc72a050015e14951",
      "status":1,
      "default":true,
      "routing":"pooled",
      "groups": [
         {
            "id_group": "6877b2eb1568590013b57fde",
            "percentage": 70
         },
         {
            "id_group": "68c9156171b6b900145f117b",
            "percentage": 30
         }
      ]
   }
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X PUT -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d '{"name":"new department1", "routing":"pooled", "groups": [{ "id_group": "6877b2eb1568590013b57fde", "percentage": 70 }, { "id_group": "68c9156171b6b900145f117b", "percentage": 30 }]}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/departments/5b55e806c93dde00143163df
```

## Delete a department

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/departments/:id`

Allows to delete a department.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The department identifier                                                                |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
 {
      "_id":"5b55e806c93dde00143163df",
      "updatedAt":"2019-08-02T08:08:22.292Z",
      "createdAt":"2018-07-23T14:36:54.410Z",
      "name":"Default Department",
      "id_project":"5b55e806c93dde00143163dd",
      "createdBy":"5aaa99024c3b110014b478f0",
      "online_msg":"Describe shortly your problem, you will be contacted by an agent..",
      "offline_msg":"",
      "__v":0,
      "id_bot":"5be9b2ecc72a050015e14951",
      "status":1,
      "default":true,
      "routing":"assigned"
   }
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X DELETE -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/departments/5b55e806c93dde00143163df
```


# Groups

## The Group model

| Key         | Type    | Description                                                     |
| ----------- | ------- | --------------------------------------------------------------- |
| id          | String  | The unique identifier for the group which is given by Tiledesk. |
| name        | String  | The group name.                                                 |
| members     | Array   | The group members                                               |
| trashed     | Boolean | Determine if the group is deleted                               |
| attributes  | Object  | The custom attributes which are set for the group.              |
| createdAt   | String  | The time when the group was created.                            |
| updatedAt   | String  | The time when the group was updated.                            |
| createdBy   | String  | The unique identifier of the row creator                        |
| id\_project | String  | The unique identifier of the project                            |

## Get all groups

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/groups`

Allows an account to list all the groups of the project.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
[
   {
      "_id":"5c34b5149f22a7001681e887",
      "updatedAt":"2019-01-08T14:35:09.621Z",
      "createdAt":"2019-01-08T14:35:00.625Z",
      "name":"gruppo1",
      "trashed":false,
      "id_project":"5b55e806c93dde00143163dd",
      "createdBy":"5ab0f3fa57066e0014bfd71e",
      "__v":0,
      "members":[
         "5ad5bd40c975820014ba9009"
      ]
   },
   {
      "_id":"5c34b52a9f22a7001681e888",
      "updatedAt":"2019-01-08T14:35:29.678Z",
      "createdAt":"2019-01-08T14:35:22.489Z",
      "name":"gruppo2",
      "trashed":false,
      "id_project":"5b55e806c93dde00143163dd",
      "createdBy":"5ab0f3fa57066e0014bfd71e",
      "__v":0,
      "members":[
         "5ab0f3fa57066e0014bfd71e"
      ]
   }
]
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X GET -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/groups
```

## Get the group by id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/groups/:id`

Fetche the group by his or her id

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| id          | string | the group identifier                                                                     |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
  {
   "_id":"5c34b52a9f22a7001681e888",
   "updatedAt":"2019-01-08T14:35:29.678Z",
   "createdAt":"2019-01-08T14:35:22.489Z",
   "name":"gruppo2",
   "trashed":false,
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5ab0f3fa57066e0014bfd71e",
   "__v":0,
   "members":[
      "5ab0f3fa57066e0014bfd71e"
   ]
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X GET -u andrea.leo@f21.it:123456 https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/groups/5c34b52a9f22a7001681e888
```

## Create a new group

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/groups`

Allows to add more groups.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name    | Type   | Description            |
| ------- | ------ | ---------------------- |
| name    | string | The group name         |
| members | array  | The group members ids. |

{% tabs %}
{% tab title="200 " %}

```
 {
   "_id":"5c34b52a9f22a7001681e888",
   "updatedAt":"2019-01-08T14:35:29.678Z",
   "createdAt":"2019-01-08T14:35:22.489Z",
   "name":"gruppo2",
   "trashed":false,
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5ab0f3fa57066e0014bfd71e",
   "__v":0,
   "members":[
      "5ab0f3fa57066e0014bfd71e"
   ]
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X POST -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d '{"name":"new group1", "members":["5ab0f3fa57066e0014bfd71e"]}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/groups
```

## Update a group

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/groups/:id`

Allows to update a group.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The group identifier                                                                     |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name    | Type   | Description            |
| ------- | ------ | ---------------------- |
| name    | string | The group name         |
| members | array  | The group members ids. |

{% tabs %}
{% tab title="200 " %}

```
 {
   "_id":"5c34b52a9f22a7001681e888",
   "updatedAt":"2019-01-08T14:35:29.678Z",
   "createdAt":"2019-01-08T14:35:22.489Z",
   "name":"gruppo2",
   "trashed":false,
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5ab0f3fa57066e0014bfd71e",
   "__v":0,
   "members":[
      "5ab0f3fa57066e0014bfd71e"
   ]
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X PUT -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  -d '{"name":"new group1", "members":["5ab0f3fa57066e0014bfd71e"]}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/groups/groups/5c34b52a9f22a7001681e888
```

## Delete a group

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/groups/:id`

Allows to delete a group.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | The group identifier                                                                     |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
 {
   "_id":"5c34b52a9f22a7001681e888",
   "updatedAt":"2019-01-08T14:35:29.678Z",
   "createdAt":"2019-01-08T14:35:22.489Z",
   "name":"gruppo2",
   "trashed":false,
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5ab0f3fa57066e0014bfd71e",
   "__v":0,
   "members":[
      "5ab0f3fa57066e0014bfd71e"
   ]
}
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X DELETE -H 'Content-Type: application/json' -u andrea.leo@f21.it:123456  https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/groups/5c34b52a9f22a7001681e888
```


# NodeJS SDK

Full [NodeJS API reference](https://tiledesk.github.io/tiledesk-nodejs-libs/TiledeskClient.html) is hosted on Github

## Introduction

With this guide you will learn how to use the Tiledesk JavaScript SDK in your `Node.js` application. Tiledesk Javascript SDK is built on top of [Tiledesk REST APIs](https://developer.tiledesk.com/apis/rest-api/introduction).

Before you add Tiledesk SDK to your Node.js app, you need a [Tiledesk account](https://gethelp.tiledesk.com/articles/creating-a-tiledesk-account/) and a [Tiledesk project](https://docs.tiledesk.com/knowledge-base/creating-a-tiledesk-account/). Once you create your project you will have a *projectID*, a *user* to play with the project's APIs, a *project secret* for custom authentication and all the stuff needed to work with Tiledesk and his APIs.

## Add Tiledesk to your project

Install `TiledeskClient` library with *npm* command:

```
npm install @tiledesk/tiledesk-client
```

Alternatively use package.json to import the library in the "dependencies" property, as in the following example:

```json
{
  "name": "Hello Tiledesk nodeJS",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@tiledesk/tiledesk-client": "^0.8.28"
  }
}
```

Then run

```
npm install
```

Once installed you can import `TiledeskClient()` class in your Node.js file using the "require" command:

```
const { TiledeskClient } = require('@tiledesk/tiledesk-client');
```

All interaction with Tiledesk APIs uses *TiledeskClient* class.

## Create a TiledeskClient instance

Before you can use the most of the APIs you need to create a TiledeskClient instance. To create the client instance you need the a Tiledesk *API Key*, the *project id* and an *authentication token*

```
const tdclient = new TiledeskClient(
{
    APIKEY: APIKEY,
    projectId: PROJECT_ID,
    token: USER_TOKEN
})
```

There are additional option to initialize the Tiledesk Client object. The full list of TiledeskClient initialization options follows:

* {string} options.APIKEY Mandatory.Tiledesk APIKEY
* {string} options.projectId Mandatory. Tiledesk projectId. Will be used in each call on project's APIs.
* {string} options.token Mandatory. Tiledesk authentication token. Will be used in each call on project's APIs.
* {string} options.**APIURL** Optional. Tiledesk server API endpoint.
* {boolean} options.log Optional. If true HTTP requests are logged.

The most important option is **APIURL** that provides the opportunity to use *TiledeskClient* with your own installation of the Tiledesk server.

You can get the token using some authentication method. The token is also provided automaticaccly while you interact with the chatbot using through APIs.

## Authentication

Before you can interact with Tiledesk APIs you need to authenticate. Tiledesk provides three *static* authentication methods:

1. *TiledeskClient.authEmailPassword()* - Authentication with email and password
2. *TiledeskClient.anonymousAuthentication()* - Authentication as anonymous user
3. *TiledeskClient.customAuthentication()* - Custom authentication

### Authentication with *email* and *password*

This is the authentication method that you need when working with Tiledesk APIs. Every API methods, except authentication ones, work on a *project* + *role* + *token* basis. To authenticate and get a *token* with email and password use the `authEmailPassword()` method from the TiledeskClient class. You must provide the APIKEY to authenticate. Actually APIKEYs are experimental and can be omitted. Just use the string 'APIKEY' in place of the real one.

```javascript
TiledeskClient.authEmailPassword(
  'APIKEY',
  /* EMAIL */,
  /* PASSWORD */,
  null,
  function(err, result) {
      if (!err && result) {
          console.log('You got your auth token!', result.token);
          console.log('Your user ID!', result.user._id);
      }
  else {
      console.err("An error occurred", err);
  }
});
```

In response you will get a *token* to interact with APIs using your account and the corresponding *user ID*.

### Authentication as Anonymous user

This authentication method is useful for anonymous user that need to interact with support APIs

```javascript
TiledeskClient.anonymousAuthentication(
  PROJECT_ID,
  APIKEY,
  null,
  function(err, result) {
    assert(result.token != null);
    let token = result.token;
  }
);
```

In response you will get a *token* to interact with APIs in anonymous mode.

### Custom authentication

With custom authentication you can work with your own users making them auto-signin in Tiledesk without previous signup. This can be used in the place of anonymous authentication to certify users coming from external application, giving them a certified identity in Tiledesk.

For this example import uuid:

```
npm install uuid
```

```javascript
const { v4: uuidv4 } = require('uuid');
var externalUserId = uuidv4();
var externalUser = {
    _id: externalUserId,
    firstname:"John",
    lastname:"Wick",
    email: "john@wick.com"
};
var signOptions = {                                                            
  subject:  'userexternal',
  audience:  'https://tiledesk.com/projects/' + YOUR_PROJECT_ID
};
var jwtCustomToken = "JWT " + jwt.sign(externalUser, YUOR_PROJECT_SECRET, signOptions);

TiledeskClient.customAuthentication(
  jwtCustomToken,
  APIKEY,
  null,
  function(err, result) {
      if (!err && result) {
          let token = result.token;
      }
  }
);
```

## The TiledeskClient class

To interact with Tiledesk APIs you need to create an instance of a TiledeskClient() class using his constructor. You MUST supply an *APIKEY*, an existing *Project ID* and a valid *token*, this last one got through some of the authentication methods above.

In the next example we first authenticate using our user credentials, then we create a new TiledeskClient instance using a `PROJECT_ID` and the `token` we got from authentication:

```javascript
TiledeskClient.authEmailPassword(
  'APIKEY',
  /* EMAIL */,
  /* PASSWORD */,
  null,
  function(err, result) {
      if (!err && result) {
          console.log('You got the token!', result.token);
          const tdclient = new TiledeskClient({
              APIKEY: /* APIKEY */,
              projectId: /* PROJECT_ID */,
              token: result.token
          });
      }
  else {
      console.err("An error occurred", err);
  }
});
```

## Working with support requests

A *Support Request* is a set of metadata and messages *decorating* a conversation. A Support Request contains data regarding the status (open/assigned/closed etc.), the web/app source page of the conversation, the end-user-id, his email etc. The main information consist of the messages sent and received by the request. Using messaging APIs is indeed the most common way to interact with the request.

Yiou can interact with the request messages using [Messaging APIs](https://developer.tiledesk.com/apis/rest-api/messages). Or you can interact directly with Request's metadata using the [Request APIs](https://developer.tiledesk.com/apis/rest-api/requests).

### Create a support request (send a message)

To create a support request you simply **send a message to a not-existing request-id**. A new Request object is automcatically created by Tiledesk every time you send a message to a no-existing request-id.

It's up to you to create a new, UNIQUE request-id, following the Tiledesk rules. If you don't want to know how to create a new request-id, to get a new one you can simply use the function `TiledeskClient.newRequestId()` passing the `PROJECT_ID` as a parameter. Sending a message to this newly created Request ID will automatically create a new Request object, as in the following example:

```
const text_value = 'test message';
const request_id = TiledeskClient.newRequestId(PROJECT_ID);
tdclient.sendSupportMessage(
  request_id,
  {text: text_value},
  (err, result) => {
    assert(err === null);
    assert(result != null);
    assert(result.text === text_value);
});
```

As soon as you send a new message to Tiledesk with the new request-id, the request is created and ready.

### Send messages to a Support Request

With the same *sendSupportMessage()* function we used above you can send additional messages to the request's conversation. In this example we send a second message to the request using the same request-id we used to create the request in the previous example.

```
tdclient.sendSupportMessage(
  request_id,
  {text: 'second message'},
  (err, result) => {
    assert(err === null);
    assert(result != null);
    assert(result.text === text_value);
});
```

With Tiledesk you can also [get sent messages](https://developer.tiledesk.com/apis/tutorials/rest-api/sending-and-receiving-messages) to a request's conversation using Webhooks, subscribing to the *Message.create* event.

### Get a support request by id

```
let REQUEST_ID = /* THE REQUEST ID */;
tdclient.getRequestById(REQUEST_ID, (err, result) => {
    const request = result;
    if (request.request_id != null) {
      console.log("Got request with first text:", request.first_text);
    }
});
```

### Query support requests

```
tdclient.getAllRequests(
  {
      limit: 1,
      status: TiledeskClient.UNASSIGNED_STATUS
  },
  (err, result) => {
    assert(result);
    const requests = result.requests;
    assert(requests);
    assert(result.requests);
    assert(Array.isArray(requests));
    assert(result.requests.length > 0);
  }
);
```

## Working with teamates

A Project's **teammate** is a user who collaborates with you on a specific project.

While the name on the *User Interface* and documentaion level is always teammate, on the APIs level a teamate is called *ProjectUser*. As the the name suggests, a ProjectUser is a Tiledesk User invited with a specific role on a specific Project.

### Update teamate status to available/unavailable

With `TiledeskClient.updateProjectUserCurrentlyLoggedIn()` you will update the status of the user token in the TiledeskClient constructor.

```javascript
const tdclient = new TiledeskClient({
    APIKEY: /* APIKEY */,
    projectId: /* PROJECT_ID */,
    token: result.token
});
tdclient.updateProjectUserCurrentlyLoggedIn(
    {
        user_available: true
    },
    function(err, result) {
        if (!err && result) {
            assert(result);
            assert(result.user_available === true);
        }
    }
);
```

### Check teamate status

```javascript
const tdclient = new TiledeskClient({
    APIKEY: /* APIKEY */,
    projectId: /* PROJECT_ID */,
    token: result.token
});
tdclient.getProjectUser(
  USER_ID,
  function(err, result) {
      if (!err && result) {
          assert(Array.isArray(result));
          assert(result[0]._id != null);
          assert(result[0].user_available === true);
          let PROJECT_USER_ID = result[0]._id;
      }
      else {
          assert.ok(false);
      }
  }
);
```

The `PROJECT_USER_ID` variable is the teamate ID of your user (`USER_ID`) on the `PROJECT_ID` you specified in the TiledeskClient custructor.

## Switch between Cloud and Self hosted instances

### Self hosted option

These APIs automatically work with the Tiledesk cloud instance.

If you are running your own self-hosted instance of Tiledesk, the APIs provide a specific option to select your endpoint.

#### Specify the API endpoint in class methods

If you are using a class method, i.e. authentication methods, use the `options.APIURL` parameter to specify the endpoint, as in the following example:

```
TiledeskClient.authEmailPassword(
    APIKEY,
    EMAIL,
    PASSWORD,
    {
      APIURL: API_ENDPOINT
    }
});
```

#### Specify the API endpoint in instance methods

If instead you are using instance methods working with an instance of TiledeskClient, you must specify the parameter in the constructor config object as config.APIRUL:

```
const tdclient = new TiledeskClient({
    APIKEY: APIKEY,
    projectId: PROJECT_ID,
    token: YOUR_TOKEN,
    APIURL: API_ENDPOINT
})
```


# Webhooks

## Introduction

Webhooks are a powerful resource that you can use to automate your use cases and improve your productivity.

Unlike the API resources, which represent static data that you can create, update and retrieve as needed, webhooks represent dynamic resources. You can configure them to automatically notify you when for example a new request occurs.

## Use cases

Typical use case for webhook integration is connecting Tiledesk to external CRM, marketing automation tools or data analytics platforms.

Follow this tutorial if you’re developing a Tiledesk integration that reacts to internal Tiledesk events, such as new incoming chat or queued visitor.

For instance if you’re integrating a marketing automation tool, you could add a new contact every time a Tiledesk visitor starts a chat.

## Getting started

To use this tool you need to have basic knowledge about webhooks and Tiledesk authorization protocol.

This tutorial is will not be helpful for integration that pulls data on demand (not in reaction to some Tiledesk event). If you just want to pull Tiledesk reports on user request, you’d rather just use [REST API](https://github.com/Tiledesk/tiledesk-docs/tree/de753b1eae5570e317666d2bdce2edd992d506a9/apis/api/README.md).

### Prerequisites

You’ll need a Tiledesk Account. Sign up to the [Tiledesk Dashboard ](https://panel.tiledesk.com/v3/dashboard)to create a new account.

## RESTHooks

Tiledesk uses RestHook patterns. REST Hooks itself is not a specification, it is a collection of patterns that treat webhooks like subscriptions. These subscriptions are manipulated via a REST API just like any other resource. More info about Rest Hook [here](http://resthooks.org).

Tiledesk can send notifications when some particular action is performed. Such a notification is called a webhook – it’s just a simple HTTP request that Tiledesk sends to your server when a particular event occurs.

To use RestHook you can:

* Create a New Subscription using Dashoboard UI. Go to **Settings** > **Project Settings** > **Developer** (tab) and click on **Manage WebHook** button.

![image](https://user-images.githubusercontent.com/9378770/121205150-b77cb980-c877-11eb-870d-c285bf0dc755.png)

* [Create a New Subscription using REST API](/apis/webhooks/subscriptions#create-a-new-subscription).

Each Subscription consists of the following properties:

* event – determines when the webhook is sent to your web server.
* target – address of your web server the webhook will be sent to.

## Webhook format

Each webhook is a HTTP POST request made to the URL that you provide. The request’s POST body contains webhook information in JSON format.

```
{
   "hook":{
      "_id":"5c4f1c2e081bde0016cd61d4",
      "updatedAt":"2019-01-28T15:13:50.807Z",
      "createdAt":"2019-01-28T15:13:50.807Z",
      "target":"https://webhook.site/xyzxyz",
      "event":"request.close",
      "id_project":"5ad5bd52c975820014ba9234",
      "createdBy":"5aaa99024c3b110014b478f0",
      "__v":0
   },
   "timestamp":1549035233858,
   "payload":{
      "_id":"5c542239721b190016a50538",
      "request_id":"support-group-LXcdORkb1Kp21ucGNEH",
      "requester_id":"5beda319507c7500150b1b80",
      "first_text":"hello",
      "department":"5b8eb4955ca4d300141fb2cc",
      "sourcePage":"http://localhost:4200/#/login",
      "id_project":"5ad5bd52c975820014ba9234",
       ...
   }
}
```

Each webhook request contains the following properties:

* hook – return the subscription object that triggered the webhook.
* payload – It contains the data of the webhook.

When your server receives a webhook from Tiledesk, it should respond with HTTP 200 response. Otherwise, Tiledesk will retry sending the webhook to your service for a number of times unless it receives the correct HTTP 200 response.

Note: Tiledesk webhooks are sent with *Content-Type: application/json* header, so please make sure that your service can handle such requests.

## Webhook Models

### Webhook events

The following Events are available and you can be notified when an action relating to that event occurs.

| Event                                        | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | Model                                                                                                     |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| request.create                               | Subscribe to requests creations                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | [Request](/apis/rest-api/requests#the-request-model)                                                      |
| request.update                               | Subscribe to request being updated                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | [Request](/apis/rest-api/requests#the-request-model)                                                      |
| request.close                                | Subscribe to request being closed                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | [Request](/apis/rest-api/requests#the-request-model)                                                      |
| message.create                               | Subscribe to messages creations (sent and receive)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | [Message](/apis/rest-api/messages#the-message-model)                                                      |
| message.create.request.channel.CHANNEL\_NAME | Subscribe to messages created (sent and receive) from a specific channel. Ex: message.create.request.channel.telegram for Telegram                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | [Message](/apis/rest-api/messages#the-message-model)                                                      |
| lead.create                                  | Subscribes to leads creations                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | [Lead](/apis/rest-api/leads#the-lead-model)                                                               |
| faq.create                                   | Subscribes to faq creations                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | [Faq](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/rest-api/chat-bots/faq.md#the-faq-model) |
| faq.update                                   | Subscribes to faq being updated                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | [Faq](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/rest-api/chat-bots/faq.md#the-faq-model) |
| faq.delete                                   | Subscribes to faq being deleted                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | [Faq](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/rest-api/chat-bots/faq.md#the-faq-model) |
| faqbot.create                                | Subscribes to bot creations                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | [Bot](/apis/rest-api/bots#the-bot-model)                                                                  |
| faqbot.update                                | Subscribes to bot being updated                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | [Bot](/apis/rest-api/bots#the-bot-model)                                                                  |
| faqbot.delete                                | Subscribes to bot being deleted                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | [Bot](/apis/rest-api/bots#the-bot-model)                                                                  |
| department.create                            | Subscribes to department creations                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | [Department](/apis/rest-api/management-api/departments#the-department-model)                              |
| department.update                            | Subscribes to department being updated                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | [Department](/apis/rest-api/management-api/departments#the-department-model)                              |
| department.delete                            | Subscribes to department being deleted                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | [Department](/apis/rest-api/management-api/departments#the-department-model)                              |
| project\_user.invite                         | Subscribes to teammate project invitation                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              | [Team](/apis/rest-api/team#the-team-model)                                                                |
| project\_user.update                         | Subscribes to teammate being updated                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | [Team](/apis/rest-api/team#the-team-model)                                                                |
| project\_user.delete                         | Subscribes to teammate project leave                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | [Team](/apis/rest-api/team#the-team-model)                                                                |
| group.create                                 | Subscribes to group creations                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | [Group](/apis/rest-api/management-api/groups#the-group-model)                                             |
| group.update                                 | Subscribes to group being updated                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | [Group](/apis/rest-api/management-api/groups#the-group-model)                                             |
| group.delete                                 | Subscribes to group being deleted                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | [Group](/apis/rest-api/management-api/groups#the-group-model)                                             |
| event.emit                                   | Subscribes to event emitting                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | [Event](/apis/rest-api/events#the-event-model)                                                            |
| event.emit.EVENT\_NAME                       | Subscribes to a specific event emitting. Example: event.emit.typing.start to subscribe to typing indicator events.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | [Event](/apis/rest-api/events#the-event-model)                                                            |
| operator.select                              | Subscribes *synchronously* to the assignment of the conversation to a specific agent or bot. Before Tiledesk assigns a conversation to an operator (agent or bot) you can create a custom endpoint that receive the webhook call and dynamically select the operator based on your custom logic (for example: skills, operating hours, etc..). The webhook sends the following payload: 1) the agents array 2) the available agents array 3) the suggested operator selected by Tiledesk engine if routing is "assigned", while if "pooled" an empty array 4) the department model 5) the project model 6) the id of the operator selected in the previeous assignment 7) the conversation in the previeous assignment. Attention only one subscription per project is supported. Find an example [here](https://repl.it/@tiledesk/tiledesk-webhook-custom-assignment) | Custom                                                                                                    |

### Webhook Notification object

A notification object contains the following fields:

* Hook attribute
* Payload attribute

#### Hook Attribute

Hook attribute contains the subscription object that triggered the webhook.

| Attribute | Type      | Description                                                 |
| --------- | --------- | ----------------------------------------------------------- |
| \_id      | string    | The Tiledesk defined id representing the subscription.      |
| createdAt | timestamp | The timestamp the subscription was created.                 |
| updatedAt | timestamp | The timestamp the subscription was updated                  |
| target    | string    | The subscription target url                                 |
| event     | string    | Corresponds to an event, eg 'lead.create', 'request.create' |

#### Payload

Payload is the data associated with the notification. To understand the payload object you must consider the model column of the Webhook Events table.

### Security - Signed Notifications

Each webhook notification is signed by Tiledesk via an *x-hook-secret* header. This header contains the webhook secret, randomically generated at the first creation (using UI or REST API) of the webhook subscription. We do this so that you can verify the notification came from Tiledesk, comparing the value x-hook-secret header with the secret value obtained during the first creation.

## Debugging a webhook

If a webhook isn't working correctly, failed invocations will be visible using [Get the subscriptions logs REST API](https://developer.tiledesk.com/apis/webhooks/subscriptions#get-the-subscriptions-logs).

In most cases, the response comes from the third-party service that receives the webhook's request, not Tiledesk itself. You typically need to work with this service to fix errors.

You can use the numeric code in the response status to diagnose issues. These response status codes are standard across HTTP requests. For a list of the standard HTTP response status codes and their meaning, see HTTP response status codes in the MDN web docs.

Note: If a service uses custom HTTP response status codes, you may need to consult their documentation.

Webhook requests have a 10-second timeout. A "Failed: 504 Gateway Timeout" response status indicates a service didn't respond to a webhook's request within this timeout period. The timeout period is not adjustable.


# Subscriptions

## Create a new subscription

<mark style="color:green;">`POST`</mark> `https://api.tiledesk.com/v3/:project_id/subscriptions`

This endpoint allows to add more subscriptions.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name   | Type   | Description      |
| ------ | ------ | ---------------- |
| event  | string | the event method |
| target | string | the target url   |

{% tabs %}
{% tab title="200 " %}

```
{
   {
   "__v":0,
   "updatedAt":"2019-03-12T12:01:56.462Z",
   "createdAt":"2019-03-12T12:01:56.462Z",
   "target":"https://webhook.site/c312005b-5042-49e9-a769-0f3ba4245b51",
   "event":"request.create",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5ab11c6b83dc240014d46095",
   "_id":"5c879fb4f1ae6600173b8c75",
   "secret":"56c189c8-33ae-4930-bd98-410a12aa45ce"
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X POST -H 'Content-Type:application/json' -u andrea.leo@f21.it:123456 -d '{"event":"request.create", "target":"https://webhook.site/c312005b-5042-49e9-a769-0f3ba4245b51"}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/subscriptions
```

## This endpoint retrieves all subscriptions

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/subscriptions`

This endpoint retrieves all active subscriptions.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
[
{
   {
   "__v":0,
   "updatedAt":"2019-03-12T12:01:56.462Z",
   "createdAt":"2019-03-12T12:01:56.462Z",
   "target":"https://webhook.site/c312005b-5042-49e9-a769-0f3ba4245b51",
   "event":"request.create",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5ab11c6b83dc240014d46095",
   "_id":"5c879fb4f1ae6600173b8c75"
},
...
]
```

{% endtab %}
{% endtabs %}

## Get a subscription by id

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/subscriptions/:id`

This endpoint retrieves a subscription by ID

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| id          | string | the subscription identifier                                                              |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
{
   {
   "__v":0,
   "updatedAt":"2019-03-12T12:01:56.462Z",
   "createdAt":"2019-03-12T12:01:56.462Z",
   "target":"https://webhook.site/c312005b-5042-49e9-a769-0f3ba4245b51",
   "event":"request.create",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5ab11c6b83dc240014d46095",
   "_id":"5c879fb4f1ae6600173b8c75"
}
```

{% endtab %}
{% endtabs %}

## This endpoint deletes a subscription by id

<mark style="color:red;">`DELETE`</mark> `https://api.tiledesk.com/v3/:project_id/subscriptions/:id`

This endpoint delete a subscription by ID

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| id          | string | the subscription identifier                                                              |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
{  
         "_id":"5c81593adf767b0017d1aa66",
         "updatedAt":"2019-03-07T17:47:38.393Z",
         "createdAt":"2019-03-07T17:47:38.393Z",
         "lead_id":"SRbb2PfbSFcgICv9VQBcURZeloh1",
         "fullname":"Guest",
         "attributes":{ ... },
         "id_project":"5b55e806c93dde00143163dd",
         "createdBy":"system",
         "__v":0
}
```

{% endtab %}
{% endtabs %}

## Update a subscription

<mark style="color:orange;">`PUT`</mark> `https://api.tiledesk.com/v3/:project_id/subscriptions/:id`

This endpoint updates a subscription.

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | The project\_id is a unique code assigned to your project when you create it in Tiledesk |
| id          | string | the subscription identifier                                                              |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |
| Content-Type  | string | use "application/json" value           |

#### Request Body

| Name   | Type   | Description      |
| ------ | ------ | ---------------- |
| event  | string | the event method |
| target | string | the target url   |

{% tabs %}
{% tab title="200 " %}

```
{
   {
   "__v":0,
   "updatedAt":"2019-03-12T12:01:56.462Z",
   "createdAt":"2019-03-12T12:01:56.462Z",
   "target":"https://webhook.site/c312005b-5042-49e9-a769-0f3ba4245b51",
   "event":"request.create",
   "id_project":"5b55e806c93dde00143163dd",
   "createdBy":"5ab11c6b83dc240014d46095",
   "_id":"5c879fb4f1ae6600173b8c75"   
}
```

{% endtab %}
{% endtabs %}

Example

```
curl -v -X PUT -H 'Content-Type:application/json' -u andrea.leo@f21.it:123456 -d '{"event":"request.create", "target":"https://webhook.site/c312005b-5042-49e9-a769-0f3ba4245b51"}' https://api.tiledesk.com/v3/5b55e806c93dde00143163dd/subscriptions/5c879fb4f1ae6600173b8c75
```

## Get the subscriptions logs

<mark style="color:blue;">`GET`</mark> `https://api.tiledesk.com/v3/:project_id/subscriptions/history`

The endpoint receives subscription call logs.

\\

**Experimental**

#### Path Parameters

| Name        | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| project\_id | string | the Project Id is a unique code assigned to your project when you create it in Tiledesk. |

#### Query Parameters

| Name | Type   | Description                                           |
| ---- | ------ | ----------------------------------------------------- |
| page | number | what page of results to fetch. default to first page. |

#### Headers

| Name          | Type   | Description                            |
| ------------- | ------ | -------------------------------------- |
| Authorization | string | authorization token. Basic Auth or JWT |

{% tabs %}
{% tab title="200 " %}

```
[
    { 
      "_id":"5e3ae8309ae7ee0017d91609",
      "event":"message.create",
      "target":"https://tiledesk.requestcatcher.com/test",
      "response":"{\"statusCode\":200,\"body\":\"request caught\",\"headers\":{\"date\":\"Wed, 05 Feb 2020 16:07:11 GMT\",\"content-length\":\"14\",\"content-type\":\"text/plain; charset=utf-8\",\"connection\":\"close\"},\"request\":{\"uri\":{\"protocol\":\"https:\",\"slashes\":true,\"auth\":null,\"host\":\"tiledesk.requestcatcher.com\",\"port\":443,\"hostname\":\"tiledesk.requestcatcher.com\",\"hash\":null,\"search\":null,\"query\":null,\"pathname\":\"/test\",\"path\":\"/test\",\"href\":\"https://tiledesk.requestcatcher.com/test\"},\"method\":\"POST\",\"headers\":{\"Content-Type\":\"application/json\",\"x-hook-secret\":\"0060287d-9486-4f00-a4db-a254f998dbd1\",\"accept\":\"application/json\",\"content-length\":6005}}}",
      "body":"\"request caught\"",
      "err":null,
      "id_project":"5e37f45c4d82de00178b96ad",
      "createdAt":"2020-02-05T16:07:12.089Z",
      "updatedAt":"2020-02-05T16:07:12.089Z",
      "__v":0
    }
    .....
]
```

{% endtab %}
{% endtabs %}

Example:

```
curl -v -X GET -u andrea.leo@f21.it:123 https://api.tiledesk.com/v3/5e37f45c4d82de00178b96ad/subscriptions/history
```


# Conversation Messages APIs tips

Discover how to get conversation messages using APIs. Real time synch is supported through webhooks

## Messages REST APIs

You can use the following APIs to get all messages relative to a conversation:

<https://developer.tiledesk.com/apis/rest-api/messages#get-the-messages-of-a-request-by-id>

You will get all the conversation messages.

> NOTE: You must remove all the messages where sender: “system” (highlighted below) if you only need messages from end-users/humans/chatbot

![](https://github-production-user-asset-6210df.s3.amazonaws.com/32564846/303445718-0d941d21-38f2-4b36-adb6-f67e5d38c5b7.png?X-Amz-Algorithm=AWS4-HMAC-SHA256\&X-Amz-Credential=AKIAVCODYLSA53PQK4ZA%2F20240208%2Fus-east-1%2Fs3%2Faws4_request\&X-Amz-Date=20240208T183915Z\&X-Amz-Expires=300\&X-Amz-Signature=e3c8ad2b2e8e76a3d7bab4474ccab01fadbe515afea5ecf2770513440224f3b3\&X-Amz-SignedHeaders=host\&actor_id=32564846\&key_id=0\&repo_id=142124434)

If you need only the attributes setup during the conversation you can use the following endpoint:

<https://api.tiledesk.com/v3/modules/tilebot/ext/parameters/requests/**REQUEST-ID>\*\*

Set in “Authentication” header’s field the JWT token of an Admin teammate of the project as in the following Postman example:

![](https://github-production-user-asset-6210df.s3.amazonaws.com/32564846/303435147-04791c6a-ae0d-45db-989d-b9373642e7b7.png?X-Amz-Algorithm=AWS4-HMAC-SHA256\&X-Amz-Credential=AKIAVCODYLSA53PQK4ZA%2F20240208%2Fus-east-1%2Fs3%2Faws4_request\&X-Amz-Date=20240208T184001Z\&X-Amz-Expires=300\&X-Amz-Signature=6c68e28d7da6f23e5384a3e0175908d9ebfb36d501b7222f771946a4a62939e2\&X-Amz-SignedHeaders=host\&actor_id=32564846\&key_id=0\&repo_id=142124434)

## Real-time messages

You can also get messages in real-time (for synchronisation purposes) configuring the provided Webhook event “Message.create” in *Project-> Developer zone*

![](https://github-production-user-asset-6210df.s3.amazonaws.com/32564846/303435371-41c4bc70-950a-4c3c-a657-b0ae20bce4bf.png?X-Amz-Algorithm=AWS4-HMAC-SHA256\&X-Amz-Credential=AKIAVCODYLSA53PQK4ZA%2F20240208%2Fus-east-1%2Fs3%2Faws4_request\&X-Amz-Date=20240208T184024Z\&X-Amz-Expires=300\&X-Amz-Signature=1d99be02d4777afc1b21f2231d4cd9fbb965634c06da3f948d0becf44c0a5bc0\&X-Amz-SignedHeaders=host\&actor_id=32564846\&key_id=0\&repo_id=142124434)


# Realtime API

The Realtime API provides programmatic access to ongoing activity in your Tiledesk server.

The Realtime API is implemented using WebSocket technology.

You can use the API to do the following:

* Display requests data
* Display agents data
* Create and display a real-time dashboard
* Predict or estimate capacity and other derived metrics

The Realtime API allows you to receive events from Tiledesk after you subscribe to one or more topics.

This API is an SSL-only API. You must be a verified user to make API requests. You can authorize against the API using JWT token.

## Topics

| Topic                                         | Description                             |
| --------------------------------------------- | --------------------------------------- |
| /PROJECT\_ID/requests                         | Get the last open requests of a project |
| /PROJECT\_ID/requests/REQUEST\_ID             | Get the requests detail                 |
| /PROJECT\_ID/requests/REQUEST\_ID/messages    | Get the request messages                |
| /PROJECT\_ID/project\_users/PROJECT\_USER\_ID | Get the agents info                     |

## Rate Limiting

We only allow a certain number of new connections per minute. The number of new connections to the Realtime API is restricted by REST API rate limits. We also allow a certain number of concurrently running connections to the Realtime API.

We reserve the right to adjust the rate limit for given endpoints in order to provide a high quality of service for all clients. If the rate limit is exceeded, Tiledesk will respond with a body that details the reason for the rate limiter kicking in.

We also limit the total amount of data exchanged through real time APIs. For example the number of Realtime requests exchanged can’t exceed a certain number of items. If this number is exeeded you can always use REST APIs to get additional data or to make more complex queries.

## Using The API

* Establish an authenticated WebSocket connection to `wss://eu.rtmv3.tiledesk.com/api/`.
* Subscribe to one or several topics.
* Process incoming events.
* Unsubscribe to topics.

## Allowed For

* Owner
* Administrator
* Agent

## Establish Connection

Connect to the wss\://eu.rtmv3.tiledesk.com/api/ WebSocket endpoint using your JWT token.

```
  var ws = new WebSocket("wss://eu.rtmv3.tiledesk.com/api/?token=YOUR_JWT_TOKEN"); 

  ws.onopen = function () {
      console.log('websocket is connected.');         
  }

  ws.onclose = function () {
      console.log('websocket is closed.');           
  }

  ws.onerror = function () {
      console.log('websocket error ...')
  }
```

## Subscribe to a topic

Once connection is established, you can send messages to subscribe to individual topics. Refer to Topics for the topic key.

```
{
   "action":"subscribe",
   "payload":{
      "topic":"/<YOUR_PROJECT_ID_HERE>/requests"
   }
}
```

To subscribe to a topic you can execute :

```
ws.send(JSON.stringify(subscriptionMessage));
```

Example:

```
var subscriptionMessage =
{
   "action":"subscribe",
   "payload":{
      "topic":"/5df26badde7e1c001743b63c/requests"
   }
}

ws.send(JSON.stringify(subscriptionMessage));
```

## Process Incoming Events

Once you have subscribed to one or several topics, listen to subsequent messages to start collecting data.

```
 ws.onmessage = function(message) {   
    console.log(message);
    try {
         var data = JSON.parse(message.data);
    } catch (e) {
       return console.log('This doesn\'t look like a valid JSON: ', message.data);
    }

   //.... ADD YOUR LOGIC HERE    
}
```

The following are sample messages received after subscribing to requests topic:

```
{
   "action":"publish",
   "payload":{
      "topic":"/5eb45fbc1f9e1f0012d62207/requests",
      "method":"CREATE",
      "message":[
         {
            "_id":"5eb4fc911f9e1f0012d62248",
            "status":200,
            "preflight":false,
            "participants":[
               "5eb45fb21f9e1f0012d62201"
            ],
            "request_id":"support-group-1a952f2f-c09a-46be-bc75-11387a95d55f",
            "requester":"5eb45fbc1f9e1f0012d62208",
            "lead":{
               ...
            },
            "first_text":"hello world",
            "department":"5eb45fbc1f9e1f0012d62209",
            ...
            "assigned_at":"2020-05-08T06:30:41.090Z",
            "id_project":"5eb45fbc1f9e1f0012d62207",
            "createdBy":"5eb45fb21f9e1f0012d62201",
            "tags":[

            ],
            "notes":[

            ],
            "channel":{
               "name":"chat21"
            },
            "createdAt":"2020-05-08T06:30:41.094Z",
            "updatedAt":"2020-05-08T06:31:00.367Z",
            "__v":0,
            "first_response_at":"2020-05-08T06:30:58.109Z",
            "waiting_time":17015,
            "id":"5eb4fc911f9e1f0012d62248",
            ....
         },
         ..
      ]
   }
}
```

## Unsubscribe

Once you stop processing some data, you can individually unsubscribe from a topic. Events will then stop being pushed on the connection.

```
{
   "action":"unsubscribe",
   "payload":{
      "topic":"/<YOUR_PROJECT_ID_HERE>/requests"
   }
}
```

## Example

You can find a simple example of the Tiledesk Realtime API [here](https://www.w3schools.com/code/tryit.asp?filename=GJH61IZ9OU0E)


# JWT Authentication

## Custom Authentication

The Custom JWT authentication provider allows users to authenticate with an authentication system that is independent from Tiledesk. The external system must return a signed [JSON Web Token](https://jwt.io/introduction/) that contains a unique ID value for the authenticated user.

Tiledesk uses the JWT to identify your application’s users and authenticate their requests but does not impose any restrictions on the external authentication system’s requirements or authentication methods.

To create a Custom JWT Token you must generate a Project Shared Secret as described below.

> NOTE: We provide a [full tutorial on Custom Authentication](https://developer.tiledesk.com/apis/authentication/jwt-auth-tutorial).

## Generating a Project Shared Secret

A Project Shared Secret is a security setting, intended to be generated, copied, and pasted into a communication with your engineering team, or directly into your codebase, in a single sitting. It should not be entered into a browser.

To generate the shared secret required for custom authentication you need:

* Open the **Dashboard** and go to **Project Name > Project Settings**.
* Go to the **Visitor Authentication** tab and click the **Generate** button.

![](https://user-images.githubusercontent.com/47848430/167668246-ea6eeebf-75d2-46a1-88ab-b6c8df02725d.png)

Note:The shared secret is intended to remain secure. As a result, it will only appear in full one time. If you don’t have access to the shared secret and need the full secret to create your token, you can reset the secret by clicking the 'Generate' button. Regenerating a new shared secret will revoke the previous token. If you have concerns the shared secret has been compromised, you should regenerate a new one. If you need to rotate the keys, you should schedule it when Chat is offline because regenerating the secret cause visitors to be disconnected from the widget.

## Create a Tiledesk JWT token

To create a JWT token you must set the following required fields of the user object :

* **\_id** is the custom unique user identifier of the external authentication system. It must start with `<YOUR_PROJECT_ID>_` ( example: 5e5f4e220b28440012117be4\_12345678 )
* **sub**. JWTs describe their subject in the sub claim. For custom authentication sub field must be equal to value `userexternal`
* **aud**. JWTs describe their audience in the aud claim. For custom authentication must be `https://tiledesk.com/projects/<YOUR_PROJECT_ID>` whether you use the cloud version of Tiledesk or if you install it on-premise.
* **email**. It's the user email

Optional fields:

* **firstname**. It's the user firstname
* **lastname**. It's the user lastname
* **attributes** other custom jwt claims.

The external authentication system must **create the JWT signing the user object with the Project Shared Secret** code.

User object example:

```
{"_id": "5e5f4e220b28440012117be4_12345678", "firstname":"Andrea", "lastname":"Leo", "email": "andrea.leo@email.com",  "attributes": {"attribute1":"value"}, "sub":  "userexternal",  "aud":  "https://tiledesk.com/projects/5c81593adf767b0017d1aa68"}
```

## Generate JWT Token Server Side

Find the template below that fits your language needs. Customize the sample as needed, making sure to replace the #{details} with your own information.

If none of these samples match your needs, JWT has a more extensive list of [JWT libraries](https://jwt.io/#libraries-io) to explore.

### NodeJS

Install [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken):

```
npm install jsonwebtoken --save-dev
```

Then, generate a token using the shared secret:

```
var jwt = require('jsonwebtoken'); 
var payload = {
  _id: '#{customerIdentifier}',
  firstname: '#{customerFirstname}',
  lastname: '#{customerLastname}',
  email: '#{customerEmail}',  
  sub: 'userexternal',
  aud: 'https://tiledesk.com/projects/#{YOUR_PROJECT_ID}',  
};
var token = jwt.sign(payload, '#{yourProjectSharedSecret}');
```

You can find a NodeJs Custom Jwt Authentication example [here](https://github.com/Tiledesk/tiledesk-custom-jwt-authentication-example).

### PHP

Download [PHP-JWT](https://github.com/firebase/php-jwt):

```
composer require firebase/php-jwt
```

Generate a token using the shared secret:

```
$payload = {
  '_id' => '#{customerIdentifier}' ,
  'firstname' => '#{customerFirstname}',
  'lastname' => '#{customerLastname}',
  'email' => '#{customerEmail}',
  'sub' => 'userexternal',
  'aud' => 'https://tiledesk.com/projects/#{YOUR_PROJECT_ID}'
};
$token = JWT::encode($payload, '#{yourProjectSharedSecret}');
```

### Java

Authentication with Java is covered with a simple Java (Maven) example on the public repo [TiledeskJavaJWTSign](https://github.com/Tiledesk/TiledeskJavaJWTSign)

We use the [JJWT library](https://github.com/jwtk/jjwt) to implement the Tiledesk JWT sign operation.

```
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
byte[] apiKeySecretBytes;
apiKeySecretBytes = SECRET_KEY.getBytes();
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
JwtBuilder builder = Jwts.builder().setId(id)
        .setIssuedAt(now)
        .setSubject(subject)
        .setIssuer(issuer)
        .claim("firstname", firstname)
        .claim("lastname", lastname)
        .claim("email", email)
        .signWith(signingKey, signatureAlgorithm);

return builder.compact();
```

Please refer to the above mentioned repo for further deatils.

## Verify the token

You can verify the JWT token using [jwt.io](https://jwt.io/) following these steps:

1. Paste the secret code
2. Paste the jwt code in the left column
3. Check the "Signature Verified" label

![image](https://github.com/Tiledesk/tiledesk-docs/assets/9378770/3bb5e170-b017-4a33-9526-a01dbc21dd70)

## Widget Authentication

See [how to setup custom authentication for the widget](/widget/auth) using the JWT token.


# JWT Custom authentication Tutorial

## Introduction

![image](https://user-images.githubusercontent.com/32564846/171425319-6b23a172-0fe7-4a33-8926-a35f73cccea8.png)

The Tiledesk Web Widget provides a default anonymous identity to his users. This means that the first time the widget starts on the end-user's browser it will assign to the user a unique, random *user-id*, that will last until the browser cache is cleared. This temporary, random identity provides many benefits, first of all the option to immediatily install and use the widget on your web site or application, without any configuration.

While "anonymous authentication" mode provides immediate and easy deployment of the Tiledesk widget, sometimes you would like to give your Tiledesk end-users a persistent, recognizable identity.

This is especially true when, for example, your end-users already have a certified identity into some other company's Identity Provider.

Tiledesk provides the option to authenticate your end-users with a custom, certified identity, using "custom JWT authentication", a very easy and market proved authentication technology.

In this tutorial we'll provide you a complete example on how you can successfully setup a custom JWT authentication for your Web Widget end-users. Let's start!

## The tutorial's application

We developed a fully working application (client + server code) already deployed at the following http address:

[custom-authentication-example.html on replit](https://tiledesk-html-site.tiledesk.repl.co/custom-authentication-example.html)

This application will provide you a fully understanding of the necessary configuration to setup custom authentication for your Tiledesk Project.

To understand how the application works and what does it mean to have a unique, *certified identity*, let's run a little test.

Just open the url and the page's embedded widget, then start a new conversation. Now send a simple message (i.e. "test"), as in the figure:

![Send a message](https://user-images.githubusercontent.com/32564846/170834302-0b590c01-0af1-443e-b8e9-8c95bd4a5217.png)

The user's conversation history is always saved on the Tiledesk servers on a *per-user-id* base and visible in the widget's home. With anonymous users, when you open this same page's url in a different browser after the first conversation (if you first opened the page in Chrome try opening it again in Firefox or Safari), the conversation history is not "conserved" between different sessions on different browsers because the user is, by default, anonymous, and a new one is created for each browser session (the user anonymous identity is anyway maintained on the same browser instance until your browser's cache is cleared).

If you run our app in different browsers (of you open anonymous windows of the same browser) you will instead *magically* see that the conversation history is always conserved. This means that the connected user is maintened across all sessions, because he effectively is **the same authorized user** on each browser's instance.

![The conversation history is conserved on all browsers](https://user-images.githubusercontent.com/32564846/170826764-aded3d7c-ef09-4940-92ba-f53eff63e2f3.png)

### Steps

To configure the frontend application you need a *Tiledesk project* (with the relative *projectd id*), your backend "authentication" service url (the REST endpoint that you will query to get the custom JWT token generated with your **project secret**) and you *frontend application* (a web page where the widget is hosted and configured for custom auth)

The following are the steps involved in our tutorial:

1. Create a Tiledesk Project
2. Setup the backend authentication app
3. Setup the frontend app

## Create a Tiledesk Project

First of all create a Tiledesk project. It's easy, just click on "Add project".

![image](https://user-images.githubusercontent.com/32564846/170837894-3dfc14ac-8db3-4f7f-9979-006721424b20.png)

Now choose a name for your project (i.e. JWT Auth Tutorial) and press Create project (leave all the options on their default values):

![image](https://user-images.githubusercontent.com/32564846/170837919-2c5a4196-8a7e-4417-b35e-8ea6b8e1dfc5.png)

Your project is ready.

## Setup the Backend authentication app

To develop our app logic, we'll need a web application endpoint that will run your own authentication code and will reply with a JWT that you'll use in the Widget.

We'll use the Repl.it service to fast create our own NodeJS web application endpoint.

Develop your application logic. Let's fork!

We simply fork the tutorial application, available at this url:

<https://replit.com/@tiledesk/tiledesk-jwt-token-example#index.js>

Use the fork button and choose a name for your app:

![image](https://user-images.githubusercontent.com/32564846/170930820-854734c8-29d3-4097-9a00-fcc4db7de604.png)

The app is forked and ready to run.

Now move back to your Tiledesk project's *Settings > Project Settings > General* section and copy the *Project id*.

![image](https://user-images.githubusercontent.com/32564846/170838183-4386a55b-f9de-42dc-8ac7-84f87f73d647.png)

Copy and paste the *project id* here in the *index.js* file of your nodeJS app on replit, as shown in the figure:

![image](https://user-images.githubusercontent.com/32564846/171025818-156bd922-52d1-43ee-85c9-11256b888b3d.png)

Now move back (again) to your Tiledesk project's *Settings > Project Settings > Developer* section. We will generate a new *secret key* that will be used to sign your JWT token. Press "GENERATE SHARED SECRET" button.

![image](https://user-images.githubusercontent.com/32564846/170951136-a8d97f3d-d6df-497f-8725-725ba0593ea8.png)

Take care that every time you generate e new secret the previous one is no more valid and you have to replace everywhere you used it.

![image](https://user-images.githubusercontent.com/32564846/171024674-d5b8fcc2-ec07-474c-9bc6-3c6112347d3e.png)

Now you can generate your secret.

![image](https://user-images.githubusercontent.com/32564846/171029452-df96b7da-5517-42d8-b0a3-ce864e486c43.png)

Copy and paste the *secret key* here in the index.js file of your nodeJS app on replit, as shown in the figure:

![image](https://user-images.githubusercontent.com/32564846/171032566-f809d043-c701-4101-a1c0-463cd2c50049.png)

We made this app just a simple endpoint that "simulates" your own, getting your user credentials from the client, look up in the database for the user and accordingly using your projectID and your *project secret* to generate a signed Tiledesk JWT to reply back to the widget.

You can now press the "Run" button on top of your project. Your backend is now running and ready to accept authentication requests from your widget.

![image](https://user-images.githubusercontent.com/32564846/171037372-4c9e6442-54b6-4dad-a457-05fd0e22d5bd.png)

All authentication requests will point to the following url (and a POST method sa we'll see later):

**Authentication Endpoint**: <https://tiledesk-jwt-token-example.tiledesk.repl.co/auth>

We'll refer to this endpoint later in the tutorial.

## Setup the Frontend

The frontend source project - a web page with the widget configuration code - is available at the following replit page:

<https://replit.com/@tiledesk/Tiledesk-HTML-Site#custom-authentication-example.html>

You can easily "fork" the project or clone it on your frontend application. Then modify it to accomplish your backend configuration (see *Backend setup*).

Now paste the project id in the *projectid* property of the Widget's settings in the page source code:

![image](https://user-images.githubusercontent.com/32564846/170838820-c9a0b7a7-b60a-4c8f-ac9d-4896a2908c92.png)

Now move to the authenticate method, and setup the authentication url using the backend endpoint. Get the service base url from the side panel (see the figure) and add /auth at the end to create the url for the authentication endopoint:

![image](https://user-images.githubusercontent.com/32564846/171047872-220d0158-c5f6-43a1-aa15-fb832db169ff.png)

Our application is now ready. You can run it and test it in many browsers. You will notice that the conversation history will refer to the same user (<andrew@scientists.com>) coming from you mock database.

![image](https://user-images.githubusercontent.com/32564846/171426383-16f42c83-1d4e-4b8a-8286-d743ce8a82ba.png)

If you have any problems do not esitate to write us on our [Community forum](https://tiledesk.discourse.group/)!

See you on our next tutorial!

Do you have suggestions on this article? Please send us your feedback writing an email to **<info@tiledesk.com>**


# Tutorials


# REST API


# Sending and receiving messages with Tiledesk APIs

## Targets

This tutorial will help you to understand how to send and receive "support messages" between Tiledesk's *End Users* and *Agents* using Tiledesk REST APIs and Webhooks.

### Steps

1. Signup a user on Tiledesk
2. Anonymous end-user authentication through APIs
3. Sending messages to a conversation
4. Receiving new messages notifications using Webhooks

## Signup on Tiledesk

To use Tiledesk APIs is mandatory to signup a new user on our beta environment available on <https://panel.tiledesk.com/v3/dashboard>

The previous APIs end-point will change as soon as the beta version will be released as **Tiledesk v2**. This tutorial will be updated accordingly.

![](/files/UYhILGGFOYRD8zJUlGeI)

After signup please follow the proposed wizard to create your first Tiledesk project.

Get the **PROJECT\_ID** of the created project under *Project Settings* menu. We will use this later.

![](/files/NDjJCxzqg5qKFypNPoRN)

## Anonymous end-user authentication through APIs

In this tutorial we will authenticate *end-users* through anonymous authentication (you can find more info on anomymous authentication [here](/apis/rest-api/authentication#anonymous-authentication-for-a-user)).

All APIs in this tutorial will use the following endpoint:

```bash
https://api.tiledesk.com/v3/
```

The previous APIs end-point will change as soon as the beta version will be released as **Tiledesk v2**. This tutorial will be updated accordingly.

```bash
curl -v -X POST -H 'Content-Type:application/json' \
-d '{"id_project":"5e2c35c8f0dbc10017bb3aac", "firstname":"John"}' \
https://api.tiledesk.com/v3/auth/signinAnonymously
```

This will reply with the JWT token that we'll use to send our first message:

```bash
{
   "success":true,
   "token":"JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.XYZ....",
   "user":{
      "_id":"fc43a0e1-ba85-404e-9a44-bf0050330898",
      "firstname":"John",
      "id":"fc43a0e1-ba85-404e-9a44-bf0050330898",
      "fullName":"John"
   }
}
```

## Sending messages to a conversation

You can send a message using the [Send Message API](/apis/rest-api/messages#send-a-message).

To send a message you need to choose a *unique* **request identifier.** A *request* is an object containing the all the metadata describing the conversation between end-user and *support team*).

The request identifier must follow the following pattern:

**support-group-\<UUID>**

Please consider that the first message you send to a conversation also creates request and corresponding conversation if they do not exist.

```bash
curl -v -X POST -H 'Content-Type:application/json' \
 -H "Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.XYZ...." \
 -d '{"text":"hello from anonym user"}' \
 https://api.tiledesk.com/v3/<PROJECT_ID>/requests/support-group-<UUID>/messages
```

Example with realistic variables instances:

```bash
curl -v -X POST -H 'Content-Type:application/json' \
 -H "Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.XYZ...." \
 -d '{"text":"hello my name is John and I need help"}' \
 https://api.tiledesk.com/v3/5e2c35c8f0dbc10017bb3aac/requests/support-group-27df7cbf-3946-4ca4-9b17-dc16114108f8/messages
```

Looking at the dashboard of your project you will see your first conversation in the Requests panel. The requests are updated in real time, so you don't have to manunally update the Requests' page. If you left unchanged all the default settings, the request will be assigned to you (make sure you are "available", looking in the lower right corner of your profile image in the left menu panel).

The agent (you) can now see the same conversation in the agent chat (first option of the menu panel will open the desktop chat).

## Receiving new messages notifications using Webhooks

You can subscribe to the messages events sent to a conversation using [Webhook](/apis/tutorials/rest-api/sending-and-receiving-messages)s.

You must first [create a subscription](/apis/webhooks/subscriptions#create-a-new-subscription) to an [event](/apis/tutorials/rest-api/sending-and-receiving-messages) that points to a url on your server.

In this case we will subscribe to *message creation* event on a custom url (/test) on requestcatcher.com, a free, beautiful service to debug your webhooks:

```
curl -v -X POST -H 'Content-Type:application/json' \
-u demo@email.com:123456 \
-d '{"event":"message.create", "target":"https://tiledesk.requestcatcher.com/test"}' \
https://api.tiledesk.com/v3/5e2c35c8f0dbc10017bb3aac/subscriptions
```

The subscription endpoint returns:

```
{
   "secret":"0fd2a8a1-a3e6-443b-9fe5-49b83612cd72",
   "_id":"5e2c6a24f5b11c00175f1705",
   "target":"https://tiledesk.requestcatcher.com/test",
   "event":"message.create",
   "id_project":"5e2c35c8f0dbc10017bb3aac",
   "createdBy":"5e2c357af0dbc10017bb3aa7",
   "createdAt":"2020-01-25T16:17:40.088Z",
   "updatedAt":"2020-01-25T16:17:40.088Z",
   "__v":0
}
```

Now you are notified for each messages sent to your Tiledesk project. Now, for example, if the agent sends a message to the end user, your webhook endpoint will be notified with the message payload.

This is the webhook notification with the message payload. You can use this notification to create a copy of all messages sent/received in your project, generate new custom events, communicate in real time on other channels etc.

```
{
   "timestamp":1579969429552,
   "payload":{
      "type":"text",
      "status":200,
      "_id":"5e2c6b958c9612001716bede",
      "sender":"5e2c357af0dbc10017bb3aa7",
      "senderFullname":"demo demo",
      "recipient":"support-group-27df7cbf-3946-4ca4-9b17-dc16114108f10",
      "text":"Hi I'm Rosy. How can help you?",
      "id_project":"5e2c35c8f0dbc10017bb3aac",
      "createdBy":"5e2c357af0dbc10017bb3aa7",
      "metadata":"",
      "attributes":{
         "client":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36",
         "sourcePage":"https://api.tiledesk.com/v3/chat/index.html",
         "userEmail":"aaa22@aaa22.it",
         "userFullname":"aaa22 aaa22"
      },
      "createdAt":"2020-01-25T16:23:49.394Z",
      "updatedAt":"2020-01-25T16:23:49.394Z",
      "__v":0,
      "request":{
         ....
      }
   },
   "hook":{
      "_id":"5e2c6a24f5b11c00175f1705",
      "target":"https://tiledesk.requestcatcher.com/test",
      "event":"message.create",
      "id_project":"5e2c35c8f0dbc10017bb3aac",
      "createdBy":"5e2c357af0dbc10017bb3aa7",
      "createdAt":"2020-01-25T16:17:40.088Z",
      "updatedAt":"2020-01-25T16:17:40.088Z",
      "__v":0
   }
}
```

Do you have feedback on this article? Please send us your feedback writing an email to <info@tiledesk.com>


# Import multiple messages into Tiledesk using REST APIs from third party app

## Targets

This tutorial will help you to understand how to insert multiple messages into Tiledesk using REST API from third party app. Suppose you have an application (ex. a chatbot framework or a customer support system) and you want to connect it with Tiledesk. For example suppose you have a chatbot software that automatically serves the users (via a widget or others channels) but at some point you want to forward the chat to Tiledesk so that the agents ( and no longer the chatbot) serve the request.

### Steps

1. Signup a user on Tiledesk
2. Anonymous end-user authentication through APIs
3. Creating the conversation (request)
4. Sending messages to a conversation

## Signup on Tiledesk

To use Tiledesk APIs is mandatory to signup a new user on our beta environment available on <https://panel.tiledesk.com/v3/dashboard>

![](/files/UYhILGGFOYRD8zJUlGeI)

After signup please follow the proposed wizard to create your first Tiledesk project.

Get the **PROJECT\_ID** of the created project under *Project Settings* menu. We will use this later.

![](/files/NDjJCxzqg5qKFypNPoRN)

## Anonymous end-user authentication through APIs

In this tutorial we will authenticate *end-users* through [Anonymous authentication REST API](/apis/rest-api/authentication#anonymous-authentication-for-a-user). We will do an anonymous authentication in order to get the id of the user (requester) who will create the conversation (next paragraph).

```bash
curl -v -X POST -H 'Content-Type:application/json' \
-d '{"id_project":"5e2c35c8f0dbc10017bb3aac", "firstname":"John"}' \
https://api.tiledesk.com/v3/auth/signinAnonymously
```

This will reply with the JWT token that we'll use to send our first message:

```bash
{
   "success":true,
   "token":"JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.XYZ....",
   "user":{
      "_id":"fc43a0e1-ba85-404e-9a44-bf0050330898",
      "firstname":"John",
      "id":"fc43a0e1-ba85-404e-9a44-bf0050330898",
      "fullName":"John"
   }
}
```

## Creating the conversation (request)

Now let's use [Create a conversation REST API](https://developer.tiledesk.com/apis/rest-api/requests#create-a-request) by setting mainly four parameters:

* YOUR\_ADMIN\_EMAIL and PASSWORD: use your admin credentials here
* SENDER: the anonymous user id created with the previous step.
* FIRST\_MESSAGE: this text is used to summarize the conversation subject. Normally this is the first message send by the user requester.
* PROJECT\_ID: your project id

```bash
curl -v -X POST -H 'Content-Type:application/json' \
-u YOUR_ADMIN_EMAIL:PASSWORD -d '{"sender":"SENDER", "first_text":"FIRST_MESSAGE"}' \ https://api.tiledesk.com/v3/PROJECT_ID/requests/
```

```bash
curl -v -X POST -H 'Content-Type:application/json' \
-u andrea.leo@email.it:xyz -d '{"sender":"fc43a0e1-ba85-404e-9a44-bf0050330898", "first_text":"How can i restore my password"}' \ https://api.tiledesk.com/v3/5e2c35c8f0dbc10017bb3aac/requests/
```

You will get a reponse like this:

```
{
   "_id":"6346cbed38c343d545cf8092",
   "request_id":"support-group-5e2c35c8f0dbc10017bb3aac-8e40526e6dfb4450a572cd4ede01f464",
   ....
}
```

Now an empty (without message) conversation is created. Pay attention to the *request\_id* field for the next paragraph.

## Sending messages to a conversation

Let us [Insert multiple messages REST API](https://developer.tiledesk.com/apis/rest-api/messages#insert-multiple-messages) to import the messages. We need the following parameters :

* *request\_id*: the *unique* request identifier generated by the previous endpoint call
* the admins credentials
* An array of messages where:
  * text: is the message text
  * sender is the user indentifier of the user who send the message
  * attributes.clienttimestamp: use this property to force the message timestamp in milliseconds.

```bash
curl -v -X POST -H 'Content-Type:application/json' \
 -u YOUR_ADMIN_EMAIL:PASSWORD \
-d '[{"sender":"bb0d809b-b093-419b-8b48-11a192cc3619","text":"How can i restore my password", "attributes":{"clienttimestamp":1665584701710}},{"sender":"chatbot1", "text":"You can find it here https://tiledesk.com", "attributes":{"clienttimestamp":1665584701711}}]'  \
 https://api.tiledesk.com/v3/5e2c35c8f0dbc10017bb3aac/requests/support-group-5e2c35c8f0dbc10017bb3aac-8e40526e6dfb4450a572cd4ede01f464/messages/multi
```

Looking at the dashboard of your project you will see your conversation in the Requests panel. The requests are updated in real time, so you don't have to manunally update the Requests' page. If you left unchanged all the default settings, the request will be assigned to you (make sure you are "available", looking in the lower right corner of your profile image in the left menu panel).

The agent (you) can now see the same conversation in the agent chat (first option of the menu panel will open the desktop chat).

Do you have feedback on this article? Please send us your feedback writing an email to <info@tiledesk.com>


# Webhooks

This section proposes a set of tutorial to show some common tasks you can address using this feature.

The main purpose of webhooks is call a user-defined action (in the form of an HTTP endpoint) when specific Tiledesk events occur.

The first tutorial [Custom Request assignment](https://developer.tiledesk.com/apis/tutorials/webhooks/custom-assignment-pooled) addresses an custom assignment every time a new request is moved to a Department's pooled routing schema.

The second tutorial [Request transcript on close](https://developer.tiledesk.com/apis/tutorials/webhooks/get-transcript-on-close) shows how you can get your chat transcript on each closing operation (i.e. for the purpose of sending it to your remote CRM to synchronize conversations)

More tutorials will come, stay tuned!


# Custom Request assignment

## Assign request to a custom agent

Sometimes you don't want to rely on Tiledesk native assignment logic, that is a round robin alghoritm through the available agents into a specied department.

Suppose that we want to assign a request (and the corrispondenr conversation) to a specific agent. You can implmemente your own logic using webhooks.

## Create your webhook project

Go on replit and fork the following app: [agent-handoff](https://replit.com/@tiledesk/agent-handoff#index.js)

Then go on Tiledesk and create a new project. You can call it "Custom routing".

![image](https://user-images.githubusercontent.com/32564846/160625434-27347b9b-bf07-4999-ad0c-f75420675168.png)

Now move in the Settings > Project Settings > Developer section and click on "MANAGE WEBHOOK"

![image](https://user-images.githubusercontent.com/32564846/160625699-9ae3a5d1-c132-45a5-ac25-329f5a788ca2.png)

Add this new webhook, taking care that the endpoint corresponds to the endpoint of your forked replit application followed by */webhooks*:

In our case this is the [endpoint](https://developer.tiledesk.com/external-chatbot/external-chatbot-tutorials/dialogflow-as-external-chatbot-integration#chatbot-handoff-to-human-agents).

Please use your application endpoint so you can modify the code as needed.

![image](https://user-images.githubusercontent.com/32564846/160626352-512f854a-198b-4978-bb7b-28ad7463dbd2.png)

Create the subscription.

Now move to the Bots section and create a new bot. Choose "Resolution" as the bot type.

![image](https://user-images.githubusercontent.com/32564846/160626693-b533601e-3e29-4b71-aa57-b0c40ac400f2.png)

Name it as you prefer, create it and press "Activate" when asked. This will "attach" the new chatbot to the Default Department making the bot immediatly available to end users.

![image](https://user-images.githubusercontent.com/32564846/160627101-0524955e-42fb-41f5-a5c9-4afa59fb91cd.png)

Leave all settings on the default.

Now move to "Routing & Departments" section.

![image](https://user-images.githubusercontent.com/32564846/160627360-7b586896-e53f-47c5-bed9-2f050eb9c1f7.png)

Select the "Default department" and change the Routing rules from the (default) "Assigned" to the "Pooled" mode.

![image](https://user-images.githubusercontent.com/32564846/160627675-5672708d-734e-43f5-bc1f-16ce103a74ce.png)

Well, it's done. Now let's test.

As soon as a new request is updated the code on your web application will receive an event "request.update".

The code will check if no participiants are present in the conversation. If participantsAgents\[] is empty this means that the request is in the Unassigned queue (aka in the "pool"). The code then simply queries all the teammates and select the first one, who the request will be assigned to. Feel free to choose your own logic to implement the assignment.

![image](https://user-images.githubusercontent.com/32564846/160655119-e7292c94-4781-4245-8761-d0f82d69e5fa.png)

### Self hosted installation

The *API\_ENDPOINT* var in the source code points to the Tiledesk cloud.

If you installed Tiledesk using the [Docker compose distribution](https://github.com/Tiledesk/tiledesk-deployment/blob/master/docker-compose/README.md) please use this value for your API\_ENDPOINT var:

On *localhost*:

API\_ENDPOINT = localhost/api/

On your own server:

API\_ENDPOINT = ${YOUR\_SERVER\_HOST}/api/

You can find more on the Docker installation endpoints [here](https://github.com/Tiledesk/tiledesk-deployment/blob/master/docker-compose/README.md#service-endpoints).


# Request transcript on close

With this tutorial we demonstrate how to easily get the request transcript in JSON format using the request's close event. This event is very useful if you want to send, for example, a personalized email, or if you want to save the conversation messages on an external system or save it on your own CRM.

## Create a new Project

**Step 1** - Fork the backend

To work with webhooks we'll need a web application endpoint where all the chatbot's requests will be forwarded. We'll use the [Replit](https://repl.it) service to fast create our own NodeJS web application endpoint.

Start forking the following app: [Webhook example App on Replit](https://replit.com/@tiledesk/webhook-get-transcript-on-close#index.js)

**Step 2** - Create the Tiledesk project

To use Tiledesk APIs or integrate your own chatbots it is mandatory to signup a new user on [Tiledesk](https://tiledesk.com/). Then go to the console, available on the following link <https://panel.tiledesk.com/v3/dashboard>

After signup please follow the proposed wizard to create your first Tiledesk project.

We choosed "Transcript project" as Project name:

![image](https://user-images.githubusercontent.com/32564846/160700738-3b28d8b9-36b4-4790-b592-a280b8186fe8.png)

As soon as you create the project you will be redirected to the project home (for this tutorial you can ignore the last step, relative to the widget's installation).

Now move in the Settings > Project Settings > Developer section and click on "MANAGE WEBHOOK".

![image](https://user-images.githubusercontent.com/32564846/160711091-bfd89cf5-d21d-4af4-ba03-81ba5919e97b.png)

Add this new webhook, taking care that the endpoint corresponds to the endpoint of your forked replit application followed by */webhooks*.

In our case this is the endpoint.

<https://webhook-get-transcript-on-close.tiledesk.repl.co/webhooks>

Please use your application endpoint so you can modify the code as needed.

![image](https://user-images.githubusercontent.com/32564846/160711171-3751392d-66d2-4295-a39d-f3e2bdf67855.png)

Now the webhook is connected to our backend.

## Analyzing the backend on Replit

The endpoint is the *app.post('/webhooks'...*

The code is explained in the following picture:

![image](https://user-images.githubusercontent.com/32564846/160710821-5b960bd0-cc77-4c70-8063-67e76a8149fc.png)

## Let's run

To run simply choose the "Simulate visitor" button on top of the console. As soon as you close a request the webhook is invoked and the transcript downloaded.

See you on our next tutorial!

Do you have suggestions on this article? Please send us your feedback writing an email to <info@tiledesk.com>


# Build Custom App - Quick start

## Introduction

You can build context-relevant, action-oriented apps (aka plugins) directly on top of Tiledesk with ease. We want customers to be confident that any app they connect to their Tiledesk account will be useful, work well and use their data responsibly.

A Tiledesk app is simply a small web application installed in the agent interface using an [iFrame](https://www.w3schools.com/tags/tag_iframe.asp) that extends the product's functionality in some way. You can use any web technology to create a Tiledesk app, for example: HTML, Javascript, NodeJs, Java, Python, etc.

### Quick start

To keep things simple in this quick start, you'll install and use an app named **Example Echo App** in Tiledesk. Example Echo App is an example app created to show you how to create a new Tiledesk app for the Tiledesk App Store. With Example Echo App you can find also how to read and use the Tiledesk context parameters passed by the Tiledesk clients (dashboard, webchat and widget) to your app.

Here's Example Echo App in the conversation dashboard sidebar:

![image](https://user-images.githubusercontent.com/9378770/171464951-c775416f-f94b-43af-b70f-b8df4ba29412.png)

#### Preparation

* If you don't already have a Tiledesk account, register at <https://panel.tiledesk.com/v3/dashboard/#/signup>
* Navigate to the **Example Echo App** in the **Tiledesk App Store**

![image](https://user-images.githubusercontent.com/9378770/171465518-2201e929-a906-4958-8890-dc56adb08797.png)

* Click **Install** to install Example Echo App on your Tiledesk project

![image](https://user-images.githubusercontent.com/9378770/171465698-0656ca63-3e7b-4dc6-a8b3-89bcd0335222.png)

#### Try it out

Go to the Monitor menu and get data from a conversation that's open in the dashboard interface.

* Open any conversation in the **Monitor** interface.
* To open the Example Echo App in the **conversation sidebar**, click the **Apps** icon in the bottom-right side of the conversation panel.

![image](https://user-images.githubusercontent.com/9378770/171465893-6ecee6e8-62fd-43ec-b9e1-f19b29b30ff5.png)

The Example Echo App is loaded by Tiledesk using an iframe. In the textarea of the app you can find the **JSON context payload** passed by the Tiledesk client (Conversation Detail in this example) to the app.

![image](https://user-images.githubusercontent.com/9378770/171464951-c775416f-f94b-43af-b70f-b8df4ba29412.png)

This app is configured to be available in both the dashboard and webchat, as well as in the appstore. If you want also to see this app in the webchat **select a conversation** from the list of conversations and in the **right sidebar** of the conversation details, click the **Apps** button.

![image](https://user-images.githubusercontent.com/9378770/171917421-787eef49-daaf-4b91-8f63-b5b1a9e1cadd.png)

The Example Echo App is loaded by Tiledesk:

![image](https://user-images.githubusercontent.com/9378770/171917304-af3ef9a5-f88e-4662-b147-2c90624c8eb3.png)

#### Read the Tiledesk Context parameters using iframe postMessage

The JSON context payload showed in the text area is passed using the [iframe postMessage method](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage). Using Javascript you can subscribe to the iframe postMessage method using the code below:

```
<script>
  window.addEventListener("message", (event) => {
    console.log('Tiledesk context payload ', event.data );
    ...  
  }, false);
</script>
```

Below you can find the structure of the JSON context payload:

* appname: the name of the app
* request: the request object
* token: the jwt token of the user logged in to the UI

Be careful with the code below you are continuously subscribed to the contextual parameters of Tiledesk. So if the context parameters change, for example because the conversation data changes (for example a new tag is added to the conversation), the subscription will be performed in real time.

#### Read the Tiledesk Context parameters using iframe query url parameters

You can also read some Tiledesk Context parameters getting the query url parameters passed in GET to the iframe. Tiledesk passes the following query parameters using the HTTP GET method:

* request\_id: A unique identifier for the request which is given to Tiledesk. Follow this pattern 'support-group-UUID'. You can find more info [here](https://github.com/Tiledesk/tiledesk-docs/blob/master/apis/rest-api/requests/README.md#the-request-model)
* project\_id: The unique identifier of the Tiledesk project
* app\_name: The name of the Tiledesk app

You can use the Tiledesk REST API, for example the [Request detail REST API](https://developer.tiledesk.com/apis/rest-api/requests#get-a-request-by-request_id), to obtain more information about the conversation passing the request\_id and the project\_id parameters.

Go to the [index.js page of the Example Echo App](https://replit.com/@nicolan74/tiledesk-helloworld-webchat-example-app#index.js) if you want to see how to retrieve the parameters sent by tiledesk using url parameters method.

### Note

The app is installed in several locations:

* Conversation detail in the Dashboard Monitor panel
* Conversation detail in the Agent Web Chat
* In the Tiledesk App Store.

However, data that's available in some locations may not be available in others. For example, your previous requests accessed conversation data. Conversation data is available in apps running in the conversation sidebar but not apps running in the Tiledesk App Store.

## Create a Tiledesk app

Now that you have your project, it's time to create your first app in the Apps menu:

* In Your Apps, click **Create a New App** button.

![image](https://user-images.githubusercontent.com/9378770/171993888-6979f011-fbe2-44f2-bd95-04b95b52a7ba.png)

* In the form panel insert :
  * The **app icon** of your app (required)
  * The **name** of your app (required)
  * The configure URL (optional). Used to create a custom configuration page for your app. Your app can in fact include a page to perform advanced configurations eg: https//myapp-for-tiledesk/ configuration. To access the custom configuration page, click on the "manage" button after installing the app
  * The **Render URL** (required): This attribute specifies the URL address of your webapp to embed via an iframe
  * The app short **description** (required)
  * The **learn more URL** (required)
  * Where you want your app to be available. Permitted values:
    * Dashboard: the app will be available in the conversation details panel of the dashboard
    * Webchat: the app will be available in the conversation details panel of the agent web chat
    * Widget: the app will be available in the home page panel of the widget (COMING SOON)
    * App Store: the app will be available in the Apps menu of the dashboard

![image](https://user-images.githubusercontent.com/9378770/171993907-008e785e-b924-4b75-8f7b-a5d3cefeb5cc.png)


# External Channels integration flow diagram

## Twilio Whatsapp Example

![image](https://user-images.githubusercontent.com/9378770/122037987-6e77b880-cdd5-11eb-81e1-4c1f266f637b.png)


# Telegram integration tutorial

## Introduction

![](https://user-images.githubusercontent.com/45603238/175036688-f26d0efe-3150-425b-bab2-6ca07b63adf6.png)

The Telegram Integration for Tiledesk allows to expand the offer of customer service through the exchange of messages between Telegram and Tiledesk support. This integration allows you to connect your company's Telegram bot to your Tiledesk account, thus creating a tunnel between the two platforms. Therefore customers can reach your support simply by writing to your Telegram bot and these messages will be delivered to the Tiledesk webchat, along with messages from other channels. Your agents will have a single work environment.

## Steps

The following are the steps involved in our tutorial:

1. Create a Tiledesk Project
2. Create a Telegram Bot
3. Configure the Webhook
4. Set the Webhook endpoint for Telegram
5. Subscribe to a Webhook on Tiledesk
6. Test the integration

## Create a Tiledesk Project

First of all create a Tiledesk project. Log in to the [Tiledesk Console](https://panel.tiledesk.com/), then click on "Add project".

![Create a new project](https://user-images.githubusercontent.com/45603238/174244101-5d096a58-857d-45e2-9311-bca7c05063bf.png)

Now choose a name for your project (i.e. Telegram Tutorial) and click the "CREATE PROJECT" button (leave all the options on their default values).

![Choose the project name](https://user-images.githubusercontent.com/45603238/175033347-d45427f5-6654-420e-a1da-f77fba15ab1b.png)

Nice, your project is ready.

## Create a Telegram Bot

Well, let's move on the Telegram app, on the desktop version or on the mobile one. Search and start the conversation with [@BotFather](https://t.me/botfather).

Now type */newbot* to create a new bot or choose from the options proposed by the bot.

So, choose a name for your bot and a username also, following the instruction given by @BotFather.

![New telegram bot](https://user-images.githubusercontent.com/45603238/174252867-0c159500-2937-4a50-9993-d11226fbc9af.png)

Your bot is now operative. Do you see the token? We will need it shortly.

## Configure the Webhook

We use the [Replit](https://replit.com/~) service to fast create our own NodeJS web application endpoint. Fork the tutorial application, available at this url: [https://replit.com/@GiovanniTroisi/tiledesk-telegram-tutorial-app](https://replit.com/@GiovanniTroisi/tiledesk-telegram-tutorial-app#index.js).

Use the fork button and choose a name for your app.

![Fork Replit project](https://user-images.githubusercontent.com/45603238/174968675-5813f440-a39f-4af8-8a3d-10596e117e98.png)

The app is forked and ready to run.

Now move back to your Tiledesk project's *Settings* > *Project Settings* > *General* section and copy the **Project Id**

![Tiledesk Project Id](https://user-images.githubusercontent.com/45603238/174268648-d3f28bab-67aa-4683-93d3-8de33e97a324.png)

Paste the Project Id in the *index.js* file of your NodeJS app on Replit, as shown in figure:

![Paste Project Id](https://user-images.githubusercontent.com/45603238/174282279-1c069dc4-02cf-4597-9002-74c4f7650440.png)

Now move back (again) to your Tiledesk project's *Settings* > *Project Settings* > *Developer* section. We will generate a new **secret key** that will be used to sign your JWT token. Press "GENERATE SHARED SECRET" button, but note that every time you generate a new secret the previous one will be no longer valid and you have to replace wherever you used it. Then click on "GENERATE".

![Shared Secret](https://user-images.githubusercontent.com/45603238/174272766-a397b947-2cca-4f5d-99b1-53efe6ff96b9.png)

That's your shared secret key, click on "Copy".

![Copy Shared Secret](https://user-images.githubusercontent.com/45603238/174273202-104b99fe-c790-4081-b60a-d843b9554eca.png)

Paste the Secret Key in the *index.js* file of your NodeJS app on Replit, as shown in figure:

![Paste Shared Secret](https://user-images.githubusercontent.com/45603238/174282285-f2720cc6-91f6-4f51-9974-18140edb3df8.png)

## Set the Webhook endpoint for Telegram

Now it's time to use the token provided by @BotFather earlier. Copy and paste it in the *index.js* file of your NodeJS app on Replit, as shown in figure:

![Paste Telegram token](https://user-images.githubusercontent.com/45603238/175038765-04233d8b-a05f-452c-95f5-4dc8c6f2bda1.png)

In the same file we need to set also the webhook endpoint for Telegram, that is the endpoint related to your webhook to which Telegram will send messages.

Click on "Run" button to start the server, then copy the URL in the red circle in *index.js*, inside the function **setWebhookEndpoint()**, adding "/telegram" at the end of the URL, like in figure:

![Endpoint Url](https://user-images.githubusercontent.com/45603238/174815348-e1dfb890-aec4-4640-acb8-100a9f545935.png)

## Subscribe to a Webhook on Tiledesk

We almost done, the last thing to do is to add a subscription for Tiledesk. Let's go!

Move to your Tiledesk project's *Settings* > *Project Settings* > *Developer* and click on the "MANAGE WEBHOOK" button.

![Manage Webhook Button](https://user-images.githubusercontent.com/45603238/174817082-e01011ae-8977-42e8-a10d-53dd21b1e5c5.png)

Then click on "ADD SUBSCRIPTION" button.

![Add subscription](https://user-images.githubusercontent.com/45603238/174286884-5a229142-cef0-4be8-8e5f-418b3568586e.png)

In the **New Subscription** popup select the **Message Create (only for Telegram channel)** option from the dropdown and type the Webhook Target that is the same URL than before, adding "/tiledesk" at the end of the URL, like in figure:

![Create subscription configuration](https://user-images.githubusercontent.com/45603238/174843423-062a80c0-dcb5-4235-bf28-aeec74cdc675.png)

Now click on "CREATE SUBSCRIPTION" button.

What you will see next will be the secret associated with your webhook. Keep the secret to interact with webhook trough webhook’s APIs (see [here](https://developer.tiledesk.com/apis/webhooks/subscriptions)). We don't need it for our goal, but save it in a safe place because it will only be displayed once.

![Webhook secret](https://user-images.githubusercontent.com/45603238/174982652-773fa46c-a3f2-4cf6-b571-bb0d484468fb.png)

**Well, the Webhook is now configured!**

## Test the integration

Finally we can test the Telegram integration. Move to Telegram app and search the bot created later (search it for name or username or just click on the link present on @BotFather). Then click on "Start".

![Start conversation on Telegram](https://user-images.githubusercontent.com/45603238/174973179-d006755f-7bb6-46e9-bec1-50f6bfcede43.png)

A default message "/start" will be sent to Tiledesk webchat and an agent can now reply.

![Tiledesk chat](https://user-images.githubusercontent.com/45603238/175004664-93cc2b04-2d48-4c43-ac54-d54d929528d6.png)

Message sent from Tiledesk will be delivered in the Telegram Bot chat, like any other conversation.

![Telegram chat](https://user-images.githubusercontent.com/45603238/175005794-baa995b3-c150-45a6-ba20-adbcd50a3ba8.png)

Done! The integration is completed.

[Here](https://replit.com/@andrealeo83/tiledesk-whatsapp-twilio-app) you can find an example code to integrate with **Twilio (WhatsApp)** based on the same principles treated in this tutorial

And [here](https://replit.com/@andrealeo83/tiledesk-facebook-app#index.js), another one example code, this time for **Facebook Messenger integration**.

If you have any problems do not esitate to write us on our [Community forum](https://tiledesk.discourse.group/)!

See you on our next tutorial!

Do you have suggestions on this article? Please send us your feedback writing an email to **<info@tiledesk.com>**


# Dashboard SDK

## Dashboard Autologin

To auto login pass the JWT token as a query parameter of the Dashboard URL as the following example:

```
https://panel.tiledesk.com/v3/dashboard/#/project/<YOUR_PROJECT_ID>/home?token=<JWT_TOKEN>
```

Example:

```
https://panel.tiledesk.com/v3/dashboard/#/project/5f47e834c85eca0012c97888/home?token=JWT XYZABC
```

## Embedded conversation info

You can run an embedded version of the dashboard inside an existing app using, for example an iframe, as in the following example which display the detail of a conversation (CONVERSATION\_UUID starts with support-group-XYZ)

```
<iframe src='https://panel.tiledesk.com/v3/dashboard/#/project/<YOUR_PROJECT_ID>/request-for-panel/support-group-<CONVERSATION_ID>?token=<JWT_TOKEN'></iframe>
```

Example:

```
<iframe src='https://panel.tiledesk.com/v3/dashboard/#/project/5f47e834c85eca0012c97888/request-for-panel/support-group-60afd5aba1971c00349801c1-1622819472803?token=JWT XYZABC'></iframe>
```

It will show :

![image](https://user-images.githubusercontent.com/9378770/121049719-40ccb700-c7b8-11eb-9572-c220cb895df1.png)


# Agent Chat SDK

## Autologin

To auto login pass the JWT token as a query parameter of your Chat url as in the following example:

```
https://panel.tiledesk.com/v3/chat/#conversation-detail?jwt=<JWT_TOKEN>
```


# Architecture overview

![Tiledesk Architecture Overview](https://tiledesk.com/wp-content/uploads/2024/10/Screenshot-2024-10-26-at-20.55.59.png)

*Tiledesk System Architecture Overview*

Tiledesk is a no-code/low-code framework that empowers organizations to build and deploy AI conversational agents while seamlessly integrating human support across multiple communication channels. The platform's architecture is designed to make building sophisticated AI agents accessible to everyone, from business users to developers, while maintaining the flexibility for advanced customization.

## System Components

### Visual Building Tools

The frontend provides intuitive, no-code interfaces built with Angular:

* **Automation Designer**: A visual flow builder for designing AI agent behaviors, conversation flows, and human handoff rules without coding
* **Dashboard**: Comprehensive interface for managing agents, conversations, and analytics
* **Widget**: Easily embeddable chat component for websites
* **Chat Applications**: Native apps for iOS and Android enabling human agents to take over conversations

### Backend Infrastructure

#### 1. AI and Automation Core

* Visual automation engine for executing conversation flows
* Intent classification using LSTM/BERT models for natural language understanding
* Smart assignment system for routing conversations between AI and human agents
* Built-in help center capabilities

#### 2. Multi-channel Communication

* Ready-to-use WhatsApp Business, Facebook Messenger, Telegram and SMS integrations
* Extensible channel architecture supporting additional messaging platforms
* MQTT and RabbitMQ ensuring reliable message delivery across channels

#### 3. Data and State Management

* MongoDB storing conversation histories and configurations
* Redis handling real-time states and caching
* SMTP server for email notifications

## Key Platform Features

* **No-Code First**: Build complex AI agents through visual interfaces without coding
* **Human-in-the-Loop**: Seamlessly transition between AI and human agents
* **Channel Flexibility**: Deploy your agents across multiple communication channels
* **Developer Extensible**: Full API access and customization capabilities for developers
* **Real-time Architecture**: Built for real-time conversations and instant handoffs
* **Open Platform**: Extend functionality through APIs and custom integrations

## Getting Started

Whether you're a business user looking to create your first AI agent or a developer planning to extend the platform, Tiledesk provides multiple entry points:

### For Business Users

* Use the visual Automation Designer to create conversation flows
* Deploy to your chosen channels through the dashboard
* Integrate the chat widget into your website

### For Developers

* Access our comprehensive API documentation
* Extend platform functionality using our developer tools
* Create custom channel integrations

## Technical Stack

* **Frontend**: Angular
* **Backend**: NodeJS
* **AI/ML**: Python (LSTM/BERT)
* **Databases**:
  * MongoDB (main database)
  * Redis (caching/real-time)
* **Message Brokers**:
  * RabbitMQ
  * MQTT
* **Communication**:
  * SMTP Server
  * WebSockets


# Components list

## Components list

Read the component readme files for more information.

### GitHub Projects Pages

* [Tiledesk project](https://github.com/tiledesk)
* [Chat21 project](https://github.com/chat21)

### Tiledesk

#### Core

* [Tiledesk Server](https://github.com/Tiledesk/tiledesk-server): This is the server engine of Tiledesk written in NodeJs and Express - MIT license.
* [Tiledesk Dashboard](https://github.com/Tiledesk/tiledesk-dashboard): This is the dashboard webapp for managing the Tiledesk platform written in Angular - MIT license.
* [Tiledesk Deployment](https://github.com/Tiledesk/tiledesk-dashboard): Tiledesk containerized deployment with Helm + Kubernetes and Docker Compose - MIT license

#### Mobile apps

* [Tiledesk Android app](https://github.com/Tiledesk/tiledesk-android): Native Tiledesk Android mobile app - MIT license
* [Tiledesk iOS app](https://github.com/Tiledesk/tiledesk-ios-app): Native Tiledesk iOS mobile app - MIT license

#### SDKs

* [Tiledesk Node js SDK](https://github.com/Tiledesk/tiledesk-nodejs-libs). Tiledesk Node JS SDK - MIT license

### Chat21 Messaging engine

Tiledek supports two Chat21 engines:

#### RabbitMQ + MQTT engine

* [Chat21 Server](https://github.com/chat21/chat21-server). Chat21 Server as RabbitMQ observer functions - MIT license
* [Chat21 HTTP Server](https://github.com/chat21/chat21-http-server). Chat21 RabbitMQ REST API server - MIT license

#### Firebase engine

* [Chat21 Cloud Functions](https://github.com/chat21/chat21-cloud-functions). Firebase cloud functions for Chat21. It's the server engine of Chat21 hosted on Google Firebase - MIT license

#### Web Clients

* [Chat21 Web Widget](https://github.com/chat21/chat21-web-widget). Live Chat Widget built with Firebase and Angular4 for customer support - MIT license
* [Chat21 Ionic Web App](https://github.com/chat21/chat21-ionic). A ionic v5 and Angular 8 desktop and mobile chat used by agents - MIT license

#### SDKs

* [Chat21 Node js SDK](https://github.com/chat21/chat21-node-sdk). Chat21 Node JS SDK - MIT license

#### Mobile SDKs

* [Chat21 Android SDK](https://github.com/Tiledesk/tiledesk-android-sdk). Native Chat21 SDK for Android - MIT license
* [Chat21 iOS SDK](https://github.com/Tiledesk/tiledesk-ios-sdk). Native Chat21 SDK for iOS - MIT license

## Components dependency diagram

![image](https://github.com/Tiledesk/tiledesk-docs/assets/9378770/ac4feff9-aea5-4ca9-a9c0-1f8ecd0fcc00)

### Components overview

[Chat21](http://www.chat21.org) is the default messaging engine of Tiledesk. Chat21 has a multi platform SDKs: native iOS and Android mobile SDKs and Web SDKs.

Widget, Web Chat and Native mobile apps are Chat21 modules.

Chat21 uses [RabbitMQ](https://www.rabbitmq.com/) + [MQTT](https://mqtt.org/) realtime engine. See the [announcement here](https://tiledesk.com/2021/02/12/tiledesk-new-messaging-engine-moving-from-firebase-to-mqtt-rabbitmq/)

### Tiledesk with RabbitMQ + MQTT Chat21 engine

![image](https://user-images.githubusercontent.com/9378770/107744465-02941f00-6d13-11eb-87b4-03c22038884e.png)

Chat21 communicates with Tiledesk through webhooks. When a Chat21 event occurs - a new message arrives, a new member join a group, etc - a new Event is created and notified to Tiledesk Server. Chat21 then makes an HTTP POST request to send the Event to the Tiledesk webhook [endpoint](https://github.com/Tiledesk/tiledesk-server/blob/master/channels/chat21/chat21WebHook.js) .

### Tiledesk network diagram

![image](https://user-images.githubusercontent.com/9378770/177378143-e5b61492-7439-4e8f-994e-1677e7c24c4d.png)

### Tiledesk-server overview

![](/files/-LfxHob-5Xx1tikPyMnq)


# Bot Design diagram

![](https://lh5.googleusercontent.com/b-cbpfjyVe-snghacTCiRPW4kRs8CUKi2ZrM42HBeZjaXJRzxgja7WYEIa5iHajcQ0pcBjXJmvtI5IGRu6mKTdewz-htY9EgHkDIr0hUeXltIAqXyu-N2lr8tTUk_HyQQ0gi2ciG)


# Multi Channel Message Flow

![tiledesk-multi-channel 001](https://user-images.githubusercontent.com/9378770/105201568-53b05900-5b41-11eb-9aee-b8a8de7eacf6.jpeg)


# Installation

## Run with Docker <a href="#run-with-docker" id="run-with-docker"></a>

Docker is the simplest way to run Tiledesk. There’s a public repository on [Docker Hub](https://hub.docker.com/u/tiledesk).

Please refer to [Running Tiledesk with Docker Compose](https://github.com/Tiledesk/tiledesk-deployment/blob/master/docker-compose/README.md).

## Run with Kubernetes <a href="#run-with-kubernetes" id="run-with-kubernetes"></a>

Use this information to deploy Tiledesk using Helm charts by running a Kubernetes cluster. This is a deployment template which can be used as the basis for your specific deployment needs.

Please refer to [Running Tiledesk with Kubernetes using Helm](/installation/running-tiledesk-with-kubernetes-helm) .


# Running Tiledesk with Kubernetes using Helm

This guide is still in beta. The docker images is nightly build so can contains bugs and instability.

The following guide bootstraps a Tiledesk deployment on a Kubernetes cluster using the Helm package manager:

<https://github.com/Tiledesk/tiledesk-deployment>

**Please help us improving this documentation**: if you encounter a problem, something you don’t understand or a typo, use [this link](https://github.com/Tiledesk/tiledesk-deployment/issues) to ask a question. You could also open a PR to directly fix the documentation on Github, if you want.


# Choosing Hardware

## Server Requirements for Tiledesk

### Minimum Infrastructure

The minimum recommended setup for hosting Tiledesk involves two separate servers:

* **Server 1**: To host the Tiledesk Server, Dashboard, Widget, and Web Chat.
* **Server 2**: Dedicated to MongoDB.

This basic infrastructure allows the servers to be up and running but does not account for advanced quality parameters such as performance, high availability, backups, redundancy, and disaster recovery.

**Instance Type Recommendation**: The default instance type recommended is an **AWS EC2 t2.small** (or equivalent), which is sufficient for testing environments. For production environments, a **c4.large** instance is ideal, providing better performance and stability.

**Alternative with Heroku**: If you prefer using Heroku, we recommend at least the **Hobby dyno** type for small applications, although Tiledesk can also run on the **Free** type for development and testing.

### Production Environment Configuration

For production environments with higher traffic and reliability requirements, consider a more robust server configuration:

* **Load Balancer**: To manage traffic and increase availability by distributing the load across multiple instances.
* **Auto-scaling**: To dynamically adjust server capacity based on traffic.
* **Backup and Disaster Recovery**: Enable regular automated backups and define a disaster recovery plan.

## Front-end Components

To serve Tiledesk’s front-end components (Dashboard, Widget, and Web Chat), we suggest using **AWS S3 + CloudFront**. This setup enables efficient and scalable distribution of static content.

### Traffic Optimization

* **Enable Gzip Compression** on CloudFront to reduce network traffic and improve loading performance. More info here: <https://aws.amazon.com/blogs/aws/new-gzip-compression-support-for-amazon-cloudfront/>

## Database

We recommend the following configurations for MongoDB:

### MongoDB Options

1. **MongoDB Atlas**:
   * **M10**: Suitable for testing or low-traffic applications. It supports continuous backups for data security.
   * **M30 or higher**: Recommended for high-traffic applications or production environments, providing better performance and scalability.
2. **Local Installation in Replica Set Mode**:
   * **Replica Set** with at least three nodes, each located in a separate Availability Zone to improve database reliability and availability. This setup reduces the risk of data loss and ensures greater service continuity.

### Additional Database Management Tips

* **Sharding (for high workloads)**: In cases of heavy database usage, consider implementing sharding to distribute the load and enhance performance.
* **Performance Monitoring**: Use tools like MongoDB Compass or integrations with monitoring systems (e.g., CloudWatch) to track the database status and optimize resource allocation.

## Other Backend Requirements (Third-Party Services)

To run Tiledesk in an on-premise environment, the following third-party backend services are required:

### Required Services

* **RabbitMQ** – *Message broker* used for internal communication between microservices.
* **Redis** – *Caching layer* that improves system performance by storing temporary data in memory.

> ⚠️ These services must be installed and properly configured before proceeding with the Tiledesk installation.

### Deployment Modes

* For **non-business-critical environments** (e.g. testing or small-scale deployments), all services can be installed in a **singlenode setup** on a single virtual machine or server.
* For **production-grade or business-critical environments**, a **high-availability (HA) setup** with service replication and failover is strongly recommended to ensure reliability and uptime.

***

## Optional: Hosting Large Language Models (LLMs)

If you plan to host a Large Language Model (LLM) such as LLaMA 3, which requires substantial computational resources, here are additional hardware specifications and recommendations:

### Hardware Specifications for LLM Hosting

#### GPU

* **Architecture**: NVIDIA Ampere or newer (e.g., A100, A6000, H100).
* **GPU Memory**: At least 40 GB of HBM2 or higher (for larger models).
* **CUDA Cores**: At least 6,912 cores to handle intensive AI workloads.
* **NVLink**: If available, use NVLink to connect multiple GPUs, increasing communication bandwidth between GPUs and improving performance for larger models.

#### CPU

* **Multi-core CPU**: Minimum 16 cores (32 threads) to support distributed workloads. Preferably a recent AMD EPYC or Intel Xeon CPU.
* **Clock Speed**: At least 2.5 GHz per core.

#### RAM

* **RAM Amount**: Minimum 128 GB DDR4/DDR5. For particularly large models, consider 256 GB or more, especially if the model will handle multiple requests simultaneously.

#### Storage

* **Storage Type**: NVMe SSD for faster data access and improved I/O performance.
* **Storage Capacity**: Minimum 1 TB, with scalability based on the model size and any auxiliary data. For long-term projects, consider a distributed storage system.

***

### Additional Optimization Suggestions

1. **Cooling and Power**: High-performance GPUs like the A100 or H100 require adequate cooling and stable power supply. Ensure that the cooling infrastructure is sufficient, especially for on-premises setups.
2. **Cluster Configurations**: For large-scale applications, consider using a GPU cluster, for example, via a Kubernetes system with GPU support. This allows for elastic scaling based on workload and provides redundancy.
3. **Networking**: For clusters, consider using a high-speed network (e.g., InfiniBand) to minimize latency between nodes and enhance overall performance.
4. **Containers and Virtualization**: Use Docker or other containers for rapid deployment and to ensure portability of the model across different platforms.
5. **Resource Management and Monitoring**: Use tools like NVIDIA’s GPU Cloud (NGC) to monitor and manage resources, optimizing GPU utilization and maintaining system stability.

***

## Cloud Hosting Considerations

Tiledesk can be deployed in private or public cloud environments, utilizing dedicated hardware configurations provided by cloud providers such as AWS, Azure, or Google Cloud, with support for high-level GPUs like NVIDIA A100 and V100. This approach offers scalability and simplified management without the need for maintaining physical hardware.

***

This guide provides a solid and scalable setup for running Tiledesk in both development and production environments, with optional infrastructure suggestions for hosting Large Language Models if needed, allowing your infrastructure to grow based on traffic demands.


# Chat21 channel configuration

Tiledesk uses [Chat21](http://www.chat21.org) as messaging platform. Refer to [Architecture overview](/architecture/schema) to undestand the product's modules. In detail the tiledesk-server component uses Chat21 channel for sending chat messages, creating groups, etc.

So in order to correctly configure your Tiledesk installation you MUST configure the following properties:

* FIREBASE\_PRIVATE\_KEY. You can get it [here](https://github.com/Tiledesk/tiledesk-docs/blob/master/installation/chat21-installation/chat21-firebase-installation/create-a-firebase-project.md#create-an-sdk-firebase-admin-account). It is in the form: `-----BEGIN PRIVATE KEY-----\ABCD78261TGV...HGAGBA82727\n-----END PRIVATE KEY-----\n`. More info about firebase private key [here](https://firebase.google.com/docs/admin/setup#initialize_the_sdk).
* FIREBASE\_CLIENT\_EMAIL. You can get it [here](https://github.com/Tiledesk/tiledesk-docs/blob/master/installation/chat21-installation/chat21-firebase-installation/create-a-firebase-project.md#create-an-sdk-firebase-admin-account). It is in the form: `firebase-adminsdk-******@************.iam.gserviceaccount.com`
* FIREBASE\_PROJECT\_ID. Get it [here](https://github.com/Tiledesk/tiledesk-docs/blob/master/installation/chat21-installation/chat21-firebase-installation/create-a-firebase-project.md#create-an-app).
* FIREBASE\_APIKEY. Get it [here](https://github.com/Tiledesk/tiledesk-docs/blob/master/installation/chat21-installation/chat21-firebase-installation/create-a-firebase-project.md#create-an-app).
* FIREBASE\_AUTHDOMAIN. Get it [here](https://github.com/Tiledesk/tiledesk-docs/blob/master/installation/chat21-installation/chat21-firebase-installation/create-a-firebase-project.md#create-an-app). It is in the form: `CHANGEIT.firebaseapp.com`
* FIREBASE\_DATABASEURL. Get it [here](https://github.com/Tiledesk/tiledesk-docs/blob/master/installation/chat21-installation/chat21-firebase-installation/create-a-firebase-project.md#create-an-app). It is in the form: `https://CHANGEIT.firebaseio.com`
* FIREBASE\_STORAGEBUCKET. You can find it [here](https://github.com/Tiledesk/tiledesk-docs/tree/7ed1cde88582e9a174199b20bd6ad610f0153fcb/configuration/installation/chat21-installation/chat21-firebase-installation/create-a-firebase-project.md#create-a-storage). It is in the form: `CHANGEIT.appspot.com`
* FIREBASE\_MESSAGINGSENDERID. Get it [here](https://github.com/Tiledesk/tiledesk-docs/blob/master/installation/chat21-installation/chat21-firebase-installation/create-a-firebase-project.md#create-an-app). A unique numerical value created when you create your Firebase project, available in the [Cloud Messaging](https://console.firebase.google.com/project/_/settings/cloudmessaging/) tab of the Firebase console **Settings** pane.
* CHAT21\_ENABLED. Enable Chat21 channel with **true** value.
* FIREBASE\_APP\_ID. Get it [here](https://github.com/Tiledesk/tiledesk-docs/blob/master/installation/chat21-installation/chat21-firebase-installation/create-a-firebase-project.md#create-an-app).
* CHAT21\_URL. Get it [here](https://github.com/Tiledesk/tiledesk-docs/blob/master/installation/chat21-installation/chat21-firebase-installation/create-a-firebase-project.md#get-the-cloud-function-url). It is in the form: `https://mytiledeskinstallation87.cloudfunctions.net`
* CHAT21\_ENGINE. Enter the default value **firebase**
* CHAT21\_APPID. Enter the default value **tilechat**
* CHAT21\_ADMIN\_TOKEN. The Chat21 admin token. The default value is `chat21-secret-orgAa,`. See [here](https://github.com/chat21/chat21-cloud-functions/blob/master/docs/setup_options.md#admin-token) to change it.

You can find other information regarding the env variable here: <https://github.com/Tiledesk/tiledesk-server/blob/master/.env.sample>


# Email parameters and templates configuration

Use this information to configure the email services for the on-premise installation for outbound email to manage all emails sent from Tiledesk to users such as project invitations, email verification, subscriptions and notifications. Tiledesk uses [NodeMailer](https://nodemailer.com/) to send the emails.

## Enable the email subsystem

To enable the email service set the follow **env property** to true of your **tiledesk-server** component. The default value is false.

```
EMAIL_ENABLED=true
```

## SMTP configuration

The following properties can be configured for the Outbound SMTP subsystem type:

* **EMAIL\_HOST**=YOUR\_EMAIL\_HOST Specifies the host name (defaults to "localhost") of the SMTP host, that is, the host name or IP address of the server to which email should be sent.
* **EMAIL\_USERNAME**=YOUR\_EMAIL\_USERNAME Specifies the user name of the account that connects to the smtp server.
* **EMAIL\_SECURE**=true #defaults to 587 if is secure is false or 465 if true If true the connection will use TLS when connecting to server. If false (the default) then TLS is used if server supports the STARTTLS extension. In most cases set this value to true if you are connecting to port 465. For port 587 or 25 keep it false.
* **EMAIL\_PORT**=25 Is the port to connect to (defaults to 587 if is secure is false or 465 if true)
* **EMAIL\_PASSWORD**=YOUR\_SMTP\_PASSWORD Specifies the password for the user name used in EMAIL\_USERNAME.
* **EMAIL\_FROM\_ADDRESS**=FROM\_EMAIL\_ADDRESS Specifies the email address from which email notifications are sent. This setting is for emails that are not triggered by a user, for example, activity notification emails.
* **EMAIL\_BASEURL**=<https://YOOURDOMAIN.com/dashboard> This is the dashboard endpoint. Default value is : <https://panel.tiledesk.com/v3/dashboard>

## Email template configuration

In Tiledesk you can customize the emails template using the following **env variables** (multiline strings) of your **tiledesk-server** component :

* **EMAIL\_ASSIGN\_REQUEST\_HTML\_TEMPLATE** Email sent to notify a new request in the assigned mode.
* **EMAIL\_ASSIGN\_MESSAGE\_EMAIL\_HTML\_TEMPLATE** Email sent to notify a new request in the assigned mode for inbound email channel.
* **EMAIL\_POOLED\_REQUEST\_HTML\_TEMPLATE** Email sent to notify a new request in the pooled mode.
* **EMAIL\_POOLED\_MESSAGE\_EMAIL\_HTML\_TEMPLATE** Email sent to notify a new request in the pooled mode for inbound email channel.
* **EMAIL\_NEW\_MESSAGE\_HTML\_TEMPLATE** Email sent to the requester to notify a new message when the requester is offline
* **EMAIL\_TICKET\_HTML\_TEMPLATE** Email sent to the requester to notify a new message for inbound email channel.
* **EMAIL\_FOLLOWER\_HTML\_TEMPLATE** Email sent to the request follower to notify an update.
* **EMAIL\_DIRECT\_HTML\_TEMPLATE** Email sent for direct message.
* **EMAIL\_RESET\_PASSWORD\_HTML\_TEMPLATE** Email sent when a user reset the password.
* **EMAIL\_PASSWORD\_CHANGED\_HTML\_TEMPLATE** Email sent when the password is changed.
* **EMAIL\_EXUSER\_INVITED\_HTML\_TEMPLATE** Email sent when a agent invites an existing platform user.
* **EMAIL\_NEWUSER\_INVITED\_HTML\_TEMPLATE** Email sent when a agent invites a new user.
* **EMAIL\_VERIFY\_HTML\_TEMPLATE** Email sent when an agent signup on the platform.
* **EMAIL\_SEND\_TRANSCRIPT\_HTML\_TEMPLATE** If the property "Transcript by email" is enabled this email is sent automatically at the end of each chat to the requester.

You can find the default email templates under the [template/email](https://github.com/Tiledesk/tiledesk-server/tree/master/template/email) folder of the tiledesk-server project

Please refer to these guides for multi-line env variables:

* [Yaml multi-line](https://yaml-multiline.info) for Kubernetes
* [Helm multi-line control](https://helm.sh/docs/chart_template_guide/yaml_techniques/#controlling-spaces-in-multi-line-strings)


# Configure the logging system

Tiledesk uses [Winston](https://github.com/winstonjs/winston) as logging library. The Tiledesk server is configured with the following transports :

* the console
* logs files under /logs/app.log folder

## Configure the log level

The default log level is INFO. If you want to change the log level use the `LOG_LEVEL` environment property as follow:

```
LOG_LEVEL="verbose"
```

## Enable logs to MongoDB

Optionally you can write the logs to the MongoDB database (adding a MongoDB transport to Winston) with the following environment property:

```
WRITE_LOG_TO_MONGODB="true"
```

You can also change (default value is INFO) the level for the MongoDB transport with the following property:

```
LOG_MONGODB_LEVEL="error"
```


