> For the complete documentation index, see [llms.txt](https://docs.chatlayer.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.chatlayer.ai/chatlayer-documentation-pt-br/integrateandcode/human-offloading-live-chat/offloading-webhook.md).

# Webhook de Offloading

O webhook de offloading permite integrar qualquer plataforma de chat ao vivo para transferência para atendimento humano. Você pode usar o webhook para:

* Receber mensagens de entrada do usuário
* Receber mensagens de saída do bot
* Agir sobre solicitações de offloading de um usuário

{% hint style="warning" %}
O Webhook de Offloading é para transferir usuários do bot para um agente humano. O [canal Webhook](https://docs.chatlayer.ai/channels/webhook-api) é um canal de integração personalizado; certifique-se de não confundir os dois!
{% endhint %}

## Configuração

Para configurar seu Chatlayer Offloading Webhook, acesse **Configurações > Offloading** e crie uma **Webhook** integração.

![](/files/b82cd2fc90a899722b3c52b4e12ebf70b32a5e6c)

Insira a URL da API do seu webservice e um Token de Verificação que permita validar as requisições recebidas.

Enviaremos uma requisição de teste para a URL da sua API quando você clicar em Salvar para validar se o seu webservice está ativo e pronto para receber requisições, conforme descrito no método Health Check.

Parabéns! Você está pronto para começar a usar sua integração personalizada de transferência para atendimento humano.

## Referência de Implementação do Webservice

Seu webservice precisará implementar os seguintes métodos da API para que possamos nos comunicar com ele. Todas as requisições chegarão em formato JSON na URL da API configurada durante a configuração do webhook de offloading no Chatlayer. Cada requisição POST em JSON tem um corpo com um **event** parâmetro que permite distinguir entre os diferentes tipos de dados recebidos. Os diferentes tipos são explicados abaixo.

Esperamos um código de status HTTP 200 para cada requisição feita ao webservice. Os dados da resposta devem estar em formato JSON.

## Verificação de Saúde da API

<mark style="color:azul;">`GET`</mark> `<your_api_url>`

Você deve enviar a resposta conforme descrito na aba Response.

#### Parâmetros de Consulta

| Nome                  | Tipo   | Descrição                                                               |
| --------------------- | ------ | ----------------------------------------------------------------------- |
| challenge.verifyToken | string | O verifyToken permite validar que a requisição foi feita pelo Chatlayer |

{% tabs %}
{% tab title="200 " %}

```
{ "status": "ok" }
```

{% endtab %}
{% endtabs %}

## Mensagens

<mark style="color:verde;">`POST`</mark> `<your_api_url>`

#### Parâmetros de Consulta

| Nome                  | Tipo   | Descrição                                                               |
| --------------------- | ------ | ----------------------------------------------------------------------- |
| challenge.verifyToken | string | O verifyToken permite validar que a requisição foi feita pelo Chatlayer |

#### Corpo da Requisição

| Nome      | Tipo   | Descrição                                       |
| --------- | ------ | ----------------------------------------------- |
| timestamp | string | O momento em que a mensagem foi gerada          |
| messages  | matriz | Um array de mensagens do usuário e do bot       |
| event     | string | O tipo de requisição, neste caso **`messages`** |
| canal     | string | O tipo de canal                                 |
| sessionId | string | O ID da sessão do usuário                       |
| version   | string | A versão do bot, DRAFT ou LIVE                  |
| botId     | string | O ID do bot                                     |

{% tabs %}
{% tab title="200 Não esperamos um corpo de resposta." %}

```
```

{% endtab %}
{% endtabs %}

Os itens no array messages têm o seguinte formato -

```javascript
{
    "actor": "bot" | "user",
    "message": UserMessage | BotMessage
}
```

**BotMessage** os objetos seguem a mesma estrutura da API do Webhook Channel, documentada [aqui](https://docs.chatlayer.ai/channels/webhook-api#message-objects).

```javascript
// Exemplo de mensagem de bot de texto
{
    "botId": "ko3123ze",
    "version": "DRAFT",
    "sessionId": "emulator-18878e66-03fb-4ee7-b2c4-eb9db1848291",
    "event": "messages",
    "messages": [
        {
            "actor": "bot",
            "message": {
                "text": "Olá, bem-vindo"
            },
            "timestamp": "2021-11-15T07:38:31.387Z"
        }
    ],
    "timestamp": "2021-11-15T07:38:31.387Z"
}

// Exemplo de mensagem de bot com resposta rápida
{
    "botId": "ko3123ze",
    "version": "DRAFT",
    "sessionId": "emulator-d3dac415-5263-482c-a30b-d1588c52d918",
    "event": "messages",
    "messages": [
        {
            "actor": "bot",
            "message": {
                "text": "Olá, bem-vindo"
            },
            "timestamp": "2021-11-15T07:47:08.383Z"
        },
        {
            "actor": "bot",
            "message": {
                "text": "Escolha o que você quer fazer?",
                "quick_replies": [
                    {
                        "title": "Executar API a partir do código",
                        "payload": "{\"title\":\"Executar API a partir do código\",\"caption\":\"Executar API a partir do código\",\"type\":\"quickreply\",\"parameters\":[],\"nextDialogstateId\":\"19f87132-e23c-4335-877d-6a36f511c2cc\",\"originalTitle\":\"Executar API a partir do código\"}",
                        "content_type": "text"
                    },
                    {
                        "title": "Plugin de API",
                        "payload": "{\"title\":\"Plugin de API\",\"caption\":\"Plugin de API\",\"type\":\"quickreply\",\"parameters\":[],\"nextDialogstateId\":\"e0b327e0-bfa0-42a7-9685-c68491625b6e\",\"originalTitle\":\"Plugin de API\"}",
                        "content_type": "text"
                    },
                    {
                        "title": "SendMessageFromCode",
                        "payload": "{\"title\":\"SendMessageFromCode\",\"caption\":\"SendMessageFromCode\",\"type\":\"quickreply\",\"parameters\":[],\"nextDialogstateId\":\"c125a34e-7fec-4385-8333-6a91e25cdcff\",\"originalTitle\":\"SendMessageFromCode\"}",
                        "content_type": "text"
                    }
                ]
            },
            "timestamp": "2021-11-15T07:47:08.384Z"
        }
    ],
    "timestamp": "2021-11-15T07:47:08.383Z"
}

// carrossel / mensagem de template genérico
{
    "botId": "ko3123ze",
    "version": "DRAFT",
    "sessionId": "emulator-39ac2f23-07ce-4878-bd7d-729e6b39efdf",
    "event": "messages",
    "messages": [
        {
            "actor": "bot",
            "message": {
                "attachment": {
                    "type": "template",
                    "payload": {
                        "template_type": "generic",
                        "elements": [
                            {
                                "title": "Item 1",
                                "image_url": "https://st.depositphotos.com/1708346/1858/i/600/depositphotos_18582903-stock-photo-carousel-at-night.jpg",
                                "buttons": [
                                    {
                                        "title": "Docs",
                                        "url": "https://docs.chatlayer.ai",
                                        "type": "web_url"
                                    }
                                ]
                            },
                            {
                                "title": "Item 2",
                                "image_url": "https://st.depositphotos.com/1708346/1858/i/600/depositphotos_18582903-stock-photo-carousel-at-night.jpg",
                                "subtitle": "Subtítulo do Item 2",
                                "buttons": [
                                    {
                                        "title": "Docs",
                                        "url": "https://docs.chatlayer.ai",
                                        "type": "web_url"
                                    }
                                ],
                                "default_action": {
                                    "url": "https://docs.chatlayer.ai",
                                    "type": "web_url"
                                }
                            }
                        ]
                    }
                }
            },
            "timestamp": "2021-11-15T08:24:32.871Z"
        }
    ],
    "timestamp": "2021-11-15T08:24:32.871Z"
}
```

**UserMessage** os objetos podem ter as seguintes estruturas:

```javascript
// Exemplos de UserMessage

// Introdução
{
    "botId": "ko3123ze",
    "version": "DRAFT",
    "sessionId": "emulator-942c05c5-b9b7-4319-81e7-6d687afaa23f",
    "event": "messages",
    "messages": [
        {
            "actor": "user",
            "message": {
                "channelType": "web",
                "sender": {
                    "id": "emulator-942c05c5-b9b7-4319-81e7-6d687afaa23f",
                    "botId": "ko3123ze",
                    "botType": "web",
                    "preferredLanguage": "en",
                    "firstname": "Visitante",
                    "isEmulator": "true"
                },
                "timestamp": "2021-11-15T08:28:05.872Z",
                "messageType": "intro",
                "id": "61921a15cdee7f37a16ee5fc"
            },
            "timestamp": "2021-11-15T08:28:05.872Z"
        }
    ],
    "timestamp": "2021-11-15T08:28:05.908Z"
}

// Texto
{
    "botId": "ko3123ze",
    "version": "DRAFT",
    "sessionId": "emulator-8f5873aa-8fee-471a-9467-81e30dec693d",
    "event": "messages",
    "messages": [
        {
            "actor": "user",
            "message": {
                "channelType": "web",
                "sender": {
                    "id": "emulator-8f5873aa-8fee-471a-9467-81e30dec693d",
                    "botId": "ko3123ze",
                    "botType": "web",
                    "isEmulator": "true"
                },
                "timestamp": "2021-11-15T08:26:13.154Z",
                "messageType": "text",
                "text": "oi",
                "id": "619219a5cdee7f9f1b6ee5f7"
            },
            "timestamp": "2021-11-15T08:26:13.154Z"
        }
    ],
    "timestamp": "2021-11-15T08:26:13.193Z"
}

// Upload
{
    "botId": "ko3123ze",
    "version": "DRAFT",
    "sessionId": "1636964964162",
    "event": "messages",
    "messages": [
        {
            "actor": "user",
            "message": {
                "channelType": "web",
                "sender": {
                    "id": "1636964964162",
                    "botId": "ko3123ze",
                    "botType": "web",
                    "firstname": "Visitante"
                },
                "timestamp": "2021-11-15T08:29:38.900Z",
                "messageType": "fileUploadInputResult",
                "urls": [
                    "https://minio.dev.chatlayer.ai/chatlayer-dev-eu-storage/f42af93e42b350fd7b874300c775756b168cc9ea4475b0c8c80e947228a26404/1636964964162_full.png"
                ],
                "data": {
                    "uploadStatus": "SUCCEEDED",
                    "fileUrl": "https://minio.dev.chatlayer.ai/chatlayer-dev-eu-storage/f42af93e42b350fd7b874300c7asdasdcc9ea4475b0c8c80e947228a26404/1636964964162_full.png"
                },
                "id": "61921a72cdee7fd1c56ee614"
            },
            "timestamp": "2021-11-15T08:29:38.900Z"
        }
    ],
    "timestamp": "2021-11-15T08:29:38.934Z"
}}

// Localização
{
    "botId": "ko3123ze",
    "version": "DRAFT",
    "sessionId": "emulator-8f5873aa-8fee-471a-9467-81e30dec693d",
    "event": "messages",
    "messages": [
        {
            "actor": "user",
            "message": {
                "channelType": "web",
                "sender": {
                    "id": "emulator-8f5873aa-8fee-471a-9467-81e30dec693d",
                    "botId": "ko3123ze",
                    "botType": "web",
                    "isEmulator": "true"
                },
                "timestamp": "2021-11-15T08:26:13.154Z",
                "messageType": "location", 
                "coordinates": { "lat": 0, "long": 0 } 
                "id": "619219a5cdee7f9f1b6ee5f7"
            },
            "timestamp": "2021-11-15T08:26:13.154Z"
        }
    ],
    "timestamp": "2021-11-15T08:26:13.193Z"
}

// Postback
{
    "botId": "ko3123ze",
    "version": "DRAFT",
    "sessionId": "emulator-6d09d652-a971-47ab-8484-223a86ff316e",
    "event": "messages",
    "messages": [
        {
            "actor": "user",
            "message": {
                "channelType": "web",
                "sender": {
                    "id": "emulator-6d09d652-a971-47ab-8484-223a86ff316e",
                    "botId": "ko3123ze",
                    "botType": "web",
                    "isEmulator": "true"
                },
                "timestamp": "2021-11-15T08:33:39.276Z",
                "messageType": "postback",
                "title": "Definir Variáveis",
                "parameters": [],
                "nextDialogstateId": "071abbc7-1d6e-4689-adef-1ea825178a72",
                "id": "61921b63cdee7f21ab6ee621"
            },
            "timestamp": "2021-11-15T08:33:39.276Z"
        }
    ],
    "timestamp": "2021-11-15T08:33:39.309Z"
}
```

## Transferência

<mark style="color:verde;">`POST`</mark> `<your_api_url>`

#### Corpo da Requisição

| Nome       | Tipo   | Descrição                                                           |
| ---------- | ------ | ------------------------------------------------------------------- |
| payload    | objeto | O payload que você configurou no action dialogstate                 |
| canal      | string |                                                                     |
| transcript | matriz | Um array contendo todas as mensagens enviadas ao longo da conversa. |
| event      | string | O tipo de requisição, neste caso **`offload`**                      |
| timestamp  | string |                                                                     |
| sessionId  | string |                                                                     |
| version    | string |                                                                     |
| botId      | string |                                                                     |

{% tabs %}
{% tab title="200 Para um offloading bem-sucedido, esperamos a seguinte resposta" %}

```
{
    "offloadSuccess": true,
    "pauseBot": true
}
```

{% endtab %}
{% endtabs %}

Os itens no array transcript têm o mesmo formato da **messages** método descrito acima.

Um exemplo da solicitação de offload pode ser o seguinte:

```
// Algum código
{
    "botId": "ko3123ze",
    "version": "DRAFT",
    "sessionId": "emulator-714a7b79-d674-4a62-a9a9-49581d7451e5",
    "timestamp": "2021-11-15T08:36:21.527Z",
    "event": "offload",
    "transcript": [
        {
            "actor": "bot",
            "message": {
                "text": "Olá, bem-vindo"
            },
            "timestamp": "2021-11-15T08:36:11.991Z"
        },
        {
            "actor": "bot",
            "message": {
                "text": "Escolha o que você quer fazer?",
                "quick_replies": [
                    {
                        "title": "Executar API a partir do código",
                        "payload": "{\"title\":\"Executar API a partir do código\",\"caption\":\"Executar API a partir do código\",\"type\":\"quickreply\",\"parameters\":[],\"nextDialogstateId\":\"19f87132-e23c-4335-877d-6a36f511c2cc\",\"originalTitle\":\"Executar API a partir do código\"}",
                        "content_type": "text"
                    },
                    {
                        "title": "Plugin de API",
                        "payload": "{\"title\":\"Plugin de API\",\"caption\":\"Plugin de API\",\"type\":\"quickreply\",\"parameters\":[],\"nextDialogstateId\":\"e0b327e0-bfa0-42a7-9685-c68491625b6e\",\"originalTitle\":\"Plugin de API\"}",
                        "content_type": "text"
                    },
                    {
                        "title": "carrossel",
                        "payload": "{\"title\":\"carrossel\",\"caption\":\"carrossel\",\"type\":\"quickreply\",\"parameters\":[],\"nextDialogstateId\":\"0844670c-ee9f-43eb-9102-f50321cb4921\",\"originalTitle\":\"carrossel\"}",
                        "content_type": "text"
                    },
                    {
                        "title": "primeiras opções",
                        "payload": "{\"title\":\"primeiras opções\",\"caption\":\"primeiras opções\",\"type\":\"quickreply\",\"parameters\":[],\"nextDialogstateId\":\"13fc7f3e-80e5-45b8-862b-d2ff436eae0e\",\"originalTitle\":\"primeiras opções\"}",
                        "content_type": "text"
                    }
                ]
            },
            "timestamp": "2021-11-15T08:36:11.992Z"
        },
        {
            "actor": "user",
            "message": {
                "parameters": [],
                "text": "primeiras opções",
                "messageType": "postback",
                "title": "primeiras opções",
                "nextDialogstateId": "13fc7f3e-80e5-45b8-862b-d2ff436eae0e",
                "channelType": "emulator",
                "sender": {
                    "id": "emulator-714a7b79-d674-4a62-a9a9-49581d7451e5",
                    "botId": "ko3123ze"
                }
            },
            "timestamp": "2021-11-15T08:36:15.009Z"
        },
        {
            "actor": "bot",
            "message": {
                "attachment": {
                    "type": "template",
                    "payload": {
                        "template_type": "button",
                        "text": "O que você quer fazer?",
                        "buttons": [
                            {
                                "title": "Definir Variáveis",
                                "type": "postback",
                                "payload": "{\"title\":\"Definir Variáveis\",\"caption\":\"Definir Variáveis\",\"type\":\"button\",\"originalTitle\":\"Definir Variáveis\",\"nextDialogstateId\":\"071abbc7-1d6e-4689-adef-1ea825178a72\",\"parameters\":[]}"
                            },
                            {
                                "title": "transferir",
                                "type": "postback",
                                "payload": "{\"title\":\"transferir\",\"caption\":\"transferir\",\"type\":\"button\",\"originalTitle\":\"transferir\",\"nextDialogstateId\":\"408c102e-7215-48f8-a76c-5a45d70dcd9d\",\"parameters\":[]}"
                            }
                        ]
                    }
                }
            },
            "timestamp": "2021-11-15T08:36:15.010Z"
        }
    ]
}
```

## Receitas

### Transferência de atendimento humano solicitada pelo usuário

Use um bloco de ação "Enviar para o provedor de offload" para acionar uma **offload** chamada à sua API.

![](/files/82f185b59ecb1093c1029bf99c3686b150131ce0)

### Enviando mensagens como agente

Use o [API de ações da conversa ](https://api.chatlayer.ai/v1/docs/#operation/executeConversationAction)para enviar mensagens como agente.

### Perguntas frequentes sobre Webhook Offloading

Aqui você pode encontrar perguntas frequentes sobre o offloading via webhook

**Por que recebo requisições no endpoint de offloading mesmo quando o usuário ainda não foi transferido?**

Enviamos os detalhes de todas as conversas que estão acontecendo entre o usuário e o bot para o endpoint de offloading sob o **event: "messages"** para que você possa assumir a conversa, se necessário. Isso também permitiria aos clientes acompanhar todas as conversas, se necessário.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

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

```
GET https://docs.chatlayer.ai/chatlayer-documentation-pt-br/integrateandcode/human-offloading-live-chat/offloading-webhook.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

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