# Construa agentes de voz com a Diska A Diska é a plataforma onde a sua empresa cria, testa e publica **agentes de voz com IA**. Um agente atende clientes pelo telefone, no seu site ou por um link, conversa em português, consulta a sua base de conhecimento e executa acções reais: marca reuniões, envia SMS, transfere a chamada para uma pessoa ou chama as suas APIs. Tudo se gere no backoffice da Diska, sem código. ![Visão geral da Diska com estatísticas de chamadas, evolução diária e estado das chamadas](https://docs.diska.ai/images/docs/dashboard/dashboard-overview.png) ## O que pode fazer hoje - **Criar agentes de voz** a partir de um template por sector ou do zero, em dois modos de edição: **Prompt Builder** (uma instrução de sistema) ou **Flow Designer** (um fluxo visual de nós e condições). - **Atender em vários canais**: chamada web no browser, widget de voz no seu site, link público, números de telefone (um número DISKA ou o seu próprio número via SIP) e WhatsApp, para agentes em modo Prompt. - **Dar acções ao agente**: agendamento em tempo real, transferência de chamada (incluindo transferência assistida), tratamento de menus IVR, SMS durante e depois da chamada, acções personalizadas que chamam as suas APIs, extratores de informação e avaliações personalizadas. - **Responder com o seu conhecimento**: atribua bases de conhecimento (documentos e páginas web) ao agente. - **Testar antes de publicar**: chamada web, chat, chamada telefónica para o seu telemóvel e simulações com suites de teste (no editor ou no Centro de Testes), em rascunho ou na versão publicada. - **Acompanhar resultados**: em Históricos tem as chamadas com transcrição, resumo e gravação (quando activa), e as conversas WhatsApp. Em Análises tem as métricas por agente. - **Integrar com os seus sistemas** através da [API da DISKA](https://docs.diska.ai/pt/api/api-channel), de webhooks e da integração com o Cal.com. ## Como o backoffice está organizado | Menu | Para que serve | Documentação | | -------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | **Visão geral** | Métricas de chamadas e, numa organização nova, os primeiros passos. | [Configuração inicial](https://docs.diska.ai/pt/getting-started/initial-setup) | | **Agentes** | Criar, editar, testar e publicar agentes. | [Criar o primeiro agente](https://docs.diska.ai/pt/getting-started/first-agent) | | **Conhecimento** | Bases de conhecimento que os agentes consultam. | [Base de conhecimento](https://docs.diska.ai/pt/knowledge-base) | | **Acções** | Agendamentos, transferências, IVR, SMS, acções personalizadas, extratores e avaliações. | [Acções](https://docs.diska.ai/pt/actions) | | **Números** | Comprar um número DISKA ou importar o seu número por SIP. | [Telefonia](https://docs.diska.ai/pt/telephony) | | **Históricos** | Chamadas e conversas WhatsApp, com transcrição, resumo e gravação. | [Históricos](https://docs.diska.ai/pt/history) | | **Análises** | Volume, duração, estados e acções executadas, por agente. | [Análises](https://docs.diska.ai/pt/history/analytics) | | **Centro de Testes** | Suites de teste para validar agentes antes de publicar. | [Centro de Testes](https://docs.diska.ai/pt/test-center) | | **Definições** | Perfil, empresa, membros, integrações (incluindo WhatsApp) e chaves API. | [Definições](https://docs.diska.ai/pt/settings) | O que cada pessoa vê depende da sua função na organização: por exemplo, só proprietários e administradores vêem **Empresa**, **Membros** e **Chaves API**. Veja [Organização e permissões](https://docs.diska.ai/pt/concepts/organization). ## Por onde começar ::card-group :::card --- description: Crie a conta, convide a equipa, crie o primeiro agente e faça uma chamada de teste. icon: i-lucide-rocket title: Começar to: https://docs.diska.ai/pt/getting-started --- ::: :::card --- description: Agentes, fluxos, versões, canais e permissões, explicados antes de construir. icon: i-lucide-lightbulb title: Conceitos to: https://docs.diska.ai/pt/concepts --- ::: :::card --- description: Dê ao agente a capacidade de agendar, transferir, enviar SMS e chamar as suas APIs. icon: i-lucide-zap title: Acções to: https://docs.diska.ai/pt/actions --- ::: :::card --- description: Desenhe a conversa com nós, condições, subfluxos e acções. icon: i-lucide-workflow title: Flow Builder to: https://docs.diska.ai/pt/flow-builder --- ::: :::card --- description: Números DISKA, número próprio por SIP, chamadas telefónicas e limites de chamada. icon: i-lucide-phone title: Telefonia to: https://docs.diska.ai/pt/telephony --- ::: :::card --- description: Ligue a sua conta WhatsApp Business e deixe um agente responder às mensagens. icon: i-lucide-message-circle title: WhatsApp to: https://docs.diska.ai/pt/whatsapp --- ::: :::card --- description: Reveja chamadas, transcrições, gravações e conversas, e acompanhe as métricas. icon: i-lucide-history title: Históricos to: https://docs.diska.ai/pt/history --- ::: :::card --- description: Publicar, testar, transferir para humano, agendar, enviar SMS e gravar chamadas. icon: i-lucide-book-open title: Guias to: https://docs.diska.ai/pt/guides --- ::: :: # Configuração inicial Antes de construir o primeiro agente, crie a sua conta, confirme os dados da empresa e traga a equipa para a organização. ## 1. Criar conta 1. Abra o backoffice da Diska e clique em **Criar conta**. 2. Preencha **Nome**, **Apelido**, **Email** e **Palavra-passe** (mínimo 8 caracteres). O **Telefone** (+244) é opcional. 3. Marque **Aceito os termos de serviço da Diska** e clique em **Criar conta**. 4. Abra o email de confirmação que recebe (veja também a pasta de spam) e clique no link. O backoffice confirma a conta e abre **Bem-vindo à Diska**. Em alternativa, use **Criar conta com Google**. ### Bem-vindo à Diska No primeiro acesso, a Diska pede os dados da sua empresa, uma única vez: - **Nome da empresa** — obrigatório; aparece na equipa, nos convites e nos agentes que criar; - **Tipo de negócio** — opcional; a Diska usa-o para lhe sugerir modelos de agente; - **Website** e **NIF** — opcionais. Clique em **Continuar** para abrir a **Visão geral**. Fica **Proprietário** da organização e pode alterar estes dados depois em **Definições → Empresa** (passo 4). As contas criadas antes deste ecrã vêem-no uma vez, com o título **Complete os dados da sua empresa**. ::callout{type="tip"} Foi convidado por um colega? Não precisa de criar uma empresa: abra o link do convite e siga o passo 6. Se criou a conta sem voltar ao link, o ecrã de boas-vindas mostra o convite em aberto com **Aceitar convite** . :: ## 2. Entrar Em **Entre na sua conta**, use o email e a palavra-passe, ou **Continuar com Google**. - Se a conta ainda não foi confirmada, o backoffice avisa e mostra **Reenviar email de confirmação**. - Se se esqueceu da palavra-passe, clique em **Esqueceu-se da palavra-passe?** e indique o email para receber um link de recuperação. - Se pertence a mais do que uma organização, troque de organização no menu no topo da barra lateral, onde aparece o nome da organização activa. ## 3. Primeiros passos na Visão geral Enquanto a organização não tiver chamadas, a **Visão geral** mostra a lista **Primeiros passos**, com o progresso («2 de 4 concluídos») e um botão para cada passo: | Passo | O que significa | Botão | | -------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------- | | Criar o primeiro agente | Escolha um modelo pronto ou comece do zero. Se indicou o tipo de negócio, o botão abre os modelos desse tipo. | **Ir aos agentes** ou **Ver modelos** | | Fazer uma chamada de teste | A chamada web corre no browser, sem precisar de número. | **Testar agente** | | Publicar o agente | Publicar fixa a versão que atende as chamadas reais. | **Abrir o agente** | | Atribuir um número | Só é preciso para chamadas telefónicas; o teste web funciona sem número. | **Ver números** | A lista só mostra os passos que a sua função pode executar (um **Membro** não vê «Atribuir um número», por exemplo). Quando chegam as primeiras chamadas, a lista dá lugar às métricas: total de chamadas, minutos, duração média e estado das chamadas. ## 4. Confirmar os dados da empresa Em **Definições → Empresa** (**Preferências da empresa**) reveja: - **Nome** — o nome da empresa mostrado na plataforma e em comunicações; - **Website** — o URL público da empresa; pode ficar vazio; - **NIF** — o número de identificação fiscal; pode ficar vazio; - **Tipo de negócio** — usado para sugerir modelos de agente; - **Região do cliente** — definida na configuração da conta; não pode ser alterada aqui; - **ID da empresa** — clique para o copiar; é útil em pedidos de suporte. Clique em **Guardar alterações**. Só proprietários e administradores vêem e editam esta página. Mais detalhes em [Empresa](https://docs.diska.ai/pt/settings/company). ## 5. Convidar a equipa Em **Definições → Membros**, clique em **Convidar utilizador**: 1. Indique o **Endereço de email** do colega. 2. Escolha a **Função**: **Membro** (acesso padrão à empresa, administração limitada) ou **Admin** (convidar utilizadores e administração principal). 3. Clique em **Enviar convite** para enviar o convite por email, ou em **Gerar link** para obter um link que partilha por outro meio. Se o email não puder ser enviado, o convite é criado na mesma e o link aparece no ecrã para o copiar. - Os convites por aceitar ficam no separador **Convites**, onde pode copiar o link ou clicar em **Revogar**. - Um convite expira ao fim de 14 dias. - Os membros activos ficam no separador **Utilizadores**, onde pode mudar a **Função** ou clicar em **Remover**. O backoffice pede confirmação antes de aplicar. Só proprietários e administradores têm acesso a **Membros**. Mais detalhes em [Membros](https://docs.diska.ai/pt/settings/members). ## 6. Aceitar um convite 1. Abra o link do convite. A página **Junte-se à sua equipa** mostra a organização, o email convidado e a função. 2. Clique em **Iniciar sessão** e entre com **o mesmo email** do convite. Se ainda não tem conta, crie-a com esse email. 3. Clique em **Aceitar convite**. O backoffice muda para a nova organização e abre a **Visão geral**. Se criou a conta só para aceitar o convite, a organização que o registo criou para si, ainda sem nome e sem nenhum dado, é arquivada ao aceitar. Se já a usou (por exemplo, criou um agente), fica disponível no selector de organização. Se tiver sessão iniciada com outro email, a página mostra **Conta diferente da convidada** e o botão **Entrar com outra conta**. ::callout{type="info"} Se depois de entrar vir **Conta por associar** , a sua sessão ainda não está ligada a um perfil Diska. Clique em **Tentar novamente** ; se foi convidado, aceite o convite a partir do email que recebeu, ou peça a um administrador que o convide com o mesmo endereço de email. :: ## 7. Funções | Função | O que pode fazer | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Proprietário** | Tudo o que um Administrador faz e atribuir a função de Proprietário. | | **Administrador** | Gerir a empresa, os membros, as integrações e as chaves API; atribuir números de telefone aos agentes; arquivar agentes; eliminar bases de conhecimento e gravações. | | **Membro** | Criar, editar, testar e publicar agentes; gerir conhecimento, acções e suites de teste. | | **Visualizador** | Consultar agentes, conhecimento, acções, históricos e análises; testar agentes e correr testes. Não edita nem publica. | - Os convites só oferecem **Membro** e **Admin**. Para dar a função **Visualizador**, convide como Membro e depois mude a função no separador **Utilizadores**. - Só um Proprietário pode atribuir a função de Proprietário, e a organização mantém sempre pelo menos um Proprietário. A tabela completa de permissões está em [Organização e permissões](https://docs.diska.ai/pt/concepts/organization). ::callout{type="tip"} Convide cada pessoa com a função mais restrita que chegue para o trabalho; pode sempre mudá-la mais tarde. :: ## Próximo passo Com a organização pronta, [crie o seu primeiro agente](https://docs.diska.ai/pt/getting-started/first-agent). # Criar o primeiro agente Esta página dá a visão geral. Para o percurso completo, com cada ecrã, siga o guia [Criar o primeiro agente](https://docs.diska.ai/pt/guides/create-first-agent). Em **Agentes**, clique em **Novo agente**. O menu oferece quatro opções: | Opção | Para quê | | ---------------------- | --------------------------------------------------------------- | | **Voice Agent** | Para chamadas e conversas por voz. Cria um agente do zero. | | **Chat Agent** | Para mensagens e live chat. Cria um agente do zero. | | **Importar de JSON** | Carregar um ficheiro de configuração exportado de outro agente. | | **Explorar templates** | Começar com um template pronto da Diska. | ## A partir de um template ![Galeria de templates por sector, com filtros de sector e tipo de agente](https://docs.diska.ai/images/docs/agents/agent-create-template.png) 1. Clique em **Novo agente → Explorar templates**. 2. Em **Escolher template**, filtre por **Setor** (Saúde, Imobiliário, Educação, Restauração, Retalho, Serviços, Seguros, Recrutamento, Hotelaria, Call Center), por **Inbound** ou **Outbound**, ou pesquise por nome. 3. Abra um template para ver a descrição, o que o agente faz, a persona e o fluxo incluídos e as ferramentas que usa. 4. Em **Modo de edição**, escolha **Prompt** (persona e instruções em texto, sem canvas) ou **Flow Designer** (passos e ligações num fluxo visual). 5. Clique em **Instalar template**. O agente é criado como rascunho e o editor abre. ## Do zero 1. Clique em **Novo agente → Voice Agent**. 2. Em **Escolha o tipo de agente**, escolha **Inbound** (chamadas recebidas), **Outbound** (chamadas efetuadas) ou **Voice Widget** (widget de voz para o seu site) e clique em **Continuar**. 3. Em **Escolha o modo de edição**, escolha **Prompt Builder** (um único prompt define o comportamento) ou **Flow Designer** (fluxos com nós e condições). 4. Clique em **Criar agente**. O editor abre com o painel **Definições globais** aberto. O **Chat Agent** salta a escolha do tipo e vai directo à escolha do modo de edição. ::callout{type="info"} O modo de edição escolhe-se ao criar o agente e não se muda depois no editor. Na dúvida, comece pelo **Prompt Builder** : é a forma mais rápida de ter um agente a funcionar. Veja [Agente de voz](https://docs.diska.ai/pt/concepts/agent) para comparar os tipos e os modos. :: ## Primeiros ajustes No editor, o nome do agente, a versão (V1, V2…) e o estado aparecem no topo. As alterações gravam-se sozinhas; o indicador mostra **Guardado às …**. - **Mensagem de saudação** (Prompt Builder): clique em **Configurar** para escolher se o **Agente fala primeiro** (com uma mensagem fixa ou gerada) ou se o **Humano fala primeiro**. - **Prompt** ou **fluxo**: escreva as instruções do agente ou desenhe o fluxo no canvas. Veja [Prompt Builder](https://docs.diska.ai/pt/concepts/prompt-builder) e [Flow Builder](https://docs.diska.ai/pt/flow-builder). - **Definições**: idioma, voz, configuração de chamada, conhecimento e segurança (gravação de chamadas e ocultação de dados pessoais). - **Ações** (Prompt Builder) ou nós de acção (Flow Designer): anexe agendamentos, transferências, SMS ou acções personalizadas que criou em [Acções](https://docs.diska.ai/pt/actions). O botão **Lista de verificação** no topo do editor mostra o que falta configurar (por exemplo, um prompt vazio ou a falta de número de telefone) e leva-o ao sítio certo. ## Testar e publicar 1. Teste o agente com **Testar → Chamada web**. Veja [Fazer uma chamada de teste](https://docs.diska.ai/pt/getting-started/test-call). 2. Clique em **Publicar**, dê um **Nome da versão** (opcional) e reveja as alterações em relação à última versão publicada. 3. Confirme em **Publicar**. O agente passa a **Ativo** e a nova versão passa a atender o tráfego real. O botão **Publicar** só fica activo quando há alterações por publicar. Um agente em modo Prompt com o prompt vazio, ou um fluxo com erros de validação, não é publicado. Mais detalhes em [Publicar um agente](https://docs.diska.ai/pt/guides/publish-agent). ## Ligar a um canal Depois de publicar, abra **Publicação** no topo do editor para ligar o agente a um canal: - **Telefone** — atribua um número DISKA ou o seu número SIP (só proprietários e administradores). Veja [Telefonia](https://docs.diska.ai/pt/telephony). - **Link público** — active um link que qualquer pessoa abre no browser para falar com o agente. - **Widget** — copie o script para incorporar o widget de voz no seu site. Veja [Incorporar o widget](https://docs.diska.ai/pt/guides/embed-widget). - **API** — integre o agente nos seus sistemas pela [API da DISKA](https://docs.diska.ai/pt/api/api-channel). Para responder no WhatsApp, ligue a sua conta em **Definições → Integrações** e escolha um agente em modo Prompt publicado. Veja [WhatsApp](https://docs.diska.ai/pt/whatsapp). ## Antes de publicar - A saudação é clara e curta. - O agente não revela dados sensíveis e respeita as políticas da sua organização. - As transferências, os SMS e as marcações só disparam quando devem. - A chamada termina de forma limpa quando o cliente se despede. ## Seguinte [Faça uma chamada de teste](https://docs.diska.ai/pt/getting-started/test-call). # Fazer uma chamada de teste No editor do agente, o botão **Testar** abre o painel de teste num destes modos: | Modo | O que faz | Precisa de número | | ---------------------- | ------------------------------------------------------------------------------------------------------ | ----------------- | | **Chamada web** | Fala com o agente por voz no browser, com o microfone. | Não | | **Chamada telefónica** | O agente liga do seu número DISKA para o seu telemóvel (**Ligar-me**). | Sim | | **Chat** | Troca de mensagens de texto com o agente. | Não | | **Simulação** | Corre as suites de teste do agente: um cliente simulado conversa por texto e cada caso passa ou falha. | Não | O mesmo menu tem **Abrir Centro de Testes**, com todas as suites e execuções da organização. Para o detalhe de cada modo, veja o guia [Testar o agente](https://docs.diska.ai/pt/guides/test-agent). ![Painel de chamada web com contacto do chamador e botão Iniciar chamada de teste](https://docs.diska.ai/images/docs/agents/web-call-panel.png) ## Rascunho ou versão publicada Com o painel de teste aberto, o editor mostra a faixa **Modo de teste · não é tráfego live** e um interruptor entre **Rascunho** e **Publicado**: - **Rascunho** testa as alterações ainda por publicar. As acções são simuladas: não sai nenhum SMS real, não se marca nada no calendário e não se transfere a chamada. - **Publicado** testa a versão que atende os clientes. As acções são reais. O interruptor só deixa escolher **Publicado** depois de o agente ter sido publicado pelo menos uma vez. ## Chamada web 1. Clique em **Testar → Chamada web**. 2. Opcional: preencha o **Contacto do chamador** (usado no fim da chamada para SMS e variáveis) e os campos **Variável: …** das variáveis pré-chamada do agente. 3. Clique em **Iniciar chamada de teste** e permita o acesso ao microfone. 4. Fale com o agente. A transcrição aparece no painel, com **Agente** e **Você**. 5. Clique em **Terminar**. O painel mostra os **Resultados pós-chamada**: dados extraídos, avaliações, SMS pós-chamada e acções executadas. A chamada web de teste não é gravada, mesmo com **Gravar chamadas** activo. ## Chamada telefónica O agente liga para o seu telemóvel a partir do número DISKA que lhe está atribuído, como numa chamada real. 1. Clique em **Testar → Chamada telefónica**. 2. Em **Versão do agente**, escolha **Rascunho — ações simuladas** ou a versão publicada (**ações reais**). 3. Confirme o número em **Chamada de** (o número do agente). 4. Em **Ligar para**, indique o seu telemóvel angolano (Africell ou Unitel), com 9 dígitos, por exemplo 923 000 000. 5. Clique em **Ligar-me** e atenda. O painel mostra o estado (a tocar, em chamada, terminada) e o botão **Desligar**. Para usar este modo: - o agente tem de ter um número DISKA activo e ter sido publicado pelo menos uma vez; - a organização tem de estar habilitada para chamadas telefónicas de saída; - só pode ter uma chamada de teste em curso de cada vez, e há um limite de chamadas de teste por hora. A chamada usa minutos reais da linha DISKA. O tempo que o seu telemóvel toca segue a **Duração do toque** e o limite de duração segue a **Configuração de chamada** da versão testada. Se **Gravar chamadas** estiver activo, a chamada é gravada (os primeiros 27 minutos). Veja [Chamadas telefónicas](https://docs.diska.ai/pt/telephony/phone-calls). ## Chat Clique em **Testar → Chat**, escreva uma mensagem e envie. Use **Novo chat** para recomeçar. É a forma mais rápida de validar respostas e conhecimento sem áudio. ## Simulação Escolha **Testar → Simulação** para ver as suites de teste do agente. Crie uma com **Suite**, gere casos com **Gerar com IA** e clique em **Executar**: cada caso mostra se passou e porquê. Veja [Testar o agente](https://docs.diska.ai/pt/guides/test-agent#simula%C3%A7%C3%A3o). ## O que validar - A saudação é clara e chega no tempo esperado. - O agente lida bem com interrupções. - Os dados que o agente deve recolher são recolhidos correctamente. - Transferências, SMS e marcações só disparam quando devem. - A chamada termina de forma limpa quando o cliente se despede. ::callout{type="info"} As chamadas reais (telefone, widget, link público, WhatsApp) usam sempre a versão **publicada** . Depois de testar o rascunho, publique para que as alterações cheguem aos clientes. :: ## Seguinte - [Publicar um agente](https://docs.diska.ai/pt/guides/publish-agent) - Crie suites de teste no [Centro de Testes](https://docs.diska.ai/pt/test-center). - Aprofunde a lógica do fluxo no [Flow Builder](https://docs.diska.ai/pt/flow-builder). # Começar Esta secção leva-o do registo na Diska até à primeira chamada de teste. Segue a mesma ordem da lista **Primeiros passos** que o backoffice mostra na **Visão geral** de uma organização nova: 1. **Criar o primeiro agente** — a partir de um template ou do zero. 2. **Fazer uma chamada de teste** — a chamada web corre no browser, sem precisar de número. 3. **Publicar o agente** — publicar fixa a versão que atende as chamadas reais. 4. **Atribuir um número** — só é preciso para chamadas telefónicas. ::card-group :::card --- description: Criar conta, entrar, rever os dados da empresa e convidar a equipa. icon: i-lucide-settings title: Configuração inicial to: https://docs.diska.ai/pt/getting-started/initial-setup --- ::: :::card --- description: Escolher um template ou começar do zero, em modo Prompt ou Flow. icon: i-lucide-bot title: Criar o primeiro agente to: https://docs.diska.ai/pt/getting-started/first-agent --- ::: :::card --- description: Testar por chamada web, chat, chamada telefónica ou simulação. icon: i-lucide-phone title: Fazer uma chamada de teste to: https://docs.diska.ai/pt/getting-started/test-call --- ::: :: # Agente de voz Um **agente** é o assistente de IA que fala com os seus clientes. Junta instruções (um prompt ou um fluxo), uma saudação, uma voz, definições de chamada, conhecimento e acções, e é publicado em versões que os canais usam. ## Componentes | Componente | Onde se configura | O que define | | ------------------ | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Instruções | Editor: **Prompt** ou canvas do fluxo | Quem é o agente, o objectivo, o tom e os limites; no Flow Designer, os passos da conversa. | | Saudação | **Mensagem de saudação** (Prompt) ou nó **Saudação** (Flow) | Se o agente fala primeiro ou espera que o cliente fale. | | Definições globais | **Definições** | Idioma, voz, configuração de chamada, conhecimento e memória, segurança e conformidade (gravação e ocultação de dados pessoais). | | Acções | **Ações** (Prompt) ou nós e passos do fluxo (Flow) | Agendar, transferir, enviar SMS, chamar APIs, extrair dados e avaliar a chamada. Veja [Acções](https://docs.diska.ai/pt/actions). | | Variáveis | **Variáveis** | Variáveis de sistema, variáveis pré-chamada (recebidas antes de a chamada começar) e resultados de acções. Veja [Variáveis](https://docs.diska.ai/pt/flow-builder/variables). | | Conhecimento | **Definições → Conhecimento e memória** | Bases de conhecimento atribuídas e notas livres. Veja [Base de conhecimento](https://docs.diska.ai/pt/knowledge-base). | | Canais | **Publicação** | Telefone, link público, widget e API. | ## Tipos de agente O tipo escolhe-se ao criar o agente e aparece no topo do editor e na lista de agentes. | Tipo | No backoffice | Para quê | | ---------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | **Inbound** | «Para chamadas recebidas.» | Atender clientes que ligam para o número do agente, abrem o link público ou usam o widget. | | **Outbound** | «Para chamadas efetuadas.» | Chamadas que o agente faz, como follow-ups e lembretes. | | **Voice Widget** | «Widget de voz para o seu site.» | Um agente cujo canal principal é o widget no seu site; a **Publicação** abre directamente no separador **Widget**. | | **Chat** | «Para mensagens e live chat.» | Conversas por texto. Criado com **Novo agente → Chat Agent**. | ::callout{type="info"} Hoje, um agente **Outbound** pode ser testado com a **Chamada telefónica** do painel de teste, em que o agente liga para o seu telemóvel. As chamadas de saída exigem que a organização esteja habilitada para chamadas telefónicas de saída, e ainda não se iniciam a partir do backoffice nem da API da DISKA. Veja [Chamadas telefónicas](https://docs.diska.ai/pt/telephony/phone-calls) . :: ## Modos de edição | Modo | Como funciona | Quando usar | | ------------------ | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Prompt Builder** | Um único prompt, com saudação, definições e acções anexadas por fase, conduz toda a conversa. | Conversas abertas, FAQ, qualificação simples. É o mais rápido para começar. Veja [Prompt Builder](https://docs.diska.ai/pt/concepts/prompt-builder). | | **Flow Designer** | Um fluxo visual de nós, condições e subfluxos, com acções em passos concretos. | Conversas com etapas, ramificações, recolha de dados com validação ou transferências em pontos definidos. Veja [Fluxo](https://docs.diska.ai/pt/concepts/flow). | O modo escolhe-se ao criar o agente (ou ao instalar um template) e não muda depois. Só os agentes em modo Prompt podem ser ligados ao WhatsApp, e a **Simulação** do painel de teste só existe em modo Flow Designer. ## Versões e publicação - O que edita fica num **rascunho**. As alterações gravam-se sozinhas e não afectam os clientes. - **Publicar** congela o rascunho numa nova versão (V1, V2…). Em modo Flow Designer, publica o fluxo principal e os subfluxos que ele alcança. - As chamadas e conversas reais usam sempre a **versão publicada**. Os testes do painel podem usar o rascunho ou a versão publicada. - Em **Versões** (**Histórico de versões**) vê cada versão com o nome, a data e o autor, e pode **Ver alterações**, **Exportar para JSON**, **Restaurar esta versão** (o rascunho volta a ficar igual a essa versão; publique para a pôr em produção) ou **Descartar rascunho**. Veja [Publicar um agente](https://docs.diska.ai/pt/guides/publish-agent). ## Estados | Estado | Significado | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | **Rascunho** | O agente ainda não foi publicado (ou foi restaurado do arquivo). Pode editá-lo e testá-lo. | | **Ativo** | O agente tem uma versão publicada, que atende o tráfego real. | | **Inativo** | O agente não está disponível; não pode ser ligado ao WhatsApp. Este estado não se define no editor. | | **Arquivado** | O agente sai da lista habitual e não pode ser editado. Encontra-o com o filtro **Arquivado** e volta a **Rascunho** com **Restaurar agente**. | O campo **Estado** em **Definições → Geral** é só de leitura: muda ao publicar e ao arquivar. Só proprietários e administradores arquivam e restauram agentes. ## Outras operações No menu de cada agente (lista de agentes ou **⋮** no editor): - **Registos de chamadas** — abre **Históricos** filtrado por esse agente; - **Copiar ID** — o identificador do agente, útil para a API e o suporte; - **Duplicar** — cria uma cópia do agente; - **Exportar para JSON** — transfere a configuração, que pode importar noutra organização com **Importar de JSON**; - **Arquivar** — retira o agente de uso (reversível). # Fluxo Num agente em modo **Flow Designer**, um **fluxo** é um grafo de nós que descreve a conversa passo a passo: o que o agente diz, o que pergunta, que caminho segue conforme a resposta e que acções executa. ## Fluxo principal e subfluxos Cada agente tem um **Fluxo principal** e pode ter subfluxos, cada um no seu separador por cima do canvas (o **+** cria um novo). Um subfluxo é um bloco reutilizável dentro do agente: as suas **Condições de entrada** definem quando pode ser activado, e o nó **Disparar subfluxo** leva a conversa até ele. O fluxo principal continua a ser a entrada do agente. Ao publicar, a Diska publica o fluxo principal e os subfluxos que ele alcança. ## Estrutura obrigatória O fluxo principal começa sempre assim: ```text Fluxo principal → Antes da conversa → Saudação → próximo passo ``` e cada **Terminar chamada** liga ao seu próprio marcador **Depois da conversa**. Um subfluxo começa com `Subfluxo → Condições de entrada`. Estes nós são estruturais e não se apagam. - **Antes da conversa** corre antes de a conversa começar. Pode anexar-lhe uma **Acção personalizada** (para carregar contexto) ou um **Tratamento IVR** (para navegar menus de voz numa chamada de saída). - **Depois da conversa** corre depois de a chamada terminar. Pode anexar-lhe **SMS pós-chamada**, **Extrator de informação** e **Avaliação personalizada**. ## Tipos de nó O seletor de nós agrupa os tipos por categoria: | Categoria | Nós | Para quê | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- | | Conversação | [Conversação](https://docs.diska.ai/pt/nodes/conversation), [Mensagem](https://docs.diska.ai/pt/nodes/message), [Terminar chamada](https://docs.diska.ai/pt/nodes/end-call) | Conduzir o diálogo e recolher dados, dizer uma mensagem exacta, terminar a chamada. | | Controlo de fluxo | [Disparar subfluxo](https://docs.diska.ai/pt/nodes/trigger-subflow), [Dividir o caminho](https://docs.diska.ai/pt/nodes/split-path), [Saltar para](https://docs.diska.ai/pt/nodes/jump-to) | Passar para um subfluxo, ramificar por condições, saltar para outro nó. | | Acções | [Acção personalizada](https://docs.diska.ai/pt/nodes/custom-action), [Enviar SMS durante a chamada](https://docs.diska.ai/pt/nodes/send-sms-during-call) | Chamar uma API e usar a resposta, enviar um SMS com a chamada em curso. | | Transferência humana | [Transferência](https://docs.diska.ai/pt/nodes/transfer) | Transferir a chamada para uma pessoa ou equipa. | | Negócio | [Agendamento](https://docs.diska.ai/pt/nodes/booking) | Marcar ou remarcar uma reunião no calendário. | No canvas, o nó **Dividir o caminho** aparece como **Condição**. Os tipos marcados como em breve no seletor (Espera, Ciclo, Definir variável, Enviar WhatsApp durante a chamada, Enviar email) ainda não se podem inserir; veja [Em breve](https://docs.diska.ai/pt/nodes/coming-soon). ### Transferência O nó **Transferência** transfere chamadas telefónicas: a linha do cliente passa para o número de destino. Também pode ser uma transferência assistida, em que quem atende primeiro ouve, na voz do agente, o motivo ou um resumo da chamada. Numa chamada web não há linha telefónica para transferir, por isso o nó segue o caminho de falha. Nas linhas telefónicas, o destino tem de ser um número; uma fila não é aceite. Veja [Transferir para humano](https://docs.diska.ai/pt/guides/transfer-to-human). ## Regras de ligação O canvas só aceita ligações válidas e explica porquê quando recusa uma. As principais: - **Fluxo principal** só liga a **Antes da conversa**. - **Antes da conversa** liga à **Saudação** ou a um passo pré-conversa (por exemplo, uma acção). - A **Saudação** não recolhe resposta, por isso não liga directamente a uma **Condição**: ponha antes um nó **Conversação**. - Uma **Conversação** passa à seguinte através de uma condição de saída, nunca por uma ligação directa. - **Terminar chamada** só liga a **Depois da conversa**, que não tem saída. A tabela completa está em [Estrutura de um fluxo](https://docs.diska.ai/pt/flow-builder/structure). Antes de publicar, a lista de verificação do editor e a validação no servidor apontam os erros do fluxo; um fluxo inválido não é publicado. Veja [Validar e publicar](https://docs.diska.ai/pt/flow-builder/validation-publishing). # Runtime O **runtime** é a parte da plataforma que põe o agente a falar: abre a sessão de voz, segue o prompt ou o fluxo, executa as acções e, no fim, regista a chamada nos **Históricos**. ## Que versão atende - As chamadas e conversas reais usam sempre a **versão publicada** do agente. - Os testes do painel **Testar** usam o rascunho ou a versão publicada, conforme escolher. No rascunho, as acções são simuladas. Veja [Fazer uma chamada de teste](https://docs.diska.ai/pt/getting-started/test-call). ## Canais | Canal | Como chega ao agente | Em Históricos | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------- | | Chamada web | Pelo browser: teste no editor, [widget](https://docs.diska.ai/pt/guides/embed-widget) no seu site ou link público. | **Web Call** | | Telefone | Um cliente liga para o número do agente (número DISKA ou o seu número por SIP), ou o agente liga, como na chamada de teste para o seu telemóvel. | **Telefone** | | WhatsApp | Mensagens para a sua conta WhatsApp Business, respondidas por um agente em modo Prompt publicado. | **WhatsApp** (separador próprio) | A [API da DISKA](https://docs.diska.ai/pt/api/api-channel) dá acesso aos agentes, chamadas, análises, números e conhecimento a partir dos seus sistemas; com a função activada pela DISKA, também inicia chamadas de saída. ## Ciclo de vida de uma chamada Cada chamada aparece em **Históricos → Chamadas** com um destes estados: | Estado | Significado | | ---------------- | ------------------------------------------------------------------------------------------------------- | | **Criada** | A sessão foi aberta, a conversa ainda não começou. | | **Em progresso** | A conversa está a decorrer. | | **Concluída** | A chamada terminou normalmente. | | **Falhou** | A chamada terminou por um problema técnico (microfone, rede ou ligação). | | **Cancelada** | A sessão foi substituída por outra antes de terminar (por exemplo, numa nova tentativa de ligação). | | **Abandonada** | A sessão deixou de dar sinal (por exemplo, o separador do browser foi fechado) e a plataforma fechou-a. | ## Durante a chamada 1. **Abertura** — o agente diz a saudação, ou espera que o cliente fale primeiro, conforme a configuração. 2. **Conversa** — o agente ouve, responde e segue o prompt ou o fluxo. A **Paciência** (em **Definições → Voz**) define quanto silêncio fecha a vez do cliente. 3. **Acções** — o agente usa as acções disponíveis nesse momento: agendar, transferir, enviar SMS, chamar APIs, consultar o conhecimento. 4. **Fim** — o agente termina a chamada quando o cliente pede, quando a tarefa fica concluída, por inactividade ou por erro. Nas chamadas telefónicas aplica-se também a **Configuração de chamada** do agente: - **Duração do toque** (10–60 s) — quanto tempo o telemóvel toca nas chamadas que o agente faz; - **Limitar duração da chamada** (1–240 min) — a chamada telefónica é desligada ao atingir o máximo, excepto se já tiver sido transferida para uma pessoa. Veja [Configuração de chamada](https://docs.diska.ai/pt/telephony/call-settings). ## Quando a chamada termina Depois de desligar, a Diska processa a chamada pela seguinte ordem: 1. **Extratores de informação** retiram os dados pedidos da conversa (por exemplo, nome, email, motivo). 2. **Avaliações personalizadas** classificam a chamada segundo os seus critérios. 3. **SMS pós-chamada** são enviados, com os dados recolhidos. 4. **Acções personalizadas** da fase «Depois da conversa» chamam as suas APIs. 5. A transcrição e um **resumo** ficam guardados nos Históricos e, se o agente tiver um **Webhook** na fase «Depois da conversa», a Diska envia-lhe os dados da chamada. Se **Gravar chamadas** estiver activo, a gravação fica disponível nos Históricos (numa chamada telefónica, os primeiros 27 minutos). Nos testes do rascunho, os SMS e o webhook não são enviados: o painel de teste mostra o resultado simulado. Veja [Acções](https://docs.diska.ai/pt/actions) e [Gravações](https://docs.diska.ai/pt/history/recordings). ## Motores de voz Escolhe o motor em **Definições → Voz → Motor de voz**; a secção mostra depois os campos desse motor. Mudar de motor muda a voz: os testes do rascunho usam-no logo, as chamadas quando publicar. - **Grok Voice 3.0** é o motor com que os agentes novos começam (voz **Celeste**, raciocínio alto), em agentes de prompt e do Flow Designer e em todos os canais. A secção mostra **Voz Grok**, **Velocidade da fala**, **Variedade da fala**, **Raciocínio**, **Termos-chave da transcrição** (nomes e marcas que o motor deve reconhecer) e **Pronúncias** (por exemplo, `Kz = kwanzas`). - **GPT-Live**, de conversa full-duplex nativa, continua disponível. Escolhe a voz em **Voz GPT-Live**: **Bossa** (voz feminina) ou **Tempo** (voz masculina), ambas nativas em português. A voz fica fixa durante toda a chamada; o sotaque de Portugal é mantido pelas instruções do agente. Um agente que nunca escolheu motor usa o GPT-Live. - Agentes mais antigos podem mostrar outro motor, conforme foram configurados. O **Idioma** é Português (Portugal) e o **Fuso horário** é África/Luanda, definido pela plataforma. # Organização e permissões Na Diska, cada empresa trabalha numa **organização**. A organização tem os seus agentes, fluxos, conhecimento, acções, números, históricos, integrações, chaves API e membros, isolados das outras organizações: os dados de organizações diferentes nunca se cruzam. ## Estrutura ```text Organização ├── Agentes (e os seus fluxos e versões) ├── Conhecimento ├── Acções ├── Números ├── Históricos e Análises ├── Centro de Testes ├── Integrações (incluindo WhatsApp) ├── Chaves API └── Membros e convites ``` ## Uma ou várias organizações - Ao criar conta, a Diska cria uma organização para si e faz de si o **Proprietário**. No primeiro acesso, o ecrã **Bem-vindo à Diska** pede-lhe o nome da empresa; pode alterá-lo depois em **Definições → Empresa**. - Ao aceitar um convite, passa a ser membro de outra organização, com a função indicada no convite. Se criou a conta só para isso, a organização vazia do registo é arquivada. - Se pertence a várias organizações, troque de organização no menu no topo da barra lateral. Trabalha sempre numa organização activa de cada vez: tudo o que vê e cria pertence a essa organização. ## Funções | Função | Resumo | | ----------------- | ------------------------------------------------------------------------------ | | **Proprietário** | Controlo total, incluindo atribuir a função de Proprietário. | | **Administrador** | Administra a empresa: definições, membros, integrações, chaves API e números. | | **Membro** | Constrói: cria, edita, testa e publica agentes, conhecimento, acções e testes. | | **Visualizador** | Consulta e testa, sem alterar nada. | Nos convites a função **Administrador** aparece como **Admin**. Os convites só oferecem Membro e Admin; a função Visualizador atribui-se depois, em **Definições → Membros**. Só um Proprietário atribui a função de Proprietário, e a organização mantém sempre pelo menos um. ## Permissões | O que pode fazer | Proprietário | Administrador | Membro | Visualizador | | ------------------------------------------------------------------------------------------ | :----------: | :-----------: | :----: | :----------: | | Ver agentes, conhecimento, acções, números, históricos, análises e suites de teste | ✓ | ✓ | ✓ | ✓ | | Testar agentes (chamada web, chat, chamada telefónica, simulação) e correr suites de teste | ✓ | ✓ | ✓ | ✓ | | Criar, editar, duplicar, importar, exportar e publicar agentes | ✓ | ✓ | ✓ | — | | Criar e editar bases de conhecimento | ✓ | ✓ | ✓ | — | | Ver a Memória partilhada (grupos, contactos e memórias) | ✓ | ✓ | ✓ | ✓ | | Criar e editar grupos de memória, contactos e memórias | ✓ | ✓ | ✓ | — | | Criar e editar acções | ✓ | ✓ | ✓ | — | | Criar e editar suites de teste | ✓ | ✓ | ✓ | — | | Assumir, devolver à IA e resolver conversas WhatsApp | ✓ | ✓ | ✓ | — | | Arquivar e restaurar agentes | ✓ | ✓ | — | — | | Comprar, importar e atribuir números de telefone | ✓ | ✓ | — | — | | Eliminar bases de conhecimento | ✓ | ✓ | — | — | | Eliminar grupos de memória | ✓ | ✓ | — | — | | Eliminar gravações de chamadas | ✓ | ✓ | — | — | | Editar Empresa, Organização, Integrações e Chaves API | ✓ | ✓ | — | — | | Convidar membros, mudar funções e remover membros | ✓ | ✓ | — | — | | Atribuir a função de Proprietário | ✓ | — | — | — | O backoffice só mostra os menus e botões que a sua função permite. Por exemplo, um Membro não vê **Empresa**, **Organização**, **Integrações**, **Chaves API** nem **Membros** em **Definições**. Detalhes em [Membros](https://docs.diska.ai/pt/settings/members). ## Sessão e acesso Entra com email e palavra-passe ou com Google. Cada pedido que o backoffice faz leva a organização activa, e a plataforma confirma em cada pedido que é membro dessa organização e que a sua função permite a operação. Se o seu acesso a uma organização for retirado, o backoffice deixa de a mostrar. As [chaves API](https://docs.diska.ai/pt/settings/api-keys) autenticam um sistema, não uma pessoa: cada chave pertence a uma organização e só dá acesso à [API da DISKA](https://docs.diska.ai/pt/api/authentication), nunca ao backoffice. # Prompt Builder Um agente em modo **Prompt Builder** é conduzido por um único **prompt**: a instrução de sistema que diz ao agente quem é, o que tem de conseguir e o que nunca pode fazer. Escolhe este modo ao criar o agente (ou ao instalar um template em modo **Prompt**). É a forma mais rápida de ter um agente a funcionar. ## O ecrã do editor - **Mensagem de saudação** — clique em **Configurar**para escolher: - **Agente fala primeiro**: o agente abre a chamada com a **Mensagem** que escrever; deixe em branco para o agente gerar a saudação; - **Humano fala primeiro**: o agente espera que a pessoa fale (**Tempo de espera** de 1 a 10 segundos) e responde com uma **Mensagem gerada pelo LLM** ou uma **Mensagem fixa**. - **Prompt** — o texto das instruções. Grava-se sozinho enquanto escreve. - No topo: **Ações**, **Variáveis**, **Versões**, **Definições**, **Publicação**, **Testar** e **Publicar**. ## O que o agente recebe Na chamada, o agente recebe o prompt completado por estas secções, quando preenchidas: | Origem | Onde se configura | Para quê | | -------------------------- | ----------------------------------------- | -------------------------------------------------------------------------------------------------- | | Saudação | **Mensagem de saudação** | Como a chamada abre. | | Personalidade e contexto | **Definições → Personalidade e objeções** | Quem é o agente, o que faz, o tom de voz e as regras permanentes. | | Objeções e casos especiais | **Definições → Personalidade e objeções** | Como responder a objeções e situações especiais (por exemplo, «se perguntarem se é IA…»). | | Notas de conhecimento | **Definições → Conhecimento e memória** | Factos curtos e respostas a perguntas frequentes, em texto livre. | | Bases de conhecimento | **Definições → Conhecimento e memória** | As bases atribuídas, pesquisadas durante a chamada. Marque-as e clique em **Guardar atribuições**. | | Acções anexadas | **Ações** | Quando e como usar cada acção anexada. | As alterações chegam às chamadas reais quando publicar uma nova versão; até lá, teste-as no rascunho. Veja [Base de conhecimento](https://docs.diska.ai/pt/knowledge-base). ## Acções por fase O botão **Ações** abre o painel **Acções**, dividido em três fases. Em cada fase, **Adicionar** mostra os tipos disponíveis; ao escolher um, selecciona uma acção já criada em [Acções](https://docs.diska.ai/pt/actions) (o atalho **Abrir Acções** leva-o lá se ainda não tiver nenhuma). | Fase | Quando corre | Tipos | | ---------------------- | ------------------------------ | ----------------------------------------------------------------------------------------------- | | **Antes da conversa** | Antes de a conversa começar. | Acção personalizada, Tratamento IVR | | **Durante a conversa** | Quando o agente decide usá-la. | Agendamento em tempo real, Transferência de chamada, Acção personalizada, SMS durante a chamada | | **Depois da conversa** | Depois de a chamada terminar. | SMS pós-chamada, Extrator de informação, Avaliação personalizada, Acção personalizada, Webhook | - **Tratamento IVR** navega menus de voz (teclas DTMF) em chamadas telefónicas de saída. Veja [IVR](https://docs.diska.ai/pt/actions/ivr). - **Transferência de chamada** transfere chamadas telefónicas, incluindo a transferência assistida. Veja [Transferências de chamada](https://docs.diska.ai/pt/actions/call-transfers). - **Webhook** envia os dados da chamada para o URL que indicar, depois da chamada. - **WhatsApp durante a chamada** e **Conectores MCP** aparecem como **Em breve**. Clique num agendamento anexado para ver as suas **Variáveis de saída** e escolher como cada **Variável de entrada** é obtida: recolhida pelo agente durante a chamada, a partir de uma variável ou com um valor fixo. ## Variáveis O painel **Variáveis** lista: - **Variáveis de sistema** — fornecidas pela plataforma; não se editam; - **Variáveis pré-chamada** — recebidas antes de a chamada começar; adicione-as com um nome e uma descrição. Nos testes, o painel **Testar** mostra um campo **Variável: …** para cada uma; - **Resultados de ações** — preenchidas pelas respostas das acções. ## Escrever um bom prompt - Diga quem é o agente, o que tem de conseguir nesta chamada e o que nunca pode fazer. - Escreva em português, a língua em que o agente fala. - Prefira regras curtas e imperativas a parágrafos longos. - Não cole documentos inteiros no prompt: atribua uma [base de conhecimento](https://docs.diska.ai/pt/knowledge-base) e use as notas de conhecimento só para factos curtos. - Diga quando usar cada acção (por exemplo, «transfere para um humano se o cliente pedir para falar com uma pessoa»). ## Testar Use **Testar → Chamada web** para uma chamada de voz no browser, ou **Testar → Chat** para uma troca rápida de texto, no rascunho ou na versão publicada. Veja [Testar o agente](https://docs.diska.ai/pt/guides/test-agent). ::callout{type="tip"} Se a conversa precisar de etapas fixas, ramificações ou recolha de dados com validação, crie o agente em modo **Flow Designer** : o modo escolhe-se ao criar o agente e não muda depois. Veja [Fluxo](https://docs.diska.ai/pt/concepts/flow) . :: # Conceitos Antes de aprofundar o Flow Builder, as acções ou a API, alinhe o vocabulário usado no resto da documentação. ::card-group :::card --- description: Tipos, modos de edição, versões e estados de um agente. icon: i-lucide-bot title: Agente de voz to: https://docs.diska.ai/pt/concepts/agent --- ::: :::card --- description: Conduzir o agente com um prompt, personalidade, notas de conhecimento e acções por fase. icon: i-lucide-file-text title: Prompt Builder to: https://docs.diska.ai/pt/concepts/prompt-builder --- ::: :::card --- description: Estrutura do fluxo, tipos de nó, subfluxos e regras de ligação. icon: i-lucide-git-branch title: Fluxo to: https://docs.diska.ai/pt/concepts/flow --- ::: :::card --- description: Canais, ciclo de vida de uma chamada, o que acontece no fim e motores de voz. icon: i-lucide-zap title: Runtime to: https://docs.diska.ai/pt/concepts/runtime --- ::: :::card --- description: Organizações, funções e o que cada função pode fazer. icon: i-lucide-building-2 title: Organização e permissões to: https://docs.diska.ai/pt/concepts/organization --- ::: :: # Criar o primeiro agente passo a passo Um agente junta a voz, as instruções (um prompt ou um fluxo), as acções que pode executar e os canais onde atende. Este guia leva-o do zero até à primeira versão publicada. ![Lista de agentes com tipo, versão, estado e última edição](https://docs.diska.ai/images/docs/agents/agents-list.png) ## Passo 1. Criar o agente 1. No menu lateral, abra **Agentes** e clique em **Novo agente**. 2. Escolha uma das opções: | Opção | Para quê | | ---------------------- | --------------------------------------------------------------- | | **Voice Agent** | Agente para chamadas e conversas por voz. | | **Chat Agent** | Agente para mensagens e live chat. | | **Importar de JSON** | Carregar um ficheiro de configuração exportado de outro agente. | | **Explorar templates** | Começar com um template pronto da Diska. | 3. Para um **Voice Agent**, escolha o tipo e clique em **Continuar**: - **Inbound** — atende chamadas recebidas; - **Outbound** — faz chamadas; - **Voice Widget** — widget de voz para o seu site. 4. Escolha o modo de edição e clique em **Criar agente**: - **Prompt Builder** — um único prompt define o comportamento do agente; - **Flow Designer** — desenha a conversa como um fluxo de nós e condições. O editor do agente abre com o painel **Definições** aberto. ::callout{type="tip"} Com **Explorar templates** pode filtrar por sector (Saúde, Imobiliário, Educação, Restauração, entre outros) e por Inbound/Outbound. A pré-visualização mostra o que o agente faz, a persona, o fluxo e as ferramentas incluídas; escolha **Prompt** ou **Flow Designer** e clique em **Instalar template** . :: ## Passo 2. Rever as definições O botão **Definições** na barra do agente abre as definições globais, organizadas em secções: | Secção | O que configura | | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Geral** | Idioma: **Multilingue** — o agente responde na língua do cliente e começa em português de Portugal. O fuso horário (África/Luanda) é definido pela plataforma. Quem é o agente, o tom e as objeções escrevem-se no **Prompt**. | | **Voz** | O motor e a voz do agente (os agentes novos começam no **Grok Voice 3.0**, com a voz **Celeste**; o **GPT-Live** oferece **Bossa**, feminina, e **Tempo**, masculina) e a **Paciência** — quanto silêncio fecha a vez do cliente (Baixa, Média ou Alta). | | **Configuração de chamada** | Duração do toque nas chamadas que o agente faz e limite de duração das chamadas telefónicas. | | **Motivos de fim de chamada** | Os motivos que o agente pode indicar ao terminar (definidos no sistema). | | **Conhecimento e memória** | As bases de conhecimento que o agente consulta e notas livres. | | **Segurança e conformidade** | Gravação de chamadas, aviso ao cliente e retenção — ver [Gravar chamadas](https://docs.diska.ai/pt/guides/record-calls) — e **Ocultar dados pessoais (PII)** — ver [Ocultar dados pessoais](https://docs.diska.ai/pt/guides/redact-personal-data). | As alterações são guardadas automaticamente: o indicador no canto superior direito mostra **Guardado às …** quando terminam. Não existe um botão Guardar. ## Passo 3. Escrever o comportamento **No Prompt Builder:** 1. Em **Mensagem de saudação**, clique em **Configurar** e escolha **Agente fala primeiro** (com uma mensagem gerada ou fixa) ou **Humano fala primeiro** (o agente espera que a pessoa fale). 2. Escreva as instruções no editor **Prompt**: objectivo, tom, informação a recolher e limites. 3. Abra **Ações** na barra do agente para anexar acções (marcações, transferências, SMS, extractores) — ver os guias seguintes. **No Flow Designer:** O canvas abre com a estrutura obrigatória `Fluxo principal → Antes da conversa → Mensagem de saudação` e um botão **+** por baixo. Clique no **+** para adicionar o primeiro passo. O guia [Usar o Flow Builder](https://docs.diska.ai/pt/guides/use-flow-builder) explica o resto. ## Passo 4. Adicionar conhecimento (opcional) Se o agente tiver de responder com base nos seus documentos ou no seu site: 1. Crie uma base em **Conhecimento** no menu lateral e adicione as fontes — ver [Base de conhecimento](https://docs.diska.ai/pt/knowledge-base). 2. No agente, abra **Definições → Conhecimento e memória**, seleccione a base e clique em **Guardar atribuições**. ## Passo 5. Testar Clique em **Testar → Chamada web** e depois em **Iniciar chamada de teste**. O browser pede acesso ao microfone e pode falar com o rascunho do agente. Ver [Testar um agente](https://docs.diska.ai/pt/guides/test-agent) para os outros modos, incluindo a chamada para o seu telemóvel. ## Passo 6. Publicar Quando o rascunho estiver pronto, clique em **Publicar**, dê um nome à versão (opcional) e confirme. A versão publicada é a que atende no telefone, no link público e no widget. Ver [Publicar e receber chamadas](https://docs.diska.ai/pt/guides/publish-agent). ::callout{type="info"} Criar e editar agentes exige o papel Proprietário, Administrador ou Membro. Um Visualizador pode abrir e testar agentes, mas não alterá-los. :: # Usar o Flow Builder O Flow Builder é o editor visual dos agentes criados em modo **Flow Designer**. Cada agente tem um **Fluxo principal** e pode ter subfluxos. Este guia mostra o essencial; a secção [Flow Builder](https://docs.diska.ai/pt/flow-builder) tem a referência completa. ## O ponto de partida Um agente novo abre com a estrutura obrigatória do Fluxo principal: ```text Fluxo principal → Antes da conversa → Mensagem de saudação → + ``` - **Fluxo principal** — a entrada da chamada. - **Antes da conversa** — passos que correm antes da saudação (por exemplo, uma acção que consulta o seu CRM). - **Mensagem de saudação** — a primeira fala: quem fala primeiro e o que diz. - **+** — onde liga o primeiro passo real. Estes nós estruturais não podem ser apagados. ## Passo 1. Adicionar um passo 1. Clique no **+** (**Adicionar próximo passo**). 2. Pesquise ou escolha o tipo de nó. Os nós aparecem agrupados em **Conversação**, **Controlo de fluxo**, **Acções**, **Transferência humana** e **Negócio**. 3. Um nó que não pode seguir-se ao passo actual aparece como **Inválido**, com o motivo. ## Passo 2. Configurar o nó Clique num nó para abrir o painel de configuração ao lado do canvas. Por exemplo, num nó **Conversação** escreve as **Instruções** do passo e, em **Recolher variáveis**, a informação que o agente deve obter (nome, telefone, email…). ## Passo 3. Ramificar a conversa Cada **Conversação** é seguida automaticamente por uma **Condição** com um caminho **Continuar**, que leva a conversa em frente. Para criar alternativas, adicione caminhos à condição: - **Prompt LLM** — descreva em linguagem natural quando seguir o caminho (ex.: "o cliente quer falar com uma pessoa"); - **Regra determinística** — compare uma variável com um valor (ex.: `plano` é igual a `premium`). Os nós de acção (**Acção personalizada**, **Enviar SMS durante a chamada**, **Transferência**, **Agendamento**) têm duas saídas: **Sucesso da acção** e **Falha da acção**. Ligue as duas. ## Passo 4. Terminar a chamada Todos os caminhos devem acabar num nó **Terminar chamada**, com um motivo de fim e uma despedida. Sem pelo menos um **Terminar chamada** alcançável, o fluxo não pode ser publicado. ## Passo 5. Reutilizar lógica com subfluxos 1. Clique no **+** à direita dos separadores do canvas para criar um subfluxo. 2. No nó **Condições de entrada**, defina quando o subfluxo pode ser activado. 3. No Fluxo principal, use o nó **Disparar subfluxo** para entrar nele. Os separadores de cada subfluxo permitem **Renomear**, **Duplicar** e **Apagar**. ## Atalhos úteis | Atalho | Acção | | --------------------------- | -------------------------------- | | `Ctrl/⌘ + K` | Pesquisar nós | | `Ctrl/⌘ + C` / `Ctrl/⌘ + V` | Copiar / colar o nó seleccionado | | `Ctrl/⌘ + D` | Duplicar o nó seleccionado | | `Ctrl/⌘ + Z` | Desfazer | | `Ctrl/⌘ + Shift + Z` | Refazer | | `Ctrl/⌘ + 0` | Ajustar o fluxo ao ecrã | | `Backspace` | Apagar o nó seleccionado | ## Validar e publicar O Flow Builder guarda automaticamente e valida o fluxo enquanto edita. O botão **Lista de verificação** na barra do agente mostra o número de problemas; clique num problema para saltar para o nó. Erros bloqueiam a publicação; avisos não. Quando não houver erros, clique em **Publicar**. Ver [Validação e publicação](https://docs.diska.ai/pt/flow-builder/validation-publishing) e [Testar um fluxo](https://docs.diska.ai/pt/flow-builder/testing). # Publicar e receber chamadas Enquanto edita, está a alterar o **rascunho** do agente. Os clientes nunca falam com o rascunho: o telefone, o link público, o widget e a API servem sempre a **versão publicada**. Publicar é, por isso, o passo que põe as suas alterações em produção. ## O que a publicação congela Cada publicação cria uma versão numerada (V1, V2, …) com: - o nome, a descrição, o prompt e a mensagem de saudação; - as definições do agente (voz, configuração de chamada, gravação e consentimento); - as acções anexadas e as bases de conhecimento atribuídas; - o número de telefone atribuído; - nos agentes em Flow Designer, o Fluxo principal e os subfluxos que ele alcança. As chamadas que começam depois de publicar usam a nova versão. ## Publicar uma versão 1. No editor do agente, clique em **Publicar**. O botão fica desactivado quando não há alterações por publicar. 2. Num agente em Flow Designer, a plataforma valida o fluxo primeiro e abre a **Lista de verificação**. Erros bloqueiam a publicação; corrija-os e tente de novo. Num agente em Prompt Builder, o prompt não pode estar vazio. 3. Na janela **Publicar**, dê um nome à versão (opcional). Use **Mostrar alterações** para comparar com a última versão publicada. 4. Clique em **Publicar**. Publicar exige o papel Proprietário, Administrador ou Membro. ::callout{type="tip"} No painel **Versões** vê o histórico. O menu de cada versão permite **Ver alterações** , **Exportar para JSON** , **Descartar rascunho** e **Restaurar esta versão** . Restaurar só alinha o rascunho com essa versão — publique a seguir para a pôr em produção. :: ## Definições de publicação O botão **Publicação** na barra do agente abre as **Definições de publicação**, com um separador por canal: | Tipo de agente | Separadores | | ----------------------- | --------------------------------------------------- | | Inbound, Outbound, Chat | **Telefone**, **Link público**, **Widget**, **API** | | Voice Widget | **Widget**, **WebSocket**, **API** | ### Telefone Em **Número de telefone**, clique em **Adicionar número de telefone** e escolha um número. A lista mostra os números activos da sua organização, cada um com o seu estado (por exemplo **Configurado**, **Sem agente** ou **Credenciais pendentes**). **Importar** abre a importação de um número SIP do seu operador. - Só **Proprietários** e **Administradores** podem atribuir, alterar ou remover números. - Um número só pode ser atendido por **um** agente Inbound. Um agente Outbound usa o número como identificação de quem liga, e vários agentes Outbound podem usar o mesmo número. ::callout{type="warning"} **Depois de atribuir ou mudar o número, publique o agente.** A linha só passa a tocar no agente quando a atribuição está na versão publicada, e atende sempre com essa versão. :: Por baixo do número ficam os webhooks do agente: **Inbound Webhook** (agentes Inbound), que recebe cada chamada antes de o agente falar e pode dar-lhe dados sobre quem liga, e **Data Webhook**, que recebe os dados de cada chamada quando termina. **Inicializar** envia um pedido de teste. Como o número, valem a partir da publicação. Ver [Webhooks do agente](https://docs.diska.ai/pt/telephony/webhooks). Para obter números, ver [Números](https://docs.diska.ai/pt/telephony/numbers); para o que acontece numa chamada, ver [Chamadas telefónicas](https://docs.diska.ai/pt/telephony/phone-calls). ### Link público O link público permite que qualquer pessoa fale com a versão publicada do agente no browser, sem conta Diska. 1. Publique o agente pelo menos uma vez — antes disso, **Ativar link público** fica desactivado. 2. Clique em **Ativar link público**. 3. Copie o **Endereço para partilhar** ou abra-o numa nova janela. O separador mostra também o **Token público** e o **Endpoint de sessão (API)**, só necessários para integrar o agente noutro player. - **Gerar novo link** cria um token novo: todos os links e códigos de widget partilhados antes deixam de funcionar de imediato. - **Desativar** impede novas chamadas pelo link. O token é mantido: ao reactivar, o mesmo link volta a funcionar. Gerir o link público exige o papel Proprietário, Administrador ou Membro. ### Widget O widget usa o mesmo canal público. Se ainda não estiver activo, clique em **Ativar canal público**. Depois copie o código para o seu site e personalize a aparência — ver [Incorporar o widget de voz](https://docs.diska.ai/pt/guides/embed-widget). ### WebSocket Disponível nos agentes **Voice Widget**: em **Sessões em tempo real**, mostra o endpoint do canal público, o pedido com que o widget e o link público abrem a conversa de voz. O protocolo da sessão não é um contrato público; ver [Tempo real](https://docs.diska.ai/pt/api/realtime). ### API Resume o que a [API da DISKA](https://docs.diska.ai/pt/api/api-channel) permite a partir do seu backend (agentes, chamadas, análises, números, conhecimento e webhooks) e liga a esta documentação com o botão **Começar com a API**. Conversar com o agente por texto e pôr o agente a ligar a clientes também é possível pela API, depois de a DISKA activar essas funções para a organização. ## Rever as chamadas As chamadas de todos os canais ficam em **Históricos**. A partir do agente, o menu **⋮ → Registos de chamadas** abre os Históricos já filtrados por esse agente. Ver [Chamadas](https://docs.diska.ai/pt/history/calls). ::callout{type="info"} O aviso **Número de telefone** na Lista de verificação não bloqueia a publicação: um agente sem número continua a funcionar no link público, no widget e na API. :: # Testar um agente O botão **Testar** no editor do agente abre o painel de teste com quatro modos — **Chamada web**, **Chamada telefónica**, **Chat** e **Simulação** — e dá acesso ao **Centro de Testes**. Todos os papéis da organização, incluindo Visualizador, podem testar agentes. ## Rascunho ou versão publicada Enquanto o painel de teste está aberto, uma faixa no topo do editor indica **Modo de teste · não é tráfego live** e qual a versão em teste: - **Rascunho** — as alterações que ainda não publicou; - **Publicado** — a versão que está em produção. Use o interruptor da faixa para mudar. Até publicar o agente pela primeira vez, só pode testar o rascunho. ::callout{type="warning"} Na **Chamada web** e na **Chamada telefónica** , o rascunho corre as acções em modo simulado, mas a **versão publicada corre-as a sério** : os SMS são enviados e as marcações são criadas; na chamada telefónica, as transferências ligam mesmo para o destino. O **Chat** e a **Simulação** nunca executam acções reais. :: ## Chamada web Fale com o agente no browser, com o microfone do computador. 1. Clique em **Testar → Chamada web**. 2. Opcional: preencha o **Contacto do chamador** (usado, por exemplo, como destinatário de SMS) e os campos **Variável: …** das variáveis pré-chamada do agente. 3. Clique em **Iniciar chamada de teste** e autorize o microfone. 4. Clique em **Terminar** para desligar. A chamada web de teste não liga a nenhuma linha telefónica: se o agente tentar transferir, a transferência não acontece e o agente continua a conversa. Esta chamada não é gravada. ## Chamada telefónica O agente liga do seu número DISKA para o seu telemóvel. É a forma de ouvir o agente exactamente como um cliente o ouve. ### Requisitos - A organização tem de estar habilitada pela Diska para chamadas telefónicas de saída. - O agente tem de ter sido publicado pelo menos uma vez **com um número DISKA activo atribuído**. A chamada sai sempre do número da versão publicada, mesmo quando testa o rascunho. - Testar a **versão publicada** (acções reais) exige poder executar acções: um **Visualizador** só pode testar o rascunho, com acções simuladas. - O destino tem de ser um telemóvel angolano (Africell ou Unitel), com 9 dígitos — por exemplo `923 000 000`. Só o indicativo +244 está disponível, e não pode ligar para o próprio número do agente. ### Fazer a chamada 1. Clique em **Testar → Chamada telefónica**. 2. Em **Versão do agente**, escolha **Rascunho — ações simuladas** ou a versão publicada (por exemplo, **V3 publicada — ações reais**). 3. Confirme o número em **Chamada de** (o número do agente). 4. Em **Ligar para**, escreva o seu telemóvel. 5. Preencha as variáveis pré-chamada, se o agente as tiver. 6. Clique em **Ligar-me** e atenda o telemóvel. A linha de estado acompanha a chamada: **A preparar a chamada…**, **A tocar no …**, **Em chamada · m\:ss** e, no fim, **Chamada terminada**. Para desligar a partir do painel, clique em **Desligar**. ::callout{type="info"} São minutos reais da linha DISKA. O telemóvel toca durante a **Duração do toque** da versão escolhida e a chamada respeita o limite de duração dessa versão — ver [Configuração de chamada](https://docs.diska.ai/pt/telephony/call-settings) . Se **Gravar chamadas** estiver activo, a chamada é gravada (os primeiros 27 minutos) — ver [Gravar chamadas](https://docs.diska.ai/pt/guides/record-calls) . A chamada fica em **Históricos** , como as restantes. :: ### Limites e mensagens | Mensagem | O que fazer | | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | Indique um telemóvel angolano (Africell ou Unitel)… | Corrija o número: 9 dígitos, a começar por 92–96. | | Esta organização ainda não está habilitada para chamadas telefónicas de saída. | Peça à Diska para habilitar as chamadas de saída. | | Publique o agente uma vez para lhe atribuir o número que faz a chamada. | Publique o agente. | | Atribua ao agente um número DISKA activo e publique-o para testar por telefone. | Atribua um número DISKA em **Publicação → Telefone** e publique. | | Indique o seu telemóvel, não o número do agente. | Use outro número de destino. | | Já tem uma chamada de teste em curso. Termine-a antes de ligar de novo. | Cada pessoa só pode ter uma chamada de teste de cada vez. | | Atingiu o limite de chamadas de teste desta hora. Tente mais tarde. | Há um limite de chamadas de teste por hora em cada organização. | | A organização atingiu o limite de chamadas em simultâneo. | Aguarde que termine outra chamada telefónica. | | O número está ocupado, desligado ou rejeitou a chamada. / A chamada não foi atendida. | Verifique o telemóvel e tente de novo. | | A linha telefónica não está disponível neste momento. | Tente mais tarde; se persistir, contacte o suporte. | ## Chat Converse com o agente por texto, sem voz. Num agente em Flow Designer, cada mensagem percorre o fluxo; num agente em Prompt Builder, o agente responde a partir do prompt. **Novo chat** recomeça a conversa. O chat nunca executa acções reais. ## Simulação **Testar → Simulação** mostra as suites de teste deste agente — as mesmas do [Centro de Testes](https://docs.diska.ai/pt/test-center), vistas a partir do editor. Uma suite junta cenários com critérios de sucesso: um cliente simulado por IA conversa com o agente por texto e cada caso passa ou falha. Funciona em agentes de Prompt Builder e de Flow Designer. O painel tem dois separadores: - **Suites de teste** — as suites do agente, com pesquisa e o botão **Suite** para criar uma nova; - **Histórico** — as execuções deste agente, com quantos casos passaram e o estado. ### Criar e executar uma suite 1. Clique em **Suite**. A suite é criada para este agente, na língua dele, e abre vazia. 2. Escolha **Gerar com IA** (marque os cenários e o número de casos e clique em **Gerar … casos de teste**) ou **Criar caso personalizado**. 3. Reveja os casos: cada um precisa do **Prompt do cenário** e de pelo menos um **Critério de sucesso**. 4. Clique em **Executar**. Aparece **Testes iniciados.** e abre a execução, com cada caso **Em curso** até terminar. A execução usa a versão escolhida na faixa de teste: **Rascunho** ou **Publicado**. Clique num caso terminado para ver os critérios (**Visão geral**) e a conversa (**Transcrição**). Tudo o que criar aqui aparece no Centro de Testes, e vice-versa. **Abrir no Centro de Testes**, no fundo do painel, abre-o já filtrado por este agente. Os detalhes de cada campo e das avaliações estão em [Centro de Testes](https://docs.diska.ai/pt/test-center). Todos os papéis podem ver e executar suites; criar e editar suites e casos exige o papel Proprietário, Administrador ou Membro. ::callout{type="tip"} Para mostrar o agente a alguém fora da equipa, active o [link público](https://docs.diska.ai/pt/guides/publish-agent) — funciona no browser, sem conta Diska. :: # Transferir para humano O agente pode passar uma chamada telefónica para uma pessoa da sua equipa — por exemplo, quando o cliente pede para falar com alguém ou quando o pedido sai do âmbito do agente. ## Onde funciona - **Chamadas telefónicas** (recebidas e feitas pelo agente, incluindo a chamada telefónica do painel de teste): a linha passa para o destino quando este atende. - **Chamadas web** (teste no browser, link público, widget): não há linha telefónica para transferir. A transferência não acontece e o agente continua a conversa. ### Destinos permitidos | Número que atende a chamada | Para onde pode transferir | | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Número DISKA | Só para **telemóveis angolanos** (Africell ou Unitel) configurados como número fixo na acção, no nó ou na lista telefónica. Um número dito durante a conversa nunca é usado. A organização tem de estar autorizada a fazer chamadas de saída. | | Número importado do seu operador (trunk SIP) | Para um número ou um SIP URI do domínio do seu trunk; a chamada sai pelo seu trunk. Ver [Ligar por SIP](https://docs.diska.ai/pt/telephony/sip-trunk). | | Número WhatsApp (chamada de voz) | Só para **telemóveis angolanos** fixos, como num número DISKA. O cliente fica na mesma chamada WhatsApp. Ver [Chamadas de voz](https://docs.diska.ai/pt/whatsapp/calls#transferir-para-uma-pessoa). | ## Passo 1. Criar a acção de transferência 1. No menu lateral, abra **Acções → Transferências de chamada** e clique em **Criar novo**. 2. No separador **Geral**, preencha: - **Nome** — identificador da acção (minúsculas, números e `_`, ex.: `transferir_vendas`); - **Descrição da condição** — quando deve a transferência acontecer (ex.: "o cliente pede para falar com um comercial"); - **Transferir para** — **Número**, **SIP URI** ou **Lista telefónica**. Para um número, use **Validar** para confirmar o formato. 3. Clique em **Guardar**. Criar e editar acções exige o papel Proprietário, Administrador ou Membro. ## Passo 2. Escolher o modo No separador **Definições de transferência**, escolha o **Modo de transferência**: | Modo | O que acontece | | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Transferência direta** | Quem atende é ligado de imediato ao cliente, sem aviso. | | **Transferência assistida com mensagem** | Quem atende ouve primeiro, na voz do agente, o motivo da transferência ("Chamada transferida pela assistente virtual. Motivo: …"). Só depois o cliente é ligado. | | **Transferência assistida com resumo contextual** | Quem atende ouve primeiro um resumo curto da chamada, na voz do agente. Só depois o cliente é ligado. | No mesmo separador, defina o que o **cliente** ouve: - **Mensagem «A tentar contactar o destinatário»** — dita ao cliente quando a transferência começa (por omissão: "Deixe-me transferi-lo para um humano. Por favor aguarde."). - **Mensagem «Destinatário falhou ou recusou»** — dita quando a transferência falha. Se o destino tocar e não atender (sem resposta, ocupado ou recusado), o agente diz «Infelizmente o número está indisponível neste momento.». Em qualquer caso, o agente continua com o cliente. O botão **Variáveis** insere `{{caller_name}}`, `{{agent_name}}`, `{{destination}}` ou `{{conversation_summary}}` nas mensagens. Na chamada, só são preenchidas as variáveis que existam na conversa nesse momento; as outras são retiradas da frase, por isso escreva mensagens que façam sentido sem elas. Enquanto o destino toca, o cliente fica em linha com o agente (sem música de espera). ## Passo 3. Definir o horário (opcional) No separador **Disponibilidade humana**, active **Activar horário de disponibilidade**, escolha os dias e as horas, o **Fuso horário** e a **Mensagem "Humano indisponível"**. Fora do horário, a transferência não é feita e o agente diz essa mensagem. Desactivado, a transferência é possível a qualquer hora. ## Passo 4. Ligar a acção ao agente **Agente em Prompt Builder:** 1. No editor, abra **Ações**. 2. Em **Durante a conversa**, clique em **Adicionar → Transferência de chamada**. 3. Escolha a transferência na lista. O agente transfere quando a **Descrição da condição** se verifica. **Agente em Flow Designer:** Adicione um nó **Transferência** (categoria **Transferência humana**) e escolha o **Destino**: - **Telefone**, **SIP URI** ou **Lista telefónica** — configurados no próprio nó; marque **Transferência assistida** para que quem atende ouça primeiro um resumo do que o fluxo recolheu (pode orientá-lo em **Resumo para handoff**); - **Acção de transferência** — usa uma acção criada no Passo 1, com o seu modo, horário, lista e mensagens. O nó tem duas saídas: **Sucesso da acção** (a chamada foi transferida) e **Falha da acção** (o destino não atendeu ou a chamada é web — o agente continua). Ligue as duas. Ver [nó Transferência](https://docs.diska.ai/pt/nodes/transfer). Em alternativa, num passo **Conversação**, abra **Acções → Adicionar → Transferência de chamada**: o agente pode transferir em qualquer momento desse passo, quando a condição da acção se verificar. ::callout{type="warning"} Transferir para uma fila ou equipa não existe nas linhas telefónicas: um nó antigo com **Fila ou equipa** impede a publicação até escolher outro destino. :: ## Passo 5. Testar - O botão **Simular** (disponível depois de guardar a acção) gera os eventos de uma transferência sem fazer nenhuma chamada. As opções do separador **Simulação** só se aplicam aí. - Para uma transferência real, use **Testar → Chamada telefónica** com a versão publicada: o agente liga-lhe e, ao pedir para falar com uma pessoa, a chamada é transferida. Com o rascunho, a transferência é simulada. Ver [Testar um agente](https://docs.diska.ai/pt/guides/test-agent). ::callout{type="info"} O limite de duração da chamada ( **Definições → Configuração de chamada** ) nunca corta uma chamada que já foi transferida para uma pessoa. :: # Marcar reuniões com Cal.com Com uma acção de **Agendamento em tempo real**, o agente marca a reunião no seu Cal.com enquanto fala com o cliente e, opcionalmente, envia um SMS de confirmação. ## Pré-requisitos 1. Uma conta Cal.com com pelo menos um tipo de evento. 2. O Cal.com ligado em **Definições → Integrações** — ver [Cal.com](https://docs.diska.ai/pt/integrations/calcom). ## Passo 1. Criar a acção de agendamento 1. No menu lateral, abra **Acções → Agendamento em tempo real**, clique em **Criar novo** e escolha **Cal.com**. 2. Preencha: - **Nome da acção** — minúsculas, números e `_` (ex.: `marcar_demo`); - **Conta Cal.com** — confirma que a ligação está activa (o ícone de definições abre as Integrações); - **Evento** — o tipo de evento Cal.com onde a reunião é criada (o botão de actualizar recarrega a lista). 3. Em **Sugestões de disponibilidade**, escolha o **Fuso horário** usado para converter a hora dita pelo cliente: África/Luanda, Europa/Lisboa ou UTC. 4. Opcional: active **SMS de confirmação** e ajuste o texto. Use `{appointment_date}` e `{appointment_link}` para inserir os detalhes. O texto por omissão é: ```text Está tudo pronto! A sua marcação está agendada para {appointment_date}. Aceda por este link: {appointment_link} ``` 5. Clique em **Guardar**. O Cal.com envia um email de confirmação para o endereço que o agente recolher na variável ``. ::callout{type="info"} A sugestão automática de horários livres está marcada como **em breve** . Por agora, o agente marca a hora pedida pelo cliente e o Cal.com valida a disponibilidade. :: ## Passo 2. Ligar a acção ao agente **Agente em Prompt Builder:** 1. No editor, abra **Ações** e, em **Durante a conversa**, clique em **Adicionar → Agendamento em tempo real**. 2. Escolha a acção. 3. Clique na acção anexada para ver as **Variáveis de entrada** e indicar de onde vem cada uma — por exemplo, o email recolhido pelo agente. **Agente em Flow Designer:** 1. Antes do agendamento, recolha o email e a hora pretendida num nó **Conversação** (em **Recolher variáveis**). 2. Adicione um nó **Agendamento** e, em **Acção de agendamento**, escolha a acção. 3. Preencha **Tipo de marcação** (Demonstração, Reunião ou Chamada de seguimento), **Título**, **Contacto / email** e **Horário** (as variáveis recolhidas), **Fuso horário** e a **Mensagem de confirmação** que o agente diz. 4. Ligue as saídas **Sucesso da acção** e **Falha da acção**. Ver [nó Agendamento](https://docs.diska.ai/pt/nodes/booking). ::callout{type="warning"} Se a plataforma não tiver o calendário disponível, um fluxo com o nó **Agendamento** não pode ser publicado e o editor mostra **Capacidades live ainda não disponíveis** . :: ## Passo 3. Testar - Com o **rascunho**, a marcação é simulada: nada é criado no Cal.com. - Com a **versão publicada**, numa chamada web ou telefónica de teste, a marcação é real — confirme no seu Cal.com que a reunião aparece no tipo de evento escolhido. O chat e a simulação nunca criam marcações. Ver [Testar um agente](https://docs.diska.ai/pt/guides/test-agent). # Enviar SMS durante e depois da chamada A Diska tem dois tipos de acção de SMS: | Acção | Quando é enviada | Exemplo | | ------------------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------- | | **SMS durante a chamada** | Quando o agente decide enviá-la, com a chamada activa. Pode esperar pela resposta do cliente. | Um código de verificação, um link de pagamento. | | **SMS pós-chamada** | Depois de a chamada terminar, se a condição se verificar na transcrição. | Um resumo do que foi combinado. | O SMS é enviado para o número do cliente — numa chamada telefónica, o número de quem fala com o agente. ::callout{type="info"} O estado do envio de SMS aparece em **Acções** , no cartão **Integrações** (linha **SMS (Ombala)** ). Se o SMS não estiver configurado na plataforma, nenhum SMS é enviado. :: ## SMS durante a chamada ### Criar a acção 1. Abra **Acções → SMS durante a chamada** e clique em **Criar novo**. 2. Preencha: - **Nome da acção** (ex.: `enviar_codigo`); - **Mensagem antes da acção** — o que o agente diz antes de enviar (ex.: "Vou enviar o código agora."); - **Corpo da mensagem** — o texto do SMS. Use `` para inserir variáveis, como ``; as variáveis detectadas aparecem em **Variáveis de placeholder**. 3. Opcional, em **Definições de resposta**: active **Aguardar resposta** para o agente esperar que o cliente responda por SMS, defina o **Tempo limite (segundos)** (no máximo efectivo, 45 segundos) e a **Mensagem de fallback** dita se a resposta não chegar. 4. Clique em **Guardar**. O botão **Simular** mostra o SMS resolvido para um **Destinatário** de teste, com uma **Resposta simulada** ou um timeout forçado — sem enviar nada. ### Ligar ao agente - **Prompt Builder:** **Ações → Durante a conversa → Adicionar → SMS durante a chamada** e escolha a acção. - **Flow Designer:** adicione o nó **Enviar SMS durante a chamada**, use **Anexar SMS durante a chamada** e preencha o **Mapeamento de variáveis de entrada** para cada variável do texto. Ligue as saídas **Sucesso da acção** e **Falha da acção**. Ver [nó Enviar SMS durante a chamada](https://docs.diska.ai/pt/nodes/send-sms-during-call). ## SMS pós-chamada ### Criar a acção 1. Abra **Acções → SMS pós-chamada** e clique em **Criar novo**. 2. Preencha: - **Nome**; - **Descrição da condição** — em que situação enviar (ex.: "o cliente aceitou a proposta"). A condição é avaliada sobre a transcrição da chamada; - **Conteúdo do SMS (variante A)**, com variáveis ``; - opcional, **Variante B (A/B opcional)** — um texto alternativo para teste A/B. 3. Clique em **Guardar**. **Simular** permite indicar um **Destinatário (E.164)** e uma **Transcrição (para condição)** para ver se a condição se verifica e qual seria o texto — sem enviar. ### Ligar ao agente - **Prompt Builder:** **Ações → Depois da conversa → Adicionar → SMS pós-chamada**. - **Flow Designer:** clique no nó **Depois da conversa** (a seguir a **Terminar chamada**) e use **Adicionar → SMS pós-chamada**. ## Testar - Com o **rascunho**, nenhum SMS é enviado: o resultado fica marcado como simulado. - Com a **versão publicada**, numa chamada web ou telefónica de teste, o SMS é mesmo enviado. Na chamada web, o destinatário é o **Contacto do chamador** que preencher no painel de teste. Ver [SMS durante a chamada](https://docs.diska.ai/pt/actions/during-call-sms) e [SMS pós-chamada](https://docs.diska.ai/pt/actions/post-call-sms) para a referência completa. ::callout{type="warning"} Os SMS enviados com a versão publicada são reais e chegam ao cliente. Teste com o rascunho até o texto estar certo. :: # Configurar uma lista telefónica Uma **lista telefónica** reúne vários números para onde o agente pode transferir uma chamada — por exemplo, Vendas e Suporte — cada um com a sua condição. Usa-se como destino de uma [transferência para humano](https://docs.diska.ai/pt/guides/transfer-to-human). ## Criar uma lista 1. Abra **Acções → Transferências de chamada** e clique em **Listas telefónicas**. 2. Clique em **Novo** (ou **Criar lista telefónica**, se ainda não tiver nenhuma). 3. Dê um **Nome** à lista. 4. Para cada destino, preencha: - **Número de telefone** — em formato internacional, ex.: `+244 923 000 000`; - **Condição de transferência** — quando usar este número, ex.: "Quando o utilizador pede vendas". 5. Use **Adicionar** para mais destinos e clique em **Guardar**. Os dois campos são obrigatórios em cada linha. Criar e editar listas exige o papel Proprietário, Administrador ou Membro. Exemplo: | Número de telefone | Condição de transferência | | ------------------ | --------------------------------- | | +244 923 000 001 | vendas, preços, comprar | | +244 923 000 002 | suporte, avaria, problema técnico | ## Como o destino é escolhido Quando o agente decide transferir durante a conversa, indica o motivo da transferência. A plataforma compara esse motivo com as palavras da **Condição de transferência** de cada número, pela ordem da lista, e usa o primeiro número cuja condição corresponda. Se nenhuma corresponder, é usado o **primeiro número da lista**. - Escreva condições com palavras-chave curtas e distintas (ex.: vendas, suporte, facturação), que o agente vai usar ao explicar o motivo. - Ponha em primeiro lugar o destino que deve atender por omissão. ::callout{type="warning"} O nó **Transferência** de um fluxo (com destino **Lista telefónica** ou com uma **Acção de transferência** ) não indica motivo, por isso usa sempre o **primeiro número** da lista. A escolha por condição aplica-se quando a transferência está anexada como acção — no Prompt Builder ou nas **Acções** de um passo **Conversação** . :: ## Usar a lista - **Numa acção de transferência:** em **Transferir para**, escolha **Lista telefónica** e seleccione a lista. - **Num fluxo:** no nó **Transferência**, escolha o destino **Lista telefónica** e seleccione a lista. Se o agente atende num **número DISKA**, todos os números da lista têm de ser telemóveis angolanos (Africell ou Unitel) — ver [Destinos permitidos](https://docs.diska.ai/pt/guides/transfer-to-human). ## Editar ou eliminar Na janela **Listas telefónicas**, use o lápis para editar e o caixote para eliminar. Uma lista usada por uma transferência não pode ser eliminada. # Incorporar o widget de voz O widget de voz permite que os visitantes do **seu site** falem com o agente pelo browser, sem conta Diska. O widget fala sempre com a **versão publicada** do agente. ## Pré-requisitos 1. O agente tem uma versão publicada — ver [Publicar e receber chamadas](https://docs.diska.ai/pt/guides/publish-agent). 2. O canal público está activo. Em **Publicação → Widget**, clique em **Ativar canal público** (é o mesmo canal do **Link público**). Activar o canal público exige o papel Proprietário, Administrador ou Membro. ## Obter o código Em **Publicação → Widget**, a secção **Código incorporável** tem duas variantes. Use o botão de copiar ao lado de cada uma. **Script (Recomendado)** — cole antes de ``. O loader desenha o botão, trata da posição e do abrir/fechar: ```html ``` **Alternativa sem JavaScript** — para sites que bloqueiam scripts de terceiros: um iframe fixo no canto inferior direito, sem loader: ```html ``` ::callout{type="warning"} Mantenha o atributo `allow="microphone"` no iframe. Sem ele, o navegador recusa o microfone dentro do frame e a chamada nunca arranca. A variante script já o define. :: ## Personalizar a aparência As definições ficam no mesmo separador e são guardadas automaticamente (**A guardar…** → **Guardado**). Aplicam-se ao widget já instalado — não precisa de voltar a colar o código. | Secção | Opções | | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Visualizador** | **Esfera** ou **Imagem** (indique um URL `https://` da imagem), mostrado enquanto o agente fala. | | **Paleta de cores** | Visualizador, Fundo do cartão, Texto do botão, Fundo do botão e Texto (cores hexadecimais). | | **Personalização de texto** | Botão de chamada, Disponibilidade, A iniciar chamada, Durante a chamada e Fim da chamada (até 60 caracteres). | | **Widget flutuante** | **Ativar widget flutuante** mostra um botão fixo num canto do site; desligado, o widget aparece onde colou o código. Com o modo flutuante pode também **Mostrar nome do agente quando recolhido**, **Expandir ao carregar a página**, escolher a **Posição** (inferior/superior, direito/esquerdo) e um **Atraso (ms)** até 60 000. | A **Pré-visualização do widget** ao lado é real: pode iniciar uma chamada com a versão publicada a partir dela. ::callout{type="info"} Nos agentes do tipo **Voice Widget** , as Definições de publicação abrem sozinhas depois de cada publicação e, com o canal público activo, mostram uma vista alargada com a pré-visualização ao lado. :: ## Actualizar o agente O widget usa sempre a última versão publicada. Para mudar o que o agente diz ou faz, edite e **publique** de novo — o código no site não muda. Se usar **Gerar novo link** no separador **Link público**, o token muda e os códigos já colados deixam de funcionar: volte a copiar o código. ## Resolução de problemas - **Não aparece nada na página.** O widget esconde-se em vez de partir o seu site. Abra a consola do navegador: `[diska-widget] indisponível` significa que o canal público está desligado ou que o agente não tem versão publicada; um erro de rede indica que o browser não conseguiu contactar a Diska. - **O pedido de microfone nunca aparece.** Confirme o atributo `allow` (variante iframe) e que o seu site é servido por HTTPS — os navegadores bloqueiam o microfone em páginas inseguras. - **A chamada fica gravada?** Só se **Gravar chamadas** estiver activo no agente — ver [Gravar chamadas](https://docs.diska.ai/pt/guides/record-calls). # Gravar chamadas Com **Gravar chamadas** activo, a Diska guarda o áudio das chamadas do agente para as ouvir em **Históricos**. A gravação está desligada por omissão em todos os agentes e só pode ser activada depois de configurar o aviso de consentimento que o agente diz ao cliente. ::callout{type="warning"} **Gravar chamadas é uma decisão legal.** Gravar sem avisar o cliente é ilegal na maioria das jurisdições. A sua empresa é responsável por cumprir as regras de protecção de dados do seu mercado — confirme-as antes de activar. :: ## Activar a gravação 1. No editor do agente, abra **Definições → Segurança e conformidade**. 2. Active **Gravar chamadas**. **Avisar que a chamada é gravada** fica activo, com uma mensagem sugerida: «Esta chamada é gravada para efeitos de qualidade e formação. Se preferir não ser gravado, diga-o e a gravação é interrompida.» 3. Adapte a mensagem: o agente lê-a palavra por palavra no início da chamada e depois continua a conversa. Tem de ter entre 20 e 600 caracteres. 4. Escolha a **Retenção das gravações** (ver abaixo). 5. **Publique o agente**: as definições de gravação fazem parte da versão, e as chamadas reais usam a versão publicada. Os agentes que já usavam **consentimento explícito** mantêm-no: o agente diz a mensagem e espera por um «sim» claro antes de gravar; se o cliente disser «não», a conversa continua sem gravação. ## Gravar sem avisar Com **Avisar que a chamada é gravada** desligado, o agente grava sem dizer nada ao cliente. Qualquer utilizador que edite o agente pode escolher esta opção; a Diska regista quem a escolheu e quando. ## O que é gravado | Chamada | Gravada? | | ----------------------------------------------------- | ----------------------------- | | Widget no seu site | Sim | | Link público | Sim | | Chamadas telefónicas (recebidas e feitas pelo agente) | Sim — os primeiros 27 minutos | | Chamada telefónica do painel de teste (**Ligar-me**) | Sim — os primeiros 27 minutos | | Chamada web de teste no backoffice | Não | | Chat e Simulação | Não (não há áudio) | Numa chamada telefónica, as vozes do cliente e do agente ficam na mesma gravação. Em cada gravação, a Diska regista qual a mensagem de consentimento que estava em vigor, para que alterar o aviso mais tarde não mude o que se aplicou às chamadas anteriores. ## Retenção As gravações são eliminadas automaticamente no fim do período de retenção: - **Período da organização** — o máximo para toda a organização. Por omissão, 90 dias. - **Retenção das gravações** (no agente, depois de activar a gravação) — **Usar o período da organização** ou 7, 30, 90, 180 ou 365 dias. O agente só pode **encurtar** o período: um valor maior do que o da organização fica limitado ao da organização. A data de eliminação é fixada quando a gravação é guardada; alterar o período depois não muda as gravações que já existem. ::callout{type="info"} O backoffice ainda não tem um controlo para alterar o período da organização. Se precisar de um período diferente de 90 dias, contacte a Diska. :: ## Ouvir uma gravação 1. Abra **Históricos → Chamadas** e clique na chamada. 2. No separador **Transcrição**, use o leitor: reproduzir/pausar, avançar na barra, mudar a velocidade e **Descarregar gravação**. Por baixo do leitor aparece o tamanho do ficheiro e a data em que será eliminada automaticamente. Quando não há áudio para ouvir, a chamada mostra o estado: **A gravar…**, **A enviar…**, **Falha na gravação**, **Gravação expirada** ou **Gravação eliminada**. Ver [Gravações](https://docs.diska.ai/pt/history/recordings). Todos os papéis com acesso a Históricos podem ouvir e descarregar gravações. ## Eliminar uma gravação Proprietários e Administradores vêem o ícone **Eliminar gravação** no leitor. A eliminação é **imediata e permanente** — não há confirmação nem forma de recuperar o áudio. A transcrição e os restantes dados da chamada mantêm-se. Use-a, por exemplo, para responder a um pedido de eliminação de dados de um cliente. ## Outras opções da secção - **Guardar transcrições** — o texto da conversa é sempre guardado. - **Ocultar dados pessoais (PII)** — troca nomes, contactos, moradas, documentos e cartões por etiquetas como `[NOME]` no texto que a chamada deixa. A gravação de áudio não é alterada. Ver [Ocultar dados pessoais](https://docs.diska.ai/pt/guides/redact-personal-data). # Ocultar dados pessoais Com **Ocultar dados pessoais (PII)** activo, a Diska retira os dados pessoais do texto que cada chamada deixa: a transcrição, o resumo, a análise pós-chamada e o webhook. Cada dado é trocado por uma etiqueta: > Falas com o **[NOME]**. O meu número é **[TELEFONE]** e moro na **[MORADA]**. A chamada em si não muda: o agente ouve e usa tudo o que o cliente diz. A ocultação acontece quando a chamada termina, antes de qualquer análise ou envio. ## Activar 1. No editor do agente, abra **Definições → Segurança e conformidade**. 2. Active **Ocultar dados pessoais (PII)**. 3. **Publique o agente.** A opção faz parte da versão e as chamadas reais usam a versão publicada. Aplica-se às chamadas que terminam depois de publicar. As chamadas anteriores não são alteradas. Nas chamadas de teste do painel vale o que está no rascunho, por isso pode experimentar antes de publicar. ## O que é ocultado | Dado | Etiqueta | Exemplos | | ------------------- | ------------------- | ------------------------------------------------------------- | | Nomes de pessoas | `[NOME]` | «Márcio Quimbundo» e, mais tarde na chamada, só «Márcio» | | Telefones | `[TELEFONE]` | «958 114 794», «+244 923 …», «nove cinco oito, um um quatro…» | | Emails | `[EMAIL]` | «», «nome arroba gmail ponto com» | | Moradas | `[MORADA]` | Rua, bairro com número de casa, prédio, andar, código postal | | Documentos | `[DOCUMENTO]` | BI, NIF, passaporte, carta de condução | | Cartões | `[CARTÃO]` | Número, validade e CVV | | Contas bancárias | `[IBAN]` | IBAN | | Datas de nascimento | `[DATA_NASCIMENTO]` | «nasci a 3 de Maio de 1990» | Os dados com formato conhecido (telefones, emails, cartões, IBAN, BI) são detectados por regras, também quando são ditos por extenso. Nomes, moradas e datas de nascimento são identificados por um modelo de linguagem, que só pode apontar excertos que existem na transcrição: não reescreve o texto. Ficam visíveis: - os contactos da empresa que estão nas instruções do agente (quando o agente dita o telefone comercial, esse número não é do cliente); - o nome do agente e o da empresa; - valores, datas e horas. ## Onde se aplica | Onde | Ocultado? | | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | | Transcrição em **Históricos** | Sim | | Resumo da chamada | Sim — é escrito a partir da chamada já ocultada | | Avaliações e sentimento | Sim — calculados sobre a chamada já ocultada | | Valores dos extractores guardados na chamada | Sim | | [Webhook pós-chamada](https://docs.diska.ai/pt/api/webhooks) | Sim | | Registo das ferramentas usadas durante a chamada | Sim | | [Memória partilhada](https://docs.diska.ai/pt/knowledge-base/shared-memory) | Sim — é criada a partir da chamada já ocultada | | Chats da API da DISKA | Sim, quando a conversa fecha | | Número de quem liga (identificação da chamada) | Não — é necessário para o SMS ao cliente, a memória e a facturação | | Gravação de áudio | Não — se o áudio não pode guardar dados pessoais, desligue **Gravar chamadas** | | Dados que uma acção guarda de propósito (uma marcação no calendário, um registo no seu CRM) | Não | | Conversas de texto no WhatsApp | Não — a opção aplica-se às chamadas | ## Acções pós-chamada Os [extractores](https://docs.diska.ai/pt/actions/information-extractors) continuam a ler a chamada completa para alimentar as acções que agem pelo cliente. O [SMS pós-chamada](https://docs.diska.ai/pt/actions/post-call-sms) e as [acções personalizadas](https://docs.diska.ai/pt/actions/custom-actions) recebem os valores reais, por exemplo o nome para «Olá {nome}». O que a Diska guarda, e o que envia no webhook, leva as etiquetas. Se precisa do nome ou do contacto do cliente no seu sistema, envie-os com uma acção personalizada: o webhook pós-chamada chega sem esses dados. ## Limitações - **A ocultação é definitiva.** O texto original não é guardado e não pode ser recuperado. - **Nenhum detector é perfeito**, sobretudo em fala transcrita. Um nome mal transcrito pode escapar, e uma palavra comum pode ser ocultada por engano. Use a ocultação como uma camada de protecção, não como a única. - **O resumo e a memória esperam pela ocultação.** Normalmente ficam prontos segundos depois da chamada. Numa chamada interrompida (por exemplo, abandonada), a plataforma oculta-a alguns minutos depois e só então os cria. - A detecção de nomes e moradas usa o mesmo fornecedor de modelos que já escreve o resumo da chamada. # Guias Nesta secção encontra instruções passo a passo para as tarefas mais comuns, do primeiro agente à chamada telefónica gravada. ::card-group :::card --- description: Do botão Novo agente à primeira chamada de teste. icon: i-lucide-bot title: Criar o primeiro agente to: https://docs.diska.ai/pt/guides/create-first-agent --- ::: :::card --- description: Desenhe a conversa com nós, condições e subfluxos. icon: i-lucide-workflow title: Usar o Flow Builder to: https://docs.diska.ai/pt/guides/use-flow-builder --- ::: :::card --- description: Versões, número de telefone, link público, widget e API. icon: i-lucide-rocket title: Publicar e receber chamadas to: https://docs.diska.ai/pt/guides/publish-agent --- ::: :::card --- description: Chamada web, chamada telefónica, chat, simulação e Centro de Testes. icon: i-lucide-flask-conical title: Testar um agente to: https://docs.diska.ai/pt/guides/test-agent --- ::: :::card --- description: Transferência directa ou assistida para uma pessoa. icon: i-lucide-phone-forwarded title: Transferir para humano to: https://docs.diska.ai/pt/guides/transfer-to-human --- ::: :::card --- description: Agendamento em tempo real com Cal.com. icon: i-lucide-calendar-check title: Marcar reuniões to: https://docs.diska.ai/pt/guides/book-meetings --- ::: :::card --- description: SMS durante e depois da chamada. icon: i-lucide-message-square title: Enviar SMS to: https://docs.diska.ai/pt/guides/send-sms --- ::: :::card --- description: Vários destinos de transferência, escolhidos por condição. icon: i-lucide-contact title: Configurar uma lista telefónica to: https://docs.diska.ai/pt/guides/configure-phone-book --- ::: :::card --- description: Ponha o agente publicado no seu site. icon: i-lucide-app-window title: Incorporar o widget de voz to: https://docs.diska.ai/pt/guides/embed-widget --- ::: :::card --- description: Consentimento, o que é gravado, retenção e onde ouvir. icon: i-lucide-mic title: Gravar chamadas to: https://docs.diska.ai/pt/guides/record-calls --- ::: :::card --- description: Nomes, contactos e documentos fora do texto das chamadas. icon: i-lucide-shield-check title: Ocultar dados pessoais to: https://docs.diska.ai/pt/guides/redact-personal-data --- ::: :: # Interface do builder O Flow Builder ocupa o centro do editor do agente. À volta do canvas estão os separadores dos fluxos, os controlos do canvas e, quando selecciona um nó, o painel de configuração. ## Separadores dos fluxos No topo do canvas há um separador por fluxo: o **Fluxo principal** e cada subfluxo. - O **+** à direita cria um subfluxo novo (**Subfluxo 1**, **Subfluxo 2**, …). - O menu de cada subfluxo permite **Renomear**, **Duplicar** e **Apagar**. - Quem não tem permissão para editar (papel Visualizador) vê a etiqueta **Só leitura** e não pode alterar o fluxo. ## Canvas A área central, onde estão os nós e as ligações. - Arraste o fundo para mover a vista e use a roda do rato para fazer zoom. - Clique num nó para o seleccionar e abrir o painel de configuração. - Cada nó mostra um indicador com o número de erros ou avisos de validação. - Para ligar dois nós, arraste da saída de um para o outro. Uma ligação não permitida é recusada, com o motivo — ver [Estrutura de um fluxo](https://docs.diska.ai/pt/flow-builder/structure). ### Controlos do canvas | Controlo | Função | | ------------------------------------ | --------------------------------------------------------------------------- | | **Pesquisar** (`Ctrl/⌘ + K`) | Procura nós por nome, tipo, variável, acção ou problema, e salta para o nó. | | **Variáveis** | Abre o painel de variáveis do agente. | | **Desfazer** / **Refazer** | Anula ou repõe a última alteração. | | **Ecrã inteiro** | Abre o canvas em ecrã inteiro. | | **Ajustar ao ecrã** | Enquadra o fluxo inteiro. | | **Reduzir zoom** / **Aumentar zoom** | Ajusta o zoom; a percentagem actual aparece ao lado. | | **Mostrar minimapa** | Mostra uma vista geral do fluxo. | ## Adicionar nós Clique num **+** (**Adicionar próximo passo**) — no fim do fluxo ou na saída de um caminho — para abrir o catálogo de nós: | Categoria | Nós | | ------------------------ | ------------------------------------------------- | | **Conversação** | Conversação, Mensagem, Terminar chamada | | **Controlo de fluxo** | Disparar subfluxo, Dividir o caminho, Saltar para | | **Acções** | Acção personalizada, Enviar SMS durante a chamada | | **Transferência humana** | Transferência | | **Negócio** | Agendamento | - Escreva em **Pesquisar nós…** para filtrar. - Um nó que não pode seguir-se ao passo actual aparece como **Inválido**, com o motivo. - Se tiver copiado um nó, o catálogo mostra também **Colar**. - Os nós ainda não disponíveis não aparecem no catálogo — ver [Nós em breve](https://docs.diska.ai/pt/nodes/coming-soon). ## Painel de configuração Ao seleccionar um nó, o painel abre ao lado do canvas com os campos desse tipo de nó — instruções, variáveis a recolher, mensagens, acções anexadas, destinos. Ao clicar num caminho de uma condição, abre o painel **Condição** desse caminho. O painel fecha-se com o botão de fechar ou com `Esc`. Cada nó tem também botões para copiar e apagar. Os nós estruturais (**Fluxo principal**, **Antes da conversa**, **Mensagem de saudação**, **Depois da conversa**) não podem ser apagados. ## Barra do agente No topo do editor, por cima do canvas: | Elemento | Função | | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | Indicador de gravação | **A guardar…**, **Guardado às …** ou **Erro ao guardar**. O fluxo é guardado automaticamente. | | **Lista de verificação** | Erros e avisos do agente e do fluxo; clique num para saltar para o nó. | | **Variáveis**, **Versões**, **Definições**, **Publicação** | Os painéis do agente. | | **Testar** | Chamada web, chamada telefónica, chat, simulação e Centro de Testes. | | **Publicar** | Valida o fluxo e publica uma nova versão. | | **⋮** | **Registos de chamadas**, **Copiar ID**, **Duplicar** e **Arquivar**. | ## Atalhos | Atalho | Acção | | ------------------------------------ | ----------------------------------------- | | `Ctrl/⌘ + K` | Pesquisar nós | | `Ctrl/⌘ + C` | Copiar o nó seleccionado | | `Ctrl/⌘ + V` | Colar | | `Ctrl/⌘ + D` | Duplicar o nó seleccionado | | `Ctrl/⌘ + Z` | Desfazer | | `Ctrl/⌘ + Shift + Z` ou `Ctrl/⌘ + Y` | Refazer | | `Ctrl/⌘ + 0` | Ajustar ao ecrã | | `Backspace` | Apagar o nó seleccionado | | `Esc` | Fechar a pesquisa, o catálogo ou o painel | Os atalhos de copiar, colar e desfazer não actuam enquanto escreve num campo de texto. # Estrutura de um fluxo Todos os fluxos têm uma estrutura fixa de entrada. O Fluxo principal e os subfluxos começam de forma diferente; a partir daí, as regras de ligação dizem que nós podem seguir-se a cada um. ## Fluxo principal ```text Fluxo principal → Antes da conversa → Mensagem de saudação → próximo passo ``` | Nó | Para que serve | | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Fluxo principal** | A entrada da chamada. | | **Antes da conversa** | Corre antes da saudação. Pode anexar-lhe **Acções personalizadas** (o **Tratamento IVR** só existe nos agentes em Prompt Builder) e ligar-lhe passos que devem acontecer antes de o agente saudar. | | **Mensagem de saudação** | A primeira fala: **Agente fala primeiro** (mensagem fixa ou gerada) ou **Humano fala primeiro** (o agente espera; pode definir quanto tempo). | Estes nós são estruturais: não podem ser apagados e a ligação `Fluxo principal → Antes da conversa → Mensagem de saudação` não pode ser desfeita — se for, a publicação é bloqueada. ## Fim da chamada Cada caminho termina num nó **Terminar chamada**, com um **Motivo de fim** (Concluído, Pedido pelo cliente, Não qualificado, Transferido ou Erro) e uma despedida. A seguir a cada **Terminar chamada** aparece automaticamente o nó **Depois da conversa**, onde anexa acções que correm depois de a chamada acabar: **SMS pós-chamada**, **Extrator de informação** e **Avaliação personalizada**. ## Subfluxos Um subfluxo começa assim: ```text Subfluxo → Condições de entrada → próximo passo ``` - Em **Condições de entrada**, adicione uma ou mais condições com **Adicionar condição de entrada**. Cada condição tem um tipo — **Manual**, **Intenção do cliente**, **Condição**, **Acção com sucesso** ou **Acção falhou** — e um nome. - Para entrar num subfluxo a partir de outro fluxo, use o nó **Disparar subfluxo** e escolha o subfluxo. Um subfluxo não pode disparar-se a si próprio. - Ao publicar, são publicados o Fluxo principal e os subfluxos que ele alcança. Use subfluxos para lógica que se repete, como validar a identidade do cliente ou recolher uma morada. ## Regras de ligação | Nó de origem | Pode seguir-se | | ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Fluxo principal** | Só **Antes da conversa**. | | **Antes da conversa** | Mensagem de saudação, Conversação, Mensagem, Acção personalizada, Enviar SMS durante a chamada, Transferência, Agendamento. | | **Mensagem de saudação** | Conversação, Mensagem, Saltar para, Disparar subfluxo, Acção personalizada, Enviar SMS durante a chamada, Transferência, Agendamento, Terminar chamada. *Não* Dividir o caminho: a saudação não recolhe resposta. | | **Conversação** | A sua **Condição** de saída, Mensagem, Saltar para, Disparar subfluxo, as quatro acções, Terminar chamada. *Não* outra Conversação directamente — passa pela Condição. | | **Mensagem** | Conversação, Mensagem, Dividir o caminho, Saltar para, Disparar subfluxo, as quatro acções, Terminar chamada. | | **Dividir o caminho** / **Condição** (cada caminho) | Conversação, Mensagem, Saltar para, Disparar subfluxo, as quatro acções, Terminar chamada. | | **Saltar para** | Conversação, Mensagem, Dividir o caminho, Disparar subfluxo, as quatro acções, Terminar chamada. | | **Disparar subfluxo** | Conversação, Mensagem, Dividir o caminho, Saltar para, as quatro acções, Terminar chamada. | | **Acção personalizada**, **Enviar SMS durante a chamada**, **Transferência**, **Agendamento** (cada saída) | Mensagem de saudação, Conversação, Mensagem, Dividir o caminho, Saltar para, Disparar subfluxo, as quatro acções, Terminar chamada. | | **Terminar chamada** | Só **Depois da conversa**. | | **Depois da conversa** | Nada — é o fecho do fluxo. | "As quatro acções" são **Acção personalizada**, **Enviar SMS durante a chamada**, **Transferência** e **Agendamento**. Cada uma tem duas saídas — **Sucesso da acção** e **Falha da acção** — e cada saída segue as regras da tabela. ## O botão + O **+** marca o sítio onde o fluxo continua. Não é um nó: clique nele para escolher o próximo passo. Os caminhos de uma condição e as saídas das acções têm o seu próprio **+**. # Variáveis do fluxo As variáveis guardam informação ao longo da chamada para a usar em instruções, mensagens, condições e acções. O painel **Variáveis** (na barra do agente ou nos controlos do canvas) lista-as em quatro grupos. ## Variáveis de sistema Disponíveis em qualquer fluxo: | Nome | Tipo | Descrição | | ------------------- | -------- | ------------------------------- | | `call_id` | texto | Identificador único da chamada. | | `user_phone_number` | telefone | Número do cliente. | | `from_phone_number` | telefone | Número de origem. | | `to_phone_number` | telefone | Número de destino. | ## Variáveis pré-chamada Valores que o agente recebe quando a chamada começa — por exemplo, o nome do cliente numa campanha. 1. Abra o painel **Variáveis**. 2. Em **Variáveis pré-chamada**, escreva o nome (`nome_da_variavel`; os espaços passam a `_`), escolha o tipo (**Texto**, **Número**, **Telefone**, **Email**, **Data** ou **Boolean**) e, opcionalmente, uma descrição. 3. Clique em **Adicionar**. No painel de teste, cada variável pré-chamada tem um campo **Variável: …** para preencher antes da chamada web ou telefónica. ## Variáveis da conversa São recolhidas pelo agente num nó **Conversação**, em **Recolher variáveis → Adicionar**: | Campo | Descrição | | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Nome** | Identificador técnico: letras, números e `_`, sem começar por número (ex.: `email_cliente`). | | **Tipo** | **String**, **Number**, **Integer**, **Boolean**, **List**, **Email** ou **Phone number**. Number e Integer aceitam **Mínimo** e **Máximo** opcionais. | | **Pergunta / instruções para recolher a variável** | Como o agente deve pedir a informação. | | **Obrigatório** | Se o passo só fica concluído com esta variável. | Um nome inválido é um erro de validação e impede a publicação. ## Resultados de acções Os nós de acção guardam o seu resultado numa variável: | Nó | Variável | | ----------------------- | ----------------------------------------------------------- | | **Acção personalizada** | A indicada em **Guardar resultado em** (ex.: `crm_result`). | | **Agendamento** | `booking_result_` | | **Transferência** | `transfer_result_` | | **Disparar subfluxo** | `subflow_result_` | ## Usar variáveis - **Em textos** (instruções, mensagens, saudação, despedida): use o botão **{ Variáveis** para inserir `{{nome_da_variavel}}`. - **Em condições:** numa **Regra determinística**, escolha a variável, o operador e o valor — ver [Condições e caminhos](https://docs.diska.ai/pt/flow-builder/branches). - **Em acções:** no mapeamento de entradas de uma acção (por exemplo, o SMS durante a chamada). ::callout{type="warning"} Se um texto ou uma condição usar uma variável que nunca é recolhida nem definida, a Lista de verificação mostra um aviso. Confirme o nome — é sensível a maiúsculas e não aceita acentos nem espaços. :: # Condições e caminhos Uma condição divide a conversa em caminhos. Os caminhos são avaliados por ordem e a conversa segue o primeiro que corresponder; se nenhum corresponder, segue o caminho **Caso contrário**. ## Onde há condições - **Depois de cada Conversação** — o Flow Builder junta automaticamente uma **Condição** com um único caminho, **Continuar**, que serve de caso contrário. Adicione caminhos para reagir ao que o cliente disse (ex.: "quer falar com uma pessoa"). - **No nó Dividir o caminho** — insira-o depois de uma Mensagem, de um Saltar para, de um Disparar subfluxo ou da saída de uma acção, para decidir com base em variáveis ou no contexto. Ver [Dividir o caminho](https://docs.diska.ai/pt/nodes/split-path). ## Configurar um caminho Clique num caminho da condição para abrir o painel **Condição**: 1. **Nome** — um nome curto, que aparece no canvas. 2. **Tipo de condição** — **Prompt LLM** ou **Regra determinística**. 3. A condição em si (ver abaixo). 4. O destino — ligue o **+** do caminho a um próximo passo. No painel do nó **Dividir o caminho**, **Adicionar caminho** cria mais caminhos e **Adicionar caso contrário** cria o caminho por omissão (o botão passa a **Alternativa activa** quando já existe). ### Prompt LLM Em **Seguir este caminho se**, descreva em linguagem natural quando seguir o caminho. O modelo decide com base na conversa. Pode inserir variáveis com **{ Variáveis**. > O cliente pediu para falar com uma pessoa ou disse que o assunto é urgente. ### Regra determinística Compara variáveis com valores. Em **Seguir este caminho se [Qualquer | Todas] das seguintes regras corresponderem**, adicione uma ou mais **Regras**, cada uma com **Variável**, **Operador** e **Valor de comparação**: | Operador | Precisa de valor | | -------------- | ---------------- | | É igual a | Sim | | É diferente de | Sim | | Contém | Sim | | Maior que | Sim | | Menor que | Sim | | Está vazio | Não | | Não está vazio | Não | | É verdadeiro | Não | | É falso | Não | Com **Qualquer**, basta uma regra ser verdadeira; com **Todas**, todas têm de ser. ::callout{type="tip"} Use regras determinísticas para lógica exacta (uma opção de menu, um valor, um sim/não recolhido) e o Prompt LLM para intenções abertas. :: ## Validação | Problema | Severidade | | ---------------------------------------------------------------- | ---------- | | Uma condição sem caminho **Caso contrário** | Erro | | Mais do que um caminho **Caso contrário** | Erro | | Um caminho Prompt LLM sem descrição | Erro | | Uma regra sem variável ou sem operador | Erro | | Um caminho sem destino ligado | Aviso | | Um caminho que repete a condição de outro (nunca será escolhido) | Aviso | | Uma regra com uma variável que nunca é recolhida nem definida | Aviso | Ver [Validação e publicação](https://docs.diska.ai/pt/flow-builder/validation-publishing). # Testar um fluxo Há várias formas de testar um fluxo, da mais rápida (texto) à mais realista (uma chamada para o seu telemóvel). Todas começam no botão **Testar** do editor do agente. ## Rascunho ou versão publicada A faixa **Modo de teste · não é tráfego live** mostra qual a versão em teste (**Rascunho** ou **Publicado**) e tem um interruptor para mudar. Teste o rascunho enquanto constrói; teste a versão publicada para confirmar o que os clientes ouvem. Na chamada web e na chamada telefónica, a versão publicada executa as acções a sério (SMS, marcações e, ao telefone, transferências). O chat e a simulação nunca o fazem. ## Chat **Testar → Chat.** Escreva como se fosse o cliente: cada mensagem percorre o fluxo e a resposta do agente aparece na conversa, com o tipo de passo quando não é uma conversação (por exemplo, `end`). **Novo chat** recomeça do início. É a forma mais rápida de verificar a ordem dos passos e as condições. ## Simulação **Testar → Simulação** mostra as suites de teste do agente (as mesmas do [Centro de Testes](https://docs.diska.ai/pt/test-center)). Num agente em Flow Designer, cada caso percorre o motor de fluxo real com um cliente simulado, e o resultado mostra o **Percurso do fluxo** — os nós visitados e se a conversa chegou ao fim — além dos critérios que passaram. Como criar e executar suites: [Testar um agente](https://docs.diska.ai/pt/guides/test-agent#simula%C3%A7%C3%A3o). ## Chamada web **Testar → Chamada web → Iniciar chamada de teste.** Fale com o agente pelo microfone do computador para validar a voz, o ritmo e as interrupções. Não há linha telefónica: um nó **Transferência** segue sempre o caminho **Falha da acção**. ## Chamada telefónica **Testar → Chamada telefónica → Ligar-me.** O agente liga-lhe do número DISKA, como a um cliente. É a única forma de testar uma **Transferência** real. Requisitos e limites em [Testar um agente](https://docs.diska.ai/pt/guides/test-agent). ## O que observar - A saudação chega rapidamente e soa natural. - O agente recolhe as variáveis certas antes de avançar. - Cada condição leva ao caminho esperado — teste também o **Caso contrário**. - As acções correm e os dois caminhos (**Sucesso da acção** e **Falha da acção**) fazem sentido. - Todos os caminhos acabam num **Terminar chamada**. ## Depois do teste As chamadas web e telefónicas ficam em **Históricos**, com a transcrição, as acções executadas e o resultado da chamada — ver [Chamadas](https://docs.diska.ai/pt/history/calls). As execuções das suites ficam em **Testar → Simulação**, separador **Histórico**, e no [Centro de Testes](https://docs.diska.ai/pt/test-center). # Validação e publicação O Flow Builder valida o fluxo enquanto edita e volta a validá-lo na plataforma antes de publicar. **Erros** bloqueiam a publicação; **avisos** não. ## Lista de verificação O botão **Lista de verificação** na barra do agente mostra quantos problemas existem. Ao abri-la vê cada problema com o tipo de nó, o fluxo onde está e a descrição; clique num problema para saltar para o nó. Os nós com problemas mostram também um indicador no canvas. - Enquanto a plataforma confirma a validação, aparece um indicador de carregamento. Se a confirmação falhar (**Não foi possível confirmar a validação no servidor.**), use o botão de repetir. - O aviso **Número de telefone** (agente sem número) não bloqueia a publicação. - A nota **Canais live** lembra o que corre em produção: WhatsApp e email ainda não; SMS sim; transferência e IVR nas chamadas telefónicas. ## Erros que bloqueiam a publicação | Onde | Mensagem (resumida) | Como resolver | | --------------------- | ---------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | | Estrutura | A estrutura obrigatória Main Flow → Antes da conversa → Mensagem de saudação foi desligada. | Volte a ligar os três nós estruturais. | | Fim | O fluxo precisa de pelo menos um nó End alcançável… | Acabe pelo menos um caminho num **Terminar chamada**. | | Ligações | Ligação não permitida (com o motivo) / A ligação referencia um nó que não existe. | Respeite as [regras de ligação](https://docs.diska.ai/pt/flow-builder/structure). | | Conversação | Conversation precisa de uma instrução clara… | Escreva as **Instruções** do passo. | | Conversação | Variável "…" tem um nome inválido. | Use só letras, números e `_`. | | Mensagem | Message precisa de conteúdo fixo ou instrução… / precisa de um próximo passo ou End. | Escreva a mensagem e ligue o passo seguinte. | | Terminar chamada | End precisa de um motivo de fim… / de uma despedida… | Escolha o **Motivo de fim** e escreva a despedida. | | Condição | Precisa de um caminho "Caso contrário"… / só pode ter um caminho de fallback. | Deixe exactamente um **Caso contrário**. | | Condição | A condição precisa de pelo menos um caminho. | Mantenha pelo menos um caminho (a saída de uma Conversa já traz **Continuar**). | | Condição | O caminho "…" precisa de um prompt LLM / de variável e operador. | Complete a condição do caminho. | | Saltar para | Jump precisa de um nó de destino / não pode apontar para si próprio / O destino do Jump já não existe. | Escolha um destino válido. | | Disparar subfluxo | Escolha o subflow… / Um subflow não pode acionar a si próprio. | Escolha outro subfluxo. | | Subfluxo | Cada trigger de entrada activo precisa de tipo e nome. | Complete as **Condições de entrada**. | | Acção personalizada | Nenhuma acção anexada / modo webhook sem URL / mapeamento de input com JSON inválido / timeout fora de 1–120 segundos. | Anexe a acção e corrija a configuração. | | SMS durante a chamada | Nenhuma acção de SMS anexada. | Anexe um **SMS durante a chamada**. | | Transferência | Transfer precisa de um destino / número / URI / lista telefónica / acção. | Complete o destino. | | Transferência | Transferir para uma fila ou equipa não existe nas linhas telefónicas. | Escolha Telefone, SIP URI, Lista telefónica ou Acção de transferência. | | Transferência | A transferência de chamadas não está disponível neste servidor (sem linha telefónica ligada). | Só aparece se a plataforma não tiver linhas telefónicas: remova o nó para publicar. | | Agendamento | Booking precisa de um título… / Seleccione uma acção de Agendamento em tempo real. | Escolha a acção de agendamento. | | Agendamento | Marcação (calendário) ainda não está ligada a um fornecedor. | Ligue o Cal.com em **Definições → Integrações** ou remova o nó. | | Qualquer nó | O nó usa um canal ainda não implementado. | Remova o nó. | Quando a plataforma não tem o calendário ou as linhas telefónicas disponíveis, o editor mostra também o aviso **Capacidades live ainda não disponíveis** por cima do canvas. ## Avisos Não bloqueiam, mas merecem revisão: - um nó desligado do fluxo, que nunca será executado; - um ciclo de onde nenhum caminho chega a **Terminar chamada**; - uma Conversação sem informação esperada ou sem variáveis a recolher; - um caminho ou um **Caso contrário** sem destino ligado; - um caminho que repete a condição de outro; - uma variável usada num texto ou numa regra que nunca é recolhida nem definida; - variáveis em falta no texto de um SMS; - um Agendamento sem variável de contacto ou de horário; - um subfluxo sem condições de entrada activas. ## Publicar 1. Clique em **Publicar**. A Lista de verificação abre e a plataforma valida todos os fluxos. 2. Se houver erros, corrija-os — a publicação não avança. 3. Sem erros, abre a janela **Publicar**: dê um nome à versão (opcional) e clique em **Publicar**. 4. A confirmação **Agente e fluxos publicados com sucesso!** indica que a nova versão está em produção. São publicados o Fluxo principal e todos os subfluxos que ele alcança, juntamente com as definições do agente. As chamadas que começarem a partir daí usam a nova versão. Se a plataforma ainda assim recusar o fluxo, aparece a mensagem **Fluxo inválido** com o primeiro problema. Publicar exige o papel Proprietário, Administrador ou Membro. Ver também [Publicar e receber chamadas](https://docs.diska.ai/pt/guides/publish-agent) e [O fluxo não publica](https://docs.diska.ai/pt/troubleshooting/flow-not-publishing). # Flow Builder O **Flow Builder** é o editor visual dos agentes criados em modo **Flow Designer**. Cada fluxo é um grafo de nós ligados entre si: a conversa começa no **Fluxo principal** e avança de nó em nó — passos de conversa, mensagens, condições, acções, transferências e fim da chamada. Para um primeiro contacto, siga o guia [Usar o Flow Builder](https://docs.diska.ai/pt/guides/use-flow-builder). Esta secção é a referência completa; os nós estão descritos um a um em [Nós](https://docs.diska.ai/pt/nodes). ::card-group :::card --- description: Separadores, canvas, catálogo de nós, painel de configuração e atalhos. icon: i-lucide-layout title: Interface do builder to: https://docs.diska.ai/pt/flow-builder/interface --- ::: :::card --- description: Nós obrigatórios, subfluxos e que nós podem seguir-se a cada um. icon: i-lucide-git-branch title: Estrutura de um fluxo to: https://docs.diska.ai/pt/flow-builder/structure --- ::: :::card --- description: Variáveis de sistema, pré-chamada, recolhidas e resultados de acções. icon: i-lucide-braces title: Variáveis do fluxo to: https://docs.diska.ai/pt/flow-builder/variables --- ::: :::card --- description: Divida a conversa com prompt LLM ou regras determinísticas. icon: i-lucide-git-fork title: Condições e caminhos to: https://docs.diska.ai/pt/flow-builder/branches --- ::: :::card --- description: Chat, simulação, chamada web e chamada telefónica. icon: i-lucide-play title: Testar um fluxo to: https://docs.diska.ai/pt/flow-builder/testing --- ::: :::card --- description: Lista de verificação, erros, avisos e como publicar. icon: i-lucide-check-circle title: Validação e publicação to: https://docs.diska.ai/pt/flow-builder/validation-publishing --- ::: :: # Conversação O nó **Conversação** é o passo principal de um fluxo: o agente ouve o cliente, responde seguindo as suas instruções e, se quiser, recolhe variáveis. Pode também ter acções anexadas, que o agente usa quando precisar durante esse passo. ## Campos | Campo | Descrição | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome do passo** | Nome mostrado no canvas (ex.: "Pedir o nome"). Num fluxo grande, evita que todos os cartões digam "Conversação". | | **Instruções** | Como o agente se deve comportar neste passo (ex.: "Primeiro peça a idade, depois o género."). O botão de maximizar aumenta a caixa de texto. | | **{ Variáveis** | Insere uma variável nas instruções. Os separadores filtram por origem: **Todas**, **Sistema**, **Recolhidas**, **Acções** e **Pré-chamada**. | ## Recolher variáveis Abra **Recolher variáveis** ("Capturar dados do utilizador para usar mais tarde") e clique em **Adicionar**: | Campo | Descrição | | -------------------------------------------------- | ------------------------------------------------------------------------------------------ | | **Nome** | Nome da variável: letras, números e `_`, sem começar por número (ex.: `nome_cliente`). | | **Tipo** | **String**, **Number**, **Integer**, **Boolean**, **List**, **Email** ou **Phone number**. | | **Pergunta / instruções para recolher a variável** | A pergunta que o agente faz (ex.: "Tem mais de 18 anos?"). | | **Mínimo (opcional)** / **Máximo (opcional)** | Só para **Number** e **Integer**. O mínimo não pode ser maior do que o máximo. | | **Obrigatório** | Se activo, o agente tem de obter esta variável antes de avançar. | Clique em **Adicionar variável** (ou **Guardar variável**, ao editar). As variáveis recolhidas ficam disponíveis nos passos seguintes, nas condições e nas acções. Ver [Variáveis](https://docs.diska.ai/pt/flow-builder/variables). ## Acções Em **Acções**, clique em **Adicionar** e escolha: | Opção | O que anexa | | ---------------------------- | --------------------------------------------------------------------------------------------------------------- | | **Marcação em tempo real** | Uma acção de [Agendamento em tempo real](https://docs.diska.ai/pt/actions/real-time-booking). Só uma por passo. | | **Transferência de chamada** | Uma [transferência de chamada](https://docs.diska.ai/pt/actions/call-transfers). | | **Acção personalizada** | Uma [acção personalizada](https://docs.diska.ai/pt/actions/custom-actions) (API). | | **SMS durante a chamada** | Um [SMS durante a chamada](https://docs.diska.ai/pt/actions/during-call-sms). | As acções anexadas podem correr a qualquer momento neste passo: o agente decide quando as usar, como num agente em Prompt Builder. Para correr uma acção num ponto fixo do fluxo, use antes um nó de acção ([Acção personalizada](https://docs.diska.ai/pt/nodes/custom-action), [Enviar SMS durante a chamada](https://docs.diska.ai/pt/nodes/send-sms-during-call), [Transferência](https://docs.diska.ai/pt/nodes/transfer) ou [Agendamento](https://docs.diska.ai/pt/nodes/booking)). ## Saída do passo Cada Conversação tem a seguir um nó de condição (no canvas, **Condição**) que começa com um único caminho, **Continuar**. Para encaminhar a conversa conforme a resposta do cliente, acrescente caminhos a essa condição. Ver [Dividir o caminho](https://docs.diska.ai/pt/nodes/split-path). A partir de uma Conversação pode seguir para Dividir o caminho, Mensagem, Saltar para, Disparar subfluxo, Acção personalizada, Enviar SMS durante a chamada, Transferência, Agendamento ou Terminar chamada. Duas Conversações nunca se ligam directamente: o caminho entre elas passa sempre por uma condição. ## Exemplo ```text Nome do passo: Motivo da chamada Instruções: Pergunte ao cliente qual é o motivo da chamada. Seja breve e cordial. Recolher variáveis: - motivo (String, obrigatório) → "Qual é o motivo da sua chamada?" - urgente (Boolean, opcional) → "É urgente?" ``` ## Validação - Erro se as **Instruções** estiverem vazias — a publicação fica bloqueada. - Aviso no painel se o nome de uma variável não for válido ("Nome de variável inválido"). # Mensagem O nó **Mensagem** faz o agente dizer um texto exacto — um aviso, uma informação, uma confirmação. Não recolhe variáveis. ## Campos | Campo | Descrição | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | **Nome** | Nome mostrado no canvas. | | **Mensagem exacta** | O texto que o agente diz, palavra por palavra. **{ Variáveis** insere uma variável no texto (ex.: o nome recolhido antes). | | **Esperar resposta do utilizador** | Activo: o agente diz a mensagem e espera que o cliente fale. Desactivo: diz a mensagem e continua de imediato para o próximo nó. | ## Ligações Uma Mensagem pode seguir para Conversação, Mensagem, Dividir o caminho, Saltar para, Disparar subfluxo, Acção personalizada, Enviar SMS durante a chamada, Transferência, Agendamento ou Terminar chamada. ## Validação - Erro se a **Mensagem exacta** estiver vazia. - Erro se o nó não tiver um passo a seguir (pelo menos Terminar chamada). # Dividir o caminho O nó **Dividir o caminho** encaminha a conversa conforme o que aconteceu até ali. Cada caminho tem uma condição e um destino; o caminho **Caso contrário** apanha tudo o que não corresponder. No canvas, o nó aparece com o nome **Condição**. Cada nó [Conversação](https://docs.diska.ai/pt/nodes/conversation) já tem uma condição a seguir, com o caminho **Continuar**: é aí que normalmente acrescenta caminhos. Para um guia completo de condições, veja [Branches e condições](https://docs.diska.ai/pt/flow-builder/branches). ## Campos | Campo | Descrição | | -------------------- | ----------------------------------------------------- | | **Nome do nó** | Nome mostrado no canvas (por omissão, "Condição"). | | Nome do caminho | Um nome curto para cada caminho (ex.: "Quer marcar"). | | **Tipo de condição** | **Prompt LLM** ou **Regra determinística**. | | **Ir para…** | O passo para onde o caminho leva. | As condições são avaliadas por ordem; se nenhuma corresponder, segue o **Caso contrário**. ### Prompt LLM Em **Seguir este caminho se**, descreva em linguagem natural quando seguir o caminho (ex.: "O cliente quer marcar uma reunião."). **{ Variáveis** insere uma variável na descrição. A IA decide com base na conversa. ### Regra determinística Em **Seguir este caminho se**, escolha **Qualquer regra corresponder** ou **Todas as regras corresponderem**, e acrescente regras com **Adicionar**. Cada regra tem: - **Variável** — uma variável do fluxo; - **Operador** — **É igual a**, **É diferente de**, **Contém**, **Maior que**, **Menor que**, **Está vazio**, **Não está vazio**, **É verdadeiro** ou **É falso**; - **Valor de comparação** — quando o operador precisa de um valor. ### Caminhos - **Adicionar caminho** acrescenta um caminho com condição. - **Adicionar caso contrário** acrescenta o caminho **Caso contrário**; quando já existe, o botão mostra **Alternativa activa** e volta a removê-lo. ## Validação - Erro se o nó não tiver nenhum caminho. - Erro se faltar o caminho **Caso contrário** — sem ele, uma resposta que não corresponda a nenhuma regra deixaria a chamada sem próximo passo. - Erro se houver mais do que um **Caso contrário**. - Erro se um caminho **Prompt LLM** não tiver descrição. - Erro se uma regra determinística não tiver variável ou operador. # Saltar para O nó **Saltar para** move a conversa para outro passo do mesmo fluxo. Serve para voltar atrás (por exemplo, repetir uma pergunta) ou para reutilizar um passo sem cruzar ligações no canvas. ## Campos | Campo | Descrição | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome do nó** | Nome mostrado no canvas. | | **Select** | A lista de passos de destino. Os filtros **Todas**, **Conversação**, **Mensagem** e **Disparar subfluxo** reduzem a lista. O destino escolhido aparece em destaque ao lado do título. | Se a lista estiver vazia, acrescente primeiro mais passos ao fluxo. ## Destinos possíveis Conversação, Mensagem, Dividir o caminho, Disparar subfluxo, Acção personalizada, Enviar SMS durante a chamada, Transferência, Agendamento ou Terminar chamada — sempre no mesmo fluxo. ## Ciclos Saltar para um passo anterior cria um ciclo, e isso é permitido ("mais alguma coisa? → responder → perguntar outra vez"). A validação só avisa quando nenhum passo do ciclo consegue terminar a chamada: garanta que existe uma saída, por exemplo um caminho de [Dividir o caminho](https://docs.diska.ai/pt/nodes/split-path) que leve a [Terminar chamada](https://docs.diska.ai/pt/nodes/end-call). ## Validação - Erro se não houver destino. - Erro se o destino for o próprio nó. - Erro se o destino já não existir no fluxo. - Aviso se o salto criar um ciclo sem saída. # Disparar subfluxo O nó **Disparar subfluxo** passa a conversa para um subfluxo do mesmo agente. Quando o subfluxo chega ao seu **Terminar chamada**, a conversa volta e continua pelo passo ligado a seguir a este nó. Os subfluxos criam-se como separadores no Flow Designer. Ver [Estrutura do fluxo](https://docs.diska.ai/pt/flow-builder/structure). ## Campos | Campo | Descrição | | --------------------------------- | ---------------------------------------------------------------------------------------------------------- | | **Escolha que subfluxo disparar** | A lista de subfluxos do agente, com o número de nós e de acções de cada um. Clique no subfluxo pretendido. | Depois de escolher, o painel confirma: "Volta a este nó depois de «nome do subfluxo» terminar." Se ainda não houver subfluxos, crie primeiro um separador de subfluxo. ::callout{type="info"} Ligue sempre um passo a seguir ao nó Disparar subfluxo: é por aí que a conversa continua quando o subfluxo termina. As variáveis recolhidas no subfluxo continuam disponíveis no fluxo principal. :: ## Condições de entrada do subfluxo No próprio subfluxo, o nó inicial define quando ele pode ser activado. Clique em **Adicionar condição de entrada** e preencha: - a caixa de activação (a condição só conta quando está marcada); - **Nome da condição**; - o tipo — **Manual**, **Intenção do cliente**, **Condição**, **Acção com sucesso** ou **Acção falhou**; - a descrição — "Quando este subfluxo deve ser usado?"; - no tipo **Condição**, a expressão (ex.: `intent == suporte ou lead_score > 70`). ## Usos típicos - Reutilizar uma validação de identidade em vários pontos do fluxo. - Isolar a recolha de uma morada ou a confirmação de dados. - Centralizar a lógica de agendamento ou de transferência num único sítio. ## Validação - Erro se não houver subfluxo escolhido. - Erro se o subfluxo escolhido for o próprio fluxo. - No subfluxo: aviso se não houver condições de entrada activas; erro se uma condição activa não tiver tipo ou nome. # Acção personalizada O nó **Acção personalizada** chama uma API externa nesse ponto do fluxo — por exemplo, para consultar uma encomenda depois de recolher o número — e guarda a resposta numa variável. O nó usa uma acção criada em **Acções → Acções personalizadas**; os campos da acção (URL, método, autenticação, mensagens) estão descritos em [Acções personalizadas](https://docs.diska.ai/pt/actions/custom-actions). ## Anexar a acção Um nó novo diz "Nenhuma acção anexada a este nó." Clique em **Anexar acção**, procure a acção e escolha-a. O cartão do nó passa a mostrar o nome, o URL e o método; o ícone do lixo remove a acção. ## Definições da acção | Campo | Descrição | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Mapeamento de input** | Objecto JSON que diz que variável do fluxo preenche cada entrada da acção: `{"entrada": "variavel_do_fluxo"}`. Ao anexar, as entradas `` da acção aparecem já listadas, com o valor vazio. | | **Guardar resultado em** | Nome da variável onde a resposta fica guardada (ex.: `crm_result`), para usar nos passos seguintes. | | **Timeout** | Segundos de espera pela resposta, de 1 a 120. | Exemplo, com uma acção que tem a entrada `` e um fluxo que recolheu a variável `encomenda`: ```json { "numero_encomenda": "encomenda" } ``` ## Como o nó chama a API O nó envia o pedido para o URL da acção, com o método e os cabeçalhos que a acção tinha quando a anexou. O corpo do pedido é um objecto JSON com os valores do **Mapeamento de input** e a identificação da acção (`action_id` e `label`). ::callout{type="warning"} O nó guarda uma cópia da acção (URL, método, cabeçalhos) no momento em que a anexa. Se depois alterar a acção em **Acções** , volte a anexá-la ao nó e publique o fluxo. :: Para que o agente use a acção completa — com o corpo do pedido, a autenticação e as mensagens configuradas — e decida ele próprio quando a chamar, anexe-a em **Acções** de um nó [Conversação](https://docs.diska.ai/pt/nodes/conversation). ## Saídas | Saída | Quando | | -------------------- | ---------------------------------------------------------------------------------------- | | **Sucesso da acção** | A API respondeu com sucesso. | | **Falha da acção** | A API respondeu com erro ou o pedido foi recusado (por exemplo, um URL de rede privada). | No painel **Testar**, com o rascunho, o pedido é simulado e o fluxo segue por **Sucesso da acção**; com a versão publicada, a API é chamada. ## Validação - Erro se não houver acção anexada ("Este nó não tem nenhuma acção anexada"). - Erro se faltar o URL. - Erro se o timeout estiver fora de 1–120 segundos. # Enviar SMS durante a chamada O nó **Enviar SMS durante a chamada** envia um SMS nesse ponto do fluxo — por exemplo, um link de pagamento logo depois de o cliente o pedir. O envio é feito pela Ombala. O nó usa uma acção criada em **Acções → SMS durante a chamada**; os campos da acção (corpo, espera por resposta, fallback) estão descritos em [SMS durante a chamada](https://docs.diska.ai/pt/actions/during-call-sms). ## Anexar a acção Um nó novo diz que não há acções de SMS anexadas. Clique em **Anexar SMS durante a chamada** e escolha a acção. O cartão do nó passa a mostrar o nome e o texto do SMS; o ícone do lixo remove a acção. ## Definições do SMS durante a chamada | Campo | Descrição | | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Pré-visualização do template** | O texto do SMS, copiado da acção. Pode ajustá-lo aqui: a alteração vale só para este nó. | | **Mapeamento de variáveis de entrada** | Objecto JSON que diz que variável do fluxo preenche cada `` do texto: `{"codigo": "codigo_gerado"}`. Ao anexar, os `` aparecem já listados, com o valor vazio. | | **Mensagem antes da acção** | Texto copiado da acção; só aparece quando a acção o tem. | Um aviso **Variáveis em falta** lista as entradas do mapeamento ainda sem variável. Um `` também é preenchido, sem mapeamento, por uma variável do fluxo com o mesmo nome. ### Destinatário Por omissão, o SMS vai para o número do cliente na chamada. Para enviar para outro número, acrescente ao mapeamento a chave `to` com o nome da variável que tem esse número: ```json { "codigo": "codigo_gerado", "to": "telemovel_alternativo" } ``` ::callout{type="warning"} O nó guarda uma cópia da acção (texto, espera por resposta, tempo limite, fallback) no momento em que a anexa. Se depois alterar a acção em **Acções** , volte a anexá-la ao nó e publique o fluxo. :: ## Saídas | Saída | Quando | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | **Sucesso da acção** | O SMS foi enviado. Com **Aguardar resposta** activo, também quando o tempo limite acaba sem resposta. | | **Falha da acção** | Não há número de destino (por exemplo, numa chamada web sem contacto), o envio por SMS não está configurado ou o fornecedor recusou o envio. | No painel **Testar**, com o rascunho, o SMS é simulado; com a versão publicada, é enviado. ## Validação - Erro se não houver acção de SMS anexada. - Aviso **Variáveis em falta** se alguma entrada do mapeamento não tiver variável. # Transferência O nó **Transferência** (categoria **Transferência humana**) passa a chamada telefónica para uma pessoa nesse ponto do fluxo — por exemplo, depois de recolher os dados do cliente. - **Numa chamada telefónica**, a linha passa para o destino quando este atende e o agente sai da chamada. Se o destino não atender, o fluxo segue por **Falha da acção** e o agente continua com o cliente. - **Numa chamada web**, não há linha telefónica: o fluxo segue sempre por **Falha da acção**. Os destinos permitidos dependem do número da chamada (número DISKA ou trunk SIP próprio) — ver [Transferências de chamada](https://docs.diska.ai/pt/actions/call-transfers). ## Campos | Campo | Descrição | | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | **Nome do nó** | Nome mostrado no canvas (ex.: "Transferir para vendas"). | | **Destino** | **Telefone**, **SIP URI**, **Lista telefónica** ou **Acção de transferência**. | | **Número de telefone** | Com **Telefone**: o número, em formato internacional (ex.: `+244 923 000 000`). | | **SIP URI** | Com **SIP URI**: o endereço (ex.: `sip:agente@exemplo.com`). | | **Lista telefónica** | Com **Lista telefónica**: a lista; o nó liga para o primeiro número da lista. | | **Acção de transferência** | Com **Acção de transferência**: uma acção criada em **Acções → Transferências de chamada**. | | **Transferência assistida** | Activo por omissão. Quem atende ouve primeiro, na voz do agente, um resumo do que o fluxo recolheu; só depois o cliente é ligado. | | **Resumo para handoff** | Com a transferência assistida: como escrever o resumo que quem atende ouve (ex.: "Resuma o pedido, dados recolhidos e próxima ação."). | ### Destino «Acção de transferência» Com uma acção, valem as definições da própria acção: o modo de transferência (directa ou assistida), o horário de disponibilidade, a lista telefónica e as mensagens. As opções **Transferência assistida** e **Resumo para handoff** do nó não se aplicam. Os campos da acção estão descritos em [Transferências de chamada](https://docs.diska.ai/pt/actions/call-transfers). ### Fila ou equipa As linhas telefónicas não têm filas. Um nó antigo com o destino **Fila ou equipa (indisponível)** mostra o aviso "As linhas telefónicas não têm filas: escolha um telefone, SIP URI, lista ou acção para publicar." e impede a publicação até escolher outro destino. Nos testes com o rascunho continua a poder correr. ## Saídas | Saída | Quando | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Sucesso da acção** | A chamada foi transferida. | | **Falha da acção** | O destino não atendeu, estava ocupado ou recusou; a chamada é web; fora do horário da acção; ou o destino não é permitido nessa linha. O agente continua com o cliente. | Ligue sempre **Falha da acção** a um passo que trate o caso — por exemplo, uma [Mensagem](https://docs.diska.ai/pt/nodes/message) que propõe uma chamada de volta. ## Testar No painel **Testar**, com o rascunho, a transferência é simulada e o fluxo segue por **Sucesso da acção**. Para uma transferência real, use **Testar → Chamada telefónica** com a versão publicada. Ver [Testar um agente](https://docs.diska.ai/pt/guides/test-agent). ## Validação - Erro se faltar o número, o SIP URI, a lista telefónica ou a acção, conforme o destino. - Erro se o destino for **Fila ou equipa**. - Erro se a plataforma não tiver linha telefónica disponível; nesse caso, remova o nó para publicar (continua disponível nos testes com o rascunho). # Agendamento O nó **Agendamento** (categoria **Negócio**) cria uma marcação no Cal.com nesse ponto do fluxo, com o email e o horário que o fluxo já recolheu. O nó usa uma acção criada em **Acções → Agendamento em tempo real**, que define a conta Cal.com, o tipo de evento, a duração e o fuso horário — ver [Agendamento em tempo real](https://docs.diska.ai/pt/actions/real-time-booking). Em produção, a marcação usa a ligação Cal.com da organização. ## Campos | Campo | Descrição | | ------------------------ | ------------------------------------------------------------------------------------------------------------------ | | **Nome do nó** | Nome mostrado no canvas (ex.: "Marcar demonstração"). | | **Acção de agendamento** | Escolha a acção na lista (**Seleccionar acção…**) ou use **Anexar**. **Remover** desliga a acção. | | **Título** | O título da marcação no Cal.com. Ao escolher a acção, é preenchido com o título do tipo de evento; pode alterá-lo. | | **Contacto / email** | A variável com o email do cliente (ex.: `lead_email`). Aceita `email@dominio.com` ou `Nome `. | | **Horário** | A variável com a data e a hora pretendidas. | O tipo de evento, a duração e o fuso horário vêm sempre da acção seleccionada. Recolha o email e o horário num nó [Conversação](https://docs.diska.ai/pt/nodes/conversation) antes do Agendamento, com variáveis do tipo **Email** e **String**. ## Saídas | Saída | Quando | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | **Sucesso da acção** | A marcação foi criada no Cal.com. | | **Falha da acção** | Falta o email ou o horário, o email não é válido, o Cal.com não está ligado ou recusou a marcação (por exemplo, horário indisponível). | No painel **Testar**, com o rascunho, a marcação é simulada (nada é criado no Cal.com); com a versão publicada, é criada. ::callout{type="info"} Para o agente marcar sozinho, em qualquer momento de um passo, e enviar o SMS de confirmação configurado na acção, anexe a acção em **Acções** de um nó [Conversação](https://docs.diska.ai/pt/nodes/conversation) ( **Marcação em tempo real** ) em vez de usar este nó. :: ## Validação - Erro se não houver acção de agendamento nem título. - Erro se o calendário estiver disponível e não houver acção seleccionada ("Seleccione uma acção de Agendamento em tempo real"). - Erro se a marcação por calendário não estiver disponível na plataforma; nesse caso, remova o nó para publicar (continua disponível nos testes com o rascunho). - Aviso se faltar a variável de contacto ou de horário. # Terminar chamada O nó **Terminar chamada** diz a despedida e termina a chamada. É terminal: não tem passo a seguir, além do nó **Depois da conversa**. O fluxo principal precisa de pelo menos um Terminar chamada alcançável. ## Campos | Campo | Descrição | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Nome do nó** | Nome mostrado no canvas. | | **Instruções** | A despedida. Em **Fixa**, escreva o texto exacto; em **IA**, escreva uma instrução para o agente gerar a despedida (ex.: "Gere uma despedida curta e profissional."). **{ Variáveis** insere uma variável no texto. | | **Motivo de fim** | **Concluído**, **Pedido pelo cliente**, **Não qualificado**, **Transferido** ou **Erro**. | | **Pré-visualização** | Mostra a despedida tal como está configurada. | O painel lembra: "Terminar chamada é terminal. Diga uma despedida curta antes de desligar." ## Acções antes de desligar Em **Acções**, clique em **Adicionar** e escolha **Marcação em tempo real**, **Transferência de chamada**, **Acção personalizada** ou **SMS durante a chamada**. As acções anexadas correm automaticamente antes da despedida e de a chamada terminar — por exemplo, para registar o resultado no seu CRM. Ver [Acções](https://docs.diska.ai/pt/actions). ## Depois da conversa O botão **Depois da conversa** ("Anexe hooks pós-chamada depois de Terminar chamada") leva ao nó onde se anexam as acções que correm depois de a chamada terminar: SMS pós-chamada, Extrator de informação e Avaliação personalizada. Ver [SMS pós-chamada](https://docs.diska.ai/pt/actions/post-call-sms), [Extratores de Informação](https://docs.diska.ai/pt/actions/information-extractors) e [Avaliações Personalizadas](https://docs.diska.ai/pt/actions/custom-evaluations). ## Validação - Erro se faltar a despedida (texto em **Fixa** ou instrução em **IA**). - Erro se faltar o motivo de fim. - Erro se o fluxo principal não tiver nenhum Terminar chamada alcançável — bloqueia a publicação. - Erro se Terminar chamada ligar a outro nó que não seja Depois da conversa. # Nós em breve Estes nós ainda não estão disponíveis e não aparecem no selector de nós: | Nó | Categoria | O que vai fazer | Estado | | ------------------------------------- | ----------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | **Espera** | Controlo de fluxo | Pausar o fluxo por um intervalo definido. | Aguarda suporte de temporização na plataforma. | | **Ciclo** | Controlo de fluxo | Repetir um segmento do fluxo. | O modelo de ciclo ainda está em desenho. | | **Definir variável** | Acções | Atribuir ou actualizar uma variável do fluxo. | Nó dedicado previsto. Entretanto, recolha valores em **Recolher variáveis** de um nó [Conversação](https://docs.diska.ai/pt/nodes/conversation). | | **Enviar WhatsApp durante a chamada** | Canais | Enviar uma mensagem WhatsApp durante uma chamada activa. | Depende do fornecedor de WhatsApp. | | **Enviar email** | Canais | Enviar um email a partir do fluxo. | O canal de email ainda não está ligado. | Para repetir passos já hoje, use [Saltar para](https://docs.diska.ai/pt/nodes/jump-to) para voltar a um passo anterior. ::callout{type="info"} Quando um destes nós ficar disponível, passa a aparecer no selector de nós e esta página é actualizada. :: # Nós Os nós são os passos de um fluxo. Para acrescentar um, clique num **+** do canvas — numa ligação entre dois passos, num caminho de uma condição ou no fim do fluxo. Abre-se o selector de nós, com pesquisa (**Pesquisar nós...**) e os nós agrupados por categoria. Use **↑**/**↓** para navegar, **↵** para escolher e **Esc** para fechar. Um nó que não pode seguir-se ao passo onde clicou aparece com a etiqueta **Inválido**; passe o rato por cima para ver o motivo. Se tiver copiado um nó, a primeira opção é **Colar**. ## Nós do selector | Categoria | Nó | Função | | ------------------------ | ----------------------------------------------------------------------------------- | ------------------------------------------------------------ | | **Conversação** | [Conversação](https://docs.diska.ai/pt/nodes/conversation) | Recolhe informação e guia o diálogo | | | [Mensagem](https://docs.diska.ai/pt/nodes/message) | Fala uma mensagem exacta (opcionalmente espera resposta) | | | [Terminar chamada](https://docs.diska.ai/pt/nodes/end-call) | Despede-se e termina a chamada | | **Controlo de fluxo** | [Disparar subfluxo](https://docs.diska.ai/pt/nodes/trigger-subflow) | Passa a conversa para um subfluxo e volta quando ele termina | | | [Dividir o caminho](https://docs.diska.ai/pt/nodes/split-path) | Divide o caminho com base em condições | | | [Saltar para](https://docs.diska.ai/pt/nodes/jump-to) | Salta para outro nó do fluxo | | **Acções** | [Acção personalizada](https://docs.diska.ai/pt/nodes/custom-action) | Chama uma API externa e guarda a resposta | | | [Enviar SMS durante a chamada](https://docs.diska.ai/pt/nodes/send-sms-during-call) | Envia um SMS durante uma chamada activa | | **Transferência humana** | [Transferência](https://docs.diska.ai/pt/nodes/transfer) | Transfere a chamada telefónica para uma pessoa | | **Negócio** | [Agendamento](https://docs.diska.ai/pt/nodes/booking) | Marca uma reunião ou demonstração | Os nós **Acção personalizada**, **Enviar SMS durante a chamada**, **Transferência** e **Agendamento** usam acções criadas em [Acções](https://docs.diska.ai/pt/actions) e têm duas saídas no canvas: **Sucesso da acção** e **Falha da acção**. Ligue as duas. ## Nós de estrutura Todos os fluxos têm nós fixos que não vêm do selector: **Antes da conversa**, **Mensagem de saudação** e, depois de **Terminar chamada**, **Depois da conversa**. Ver [Estrutura do fluxo](https://docs.diska.ai/pt/flow-builder/structure). ## Ainda não disponíveis Espera, Ciclo, Definir variável, Enviar WhatsApp durante a chamada e Enviar email ainda não estão disponíveis e não aparecem no selector. Ver [Nós em breve](https://docs.diska.ai/pt/nodes/coming-soon). # Transferências de chamada Uma **transferência de chamada** passa a chamada telefónica activa do agente para outro número, para um SIP URI ou para um número escolhido de uma lista telefónica. Abra **Acções → Transferências de chamada**. Para um passo-a-passo completo, veja o guia [Transferir para humano](https://docs.diska.ai/pt/guides/transfer-to-human). ## Onde funciona - **Chamadas telefónicas** — recebidas ou feitas pelo agente, incluindo a chamada telefónica do painel **Testar**. A linha passa para o destino quando este atende. - **Chamadas web** — não há linha telefónica para transferir: o agente é avisado e continua a conversa. Enquanto o destino toca (cerca de 20 segundos), o cliente continua em linha com o agente, sem música de espera. Se ninguém atender, o destino estiver ocupado ou recusar, a transferência falha e o agente continua com o cliente. ### Destinos permitidos | A chamada entrou ou saiu por | Para onde pode transferir | | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Um **número DISKA** | Só para **telemóveis angolanos** (Unitel ou Africell) fixados na acção, no nó do fluxo ou numa lista telefónica. Um número dito pelo cliente durante a conversa nunca é usado. A organização tem de estar autorizada pela Diska a fazer chamadas de saída pelas linhas DISKA. | | Um **número importado** (trunk SIP do seu operador) | Para um número ou um SIP URI no domínio do seu trunk (`sip:número@domínio`); a chamada sai pelo seu trunk. | | Um **número WhatsApp** (chamada de voz) | Só para **telemóveis angolanos** fixados, como num número DISKA; o cliente fica na mesma chamada WhatsApp. Ver [Chamadas de voz](https://docs.diska.ai/pt/whatsapp/calls#transferir-para-uma-pessoa). | Ver [Números](https://docs.diska.ai/pt/telephony/numbers), [Ligar por SIP](https://docs.diska.ai/pt/telephony/sip-trunk) e, para o que acontece na linha, [Transferências por telefone e SIP](https://docs.diska.ai/pt/telephony/transfers). ## A lista de transferências A lista mostra **Nome**, **Condição**, **Destino**, **Tipo** (modo de transferência) e **Runtime** (estado da linha telefónica). Pode filtrar por destino (**Número**, **SIP URI**, **Lista telefónica**) e por tipo (**Direta**, **Assistida (mensagem)**, **Assistida (resumo)**). O botão **Listas telefónicas** abre a gestão das listas (ver a secção **Listas telefónicas** abaixo). ## Criar uma transferência Clique em **Criar novo**. O editor tem quatro separadores. ### Geral | Campo | Descrição | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome** | Identificador da acção em `snake_case` (ex.: `transferir_vendas`). | | **Descrição da condição** | Obrigatório. Quando deve a transferência acontecer (ex.: "o cliente pede para falar com um comercial"). O agente usa este texto para decidir quando transferir. | | **Transferir para** | **Número**, **SIP URI** ou **Lista telefónica**. | | **Número de telefone** | Em formato internacional (ex.: `+244 922 884 032`). **Validar** confirma o formato e normaliza o número. | | **SIP URI** | No formato `sip:utilizador@dominio`. | | **Lista telefónica** | Escolha uma lista; o número é escolhido no momento da transferência (ver abaixo). | ### Definições de transferência **Modo de transferência**: | Modo | O que acontece numa chamada telefónica | | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Transferência direta** | Quem atende é ligado de imediato ao cliente, sem aviso. | | **Transferência assistida com mensagem** | Quem atende ouve primeiro, na voz do agente, o motivo da transferência ("Chamada transferida pela assistente virtual. Motivo: …"). Só depois o cliente é ligado. | | **Transferência assistida com resumo contextual** | Quem atende ouve primeiro, na voz do agente, um resumo curto gerado no momento da transferência a partir do motivo indicado pelo agente. Só depois o cliente é ligado. | Se a mensagem para quem atende não ficar pronta a tempo, a chamada é ligada na mesma: uma transferência nunca se perde por causa do aviso. Mensagens para o **cliente**: - **Mensagem «A tentar contactar o destinatário»** (em **Antes da transferência**) — o que o agente diz ao cliente quando a transferência começa. Por omissão: "Deixe-me transferi-lo para um humano. Por favor aguarde." - **Mensagem «Destinatário falhou ou recusou»** (em **Depois da transferência**) — o que o agente diz quando a transferência não se consegue fazer. Quando o destino não atende, está ocupado ou recusa, o agente informa que o número está indisponível neste momento. ### Disponibilidade humana Active **Activar horário de disponibilidade** para limitar as transferências a um horário. Desactivado, a transferência é possível a qualquer hora. - Marque os dias e indique a hora de início e de fim de cada um (por omissão, segunda a sexta, 09:00–17:00). - **Fuso horário** — o fuso do horário. O valor inicial é `Africa/Luanda`. - **Mensagem "Humano indisponível"** — fora do horário, a transferência não é feita e o agente usa esta mensagem. ### Simulação Opções usadas apenas pelo botão **Simular**: **Música de espera (id)**, **Mensagens de estágio**, **Max retries (simulação)**, **SIP X-headers**, **Screening (simular)** e **Deteção humana (simular)**. Nas chamadas telefónicas reais o cliente fica com o agente enquanto o destino toca (sem música de espera) e os headers SIP não são enviados. Clique em **Guardar**. ## Simular Depois de guardar, o botão **Simular** (no topo do editor) gera os eventos de uma transferência com as opções do separador **Simulação**, sem fazer nenhuma chamada. O resultado aparece numa notificação com o desfecho e o destino. Para testar uma transferência real, use **Testar → Chamada telefónica** com a versão publicada do agente; com o rascunho, a transferência é simulada. Ver [Testar um agente](https://docs.diska.ai/pt/guides/test-agent). ## Ligar ao agente - **Prompt Builder** — em **Acções → Durante a conversa**, clique em **Adicionar → Transferência de chamada** e escolha a acção. O agente transfere quando a **Descrição da condição** se verifica, e indica o motivo da transferência. - **Flow Designer** — num nó [Transferência](https://docs.diska.ai/pt/nodes/transfer) com o destino **Acção de transferência**, ou em **Acções** de um nó Conversação ou Terminar chamada (**Transferência de chamada**). ## Listas telefónicas Uma lista telefónica agrupa vários números, cada um com uma condição, para encaminhar a transferência para a pessoa certa. 1. Em **Transferências de chamada**, clique em **Listas telefónicas** e depois em **Novo**. 2. Dê um **Nome** à lista. 3. Para cada entrada, indique o **Número de telefone** e a **Condição de transferência** (ex.: "Quando o utilizador pede vendas"). Use **Adicionar** para mais entradas (até 50). 4. Clique em **Guardar**. Como o número é escolhido: - Quando o agente decide transferir (Prompt Builder, ou transferência anexada a um passo de Conversação), a plataforma usa a primeira entrada cuja condição tenha palavras presentes no motivo indicado pelo agente; se nenhuma corresponder, usa o primeiro número da lista. - Num nó **Transferência** de um fluxo, é usado o primeiro número da lista. Uma lista que esteja ligada a transferências não pode ser eliminada. Ver o guia [Configurar lista telefónica](https://docs.diska.ai/pt/guides/configure-phone-book). # IVR Quando o agente liga para uma empresa que atende com um menu automático ("prima 1 para vendas, 2 para apoio…"), a acção **IVR** diz-lhe para onde quer chegar e que teclas existem. Durante a chamada, o agente ouve o menu e marca as teclas na linha. Abra **Acções → IVR**. ## Onde funciona - **Chamadas telefónicas de saída** — o agente marca as teclas (DTMF) na linha da chamada. - **Chamadas web** — não há linha telefónica: o agente é avisado de que não pode marcar teclas e continua a conversa. A linha **Telefonia SIP** da caixa **Integrações** (e o estado no topo da página) tem de estar **Ativo**. Ver [Acções](https://docs.diska.ai/pt/actions). ## Criar uma acção IVR Clique em **Criar novo** e preencha: | Campo | Descrição | | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome** | Obrigatório, texto livre até 64 caracteres (ex.: "Chegar a vendas"). | | **Instruções de IVR** | Obrigatório. Para onde o agente deve tentar navegar no menu (ex.: "Navegar até ao departamento de vendas."). O agente recebe este objectivo junto com o menu. | | **Itens do menu** | Opcional. Cada item tem um **dígito** e uma **etiqueta** (ex.: `1` → Vendas). Use o ícone de ramificação para acrescentar um submenu a um item e o ícone do lixo para o remover. | Nos dígitos use `0`–`9`, `*` e `#`. Se não conhece o menu, deixe os itens vazios e descreva o objectivo nas instruções. ::callout{type="tip"} Para usar esta função, o agente deve esperar pelo que ouve na linha antes de falar. Num agente de saída que vai encontrar um IVR, configure a saudação com **Humano fala primeiro** . :: Clique em **Guardar**. A lista mostra **Nome**, **Objectivo** (as instruções) e **Agentes**. ## Simular o plano Depois de guardar, **Simular plano** percorre o menu pelo primeiro item de cada nível e mostra, em **Última simulação**, o caminho de teclas (**Path**), se o menu é válido e os passos (dígito — etiqueta). Nenhuma tecla é marcada em nenhuma chamada. O menu é inválido quando há dígitos repetidos no mesmo nível ou itens sem dígito. ## Ligar ao agente No Prompt Builder, abra **Acções → Antes da conversa**, clique em **Adicionar → Tratamento IVR** e escolha a acção. A partir daí, em cada chamada o agente pode marcar as teclas quando ouvir o menu. Para testar com a chamada real, use **Testar → Chamada telefónica** com a versão publicada; com o rascunho, as teclas são simuladas. Ver [Testar um agente](https://docs.diska.ai/pt/guides/test-agent). ::callout{type="info"} O Tratamento IVR existe só nos agentes em Prompt Builder: nos agentes de fluxo, o nó **Antes da conversa** não o oferece. :: # SMS durante a chamada Um **SMS durante a chamada** é enviado enquanto a conversa decorre, por exemplo com um código de verificação, um link ou os dados de uma confirmação. O envio é feito pela Ombala. Abra **Acções → SMS durante a chamada**. Para um passo-a-passo, veja o guia [Enviar SMS](https://docs.diska.ai/pt/guides/send-sms). ## Antes de começar A linha **SMS (Ombala)** da caixa **Integrações** tem de estar **Ativo**. Com **Por configurar** ("O envio por SMS ainda não está configurado na plataforma."), o envio falha nas chamadas reais. A entrega depende do operador e do destinatário. ## Criar um SMS Clique em **Criar novo** e preencha: | Campo | Descrição | | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | **Nome da acção** | Obrigatório, em `snake_case` (ex.: `enviar_codigo`). | | **Mensagem antes da acção** | O que o agente diz antes de enviar (ex.: "Vou enviar o código agora."). | | **Corpo da mensagem** | Obrigatório. O texto do SMS. Use `` para os valores que mudam em cada chamada (ex.: `O seu código é .`). | | **Variáveis de placeholder** | Lista, só de leitura, dos `` encontrados no corpo. | Em **Definições de resposta**: | Campo | Descrição | | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | **Aguardar resposta** | O agente pausa até o cliente responder por SMS. | | **Tempo limite (segundos)** | Entre 1 e 600. A espera real nunca passa de **45 segundos**, para não suspender a conversa. | | **Mensagem de fallback** | Texto devolvido ao agente quando o tempo limite acaba sem resposta (ex.: "Ainda não recebi a sua resposta. Quer que eu reenvie?"). | ::callout{type="warning"} O fornecedor de SMS só envia mensagens: as respostas por SMS ainda não chegam à Diska. Com **Aguardar resposta** activo, a espera termina sempre no tempo limite (no máximo 45 segundos) e o agente continua com a mensagem de fallback. :: Clique em **Guardar**. A lista mostra **Nome**, **Corpo da mensagem**, **Resposta** (**Aguarda resposta** ou **Sem espera**), **Agentes** e **Runtime** (estado do SMS). ## Simular Depois de guardar, o editor mostra a secção **Simulação**: - **Destinatário** — um número (ex.: `+244…`); - **Resposta simulada** — a resposta que o cliente "daria" (por omissão "Sim, confirmo."); - **Forçar timeout** — simula o fim do tempo limite sem resposta. Clique em **Simular** no topo do editor. O resultado mostra o estado, a resposta simulada ou, com timeout, a mensagem de fallback. Nenhum SMS é enviado. ## Ligar ao agente - **Prompt Builder** — em **Acções → Durante a conversa**, **Adicionar → SMS durante a chamada**. O agente decide quando enviar, diz a mensagem antes da acção e preenche os `` com dados da conversa. Por omissão, o SMS vai para o número do cliente na chamada. - **Flow Designer** — com o nó [Enviar SMS durante a chamada](https://docs.diska.ai/pt/nodes/send-sms-during-call), ou em **Acções** de um nó Conversação ou Terminar chamada (**SMS durante a chamada**). ## Chamada telefónica ou web Numa chamada telefónica, o número do cliente é conhecido e o SMS segue para ele. Numa chamada web, o SMS só é enviado se a chamada tiver um número de destino (por exemplo, o **Contacto do chamador** indicado no teste, ou um número mapeado no fluxo); sem número, o envio falha. No painel **Testar**, com o rascunho, o SMS é simulado; com a versão publicada, é enviado. # SMS pós-chamada Um **SMS pós-chamada** é enviado depois de a chamada terminar, quando a conversa cumpre uma condição sua — por exemplo, "o cliente pediu a tabela de preços". O envio é feito pela Ombala. Abra **Acções → SMS pós-chamada**. ## Antes de começar A linha **SMS (Ombala)** da caixa **Integrações** tem de estar **Ativo**; sem isso, o SMS não é enviado. ## Criar um SMS pós-chamada Clique em **Criar novo** e preencha: | Campo | Descrição | | -------------------------------- | --------------------------------------------------------------------------------------------- | | **Nome** | Obrigatório, em `snake_case` (ex.: `enviar_precos`). | | **Descrição da condição** | Obrigatório. Em que condições deve a mensagem ser enviada (ex.: "o cliente pediu os preços"). | | **Conteúdo do SMS (variante A)** | Obrigatório. O texto do SMS. Use `` para valores dinâmicos. | | **Variante B (A/B opcional)** | Texto alternativo para um teste A/B. | | **Variáveis de placeholder** | Lista, só de leitura, dos `` encontrados no conteúdo. | Clique em **Guardar**. A lista mostra **Nome**, **Condição**, **Conteúdo do SMS**, **Agentes** e **Runtime** (estado do SMS). ## O que acontece depois da chamada 1. A plataforma lê a transcrição e a IA decide se a **Descrição da condição** se verifica. Sem transcrição, o SMS não é enviado. 2. Se houver variante B, é escolhida uma das variantes; o mesmo destinatário recebe sempre a mesma. 3. Os `` são preenchidos com as variáveis da chamada com o mesmo nome, incluindo os valores dos [extratores de informação](https://docs.diska.ai/pt/actions/information-extractors) (pelo nome do extrator ou pela sua variável tipada). Um `` sem valor fica vazio. 4. O SMS vai para o número do cliente. Se a chamada não o tiver (por exemplo, uma chamada web), é usado um número recolhido na conversa ou um extrator chamado `phone`; sem número, o SMS não é enviado. O resultado de cada SMS (enviado, ignorado ou falhado, e a variante usada) aparece em **Históricos**, no detalhe da chamada, separador **Análise → SMS pós-chamada**. Ver [Chamadas](https://docs.diska.ai/pt/history/calls). ## Simular (dry-run) Depois de guardar, o editor mostra a secção **Dry-run**: - **Destinatário (E.164)** — o número de teste; - **Transcrição (para condição)** — um excerto de conversa. Clique em **Simular**. A notificação diz **Dry-run: enviaria** ou **Dry-run: não envia** (com o motivo). Nenhum SMS é enviado. ::callout{type="info"} O dry-run faz uma verificação simplificada: procura na transcrição as palavras da condição. Na chamada real, a condição é avaliada pela IA sobre a transcrição completa. :: ## Ligar ao agente - **Prompt Builder** — em **Acções → Depois da conversa**, **Adicionar → SMS pós-chamada**. - **Flow Designer** — no nó **Depois da conversa** (a seguir a Terminar chamada), **Adicionar → SMS pós-chamada**. Nas chamadas reais conta a configuração publicada do agente. Num teste com o rascunho, a condição é avaliada mas o SMS não é enviado. # Acções personalizadas Uma **acção personalizada** faz um pedido HTTP a uma API externa — o seu CRM, sistema de reservas ou ERP — e devolve a resposta ao agente. Abra **Acções → Acções personalizadas**. A lista mostra **Nome**, **Método**, **URL do endpoint**, **Autenticação**, **Agentes** e **Estado** (**Não inicializado**, **Inicializado** ou **Falhou**), com filtros por método, autenticação e estado. ## Criar uma acção Clique em **Criar novo**. O editor tem duas colunas: à direita configura a acção, à esquerda (**Resultados**) testa-a. **Ocultar resposta** / **Ver resposta** esconde ou mostra a coluna de resultados. ### Separador «Configurar» | Campo | Descrição | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Nome da acção** | Obrigatório, em `snake_case` (ex.: `consultar_encomenda`). | | **Descrição** | Diga à IA como e quando usar esta ferramenta (ex.: "Usa quando o cliente perguntar pelo estado de uma encomenda."). Num agente em Prompt Builder, é com este texto que o agente decide chamar a API. | | **Método do endpoint e URL** | `GET`, `POST`, `PUT`, `PATCH` ou `DELETE`, e o URL completo. Use `` para partes variáveis (ex.: `https://api.exemplo.ao/encomendas/`). | | **Autenticação** | **Sem autenticação** ou **Personalizada**. Na personalizada indique um **Bearer token** (enviado como `Authorization: Bearer …`) ou um **Cabeçalho** e o seu **Valor**. Os valores ficam guardados cifrados. | | **Tempo limite** | De 1 a 30 segundos (**Máx. 30 segundos**). Com **Sem tempo limite**, a plataforma espera até 10 segundos. | | **Cabeçalhos** | Pares chave/valor; a chave não pode ficar vazia. | | **Corpo do pedido** | JSON enviado em `POST`, `PUT` e `PATCH` (inactivo em `GET` e `DELETE`). Tem de ser JSON válido e não pode ficar vazio. Use `` para valores dinâmicos. | | **Variáveis de entrada** | Detectadas automaticamente a partir do URL, cabeçalhos e corpo. | O URL não pode apontar para endereços locais ou de redes privadas: a Diska recusa-o por segurança. ### Separador «Instruções de IA» O que o agente deve dizer nas diferentes fases da acção: | Campo | Descrição | | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | **Mensagem inicial** | O que dizer ao começar a executar a acção. | | **Mensagem de atraso** | O que dizer se a acção demorar mais do que o esperado. | | **Limiar de atraso** | Quanto tempo esperar (0–30 s) antes da mensagem de atraso. | | **Max retries (HTTP)** | De 0 a 5. É mostrado na simulação; nas chamadas, a acção faz um único pedido. | | **Mensagem de falha** | O que dizer se a acção falhar. | | **Deixar o agente falar naturalmente** | O agente diz algo adequado ao contexto e, se não conseguir, usa as suas mensagens. Desactive para usar apenas as suas mensagens. | Clique em **Guardar**. ## Testar: Inicializar e Simular Na coluna **Resultados**, em **Configurar entradas**, indique um **Valor de teste** para cada **Variável dinâmica**. Depois: - **Inicializar** — guarda a acção e faz o pedido real à API com os valores de teste. O **Estado** passa a **Inicializado** (resposta 2xx) ou **Falhou**, e a resposta aparece em **Corpo da resposta**. - **Simular (sem HTTP live)** — disponível depois de guardar. Mostra o pedido que seria enviado e a sequência de mensagens do agente, sem chamar a API. ## Ligar ao agente ### Prompt Builder Em **Acções**, a acção personalizada pode entrar nos três grupos: | Grupo | O que acontece | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Antes da conversa** | A API é chamada antes de a conversa começar; a resposta fica disponível como variáveis da chamada. A conversa só começa depois de o pedido terminar, por isso use APIs rápidas. | | **Durante a conversa** | O agente chama a API quando a **Descrição** o indicar e preenche os `` com dados da conversa. Os campos da resposta ficam disponíveis como resultados de acções. | | **Depois da conversa** | A API é chamada depois de a chamada terminar. | Cada acção anexada tem um **Mapeamento de variáveis** opcional (fonte → destino) para preencher as entradas a partir de variáveis da chamada. ### Flow Designer - Com o nó [Acção personalizada](https://docs.diska.ai/pt/nodes/custom-action), num ponto fixo do fluxo. - Em **Acções** de um nó Conversação (o agente usa-a quando precisar, durante esse passo) ou de um nó Terminar chamada (corre antes da despedida). - No nó **Antes da conversa**. No painel **Testar**, com o rascunho, os pedidos são simulados; com a versão publicada, a API é chamada. # Extratores de Informação Um **extrator de informação** lê a transcrição depois da chamada e responde a uma pergunta sobre ela — por exemplo, "O cliente está interessado no serviço?" ou "Qual é o email do cliente?". O valor fica na chamada e segue no webhook pós-chamada. Abra **Acções → Extratores de Informação**. A lista mostra **Nome**, **Dados a extrair**, **Tipo** e **Agentes**, com filtro por tipo. ## Criar um extrator Clique em **Criar novo** e escolha: - **Novo extrator** — começa em branco; - **Explorar templates** — abre **Templates de Extratores**, com modelos prontos (`user_name`, `user_email`, `user_company`, `user_address`, `dnd`, `call_outcome`, `reason_for_call`, `issue_description`, `user_interest_level`, `callback_requested`, `budget_range`, `lead_qualification`). Escolha um e clique em **Usar este modelo**; pode editar tudo depois. Preencha: | Campo | Descrição | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | **Nome** | Obrigatório, em `snake_case`. É a chave do valor no webhook pós-chamada (ex.: `user_email`). | | **Variável tipada (binding)** | Opcional. Nome de uma variável onde o valor também é gravado (ex.: `customer_name`). | | **Tipo** | **Sim / Não** (verdadeiro ou falso), **Escolha Única** (uma de várias opções) ou **Pergunta Aberta** (texto livre). | | **Dados a extrair** | Obrigatório. A pergunta, em texto simples (ex.: "O utilizador está interessado no serviço?"). Não use JSON nem os caracteres `{}`, `[]` ou `<>`. | | **Opções** | Só em **Escolha Única**: pelo menos duas. O valor é sempre uma destas opções, ou vazio. | | **Exemplos de saída** | Só em **Pergunta Aberta**, opcional: ajudam a IA a seguir o formato (ex.: `João Silva`). | Clique em **Guardar**. ## Re-run: testar sem nova chamada Depois de guardar, cole um excerto de conversa em **Transcrição (re-run sem nova chamada)** e clique em **Re-run**. A notificação mostra o valor extraído. Não é feita nenhuma chamada. ## Ligar ao agente - **Prompt Builder** — em **Acções → Depois da conversa**, **Adicionar → Extrator de informação**. - **Flow Designer** — no nó **Depois da conversa**, **Adicionar → Extrator de informação**. Os extratores correm depois de cada chamada do agente. ## Onde ver os resultados - Em **Históricos**, no detalhe da chamada, separador **Análise → Dados extraídos** (com o **Histórico por extractor**). Quando a informação não aparece na conversa, o valor fica vazio e é mostrado como `n.a.`. Ver [Chamadas](https://docs.diska.ai/pt/history/calls). - No webhook pós-chamada, em `extracted_data`. Ver [Webhooks](https://docs.diska.ai/pt/api/webhooks). - Nos [SMS pós-chamada](https://docs.diska.ai/pt/actions/post-call-sms): um `` com o nome do extrator (ou da sua variável tipada) é preenchido com o valor extraído. Com [Ocultar dados pessoais](https://docs.diska.ai/pt/guides/redact-personal-data) activo, o SMS pós-chamada e as acções personalizadas continuam a receber o valor real; o valor guardado em **Históricos** e enviado no webhook leva a etiqueta (por exemplo `[NOME]`). ::callout{type="tip"} Se as chamadas forem web e quiser enviar SMS pós-chamada, crie um extrator **Pergunta Aberta** chamado `phone` que recolha o telemóvel do cliente: quando a chamada não tem número, o SMS pós-chamada usa esse valor. :: # Avaliações Personalizadas Uma **avaliação personalizada** pontua a conversa depois da chamada com um critério definido por si — por exemplo, "O agente foi profissional e confirmou os dados do cliente?". O resultado indica se a chamada **Passou** ou **Falhou**. Abra **Acções → Avaliações Personalizadas**. A lista mostra **Nome**, **O que avaliar**, **Tipo de saída** (com o limite de aprovação) e **Agentes**, com filtro por tipo de saída. ::callout{type="info"} Estas avaliações correm sobre chamadas reais, depois de terminarem. Para testar um agente com cenários antes de o publicar, use as avaliações do [Centro de Testes](https://docs.diska.ai/pt/test-center/evaluations) . :: ## Criar uma avaliação Clique em **Criar novo** e preencha: | Campo | Descrição | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Nome da acção** | Obrigatório, em `snake_case` (ex.: `marcacao_confirmada`). | | **O que avaliar** | Obrigatório. O critério, em linguagem natural (ex.: "Avaliar o tom e o profissionalismo do agente durante a chamada"). | | **Tipo de saída** | **Numérico** (escala de 1 a 10), **Descritivo** (Excelente, Bom, Razoável, Fraco), **Escala Likert** (de Concordo totalmente a Discordo totalmente) ou **Verdadeiro / Falso**. | | **Limite de aprovação** | O valor de referência para aprovar: um número de 1 a 10 no tipo numérico, ou um dos valores da escala nos outros tipos (ver abaixo). | | **Rubricas (scorecard)** | Opcional. Use **Critério** para acrescentar critérios com nome (ex.: `empatia`), peso e descrição. | Clique em **Guardar**. ### Como se decide «Passou» ou «Falhou» - **Numérico** — passa quando a pontuação é igual ou superior ao limite. - **Verdadeiro / Falso** — passa quando o resultado é igual ao valor escolhido no limite. - **Descritivo** e **Escala Likert** — passa quando o resultado coincide com o valor escolhido no limite. Para aprovar "a partir de" um nível, prefira o tipo **Numérico**. Nas chamadas, as rubricas aparecem como scorecard indicativo, com uma pontuação ponderada; o resultado **Passou**/**Falhou** vem da avaliação comparada com o limite de aprovação. ## Simular Depois de guardar, cole um excerto de conversa em **Transcrição de teste (simular)** e clique em **Simular**. A notificação mostra **Simulação: passou**, **Simulação: falhou** ou **Simulação: sem resultado conclusivo**. Não é feita nenhuma chamada. Se a avaliação tiver rubricas, a simulação dá a mesma pontuação de teste a cada critério e o resultado mostrado vem dessa pontuação. Para ver como a IA avalia a transcrição, simule antes de acrescentar rubricas. ## Ligar ao agente - **Prompt Builder** — em **Acções → Depois da conversa**, **Adicionar → Avaliação personalizada**. - **Flow Designer** — no nó **Depois da conversa**, **Adicionar → Avaliação personalizada**. ## Onde ver os resultados - Em **Históricos**, no detalhe da chamada, separador **Análise → Avaliações / scorecards**: cada avaliação com **Passou**, **Falhou** ou `n.a.`, a justificação e o scorecard. O botão **CSV** exporta as avaliações. Ver [Chamadas](https://docs.diska.ai/pt/history/calls). - No webhook pós-chamada, em `evaluations`. Ver [Webhooks](https://docs.diska.ai/pt/api/webhooks). # Agendamento em tempo real Uma acção de **agendamento em tempo real** permite ao agente criar uma marcação no Cal.com durante a chamada, num tipo de evento da sua conta. Abra **Acções → Agendamento em tempo real** (é a primeira página da área Acções). Para um passo-a-passo, veja o guia [Marcar reuniões](https://docs.diska.ai/pt/guides/book-meetings). ## Antes de começar Ligue a sua conta Cal.com em **Definições → Integrações**. Sem a ligação, não é possível guardar uma acção de agendamento. Ver [Cal.com](https://docs.diska.ai/pt/integrations/calcom). ## Criar uma acção Clique em **Criar novo** e escolha **Cal.com** ("Criar marcações a partir de tipos de evento Cal.com e slots disponíveis."). Preencha: | Campo | Descrição | | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome da acção** | Obrigatório, em `snake_case` (ex.: `marcar_demonstracao`). | | **Conta Cal.com** | Estado da ligação e email da conta. O ícone de definições leva a **Definições → Integrações**. | | **Evento** | Obrigatório. O tipo de evento do Cal.com (título, ID, duração e local). O botão de actualizar volta a carregar os tipos de evento. | | **Fuso horário** | Em **Sugestões de disponibilidade**: **África/Luanda** (por omissão), **Europa/Lisboa** ou **UTC**. É o fuso enviado ao Cal.com com a marcação. | | **SMS de confirmação** | Interruptor e texto do SMS enviado ao cliente depois de a marcação ser criada. | O Cal.com envia o email de confirmação da marcação para o email do convidado (``), que define ao ligar a acção ao agente. Clique em **Guardar**. A lista mostra **Nome**, **Evento**, **Fuso**, **SMS** (**Ativo** ou **Desativado**) e **Cal.com** (**Configurado** ou **Por configurar**). ::callout{type="info"} Em **Sugestões de disponibilidade** , a sugestão automática de horários livres aparece como **em breve** . Por agora, o agente marca a hora pedida pelo cliente e o Cal.com valida a disponibilidade. :: ### SMS de confirmação Com o interruptor activo, depois de criar a marcação o agente envia um SMS para o número do cliente na chamada (requer a linha **SMS (Ombala)** em **Ativo**). No texto pode usar: - `` — nome do convidado; - `` — email do convidado; - `` — data e hora da marcação; - `` — título do evento; - `` — identificador da marcação. O SMS de confirmação é enviado quando a marcação é feita pelo agente em Prompt Builder ou por uma marcação anexada a um passo de Conversação de um fluxo. ## Ligar ao agente ### Prompt Builder Em **Acções → Durante a conversa**, clique em **Adicionar → Agendamento em tempo real** e escolha a acção. Clique no cartão da acção para abrir **Variáveis de entrada** e escolher de onde vem o email do convidado (`{lead_email}`): | Origem | Descrição | | ------------------------- | ---------------------------------------------------------------------------------------- | | **Recolhido pelo agente** | Por omissão. O agente pede o email durante a chamada, seguindo a instrução que escrever. | | **Saída de acção** | O email vem da resposta de uma acção personalizada. | | **Sistema** | Uma variável de sistema. | | **Variáveis pré-chamada** | Uma variável recebida antes de a chamada começar. | | **Valor fixo** | Um email fixo. | O agente pede a data e a hora pretendidas, e cria a marcação quando tem o email e o horário. ### Flow Designer - Com o nó [Agendamento](https://docs.diska.ai/pt/nodes/booking), num ponto fixo do fluxo. - Em **Acções** de um nó Conversação (**Marcação em tempo real**): o agente pode marcar a qualquer momento desse passo. Cada passo aceita uma marcação. ## O que acontece na chamada - A marcação é criada no Cal.com com a conta ligada da organização, no tipo de evento e com a duração da acção. - Se o email não for válido ou faltar a data e hora, a marcação não é feita e o agente é avisado. - Se o horário não estiver disponível, o Cal.com recusa e o agente é avisado. No painel **Testar**, com o rascunho, a marcação é simulada (nada é criado no Cal.com); com a versão publicada, é criada. # Acções As **acções** dão ao agente capacidades para além da conversa: transferir a chamada, marcar teclas num menu IVR, enviar SMS, chamar a API da sua empresa, extrair dados e avaliar a chamada, e marcar reuniões no Cal.com. Cada acção cria-se uma vez, na área **Acções** do menu lateral, e depois liga-se aos agentes que a usam. A mesma acção pode servir vários agentes. ## Tipos de acção | Acção | Quando corre | Para que serve | | ----------------------------------------------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------ | | [Transferências de chamada](https://docs.diska.ai/pt/actions/call-transfers) | Durante a chamada | Passar uma chamada telefónica para uma pessoa (número, SIP URI ou lista telefónica). | | [IVR](https://docs.diska.ai/pt/actions/ivr) | Durante a chamada | Navegar menus de voz (teclas DTMF) em chamadas telefónicas de saída. | | [SMS durante a chamada](https://docs.diska.ai/pt/actions/during-call-sms) | Durante a chamada | Enviar um código, link ou confirmação por SMS enquanto a chamada decorre. | | [SMS pós-chamada](https://docs.diska.ai/pt/actions/post-call-sms) | Depois da chamada | Enviar um SMS de seguimento quando uma condição se verifica. | | [Acções personalizadas](https://docs.diska.ai/pt/actions/custom-actions) | Antes, durante ou depois | Chamar uma API HTTP externa e usar a resposta. | | [Extratores de Informação](https://docs.diska.ai/pt/actions/information-extractors) | Depois da chamada | Extrair um dado da conversa (sim/não, escolha, texto). | | [Avaliações Personalizadas](https://docs.diska.ai/pt/actions/custom-evaluations) | Depois da chamada | Pontuar a conversa com um critério seu. | | [Agendamento em tempo real](https://docs.diska.ai/pt/actions/real-time-booking) | Durante a chamada | Criar uma marcação num tipo de evento do Cal.com. | ## A área Acções Abra **Acções** no menu lateral. A barra à esquerda lista os oito tipos, com o número de acções de cada um; a página abre em **Agendamento em tempo real**. Todas as listas funcionam da mesma forma: - **Pesquisar...** filtra pelo nome; alguns tipos têm filtros extra (destino, tipo, método, estado). - **Criar novo** abre o editor. Clicar numa linha abre a acção para editar. - O menu **⋮** de cada linha tem **Copiar ID**, **Duplicar** e **Eliminar**. - No editor, **Usado em agentes** mostra os agentes que usam a acção. - Se fechar o editor com alterações por guardar, a Diska pergunta se quer **Descartar** ou **Continuar a editar**. O **Nome** da maioria das acções é um identificador em `snake_case` (minúsculas, números e `_`, até 64 caracteres): o editor converte o que escreve, por exemplo "Transferir Vendas" passa a `transferir_vendas`. O IVR aceita um nome livre. Criar, editar e eliminar acções exige o papel **Proprietário**, **Administrador** ou **Membro**. O papel **Visualizador** só consulta. Ver [Membros](https://docs.diska.ai/pt/settings/members). ### Caixa «Integrações» No fundo da barra lateral, a caixa **Integrações** mostra se os serviços de que as acções dependem estão prontos. O estado actualiza-se sozinho a cada 15 segundos. | Linha | O que indica | | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **SMS (Ombala)** | Se o envio de SMS está configurado na plataforma. Usado pelos SMS durante e pós-chamada e pelo SMS de confirmação das marcações. | | **Telefonia SIP** | Se a linha telefónica da plataforma está pronta. Usada pelas transferências e pelo IVR, que só correm em chamadas telefónicas. | | **Webhook pós-chamada** | Se existe um destino para os eventos pós-chamada: um webhook da organização subscrito a `call.completed` ou um **Webhook** em **Depois da conversa** de um agente publicado. Ver [Webhooks](https://docs.diska.ai/pt/api/webhooks). | | Estado | Significado | | ------------------ | ------------------------------------------------------------------- | | **Ativo** | Pronto a usar. | | **Por configurar** | Ainda não configurado. | | **Indisponível** | A linha telefónica está configurada mas não responde neste momento. | | **Não confirmado** | Não foi possível verificar; use **Tentar novamente**. | | **A verificar…** | A consulta está a decorrer. | O editor de transferências, a página IVR e os editores de SMS mostram o mesmo estado no topo. ## Ligar uma acção a um agente Criar a acção não basta: tem de a ligar ao agente e publicar o agente. ### Agente em Prompt Builder No editor do agente, abra o painel **Acções**. As acções estão agrupadas em três momentos; em cada grupo clique em **Adicionar** e escolha a acção. | Grupo | O que pode adicionar | Como corre | | ---------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | **Antes da conversa** | Acção personalizada, Tratamento IVR | A acção personalizada corre antes de a conversa começar. O IVR fica disponível para o agente marcar teclas durante a chamada. | | **Durante a conversa** | Agendamento em tempo real, Transferência de chamada, Acção personalizada, SMS durante a chamada | O agente decide quando usar cada acção, com base na condição ou descrição da acção. | | **Depois da conversa** | SMS pós-chamada, Extrator de informação, Avaliação personalizada, Acção personalizada, Webhook | Corre depois de a chamada terminar. | **WhatsApp durante a chamada** e **Conectores MCP** aparecem com a etiqueta **Em breve** e ainda não podem ser adicionados. Ver [Prompt Builder](https://docs.diska.ai/pt/concepts/prompt-builder). ### Agente em Flow Designer Num fluxo, as acções entram de três formas: - **Como nó** — os nós [Acção personalizada](https://docs.diska.ai/pt/nodes/custom-action), [Enviar SMS durante a chamada](https://docs.diska.ai/pt/nodes/send-sms-during-call), [Transferência](https://docs.diska.ai/pt/nodes/transfer) e [Agendamento](https://docs.diska.ai/pt/nodes/booking) correm a acção nesse ponto do fluxo e têm duas saídas: **Sucesso da acção** e **Falha da acção**. - **Anexadas a um passo** — em **Acções** de um nó [Conversação](https://docs.diska.ai/pt/nodes/conversation) (o agente pode usá-las a qualquer momento desse passo) ou de um nó [Terminar chamada](https://docs.diska.ai/pt/nodes/end-call) (correm antes da despedida). Pode anexar Marcação em tempo real, Transferência de chamada, Acção personalizada e SMS durante a chamada. - **Nos nós de estrutura** — **Antes da conversa** aceita Acção personalizada (o Tratamento IVR só existe nos agentes em Prompt Builder); **Depois da conversa** aceita SMS pós-chamada, Extrator de informação e Avaliação personalizada. Ver [Estrutura do fluxo](https://docs.diska.ai/pt/flow-builder/structure). ## Chamada telefónica ou chamada web | Acção | Chamada telefónica | Chamada web (browser, widget, link público) | | -------------------------------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------------- | | Transferência de chamada | A linha passa para o destino quando este atende. | Não há linha para transferir: o agente é avisado e continua a conversa. | | IVR | O agente marca as teclas na linha. | Não há linha: o agente é avisado e continua a conversa. | | SMS durante a chamada | Enviado para o número do cliente. | Só é enviado se a chamada tiver um número de destino. | | SMS pós-chamada | Enviado para o número do cliente. | Só é enviado se houver um número do cliente (por exemplo, recolhido na conversa). | | Acção personalizada, extratores, avaliações, agendamento | Funcionam da mesma forma. | Funcionam da mesma forma. | Ver [Chamadas telefónicas](https://docs.diska.ai/pt/telephony/phone-calls). ## Testar sem efeitos reais Cada editor tem a sua simulação (**Simular**, **Simular plano**, **Re-run** ou **Inicializar**), descrita na página de cada acção. No painel **Testar** do agente, a versão testada decide o que acontece. O cabeçalho do painel mostra **Rascunho** ou **Publicado**; na chamada telefónica, escolhe-a em **Versão do agente**. - **Rascunho** (**Rascunho — ações simuladas**): SMS, marcações, transferências, IVR e chamadas de API são simulados; nada sai da plataforma. Depois da chamada, os extratores e as avaliações correm na mesma, mas o SMS pós-chamada não é enviado. - **Publicado** (por exemplo **V3 publicada — ações reais**): as acções correm a sério. Ver [Testar um agente](https://docs.diska.ai/pt/guides/test-agent). ::callout{type="warning"} As acções não têm versões. Quando altera uma acção em **Acções** (um número de transferência, o URL de uma API, uma condição), a alteração vale de imediato para todos os agentes que a usam, incluindo os já publicados. A excepção são os nós **Acção personalizada** e **Enviar SMS durante a chamada** , que guardam uma cópia da acção no momento em que a anexa: para aplicar alterações nesses nós, volte a anexar a acção e publique o fluxo. :: # Fontes Cada base de conhecimento recebe conteúdo de quatro formas. Abra a base em **Conhecimento** e use o botão **Adicionar item** (ou, numa base vazia, os atalhos no centro da página). | Opção | Tipo na tabela | Para quê | | ----------------------------- | -------------- | -------------------------------------------------------------- | | **Carregar PDFs** | PDF | Manuais, tabelas de preços, regulamentos já em PDF. | | **Criar documento em branco** | Manual | Escrever ou colar texto directamente (FAQs, respostas-padrão). | | **Importar de URL** | URL | Uma página pública do seu site. | | **Crawl de site** | URL | Várias páginas do mesmo site de uma só vez. | Todas as fontes são indexadas automaticamente ao serem adicionadas ou editadas: o texto é dividido em segmentos e preparado para a pesquisa semântica que o agente faz durante a conversa. ## PDF 1. Escolha **Carregar PDFs**, ou arraste os ficheiros para a zona **Arraste PDFs para aqui** da página da base. Pode enviar vários PDFs de uma vez. 2. Uma barra de progresso acompanha cada envio. 3. No fim, uma mensagem indica o resultado: - **Texto extraído e indexado para retrieval.** — pronto a usar. - **Texto extraído; indexação pendente ou parcial.** — o texto existe, mas a indexação ainda não terminou ou falhou; use **Reindexar**. - **Ficheiro guardado. Extração limitada / indexing pending.** — o PDF não tem texto que a plataforma consiga ler. Limites e regras: - Só são aceites ficheiros PDF válidos, até 25 MB cada. - O texto é lido das primeiras 100 páginas de cada PDF. - O PDF tem de ter **texto seleccionável**. Um PDF digitalizado (imagens de páginas) fica guardado, mas sem texto, e o agente não o consegue usar. Exporte uma versão com texto ou copie o conteúdo para um documento em branco. O ficheiro original fica guardado: use **Descarregar** no menu da linha para o obter. ## Documento escrito 1. Escolha **Criar documento em branco**. 2. Preencha **Nome** e **Conteúdo** (até 200 000 caracteres). 3. Clique em **Guardar**. Estes são os únicos documentos que pode alterar na plataforma: use **Editar** no menu da linha. A edição volta a indexar o documento. ::callout{type="tip"} Dê nomes descritivos aos documentos (por exemplo «Preços — planos empresariais»). O nome aparece como origem de cada excerto que o agente usa, o que facilita perceber de onde veio uma resposta. :: ## Página web (URL) 1. Escolha **Importar de URL**. 2. Preencha **Nome** e **URL da página** — um endereço completo `https://…`. 3. Clique em **Adicionar URL**. A plataforma lê o texto visível dessa única página (não segue ligações). Só são aceites páginas públicas: endereços locais e de redes privadas são bloqueados. O conteúdo é importado uma vez — se a página mudar, elimine o documento e importe-a novamente. ## Crawl de site 1. Escolha **Crawl de site**. 2. Preencha **Nome**, **URL inicial** e **Máximo de páginas** (1 a 10). 3. Clique em **Iniciar crawl**. A plataforma começa no URL inicial e segue as ligações dentro do **mesmo domínio**, criando um documento do tipo URL por página (com o título da página como nome). A plataforma aplica também o seu próprio limite de páginas por crawl, por isso pode importar menos páginas do que o máximo indicado — a mensagem **Crawl concluído** diz quantas páginas foram importadas. Tal como na importação de URL, o conteúdo não é actualizado automaticamente. ## Estados dos documentos A coluna **Estado** mostra se o documento está pronto a ser usado, com uma explicação curta por baixo quando é útil. | Estado | Significado | O que fazer | | ---------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | **Indexado** | Texto segmentado e indexado. O agente encontra-o na pesquisa durante a conversa. | Nada. | | **Pronto** | Texto disponível, mas sem indicação de indexação concluída. | Se o agente não o encontrar, use **Reindexar**. | | **Indexação pendente** | O texto existe e aguarda indexação. | Aguarde ou use **Reindexar**. | | **Sem texto / indexação pendente** | Ficheiro guardado sem texto legível (típico de PDF digitalizado). | Carregue um PDF com texto seleccionável ou crie um documento em branco com o conteúdo. | | **Sem indexação** | Não havia texto suficiente para indexar. | Igual ao anterior. | | **Extração falhou** | O PDF foi guardado, mas a leitura do texto falhou. | Tente outro ficheiro. | | **Indexação falhou** | A indexação não terminou. | Use **Reindexar** ou **Reindexar tudo**; se persistir, contacte a Diska. | Os PDFs ainda em envio aparecem apenas na barra de progresso. Se um envio falhar, a mensagem de erro aparece por baixo da barra e o documento não é adicionado. ## Reindexar - **Reindexar** (menu da linha) volta a indexar um documento e indica quantos segmentos foram criados. - **Reindexar tudo** (topo da página da base) reindexa todos os documentos de seguida e mostra quantos ficaram bem. Não precisa de reindexar depois de criar ou editar um documento — isso já é automático. Use estas opções quando um documento mostra **Indexação falhou** ou **Indexação pendente** durante muito tempo. ## Eliminar **Eliminar** no menu da linha remove o documento e, se existir, o ficheiro original. A eliminação aplica-se de imediato a todos os agentes que usam a base. ## Por API As bases e os documentos também podem ser criados pela [API da DISKA](https://docs.diska.ai/pt/api/api-channel) (âmbitos `knowledge:read` e `knowledge:write`): listar e criar bases, criar documentos escritos, importar URLs e carregar PDFs. É útil para manter a base sincronizada a partir do seu CMS ou CRM. Ver [Endpoints](https://docs.diska.ai/pt/api/endpoints). # Citações Quando o agente pesquisa a base de conhecimento durante uma conversa, cada excerto que recebe vem identificado com a sua origem — **base / documento**. O agente é instruído a responder apenas com esses excertos e a indicar a fonte quando afirma factos. Pode auditar essas pesquisas depois da chamada. ## Ver as pesquisas de uma chamada 1. Abra **Históricos → Chamadas** e clique na chamada. 2. Abra o separador **Acções**. 3. Procure as entradas `search_knowledge` — uma por cada pesquisa que o agente fez. 4. Expanda **Pedido / resposta** para ver: | Campo | O que mostra | | ------------------- | -------------------------------------------------------------------------------------------------------------- | | `query` (pedido) | A pergunta que o agente pesquisou. | | `found` | `true` se encontrou conteúdo relevante; `false` se não encontrou nada. | | `results[].source` | A origem do excerto, no formato `Nome da base / Nome do documento`. | | `results[].content` | O texto exacto que o agente recebeu. | | `message` | A orientação dada ao agente — por exemplo, dizer ao cliente que não tem a informação quando `found` é `false`. | Compare o `content` com o que o agente disse na **Transcrição**: se a resposta não corresponde a nenhum excerto, o agente não se baseou na base de conhecimento. As mesmas pesquisas aparecem nas chamadas de teste feitas no painel do agente, porque também ficam em **Históricos**. Ver [Chamadas](https://docs.diska.ai/pt/history/calls). ## Diagnóstico no Centro de Testes Nos resultados de uma execução do [Centro de Testes](https://docs.diska.ai/pt/test-center), cada caso mostra um bloco **Diagnóstico da base de conhecimento** com o modo usado e quantos documentos e excertos entraram (`mode=… · docs=… · chunks=…`): | Modo | Significado | | ------------------- | ---------------------------------------------------------------------------------------------------- | | `retrieval` | A pesquisa encontrou excertos relevantes. | | `full_doc_fallback` | Não houve excertos relevantes; foi usado o texto completo dos documentos, até ao limite de contexto. | | `instructions_only` | Só as instruções das bases foram usadas, sem conteúdo de documentos. | | `empty` | Nenhum conhecimento disponível (por exemplo, nenhuma base atribuída). | | `n/a` | O caso não usou a base de conhecimento. | ## Boas práticas - Dê nomes descritivos às bases e aos documentos — são eles que aparecem como origem. - Divida conteúdo longo em documentos temáticos: os excertos ficam mais precisos e o limite de contexto inicial chega para mais assuntos. - Escreva a instrução **Quando deve o agente consultar esta base?** com situações concretas. - Quando o agente responde mal, veja primeiro se a pesquisa devolveu `found: false` (falta conteúdo) ou o excerto errado (conteúdo ambíguo ou desactualizado). - Confirme que os documentos estão **Indexado** — ver [estados dos documentos](https://docs.diska.ai/pt/knowledge-base/sources#estados-dos-documentos). # Memória partilhada A **Memória partilhada** faz com que os agentes se lembrem dos seus contactos. Depois de cada chamada, a Diska guarda um resumo e o que o cliente disse sobre si. Na chamada seguinte do mesmo contacto, com o mesmo agente ou com outro agente do grupo, o agente começa já com esse contexto: cumprimenta o cliente pelo nome, retoma o que ficou pendente e não volta a perguntar o que já sabe. Encontra-a no menu **Memória partilhada**. Se o menu não aparecer, a funcionalidade ainda não está activa na sua organização: peça-a à Diska. ## Para que serve - **Apoio ao cliente** — o cliente não tem de explicar o problema outra vez quando volta a ligar. - **Vendas e seguimento** — o agente lembra-se do produto por que o cliente perguntou e retoma a conversa. - **Marcações** — preferências de horário e pedidos anteriores ficam à mão do agente seguinte. - **Equipas com vários agentes** — o agente de atendimento e o agente de saída partilham o que cada um aprendeu. ## Como funciona | Elemento | O que é | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Grupo de memória** | Um espaço de memória partilhado. Tem nome, descrição e um período de **retenção**. | | **Contactos** | As pessoas que o grupo reconhece, pelo número de telefone. São os contactos adicionados pela equipa e, com a memória automática activa (ver mais abaixo), também quem ligar pela primeira vez. | | **Agentes associados** | Os agentes que usam o grupo. Todos lêem e alimentam a mesma memória. Agentes fora do grupo não a vêem. | | **Memórias** | Factos, interesses, preferências e pendentes ditos pelo cliente, e notas da equipa. Cada uma guarda a data e a chamada de onde veio. | | **Interacções** | Um resumo curto de cada chamada, com o resultado e o agente que atendeu. | 1. **Antes de atender**, o agente procura o número de quem liga nos contactos do grupo. Se o encontrar, recebe as memórias e os resumos das últimas chamadas. 2. **Durante a chamada**, usa esse contexto para não repetir perguntas e retomar o que ficou pendente. 3. **Depois da chamada**, a Diska resume a conversa e guarda o que é útil para a próxima vez. A memória fica disponível poucos segundos depois de a chamada terminar. A memória só é usada em **chamadas telefónicas** em que o número vem da rede: chamadas recebidas nos seus números, chamadas feitas pelo agente (incluindo [Campanhas](https://docs.diska.ai/pt/telephony/campaigns)) e chamadas de teste para um telemóvel. Uma chamada de teste no browser, o link público e o WhatsApp não têm um número fiável e não usam memória. ## 1. Criar um grupo 1. Em **Memória partilhada**, clique em **Novo grupo**. 2. Indique o **Nome do grupo**, uma **Descrição** (opcional) e a **Retenção das memórias**: 30 dias, 90 dias, 6 meses, 1 ano ou 2 anos. 3. Se quiser que o grupo registe sozinho quem liga pela primeira vez, marque **Memória automática de novos contactos**. 4. Clique em **Criar**. ::callout{type="tip"} Use nomes que digam para que serve o grupo, por exemplo «Clientes da oficina» ou «Leads de Luanda». Grupos separados são memórias separadas: um contacto num grupo não é conhecido pelos agentes de outro. :: Em cada grupo, o menu **⋮** tem **Editar**, **Copiar ID** e **Eliminar**. Eliminar um grupo apaga a lista de contactos e todas as memórias do grupo. Os agentes associados deixam de usar memória até escolher outro grupo. ## 2. Adicionar contactos 1. Abra o grupo e, em **Contactos**, clique em **Adicionar contacto**. 2. Escolha o indicativo do país e escreva o **Número de telefone**. Indique o **Nome**, o **Apelido** e, se quiser, o **Email**. 3. Clique em **Guardar**. O número é guardado no formato internacional (por exemplo, +244 923 000 000). Se o número já existir noutro grupo, é o mesmo contacto. Não é possível ter o mesmo número duas vezes no mesmo grupo. No menu **⋮** de cada contacto: - **Memórias e histórico** mostra o que o grupo se lembra do contacto e o resumo de cada chamada, com ligação para a chamada em **Históricos**. - **Ver chamadas** abre os Históricos filtrados pelo número. - **Editar**, **Copiar ID** e **Remover do grupo**. Remover apaga as memórias desse contacto neste grupo. Com a memória automática activa, não precisa de adicionar os contactos um a um: veja a secção seguinte. ## Memória automática de novos contactos Com a opção **Memória automática de novos contactos** marcada nas definições do grupo (está desmarcada por defeito): 1. Um número que o grupo não conhece liga para um agente associado. 2. Depois da chamada, a Diska resume a conversa. Se houver algo útil a lembrar, regista o número como contacto do grupo e guarda o **nome** que o cliente disse, os **interesses** (por exemplo, «perguntou por iogurte de morango»), os pedidos, as preferências, o resultado e os pendentes, com a data da chamada. 3. Na chamada seguinte, o agente cumprimenta o cliente pelo nome e retoma o assunto, sem voltar a perguntar o que já sabe. Regras: - Só chamadas **recebidas** com número identificado. Chamadas feitas pelo agente, chamadas de teste, números ocultos e o link público não registam ninguém. - Um engano, uma chamada em silêncio ou só com cumprimentos não cria contacto. - Se o agente pedir consentimento explícito para gravar e o cliente recusar (ou não responder), a chamada não é guardada em memória, nem para contactos novos nem para os existentes. - Se o número já for um contacto da organização, é reutilizado; o nome que já tinha não é alterado. Um nome escrito pela equipa nunca é substituído pelo que o cliente disser; um nome que veio de uma chamada é corrigido se o cliente o corrigir numa chamada seguinte. - Cada grupo regista no máximo 200 números novos por dia. - Na lista de contactos, a coluna **Origem** mostra **Automático** ou **Manual**. **Desactivar** a opção não apaga nada: os contactos já registados e as suas memórias continuam e continuam a ser reconhecidos. Deixam apenas de entrar números novos. Se a opção for desligada durante uma chamada, essa chamada já não regista o número; se for ligada durante uma chamada, o registo começa na chamada seguinte. Os contactos registados automaticamente seguem a retenção do grupo: quando já não há nada guardado sobre eles, saem do grupo. ## 3. Associar um agente 1. Abra o agente e vá a **Definições → Conhecimento e memória**. 2. Em **Memória partilhada**, clique em **Associar grupo**, escolha o grupo e clique em **Associar**. 3. Publique o agente. As chamadas reais usam a versão publicada. Cada agente usa um grupo de cada vez. Para trocar, clique no lápis; para deixar de usar memória, clique em ✕. O separador **Agentes associados** do grupo mostra os agentes que o usam, no rascunho ou na versão publicada. A memória funciona com agentes do Prompt Builder e do Flow Designer, em qualquer motor de voz. Num fluxo, a memória acompanha a chamada em todos os nós. ## 4. Como o agente usa a memória Não precisa de mudar o prompt. Quando reconhece o contacto, a Diska entrega ao agente as memórias **antes** das instruções do agente, com regras próprias: - **Abertura:** o agente cumprimenta o cliente pelo nome e resume numa frase a última conversa ou o que ficou pendente — por exemplo, «Olá, João! Da última vez perguntou pelo iogurte de morango. Em que posso ajudar hoje?». Isto prevalece sobre a abertura do seu guião, que normalmente pergunta com quem está a falar. - **Durante a chamada:** não volta a perguntar o que já está na memória e continua válido; confirma o que é antigo (moradas, horários, decisões) antes de o usar; segue a correcção se o cliente corrigir algo. - **Um interesse não é uma compra:** o agente não diz que o cliente comprou ou encomendou algo que só perguntou. - **Identidade:** o número de telefone não prova quem está a falar. Antes de revelar ou alterar dados pessoais, marcações, valores ou contas, o agente confirma com quem está a falar. Se quiser, pode acrescentar ao prompt regras do seu negócio sobre o uso da memória. Por exemplo: ```text Se o cliente já tiver dito o modelo do carro numa chamada anterior, não voltes a perguntar: confirma-o. Se houver um pedido de orçamento pendente, pergunta logo se o cliente o recebeu. ``` ## Partilhar a memória entre agentes Todos os agentes associados ao mesmo grupo partilham o que aprendem sobre cada contacto, desde que o número seja o mesmo. Exemplo: 1. O cliente liga para o agente de atendimento e diz que procura iogurte de morango. 2. Dias depois, o agente de saída liga-lhe numa campanha. 3. O agente de saída já sabe o nome do cliente e o que ele procurava. A memória é partilhada entre chamadas telefónicas. As conversas por WhatsApp e as chamadas pelo browser não usam nem alimentam a memória partilhada. ## Corrigir e apagar memórias Em **Memórias e histórico** pode: - corrigir uma memória (lápis) ou apagá-la (caixote do lixo); - acrescentar uma **Nota**, um **Facto**, um **Interesse**, uma **Preferência** ou um **Pendente** escritos pela equipa; - **Apagar todas as memórias** do contacto neste grupo, mantendo-o no grupo. As memórias descrevem o contacto. Não são instruções para o agente: textos como «ignora as regras» são recusados. As instruções do agente pertencem ao prompt. ## Processamento das memórias A página do grupo mostra o **Processamento das memórias**: quanto tempo demora a memória a ficar disponível depois da chamada (mediana e p95), quantas chamadas foram processadas e quantos contactos novos entraram nas últimas 24 horas, e se há alguma chamada à espera ou com falha. As falhas são tentadas de novo automaticamente; não precisa de fazer nada. ## Resolução de problemas | Problema | Causas prováveis | O que fazer | | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | O agente não se lembrou do cliente | O agente não está associado ao grupo ou não foi publicado depois de o associar; o número não está no grupo e a memória automática está desligada; a chamada foi feita pelo browser, pelo link público ou de um número oculto. | Associe o grupo e publique o agente; adicione o contacto ou active a memória automática; teste por telefone. | | O contacto não tem interacções | A chamada foi feita antes de associar o agente; foi um engano ou uma chamada sem conversa; o cliente recusou o consentimento pedido pelo agente. | Faça uma nova chamada depois de associar e publicar o agente. | | O agente usou um nome errado | O nome veio de uma chamada e a transcrição percebeu-o mal. | Corrija o nome do contacto em **Editar**: um nome escrito pela equipa prevalece sempre. | | Outro agente não conhece o contacto | Esse agente usa outro grupo, ou nenhum. | Associe o mesmo grupo aos dois agentes e publique-os. | | Um número novo não ficou registado | A memória automática está desligada; foi uma chamada feita pelo agente ou de teste; a chamada não teve nada útil a lembrar; o grupo atingiu o limite de 200 números novos nesse dia. | Confirme a opção nas definições do grupo e o estado da chamada em **Memórias e histórico**. | ## Perguntas frequentes **Que agentes podem usar a memória?** Agentes de voz publicados, do Prompt Builder ou do Flow Designer, em chamadas telefónicas. **Como é reconhecido o contacto?** Pelo número de telefone que a rede entrega, em formato internacional. **Vários agentes podem usar o mesmo grupo?** Sim. Cada agente usa um grupo de cada vez, e um grupo pode servir vários agentes. **Funciona no WhatsApp ou no chat do site?** Ainda não. A memória partilhada é só para chamadas telefónicas. **A transcrição completa fica na memória?** Não. A memória guarda só um resumo curto e itens curtos. A transcrição da chamada fica nos **Históricos**, como as outras chamadas. **Quanto tempo ficam guardadas as memórias?** O período de retenção do grupo, entre 30 dias e 2 anos. Depois disso são apagadas automaticamente. ## Segurança e privacidade - Cada organização só vê os seus grupos, contactos e memórias. - O número de telefone identifica o contacto, mas não prova quem está a falar. O agente é instruído a confirmar a identidade antes de revelar ou alterar dados pessoais, marcações, valores ou contas. - Não é guardada a transcrição. Fica só um resumo curto e itens curtos. Números de cartão, IBAN, números de documento, palavras-passe e códigos são retirados antes de guardar. - Num agente com [Ocultar dados pessoais](https://docs.diska.ai/pt/guides/redact-personal-data) activo, a memória é criada a partir da chamada já ocultada: o resumo não guarda nomes, contactos nem moradas ditos na chamada. O contacto continua identificado pelo número de telefone. - Memórias antigas são apresentadas ao agente como tal, e ele confirma-as antes de as usar. - Se a memória não responder a tempo, a chamada é atendida normalmente, sem memória. - As memórias são apagadas automaticamente quando passam o período de retenção do grupo. # Base de conhecimento A **Base de conhecimento** guarda o conteúdo que os agentes consultam durante as conversas: FAQs, tabelas de preços, políticas, manuais ou páginas do seu site. Encontra-a no menu **Conhecimento**. ## Como está organizada | Elemento | O que é | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | Base | Um conjunto temático de documentos (por exemplo, «Apoio ao cliente» ou «Tarifário 2026»). Uma organização pode ter várias bases. | | Instrução da base | O campo **Quando deve o agente consultar esta base?** — descreve em que situações o agente deve recorrer a esta base. | | Documento | Cada fonte adicionada à base: um PDF, um documento escrito na plataforma ou uma página web. Ver [Fontes](https://docs.diska.ai/pt/knowledge-base/sources). | | Atribuição | A ligação entre uma base e um agente. Um agente pode ter várias bases; a mesma base pode servir vários agentes. | ## Criar uma base 1. No menu **Conhecimento**, clique em **Nova base**. 2. Preencha: - **Nome** — por exemplo, «Guias de apoio ao cliente». - **Quando deve o agente consultar esta base?** — descreva o gatilho, não uma instrução genérica. Exemplo: «O cliente pergunta por preços, planos ou condições de pagamento». - **Descrição (opcional)**. 3. Clique em **Criar**. A plataforma abre a base para começar a [adicionar conteúdo](https://docs.diska.ai/pt/knowledge-base/sources). Na lista de bases, cada cartão mostra o número de documentos, quantos agentes a usam (ou **Não atribuída**) e a data da última alteração. Passe o cursor sobre um cartão para **Editar** ou **Eliminar** a base. Eliminar uma base remove também os seus documentos e as atribuições a agentes. ## Atribuir bases a um agente 1. Abra o agente e clique em **Definições** na barra superior do builder. 2. No painel **Definições globais**, abra a secção **Conhecimento e memória**. 3. Em **Bases de conhecimento atribuídas**, marque as bases que o agente deve usar. 4. Clique em **Guardar atribuições**. Na mesma secção existe o campo **Notas de conhecimento (texto livre)**, útil para factos curtos que não justificam um documento. ::callout{type="info"} Os testes em **Rascunho — ações simuladas** no painel de teste do agente usam logo as bases que acabou de atribuir. As chamadas reais, os testes da versão publicada e o WhatsApp só usam as bases que já estavam atribuídas quando a versão foi publicada: depois de atribuir uma base nova, [publique o agente](https://docs.diska.ai/pt/guides/publish-agent) para ela chegar aos clientes. Retirar uma base, pelo contrário, tem efeito imediato, e as alterações ao conteúdo de uma base atribuída (novos documentos, edições, eliminações) também. :: ## Como o agente usa o conhecimento 1. **No início da conversa**, o agente recebe a instrução de cada base atribuída e o texto dos documentos, até um limite de contexto. Documentos longos são cortados e, se o limite se esgotar, os restantes ficam de fora deste resumo inicial. 2. **Durante a conversa**, sempre que precisa de um facto, o agente pesquisa semanticamente as bases atribuídas e recebe os excertos mais relevantes, cada um identificado pela base e pelo documento de origem. É instruído a responder apenas com esses excertos. 3. **Se a pesquisa não encontrar nada**, o agente diz ao cliente que não tem essa informação, em vez de inventar. Isto aplica-se às chamadas (web, widget, link público e telefone) e às conversas de [WhatsApp](https://docs.diska.ai/pt/whatsapp). Para a pesquisa durante a conversa, o documento tem de estar com o estado **Indexado** — ver [estados dos documentos](https://docs.diska.ai/pt/knowledge-base/sources#estados-dos-documentos). Para saber de onde veio uma resposta, veja [Citações](https://docs.diska.ai/pt/knowledge-base/citations). ## Permissões | Acção | Proprietário / Administrador | Membro | Visualizador | | ---------------------------------- | :--------------------------: | :----: | :----------: | | Ver bases e documentos | ✓ | ✓ | ✓ | | Criar bases e adicionar documentos | ✓ | ✓ | — | | Editar e reindexar | ✓ | ✓ | — | | Eliminar bases e documentos | ✓ | — | — | | Atribuir bases a um agente | ✓ | ✓ | — | ## Seguinte - [Adicionar fontes](https://docs.diska.ai/pt/knowledge-base/sources) — PDF, documento escrito, URL e crawl de site. - [Citações](https://docs.diska.ai/pt/knowledge-base/citations) — confirmar que documento originou cada resposta. - [A KB não responde](https://docs.diska.ai/pt/troubleshooting/kb-not-answering) — diagnóstico quando o agente não usa o conhecimento. # Avaliações No fim de cada conversa simulada, o Centro de Testes avalia os **Critérios de sucesso** do caso e decide se o caso passou. ## Como cada critério é avaliado Um avaliador automático (um modelo de IA) lê o cenário, a transcrição completa e o diagnóstico da base de conhecimento, e decide, critério a critério, se a conversa o cumpre. É instruído a ser rigoroso e a basear-se no que está na transcrição. Para cada critério, o resultado mostra: - **Passou** ou **Falhou**; - uma explicação curta do porquê. Se o avaliador não conseguir avaliar um critério, o critério conta como falhado, com a explicação **Critério não avaliado pelo juiz.** ou **Avaliação automática indisponível: …**. ## Quando o caso passa Em **A chamada tem sucesso quando**, cada caso define o modo: | Modo | O caso passa se… | | ---------------------- | ------------------------------ | | **Todos os critérios** | todos os critérios passarem. | | **Qualquer critério** | pelo menos um critério passar. | A pontuação aparece ao lado de **Critérios de sucesso** no resultado, como critérios aprovados / total (ex.: 3/4). Um caso com estado **Erro** teve uma falha técnica e não foi avaliado. ## Verificação da base de conhecimento Com **Validar se a base de conhecimento entra no runtime** activo, o caso ganha um critério extra, **Knowledge Base injectiu conteúdo no runtime**. Passa quando a base de conhecimento do agente forneceu documentos, excertos ou instruções durante a conversa. Este critério conta para a pontuação e para o modo do caso como os restantes. O resultado mostra também o **Diagnóstico da base de conhecimento** — o modo de pesquisa e quantos documentos e excertos foram usados. ## Escrever bons critérios - Escreva critérios observáveis na transcrição: "O agente pediu o nome do cliente", "O agente confirmou a data e a hora da marcação". - Um critério por ideia: é mais fácil perceber o que falhou. - Evite critérios subjectivos ("bom atendimento") — o avaliador não tem como os verificar. - Inclua o que o agente **não** deve fazer: "O agente não revelou dados de outros clientes". - Use **Qualquer critério** quando há várias respostas certas e equivalentes. ::callout{type="info"} Estas avaliações correm só no Centro de Testes. Para avaliar automaticamente as chamadas reais depois de terminarem, use as [Avaliações personalizadas](https://docs.diska.ai/pt/actions/custom-evaluations) . :: # Centro de Testes O **Centro de Testes** valida o agente com conversas simuladas: um cliente simulado por IA segue o cenário que escrever, fala com o agente por texto e, no fim, cada critério de sucesso é avaliado automaticamente. Use-o antes de publicar e sempre que alterar o agente. Abra-o no menu lateral, em **Centro de Testes**. Tem duas páginas: **Suites de teste** e **Histórico de execuções**. ::callout{type="info"} As suites de um agente também aparecem no editor do agente, em **Testar → Simulação** : pode criá-las, gerar casos e executá-las sem sair do agente. São as mesmas suites — ver [Testar um agente](https://docs.diska.ai/pt/guides/test-agent#simula%C3%A7%C3%A3o) . :: ## Conceitos | Conceito | Descrição | | ------------------ | ------------------------------------------------------------------------------------ | | **Suite de teste** | Um conjunto de casos ligado a um agente. | | **Caso de teste** | Um cenário: o que o cliente simulado faz e os critérios que a conversa deve cumprir. | | **Execução** | Uma corrida de todos os casos de uma suite, com o resultado de cada um. | ## Criar uma suite 1. Em **Suites de teste**, clique em **Suite de teste**. 2. Preencha: - **Nome**; - **Agente** — a suite fica permanentemente ligada a este agente; - **Idioma** — Português (PT), Português (BR) ou Inglês; - **Correr por defeito contra o rascunho (não o publicado)** — desmarque para testar a versão publicada. 3. Clique em **Criar**. A suite abre vazia. ## Criar casos Numa suite vazia, escolha **Criar caso personalizado** ou **Gerar com IA**. Numa suite com casos, use **Adicionar**. Cada caso tem: | Campo | Descrição | | ------------------------------------------------------ | -------------------------------------------------------------------------------------- | | **Nome** | Identifica o caso. | | **Prompt do cenário** | As instruções para o cliente simulado: quem é, o que quer, como se comporta. | | **Critérios de sucesso** | O que a conversa deve cumprir, um por linha (**+ Critério** para mais; até 20). | | **A chamada tem sucesso quando** | **Todos os critérios** ou **Qualquer critério** passam. | | **Validar se a base de conhecimento entra no runtime** | Junta um critério que confirma que a base de conhecimento do agente forneceu conteúdo. | Clique em **Guardar alterações**. O nome, o prompt do cenário e pelo menos um critério são obrigatórios — casos incompletos impedem a execução. ### Gerar com IA Disponível enquanto a suite não tem casos: 1. Clique em **Gerar com IA**. 2. Escolha os **Cenários comuns**: Precisão das respostas, Cumprimento do fluxo, Utilizador stressado ou irritado, Conclusão da tarefa, Base de conhecimento e citações, Ferramentas e acções (honestidade), Naturalidade conversacional, Frases repetitivas e muletas. 3. Escolha o **Número de casos** (1 a 25). 4. Clique em **Gerar … casos de teste** (o botão mostra o número escolhido). Os casos são criados à medida do agente, com critérios sugeridos. Pode fechar a janela enquanto são gerados. Reveja-os e edite-os antes de correr. ## Executar Clique em **Executar** (no cartão da suite ou dentro dela) e confirme **Executar testes**. Aparece **Testes iniciados.** e abre o **Histórico de execuções** com a execução seleccionada. Em **Testar → Simulação**, no editor do agente, **Executar** começa logo, sem confirmação, contra a versão escolhida na faixa de teste (**Rascunho** ou **Publicado**). Os casos correm um a um. Em cada caso, o cliente simulado e o agente trocam até 12 turnos de texto e depois os critérios são avaliados — ver [Avaliações](https://docs.diska.ai/pt/test-center/evaluations). ::callout{type="warning"} É uma simulação de texto: não usa voz e nunca executa acções reais (SMS, marcações, transferências). Num agente em Flow Designer, a conversa percorre o motor de fluxo real; num agente em Prompt Builder, o agente responde a partir do prompt. Para ouvir a voz e testar acções reais, use a [chamada telefónica de teste](https://docs.diska.ai/pt/guides/test-agent) . :: ## Rever resultados O **Histórico de execuções** lista as execuções com **Data**, **Agente**, **Suite de teste**, **Resultados** (ex.: "3 de 4 casos passaram") e **Estado**. Pode filtrar por agente e por suite. | Estado da execução | Significado | | ------------------ | ---------------------------------------------------- | | **Em fila** | A aguardar. | | **Em curso** | Os casos estão a correr. | | **Concluído** | Todos os casos passaram. | | **Falhou** | Pelo menos um caso não passou, ou a execução falhou. | Clique numa execução para ver cada caso, com o estado **Passou**, **Falhou** ou **Erro** (falha técnica) e dois separadores: - **Visão geral** — os **Critérios de sucesso** com a pontuação (ex.: 3/4), o resultado e a explicação de cada critério; o **Diagnóstico da base de conhecimento**; o **Percurso do fluxo** (agentes em Flow Designer: nós visitados e se chegou ao fim); e o **Prompt do cenário**. - **Transcrição** — a conversa completa entre o cliente simulado e o agente. Cada execução mostra também **Pronto para publicar** ou **Publicação com pendências**, com a lista de pendências (por exemplo, nenhuma base de conhecimento utilizável). A **Lista de verificação** do editor continua a ser a referência para publicar. ## Gerir suites e casos - Menu da suite: **Histórico de execuções**, **Copiar ID**, **Duplicar** e **Eliminar suite de teste**. - Menu de cada caso: **Editar**, **Copiar ID** e **Eliminar**. ## Permissões | Acção | Papéis | | ----------------------------- | ------------------------------------ | | Ver suites e resultados | Todos | | Executar suites | Todos, incluindo Visualizador | | Criar e editar suites e casos | Proprietário, Administrador e Membro | ## Seguinte Quando os testes passarem, publique o agente e ligue-o aos canais — ver [Publicar e receber chamadas](https://docs.diska.ai/pt/guides/publish-agent). Se os testes falharem sem razão aparente, ver [Os testes falham](https://docs.diska.ai/pt/troubleshooting/tests-failing). # Visão geral A **Visão geral** é a página que abre depois de entrar no backoffice (menu **Visão geral**). Mostra uma de duas coisas, conforme já haja chamadas nos últimos sete dias. ## Primeiros passos Enquanto não houver chamadas nos últimos sete dias, a página mostra o cartão **Primeiros passos** com o que falta fazer, por esta ordem: | Passo | Fica concluído quando | Botão | | ------------------------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | **Criar o primeiro agente** | Existe pelo menos um agente. | **Ir aos agentes** | | **Fazer uma chamada de teste** | Há chamadas registadas nos últimos sete dias. A chamada web corre no browser, sem número. | **Testar agente** — abre o painel de teste do agente | | **Publicar o agente** | Pelo menos um agente está publicado. | **Abrir o agente** — o botão de publicação está na barra do builder | | **Atribuir um número** | Pelo menos um agente tem um número de telefone. Só é preciso para chamadas telefónicas. | **Ver números** | - O contador **X de Y concluídos** mostra o progresso, e o próximo passo por fazer fica destacado. - Os passos que a sua função não permite executar não aparecem (por exemplo, atribuir números é só para Proprietários e Administradores). Os passos já concluídos continuam visíveis. - Se nenhum passo couber à sua função, a página pede-lhe que fale com um administrador da organização. Para o primeiro teste, siga [Fazer uma chamada de teste](https://docs.diska.ai/pt/getting-started/test-call). ## Resumo da semana Assim que houver chamadas, a página passa a mostrar os **últimos sete dias**: - **Estatísticas de chamadas** — **Total de chamadas**, **Total de minutos** e **Duração média**, cada um com a variação face aos sete dias anteriores. Quando não há dados no período anterior, a variação aparece como «—». - **Chamadas por dia** — o volume diário do período. - **Estado das chamadas** — a repartição por estado final (Concluída, Falhou, Cancelada, Abandonada, Em progresso). O botão **Ver análises completas** abre as [Análises](https://docs.diska.ai/pt/history/analytics), onde pode mudar o período, filtrar por agente e exportar. ::callout{type="info"} A Visão geral conta as mesmas chamadas que [Históricos → Chamadas](https://docs.diska.ai/pt/history/calls) , incluindo as chamadas de teste. As conversas de WhatsApp não entram nestas métricas. :: # Chamadas Em **Históricos → Chamadas** fica o registo de todas as chamadas dos agentes da organização, da mais recente para a mais antiga, 25 por página. ## A lista | Coluna | O que mostra | | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Data** | Dia e hora de início. | | **Agente** | O agente que atendeu ou fez a chamada. | | **Duração** | Minutos e segundos (ou horas, minutos e segundos). | | **Contacto** | Numa chamada telefónica recebida, o número de quem ligou; numa chamada que o agente fez, o número de destino. Por baixo, o nome do contacto quando é conhecido. | | **Call ID** | O identificador da chamada, abreviado. Clique para o copiar inteiro. | | **Tipo** | **Web Call** (chamada no browser: painel de teste, widget ou link público) ou **Telefone**. | | **Estado** | O estado da chamada (ver abaixo). | Clique numa linha para abrir o detalhe. ### Estados | Estado | Significado | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | **Concluída** | A chamada terminou normalmente. | | **Em progresso** | A chamada ainda está a decorrer. | | **Falhou** | A chamada terminou por um erro. | | **Abandonada** | O browser de quem ligava deixou de responder a meio da chamada (por exemplo, o separador foi fechado). Não indica uma avaria. | | **Cancelada** | A ligação foi substituída por outra antes de a conversa começar (por exemplo, a chamada foi reiniciada). Normalmente não tem transcrição. | ### Pesquisar e filtrar - **Pesquisar por Call ID ou contacto** — procura no Call ID, no número ou nome do contacto e no identificador da sessão. - **Todos os estados** — filtra por um estado. - **Qualquer data** — **Hoje**, **Últimos 7 dias**, **Últimos 30 dias** ou **Personalizado** (duas datas, inclusivas). Se a data inicial for posterior à final, a página avisa: «A data inicial é posterior à data final.» - **Actualizar** — recarrega a lista. Para ver só as chamadas de um agente, use **Registos de chamadas** no menu **⋮** do agente (ou **Ver registos de chamadas** na lista de agentes). A lista abre filtrada por esse agente; para voltar a ver todas, abra **Históricos** no menu lateral. ## Detalhe da chamada O painel **Detalhes da chamada** mostra no topo o tipo (**Web Call**, **Telefone**, **WhatsApp** ou **Chat**) e o Call ID abreviado. O botão **Copiar link** copia um endereço directo para esta chamada, que pode partilhar com colegas da organização. O painel tem quatro separadores. ### Detalhes | Campo | Descrição | | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Data** | Data e hora de início. | | **Estado** | Estado final da chamada. | | **Contacto** | Número e nome do contacto, quando existem. | | **Tipo** | O canal (**Web Call**, **Telefone**…) e, por baixo, a origem: **Widget ou link público** (um cliente real no browser), **Teste no backoffice** (o teste web do painel), **Demonstração no site** ou **Chamada de teste do painel** (a chamada que o agente faz para o seu telemóvel a partir do painel de teste). | | **Agente** | O agente da chamada. | | **Duração** | Duração total. | | **Motivo de fim** | Como a chamada terminou (ver abaixo). | | **Call ID** | Identificador completo, com botão para copiar. Indique-o ao contactar o suporte da Diska. | | **Sessão** | O identificador técnico da sessão, quando existe. | Motivos de fim mais comuns: | Motivo | Significado | | ---------------------------------------------------------------- | ----------------------------------------------------------------- | | **Cliente desligou** | O cliente terminou a chamada. | | **Cliente pediu para terminar** | O cliente pediu ao agente para terminar. | | **Agente terminou** / **Concluída pela agente** | O agente encerrou a conversa. | | **Tarefa concluída** / **Fluxo concluído** | O objectivo da conversa ou o fluxo chegou ao fim. | | **Terminada por silêncio** / **Terminada por inatividade** | Ninguém falou durante demasiado tempo. | | **Página fechada** / **Página em segundo plano** | Numa chamada web, a página foi fechada ou ficou em segundo plano. | | **Ligação perdida** / **Reconexão falhou** / **Erro de ligação** | Problema de rede durante a chamada. | | **Microfone desligou-se** | O microfone de quem ligava deixou de enviar áudio. | | **Sessão expirada** | A sessão excedeu o tempo permitido. | ### Transcrição - No topo, o leitor da gravação, quando a chamada foi gravada — ver [Gravações](https://docs.diska.ai/pt/history/recordings). - Depois, a conversa por ordem: **Chamada iniciada** e cada intervenção com a hora, identificada pelo nome do agente, **Cliente**, **Sistema** ou **Ferramenta**. Se não houver texto, aparece «Sem transcrição gravada para esta chamada.» Num agente com [Ocultar dados pessoais](https://docs.diska.ai/pt/guides/redact-personal-data) activo, os dados pessoais aparecem como etiquetas — `[NOME]`, `[TELEFONE]`, `[MORADA]`… — na transcrição, no resumo e na análise. ### Análise O resultado do processamento feito no fim da chamada: - **Dados extraídos** — os valores recolhidos pelos [extractores de informação](https://docs.diska.ai/pt/actions/information-extractors), com **Histórico por extractor**. Sem extractores configurados aparece «Sem extractores ou ainda sem pipeline pós-chamada.» - **Avaliações / scorecards** — cada [avaliação personalizada](https://docs.diska.ai/pt/actions/custom-evaluations) com **Passou**, **Falhou** ou **n.a.**, o **Score ponderado**, os critérios e a justificação. O botão **CSV** exporta as avaliações recentes deste agente. - **SMS pós-chamada** — cada [SMS pós-chamada](https://docs.diska.ai/pt/actions/post-call-sms) enviado, com o estado de entrega, a pré-visualização e a **Variante A/B**, quando aplicável. - **Resumo** — o resumo da chamada, quando existe. ### Acções O separador **Acções** (com o número de acções no título) lista cada acção ou ferramenta que o agente executou: o nome técnico (por exemplo `search_knowledge` para uma pesquisa na base de conhecimento), a hora, a latência em ms e o estado. Expanda **Pedido / resposta** para ver os dados enviados e recebidos — útil para confirmar uma marcação, um SMS ou uma transferência, ou para ver as [citações](https://docs.diska.ai/pt/knowledge-base/citations) da base de conhecimento. Sem acções, aparece «Nenhuma acção/tool foi executada nesta chamada.» ## Exportar para CSV O botão **Exportar tudo (CSV)** passa a **Exportar filtrado (CSV)** quando há uma pesquisa, estado ou data activos. O ficheiro `chamadas-AAAA-MM-DD.csv` inclui todas as chamadas do filtro actual (não só a página visível), até 5000 linhas, com as colunas: `id`, `started_at`, `agent`, `duration_seconds`, `contact`, `channel`, `status`, `end_reason` Os valores de `channel`, `status` e `end_reason` vêm em código (por exemplo `phone`, `completed`, `user_hangup`). Se o filtro tiver mais de 5000 chamadas, a mensagem final indica quantas foram exportadas — use um intervalo de datas mais curto para obter o resto. ::callout{type="info"} As chamadas e as transcrições não podem ser eliminadas no backoffice. Se precisar de apagar o áudio de uma chamada (por exemplo, a pedido do cliente), um Proprietário ou Administrador pode [eliminar a gravação](https://docs.diska.ai/pt/history/recordings#eliminar) . :: Para integrar o histórico no seu CRM, use a [API da DISKA](https://docs.diska.ai/pt/api/api-channel) ou os [webhooks](https://docs.diska.ai/pt/api/webhooks). # Gravações Quando um agente grava chamadas, o áudio fica disponível no detalhe de cada chamada em **Históricos → Chamadas**, no topo do separador **Transcrição**. ## Que chamadas são gravadas Só são gravadas as chamadas de agentes com **Gravar chamadas** activo. Essa opção só pode ser ligada depois de escolher o tipo de consentimento e escrever a mensagem que o agente diz ao cliente. Veja como configurar em [Gravar chamadas](https://docs.diska.ai/pt/guides/record-calls). Com a gravação activa, ficam gravadas: - as chamadas do widget no seu site e do link público; - as chamadas telefónicas, recebidas ou efectuadas, incluindo a chamada telefónica de teste do painel do agente. Numa chamada telefónica ficam gravados os **primeiros 27 minutos**. A chamada web de teste no painel do agente não é gravada. As chamadas feitas antes de activar a gravação também não. ## Ouvir e descarregar Abra a chamada e o separador **Transcrição**. Se houver áudio disponível, o leitor permite: - reproduzir e pausar, e clicar na barra para saltar para outro ponto; - mudar a velocidade de reprodução (botão com a velocidade actual); - **Descarregar gravação** (ícone de download) — guarda o ficheiro de áudio. Por baixo do leitor: **Gravação da chamada**, o tamanho do ficheiro e a data em que será eliminada automaticamente («Eliminada automaticamente a …»). ::callout{type="info"} O endereço de reprodução e de download é temporário: expira cinco minutos depois de abrir o separador **Transcrição** . Se a reprodução ou o download falharem depois de algum tempo com o painel aberto, feche e volte a abrir a chamada. :: ## Estados da gravação | O que vê | Significado | | ----------------------------------------------------- | --------------------------------------------------------------------------------------------- | | O leitor de áudio | **Gravação disponível** — pode ouvir e descarregar. | | **Falha na gravação** | «O áudio desta chamada não chegou a ser guardado.» Pode aparecer também o motivo técnico. | | **Gravação expirada** | «O áudio foi eliminado automaticamente pelo período de retenção.» | | **Gravação eliminada** | «O áudio foi eliminado permanentemente.» — alguém da organização eliminou-o. | | Nada | A chamada não foi gravada (o agente não gravava nessa altura, ou é uma chamada web de teste). | | «Não foi possível carregar a gravação desta chamada.» | A informação da gravação não pôde ser obtida agora. Tente mais tarde. | Em todos os casos, a transcrição e o resto do registo da chamada mantêm-se. ## Retenção Cada gravação tem um prazo, findo o qual o áudio é eliminado automaticamente e a chamada passa a mostrar **Gravação expirada**. - **Período da organização** — o máximo para toda a organização. Por omissão são 90 dias; para o alterar, contacte a Diska. - **Retenção desta gravação** — nas definições de gravação do agente pode escolher um período mais curto: **7 dias**, **30 dias**, **90 dias**, **180 dias** ou **365 dias**, ou **Usar o período da organização**. O agente só pode encurtar o período da organização, nunca alargá-lo; um valor maior fica limitado ao da organização. O prazo é fixado no momento em que a gravação é guardada. Alterar a retenção depois só afecta as gravações seguintes. ## Eliminar Proprietários e Administradores vêem no leitor o ícone **Eliminar gravação**. Ao clicar: - o áudio é apagado **de imediato**, sem pedido de confirmação, e não pode ser recuperado; - a chamada passa a mostrar **Gravação eliminada**; - a transcrição, as acções e os dados extraídos mantêm-se. Use esta opção, por exemplo, para responder a um pedido de um cliente para apagar a gravação da sua chamada. Os outros perfis podem ouvir e descarregar, mas não eliminar. # Análises A página **Análises** (menu **Análises**) agrega as chamadas de [Históricos → Chamadas](https://docs.diska.ai/pt/history/calls) num período. Está disponível para todos os perfis que vêem os Históricos. ## Filtros | Filtro | Opções | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Tipo de agente | **Todos os tipos**, **Recebidas** ou **Efectuadas**. Filtra pelo tipo do agente (agentes de chamadas recebidas ou de chamadas efectuadas), não pela direcção de cada chamada. | | Agente | **Todos os agentes** ou um agente específico. | | Período | **Diário** (últimas 24 horas), **Semanal** (últimos 7 dias) ou **Mensal** (últimos 30 dias). | Cada métrica é comparada com o período anterior de igual duração (por exemplo, os 7 dias antes dos últimos 7). A variação aparece em percentagem; quando o período anterior não tem dados, aparece «—». Sem chamadas no período, a página mostra «Ainda sem dados para analisar». ## Cartões | Cartão | O que mostra | | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Acções executadas** | Quantas vezes cada acção correu durante as chamadas (**Utilização**) e a evolução diária. Escolha a acção na lista — por exemplo **Agendamento**, **Transferência de chamada**, **SMS durante a chamada**, **SMS pós-chamada**, **Acção personalizada**, **Extractor de informação** ou **Avaliação personalizada**. | | **Sentimento** | **Interacções positivas**: a percentagem de chamadas com tom positivo, sobre as chamadas classificadas («N de M chamadas analisadas»), com a repartição Positivo / Neutro / Negativo. O tom é classificado no fim de cada chamada. | | **Desempenho dos agentes** | Ranking dos agentes por **Minutos**, **Chamadas** ou **Conclusão técnica** (percentagem de chamadas com estado Concluída), com a variação face ao período anterior. | | **Estatísticas de chamadas** | **Total de chamadas**, **Total de minutos**, **Duração média** e o gráfico **Chamadas por dia**. | | **Chamadas falhadas** | As chamadas mais recentes com estado Falhou (até 20). Clique numa linha para abrir a chamada em Históricos. | | **Estado das chamadas** | Repartição por estado final: Concluída, Falhou, Cancelada, Abandonada, Em progresso. | | **Motivo de fim de chamada** | Repartição por motivo de fim (Cliente desligou, Agente terminou, Terminada por silêncio…). | ## Exportar CSV **Exportar CSV** descarrega `analises--AAAA-MM-DD.csv` com os mesmos filtros e período que está a ver, em secções: - **Resumo** — período, chamadas, minutos e duração média, com a variação; - **Chamadas por dia** — chamadas e minutos por dia; - **Estado das chamadas**; - **Motivo de fim**; - **Desempenho por agente** — chamadas e minutos por agente. ## O que conta - Todas as chamadas registadas em Históricos, incluindo as chamadas de teste feitas no painel do agente — tenha isso em conta ao ler os números de um período com muitos testes. - As conversas de WhatsApp não entram nas Análises. - A duração vem do início e do fim de cada chamada. Os mesmos números estão disponíveis por API — ver [API da DISKA](https://docs.diska.ai/pt/api/api-channel). # Históricos e análises Tudo o que os agentes fazem fica registado. O backoffice organiza esses registos em três sítios do menu lateral: | Menu | O que encontra | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | **Visão geral** | A página inicial: o resumo dos últimos sete dias ou, numa organização nova, os primeiros passos. | | **Históricos** | **Chamadas** — cada chamada com transcrição, acções, dados extraídos, avaliações e gravação. **WhatsApp** — as conversas do canal WhatsApp. | | **Análises** | Métricas por período, agente e tipo de agente, com exportação para CSV. | ## Que chamadas aparecem Em **Históricos → Chamadas** ficam todas as chamadas dos agentes da organização: - chamadas web feitas no painel de teste do agente; - chamadas do widget no seu site e do link público; - chamadas telefónicas recebidas e efectuadas pelos números da organização, incluindo a chamada telefónica de teste do painel do agente. As conversas de WhatsApp têm a sua própria lista em **Históricos → WhatsApp** e não contam nas **Análises** — ver [Conversas WhatsApp](https://docs.diska.ai/pt/whatsapp/conversations). ## Permissões | Acção | Proprietário / Administrador | Membro | Visualizador | | ----------------------------------------------- | :--------------------------: | :----: | :----------: | | Ver Visão geral, chamadas, gravações e análises | ✓ | ✓ | ✓ | | Exportar CSV | ✓ | ✓ | ✓ | | Eliminar uma gravação | ✓ | — | — | As chamadas e as transcrições não podem ser eliminadas a partir do backoffice. Só o áudio das gravações pode ser eliminado — ver [Gravações](https://docs.diska.ai/pt/history/recordings). ## Nesta secção ::card-group :::card --- description: O resumo da semana e a lista de primeiros passos. icon: i-lucide-layout-dashboard title: Visão geral to: https://docs.diska.ai/pt/history/dashboard --- ::: :::card --- description: Filtrar, abrir o detalhe de uma chamada e exportar CSV. icon: i-lucide-phone-call title: Chamadas to: https://docs.diska.ai/pt/history/calls --- ::: :::card --- description: Ouvir, descarregar e eliminar o áudio das chamadas. icon: i-lucide-audio-lines title: Gravações to: https://docs.diska.ai/pt/history/recordings --- ::: :::card --- description: Volume, duração, sentimento, acções e desempenho por agente. icon: i-lucide-chart-line title: Análises to: https://docs.diska.ai/pt/history/analytics --- ::: :: # Ligar o número A ligação faz-se em **Definições → Integrações**, na secção **WhatsApp**. Só Proprietários e Administradores vêem esta página. Não precisa de copiar tokens nem identificadores: autoriza a Diska numa janela da Meta e a plataforma valida o resto. ## Ligar o primeiro número 1. Em **Definições → Integrações**, na secção **WhatsApp**, clique em **Ligar WhatsApp**. 2. Em **Agente para novas conversas**, escolha o agente que vai responder. Só aparecem agentes do Prompt Builder com versão publicada; se não houver nenhum, aparece **Publique um agente primeiro**. 3. Clique em **Preparar ligação** e, depois, em **Continuar na Meta**. 4. Na janela da Meta, entre com a sua conta e escolha a empresa, a conta WhatsApp Business e o número a ligar. Se a janela não abrir, permita pop-ups para o backoffice da Diska e tente de novo. 5. Ao fechar a janela, a Diska valida a autorização (**A validar ligação…**). No fim aparece **WhatsApp ligado** — «Número validado e agente associado.» Conclua a autorização na Meta sem interrupções: se demorar demasiado, a preparação expira e tem de recomeçar. Para ligar mais números, use **Ligar outro número**. Cada número só pode pertencer a uma organização Diska. ## O cartão da ligação Cada número ligado tem um cartão. No topo, sempre visíveis: | Campo | Descrição | | ----------------------------------- | ----------------------------------------------------------------------------------------------------------- | | **Número** e **nome apresentado** | O número que os clientes vêem e o nome verificado na Meta. | | **Estado** | O estado da ligação, à direita (ver abaixo). | | **Agente das mensagens** | O agente que atende as novas conversas. | | **Webhook** | **Ligado**, **Falhou** ou **Por validar** — se a Meta está a enviar as mensagens deste número para a Diska. | | **Ligado desde** / **Desligado em** | Data da ligação ou da desligação. | Quando há algo a resolver, aparece logo abaixo: o alerta do estado, com **Repetir subscrição do webhook** quando o webhook falhou e a ligação o permite, e a lista **Por resolver antes de atender clientes** — por exemplo «Associar um agente publicado em Prompt Mode» ou «Confirmar o registo e a verificação do número». Seguem-se os botões do número, como **Alterar agente** e **Desligar**. O resto do cartão está dividido em secções que se abrem com um clique: - **Chamadas de voz** — activar as chamadas e escolher o agente que as atende. O título mostra **Activas** ou **Desligadas**. Veja [Chamadas de voz](https://docs.diska.ai/pt/whatsapp/calls). - **Templates de mensagem** — os templates aprovados na Meta. Veja [Templates](https://docs.diska.ai/pt/whatsapp/templates). - **Diagnóstico técnico**— o título mostra a saúde operacional. Dentro estão o estado da credencial, a última mensagem recebida, a última resposta enviada, o último evento de entrega, a fila de envios e os identificadores WABA e Phone Number ID, com os botões: - **Validar com a Meta** — consulta a Meta e actualiza o estado. Não envia mensagens nem altera o número ou a credencial. - **Actualizar estado** — recarrega o cartão. - **Ver histórico** — abre **Históricos → WhatsApp**. ## Estados da ligação | Estado | Significado | O que fazer | | --------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | | **Activo** | As mensagens recebidas vão para o agente e as respostas seguem por este número. | Nada. | | **Configuração incompleta** | Faltam passos antes de atender clientes. | Veja a lista **Por resolver antes de atender clientes**. | | **Requer atenção** | A ligação funciona, mas há alertas por resolver (por exemplo, envios com falha). | Veja os alertas no cartão e as conversas afectadas. | | **Webhook com falha** | A Meta não está a enviar as mensagens deste número para a Diska. | Clique em **Repetir subscrição do webhook**. | | **Número indisponível** | O número não está registado ou verificado na Meta. | Conclua a verificação no WhatsApp Manager e use **Reconectar**. | | **Autorização expirada** | A credencial da Meta expirou ou é inválida. | Use **Reconectar**. | | **Autorização removida** | A autorização foi removida na Meta. | Use **Reconectar**. O histórico foi preservado. | | **Desligação pendente** | O atendimento já está desactivado na Diska, mas a Meta ainda não confirmou. | Use **Concluir desligação** ou **Reconectar**. | | **Só chamadas** | As mensagens estão desligadas neste número, mas as chamadas de voz estão activas. | Nada, se for intencional. Para voltar a atender mensagens, use **Reconectar**. | | **Desligado** | Sem atendimento nem envios por este número. | Pode reconectar quando quiser; o histórico foi preservado. | ## Enviar uma mensagem de teste **Mensagem de teste** envia uma mensagem pelo número ligado sem criar conversa nem alterar o atendimento do agente. 1. Indique o **Número de destino** em formato internacional (por exemplo `+244 923 456 789`). 2. Escolha: - **Texto de teste** — envia «Mensagem de teste da Diska: este número WhatsApp está ligado e pronto a responder.» Só é entregue se esse número escreveu para o WhatsApp ligado nas últimas 24 horas. Envie primeiro um «Olá» desse telemóvel. - **Template aprovado** — um template de utilidade aprovado e sem variáveis. 3. Confirme que o número é da sua equipa ou aceitou receber a mensagem e clique em **Enviar teste**. O resultado passa por **A enviar**, **Aceite pela Meta, a aguardar entrega**, **Enviada pela Meta**, **Entregue** e **Lida**; ou **Falhou** / **Envio por confirmar**. Se a Meta não confirmar o envio, verifique o telemóvel antes de repetir. Há um limite de testes por hora. ## Alterar o agente **Alterar agente** escolhe outro agente publicado do Prompt Builder. O novo agente atende as **novas** conversas; as conversas já iniciadas mantêm o agente e o contexto actuais. ## Reconectar, trocar de número e desligar - **Reconectar** renova a autorização e restaura o webhook. Na Meta, seleccione **o mesmo número**. A ligação, as conversas e o histórico ficam preservados. - **Trocar de número**: ligue o novo número com **Ligar outro número** e depois desligue o anterior. O histórico do anterior fica preservado. - **Desligar** desactiva o atendimento automático e os envios por esse número. Os envios pendentes são bloqueados e não são retomados automaticamente; uma mensagem que esteja a ser enviada tem de terminar primeiro. O histórico fica preservado e pode reconectar mais tarde. ## Erros frequentes | Mensagem | O que fazer | | ------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | «Ligação cancelada. Pode voltar a tentar quando quiser.» | A janela da Meta foi fechada antes do fim. Volte a tentar. | | «A autorização não terminou a tempo. Volte a ligar o WhatsApp.» / «Esta autorização expirou. Inicie novamente a ligação.» | Recomece em **Preparar ligação** e conclua a autorização na Meta de seguida. | | «Não foi possível abrir a Meta. Verifique a ligação e os bloqueadores do navegador.» | Permita pop-ups e desactive bloqueadores para o backoffice. | | «Escolha uma conta Cloud API com um número. Coexistência e migrações ainda não são suportadas neste fluxo.» | Use um número na Cloud API que não esteja em uso na app WhatsApp Business. | | «Este número ou conta WhatsApp já está associado a outra organização. Contacte a Diska.» | Cada número só pode estar numa organização. | | «Este número já está ligado. Use Reconectar na conexão existente.» | Use **Reconectar** no cartão do número. | | «Conclua a verificação do número no WhatsApp Manager e volte a ligar.» | Verifique o número na Meta e tente de novo. | | «Autorize a gestão da conta WhatsApp e o envio de mensagens na Meta.» | Na janela da Meta, aceite todas as permissões pedidas. | | «Escolha um agente em Prompt Mode com uma versão publicada.» | Publique um agente do Prompt Builder e escolha-o. | Para outros erros, a mensagem indica se o histórico foi preservado; tente novamente ou contacte a Diska. # Templates Fora da janela de 24 horas — ou para contactar um cliente que nunca escreveu — o WhatsApp só permite enviar **templates**: mensagens previamente aprovadas pela Meta. Na Diska, os templates são enviados pela equipa, numa conversa, e só para clientes com consentimento registado para a categoria do template. ## Criar templates Os templates criam-se e submetem-se para aprovação no **WhatsApp Manager** da Meta, na conta WhatsApp Business ligada. A Diska não cria nem edita templates: importa-os da Meta. Para poderem ser enviados pela Diska, os templates têm de cumprir estas regras: | Regra | Detalhe | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Categoria | **Notificações de serviço** (Utility) ou **Marketing**. Templates de **Autenticação** não podem ser enviados. | | Formato | Só texto: cabeçalho de texto (opcional), corpo (obrigatório) e rodapé (opcional, sem variáveis). Botões e cabeçalhos com imagem, vídeo ou documento ainda não são suportados. | | Variáveis | Todas com nome (`{{nome}}`) ou todas numeradas por ordem (`{{1}}`, `{{2}}`, …). Só no cabeçalho e no corpo. | | Exemplo da Meta | O template de exemplo da Meta pode ser consultado, mas não enviado. Use um template próprio aprovado. | ## Sincronizar Cada número ligado tem, em **Definições → Integrações → WhatsApp**, a secção **Templates de mensagem**. Abra-a para ver os templates. 1. Depois de criar ou alterar templates na Meta, clique em **Sincronizar com Meta** (Proprietário ou Administrador). 2. Expanda um template para ver a pré-visualização, a categoria, a data de sincronização e as variáveis. Estados possíveis: **Aprovado**, **Em análise**, **Rejeitado**, **Em pausa**, **Desactivado**, **Removido**. Só os templates **Aprovado** e em formato suportado aparecem para envio. Os restantes mostram «Consulta disponível. Este formato ainda não pode ser enviado pela Diska.» O estado e o conteúdo são confirmados novamente na Meta antes de cada envio. ## Consentimento Receber uma mensagem do cliente abre a janela de resposta, mas **não** autoriza contactos futuros. Antes de enviar um template, registe o consentimento do cliente para a categoria do template, no painel **Consentimento para iniciar contacto** da conversa — ver [Conversas](https://docs.diska.ai/pt/whatsapp/conversations#consentimento). Sem consentimento registado, o envio é recusado: «É necessário registar consentimento para esta categoria antes de enviar.» ## Enviar um template 1. Abra a conversa em **Históricos → WhatsApp** (ou crie-a com **Iniciar contacto**) e **assuma o atendimento** — só o operador responsável pela conversa pode enviar. 2. No rodapé da conversa: - com a janela de 24 horas fechada, aparece directamente o formulário de template; - com a janela aberta, escolha **Template** (em vez de **Mensagem**). 3. Em **Template aprovado**, escolha o template. O conteúdo e o idioma são enviados tal como aprovados pela Meta. 4. Preencha cada **Variável** — até 500 caracteres, sem quebras de linha. 5. Confira a **Pré-visualização** e clique em **Enviar template**. Se a confirmação do envio não chegar, o botão passa a **Confirmar envio pendente**: ao repetir, é usada a mesma identificação e a mensagem não é enviada duas vezes. Se não houver templates aprovados, aparece «Sem templates de texto aprovados. Sincronize em Definições → Integrações → WhatsApp.» ## Erros frequentes | Mensagem | O que fazer | | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | «É necessário consentimento registado para a categoria deste template.» | Registe o consentimento do cliente para essa categoria. | | «O template não está aprovado ou precisa de nova sincronização com a Meta.» | Confirme o estado na Meta e sincronize. | | «O template foi alterado. Actualize a lista e confirme novamente a pré-visualização.» | O template mudou na Meta: sincronize e reveja antes de enviar. | | «Preencha todas as variáveis, com até 500 caracteres e sem quebras de linha.» | Corrija os valores das variáveis. | | «Este formato de template ainda não pode ser enviado pela Diska.» | Crie uma versão só com texto. | | «O envio de templates não está disponível neste momento.» | O envio de templates está temporariamente indisponível. Tente mais tarde. | | «Não foi possível sincronizar com a Meta. O catálogo anterior foi preservado.» | Tente sincronizar mais tarde. | # Conversas As conversas de WhatsApp ficam em **Históricos → WhatsApp** (página **Conversas WhatsApp**). Aqui acompanha o que a IA está a responder, assume conversas e responde ao cliente na mesma conversa. ## A lista Cada linha mostra o número do cliente, a hora da última mensagem, o agente e quem está a atender, a última mensagem e etiquetas com o estado do atendimento, o estado operacional, a entrega e as mensagens **por ler**. A lista actualiza-se sozinha a cada 15 segundos; use **Actualizar** para forçar. Filtros: | Filtro | Opções | | ---------------------- | ----------------------------------------------------------------------------------- | | **Agente** | Todos os agentes ou um agente. | | **Conexão / número** | Todos os números ou um número ligado. | | **Conversa** | **Abertas** ou **Encerradas**. | | **Atendimento** | **Em atendimento pela IA**, **Aguardando humano**, **Com operador**, **Resolvida**. | | **Estado operacional** | **Falhas**, **Entregas incertas**, **Pendentes**, **Bloqueadas**. | | **Desde** / **Até** | Intervalo de datas. | As conversas de WhatsApp não aparecem em **Históricos → Chamadas** nem contam nas Análises. ## Estados do atendimento | Estado | Quem responde | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Em atendimento pela IA** | O agente responde automaticamente. | | **Aguardando humano** | A IA está em pausa e a conversa aguarda um operador. Acontece quando o agente pede atendimento humano (o motivo aparece como **Motivo:**) ou quando o cliente volta a escrever numa conversa resolvida. | | **Com operador** | Um membro da equipa assumiu a conversa; a IA está em pausa. | | **Resolvida** | Atendimento concluído; o histórico fica preservado. | ## Assumir e devolver o atendimento No topo da conversa, o bloco de gestão do atendimento mostra quem está responsável e os botões disponíveis: - **Assumir atendimento** — passa a conversa para si (**Com operador**) e põe a IA em pausa. - **Reatribuir a mim** — Proprietários e Administradores podem assumir uma conversa que está com outro operador. - **Devolver à IA** — o agente volta a responder. - **Resolver conversa** — fecha o atendimento. - **Reabrir e assumir** — reabre uma conversa resolvida e atribui-a a si. Só o operador responsável (ou um Proprietário ou Administrador) pode devolver ou resolver uma conversa que está **Com operador**. Quem tem a função Visualizador vê o histórico, mas não pode responder. ## Responder Para responder, a conversa tem de estar **Com operador** e atribuída a si. ### A janela de 24 horas A etiqueta no topo da conversa indica o que pode enviar: - **Janela de atendimento ativa** — o cliente escreveu nas últimas 24 horas. Pode enviar mensagens livres até à hora indicada («Pode responder até …»). - **Template necessário** — passaram mais de 24 horas desde a última mensagem do cliente, ou ele nunca escreveu. Só pode enviar um [template aprovado](https://docs.diska.ai/pt/whatsapp/templates), com consentimento. ### Enviar uma mensagem 1. Escreva em **Resposta ao cliente** (até 4096 caracteres; 1024 com anexo). 2. Opcionalmente, use **Anexar ficheiro**. 3. Clique em **Enviar**. | Anexo | Formatos | Tamanho máximo | | --------- | ----------------------- | ----------------- | | Imagem | JPG, PNG | 5 MB | | Documento | PDF | 10 MB | | Texto | TXT | 1 MB | | Áudio | MP3, M4A, OGG, AAC, AMR | 16 MB e 5 minutos | O áudio é enviado sem legenda; envie o texto numa mensagem separada. PDFs com conteúdo activo são recusados — exporte uma cópia simples. Se a confirmação do envio não chegar, o botão passa a **Confirmar envio**: ao repetir, é usada a mesma identificação e o cliente não recebe a mensagem duas vezes. ## Mensagens e anexos Cada mensagem mostra o remetente (**Cliente**, **Agente IA**, **Operador · nome** ou **Sistema**), a hora e o estado: **Recebida**, **A enviar**, **Enviada**, **Entregue**, **Lida**, **Falhou**, **Entrega incerta**, **Bloqueada** ou **Tipo não suportado**. Em **Dados da mensagem** encontra o ID da Meta e as horas de recepção e envio. - Os anexos do cliente abrem com **Abrir anexo** (imagem, áudio ou documento para descarregar). - Se a IA não conseguir interpretar um anexo, aparece «Anexo disponível para o operador. A IA não conseguiu interpretar o conteúdo.» — assuma a conversa e responda. - Os anexos ficam guardados durante um período limitado. Depois, aparece «O prazo de conservação deste anexo terminou.», mas o registo da mensagem mantém-se. - Tipos de mensagem que a Diska ainda não processa (por exemplo, vídeo ou localização) aparecem como «Este tipo de mensagem ainda não é suportado.» ## Consentimento O painel **Consentimento para iniciar contacto** mostra, por categoria (**Notificações de serviço**, **Marketing**, **Autenticação**), se o cliente autorizou contactos iniciados pela empresa. Receber uma mensagem do cliente abre a janela de resposta, mas não conta como autorização. Para registar uma autorização: 1. Clique em **Registar autorização**. 2. Escolha a **Categoria autorizada** e a **Origem**: **Confirmação escrita**, **Formulário web**, **Contrato**, **Autorização verbal registada** ou **Teste controlado autorizado**. 3. Indique a **Data e hora do consentimento ou revogação**, a **Finalidade** e a **Evidência** (onde a autorização ficou registada — sem credenciais nem dados sensíveis). 4. Confirme a declaração e clique em **Guardar registo**. **Registar revogação** bloqueia novos templates de todas as categorias. **Ver registos** mostra o histórico de autorizações e revogações. Se o cliente escrever um pedido explícito para não receber mais mensagens — por exemplo «STOP», «Sair», «Parar mensagens» ou «Não quero receber mais mensagens» — a Diska regista automaticamente a revogação, com a origem **Pedido do cliente no WhatsApp**. ## Iniciar contacto Para escrever a um cliente que ainda não tem conversa: 1. Em **Históricos → WhatsApp**, clique em **Iniciar contacto**. 2. Escolha o **Número da empresa** e indique o **WhatsApp do cliente** com o indicativo (por exemplo `+244…`). 3. Clique em **Abrir conversa**. Abrir o contacto não envia nada. A conversa abre já atribuída a si: registe o consentimento e envie um [template aprovado](https://docs.diska.ai/pt/whatsapp/templates#enviar-um-template). Se já existir uma conversa com esse número, a Diska abre o mesmo histórico. ## Actividade e diagnóstico - **Atividade do atendimento** — quem assumiu, devolveu, resolveu ou reabriu a conversa, e quando. - **Diagnóstico operacional** (Proprietário e Administrador) — tentativas de envio, falhas e eventos de entrega. Os envios incertos não são reenviados automaticamente; depois de investigar uma falha, use **Registar análise** para a documentar. ## Erros frequentes | Mensagem | O que fazer | | --------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | | «Assuma esta conversa antes de responder.» | Clique em **Assumir atendimento**. | | «Esta conversa está atribuída a outro operador.» | Peça ao operador ou a um Proprietário ou Administrador para a reatribuir. | | «A janela de resposta terminou. Use um template aprovado com consentimento ou aguarde uma mensagem do cliente.» | Envie um template. | | «O atendimento mudou entretanto. Actualize a conversa e tente novamente.» | Outra pessoa alterou a conversa: clique em **Actualizar**. | | «Foram enviadas várias mensagens seguidas. Aguarde um minuto.» | Aguarde e volte a enviar. | | «O formato ou tamanho do ficheiro não é suportado.» | Veja a tabela de anexos acima. | | «A conexão WhatsApp está desactivada.» | O número foi desligado — ver [Ligar o número](https://docs.diska.ai/pt/whatsapp/connect). | # Chamadas de voz Com as **chamadas de voz WhatsApp**, o cliente toca no ícone de chamada na conversa com a sua empresa e é atendido por um agente da Diska. É como uma [chamada telefónica](https://docs.diska.ai/pt/telephony/phone-calls): o agente usa a versão publicada, com a mesma voz, as mesmas regras, a mesma [base de conhecimento](https://docs.diska.ai/pt/knowledge-base) e as mesmas acções. Se for preciso, passa a chamada a uma pessoa da equipa. ::callout{type="info"} Esta página trata das **chamadas de voz** . Para as mensagens de texto, veja [WhatsApp](https://docs.diska.ai/pt/whatsapp) . :: ## Como funciona 1. O cliente abre a conversa com a sua empresa no WhatsApp e toca no ícone de chamada. 2. A Meta encaminha a chamada para a Diska e o agente atende. 3. A conversa decorre como numa chamada telefónica. Quando a condição de uma acção de transferência se verifica, o agente [passa a chamada a uma pessoa](https://docs.diska.ai/#transferir-para-uma-pessoa). 4. A chamada fica registada em **Históricos → Chamadas**, com o canal **WhatsApp**. Para o cliente, é uma chamada WhatsApp normal, feita pela ligação à internet. Só há chamadas **recebidas**: o agente não liga para os clientes pelo WhatsApp. ## Requisitos - O número WhatsApp Business ligado à Diska, na **Cloud API** da Meta. Veja [Ligar o número](https://docs.diska.ai/pt/whatsapp/connect). - O limite de mensagens que a Meta exige para chamadas: pelo menos **2000 destinatários únicos por dia** nesse número. Este limite é atribuído pela Meta, consoante o volume e a qualidade das suas conversas. - Um agente **Inbound** activo e com versão publicada para atender as chamadas. - Para transferir para uma pessoa: a organização autorizada a fazer chamadas de saída e um número DISKA da organização para identificar as transferências. - A função **Proprietário** ou **Administrador** na organização Diska para activar as chamadas. ## Activar as chamadas As chamadas activam-se em **Definições → Integrações**, na secção **WhatsApp**: no cartão do número, abra **Chamadas de voz**. 1. Em **Agente que atende as chamadas**, escolha o agente. Só aparecem agentes Inbound activos e com versão publicada. 2. Opcional: em **Número DISKA para transferências**, escolha o número que aparece a quem recebe uma chamada transferida. Para não transferir, deixe **Sem transferências**. 3. Clique em **Guardar alterações**. 4. Clique em **Activar chamadas** e confirme. A Diska configura as chamadas do número na Meta, o que pode demorar alguns segundos. O título da secção passa a mostrar **Activas**, e o texto indica o número. A partir daí, os clientes vêem o ícone de chamada na conversa com a sua empresa. Para deixar de receber chamadas, clique em **Desactivar chamadas** e confirme. Os clientes deixam de poder ligar para esse número pelo WhatsApp; as mensagens continuam como estão. Enquanto as chamadas estiverem activas, pode mudar o agente, mas não retirá-lo. ::callout{type="info"} Se a secção **Chamadas de voz** não aparecer no cartão do número, as chamadas WhatsApp ainda não estão disponíveis para a sua organização. Fale com a Diska. :: ### Se a activação falhar | Mensagem | O que fazer | | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | «A Meta não activou as chamadas neste número. Confirme os requisitos: número na Cloud API e limite de pelo menos 2000 destinatários únicos por dia.» | O número ainda não cumpre os requisitos da Meta. Tente de novo quando a Meta aumentar o limite de mensagens do número. | | «As chamadas deste número já estão ligadas a outro serviço na Meta. Desligue-as no WhatsApp Manager e tente de novo.» | A Diska nunca substitui outra configuração de chamadas. Desligue-a primeiro e active de novo. | | «Reconecte o número WhatsApp antes de activar as chamadas.» | A ligação do número precisa de ser renovada. Veja [Ligar o número](https://docs.diska.ai/pt/whatsapp/connect). | | «Escolha primeiro o agente que atende as chamadas.» | Escolha e guarde o agente antes de activar. | | «A Meta não aceitou a configuração de áudio das chamadas. As chamadas ficaram desligadas; contacte a Diska.» | Contacte a Diska. As chamadas ficam desligadas, para nenhum cliente ouvir uma chamada falhada. | ## Que agente atende O agente das chamadas é independente do **Agente para novas conversas**, que responde às mensagens. Um número pode ter um agente para as mensagens e outro para as chamadas, ou o mesmo agente nos dois. Mudar um não muda o outro. Tem de ser um agente **Inbound**, activo e com versão publicada. Uma alteração ao agente só chega às chamadas WhatsApp depois de a [publicar](https://docs.diska.ai/pt/guides/publish-agent). | Disponível numa chamada WhatsApp | Não disponível | | ---------------------------------------- | ------------------------------------------------------------- | | Pesquisa na base de conhecimento | Tratamento IVR e teclas (DTMF) | | Acções personalizadas | Transferências para SIP URIs, números fixos ou internacionais | | Marcações em tempo real | Chamadas feitas pelo agente (agentes Outbound e Campanhas) | | Transferências para telemóveis angolanos | | ## Transferir para uma pessoa A Meta não permite transferir uma chamada WhatsApp para outro número. Por isso, o cliente **fica na mesma chamada**: a Diska liga para a pessoa e junta-a à conversa. 1. O agente decide transferir, quando a condição da acção se verifica, e avisa o cliente. 2. O cliente ouve o sinal de chamada enquanto o telemóvel da pessoa toca, até 30 segundos. 3. Quando a pessoa atende, fala com o cliente na mesma chamada WhatsApp e o agente sai. 4. Se a pessoa não atender, estiver ocupada ou rejeitar, o cliente volta ao agente, que diz «Infelizmente o número está indisponível neste momento.» e continua a conversa. A transferência usa as [acções de transferência](https://docs.diska.ai/pt/actions/call-transfers) e o [nó de transferência](https://docs.diska.ai/pt/nodes/transfer) que já tem, com as regras de um número DISKA: - **Destino:** só telemóveis angolanos (Africell ou Unitel), com o número fixo na acção, no nó ou numa **Lista telefónica**. Um número dito durante a conversa nunca é usado. - **Autorização:** a organização tem de estar autorizada a fazer chamadas de saída. A ligação ao telemóvel sai pela rede DISKA. - **Identificação:** quem atende vê o **Número DISKA para transferências** escolhido em **Chamadas de voz**, não o número WhatsApp do cliente. Sem esse número, as transferências não estão disponíveis nesse número WhatsApp. - **Modos assistidos:** a transferência assistida com mensagem e a assistida com resumo contextual ligam a chamada **directamente**. Quem atende não ouve o aviso antes. - **Horário:** o horário de disponibilidade da acção aplica-se como no telefone. Fora do horário, o agente diz a mensagem de indisponibilidade. - **Duração:** depois de transferida, a chamada pode durar até 1 hora. ## Limite de chamadas simultâneas As chamadas WhatsApp contam no [limite de chamadas simultâneas](https://docs.diska.ai/pt/telephony/concurrency) da organização, juntamente com as chamadas telefónicas. Com o limite atingido, as novas chamadas não são atendidas. ## Limitações - Só chamadas recebidas: o agente não liga para os clientes pelo WhatsApp. - Não há teclas (DTMF): o Tratamento IVR e os menus por teclas não funcionam. - As transferências só vão para telemóveis angolanos, e os modos assistidos ligam directamente. - Cada número WhatsApp tem um único agente para as chamadas. - A qualidade do áudio depende da ligação à internet do cliente. ## Perguntas frequentes **Posso usar o número WhatsApp que a empresa já usa, ou tem de ser um número da Diska?** Pode usar o seu próprio número, desde que esteja ligado à Diska na Cloud API e tenha o limite de 2000 destinatários únicos por dia. Se o número está hoje na app WhatsApp ou WhatsApp Business do telemóvel, tem de passar para a Cloud API, e deixa de poder ser usado na app. A coexistência (a app e a Cloud API no mesmo número) não serve, porque a Meta não permite chamadas pela API nesse modo. O número DISKA só é preciso para transferir as chamadas para uma pessoa. **O mesmo agente pode atender o telefone e o WhatsApp?** Sim. Um agente Inbound publicado pode atender números de telefone e números WhatsApp ao mesmo tempo. **Posso ter um agente nas mensagens e outro nas chamadas?** Sim, no mesmo número WhatsApp. **Posso mudar a voz, o idioma ou as instruções do agente?** Sim, como em qualquer agente. As chamadas WhatsApp usam a versão publicada. **Quem recebe a transferência vê o número do cliente?** Não. Vê o número DISKA definido para as transferências desse número WhatsApp. **Vejo o número de quem ligou?** Normalmente, sim. Quando a Meta só identifica o cliente pelo identificador do WhatsApp, a chamada aparece sem número. **O cliente paga a chamada?** Não é uma chamada telefónica: o WhatsApp usa a ligação à internet do cliente. **Onde vejo as chamadas?** Em **Históricos → Chamadas**, com o canal **WhatsApp**. ## Mais informação - [Transferências por telefone e SIP](https://docs.diska.ai/pt/telephony/transfers) - [Transferências de chamada](https://docs.diska.ai/pt/actions/call-transfers) - [Calling API do WhatsApp (Meta)](https://developers.facebook.com/docs/whatsapp/cloud-api/calling){rel=""nofollow""} # WhatsApp O canal **WhatsApp** liga um número da sua conta WhatsApp Business (Meta) à Diska. A partir daí: - **o agente responde automaticamente** às mensagens que os clientes enviam para esse número, por texto; - a equipa acompanha tudo em **Históricos → WhatsApp** e pode **assumir a conversa** a qualquer momento; - para iniciar ou retomar contacto fora da janela de 24 horas, a equipa envia **templates aprovados** pela Meta, com consentimento registado; - os clientes também podem **ligar** para o número e falar por voz com um agente: veja [Chamadas de voz](https://docs.diska.ai/pt/whatsapp/calls). ## Que agente responde Cada número ligado tem um **agente para novas conversas**. Tem de ser um agente criado com o **Prompt Builder** e com uma versão publicada — os agentes do Flow Designer não podem ser associados ao WhatsApp. O WhatsApp usa a **versão publicada** do agente, com a mesma personalidade, regras, [base de conhecimento](https://docs.diska.ai/pt/knowledge-base) e acções: | Disponível nas mensagens | Não se aplica às mensagens | | ---------------------------------------------------------------------------------------- | -------------------------- | | Pesquisa na base de conhecimento | Transferências de chamada | | Acções personalizadas | Tratamento IVR | | SMS e marcações em tempo real | | | Pedir atendimento humano (a IA fica em pausa e a conversa passa a **Aguardando humano**) | | O agente adapta-se ao canal escrito: mensagens curtas, uma pergunta de cada vez, sem referências a chamadas ou ao microfone. Quando o cliente envia uma imagem, um documento ou uma mensagem de voz, o agente tenta interpretá-lo; se não conseguir, o anexo fica disponível para a equipa. ## Requisitos - Uma conta WhatsApp Business na Meta com um número na **Cloud API**, registado e verificado no WhatsApp Manager. Números em coexistência com a app WhatsApp Business e migrações ainda não são suportados na ligação. - Um agente do Prompt Builder publicado. - A função **Proprietário** ou **Administrador** na organização Diska para ligar e gerir o número. ::callout{type="warning"} A ligação de novos números pela própria empresa pode ainda não estar aberta à sua organização. Nesse caso, em **Definições → Integrações** aparece **Novas ligações em preparação** com o motivo — por exemplo, «Onboarding de empresas externas a aguardar validação Meta.» — e o botão **Ligar WhatsApp** fica desactivado. Contacte a Diska para ligar o seu número. :: ## Permissões | Acção | Proprietário / Administrador | Membro | Visualizador | | ------------------------------------------------------------------------------------------------ | :--------------------------: | :----: | :----------: | | Ligar, reconectar e desligar números; alterar o agente; mensagem de teste; sincronizar templates | ✓ | — | — | | Ver as conversas | ✓ | ✓ | ✓ | | Assumir conversas, responder, enviar templates, registar consentimento, iniciar contacto | ✓ | ✓ | — | | Reatribuir a si uma conversa de outro operador; diagnóstico operacional | ✓ | — | — | ## Perguntas frequentes **Os clientes podem ligar para o agente pelo WhatsApp (chamada de voz)?** Sim, depois de activar as chamadas na secção **Chamadas de voz** do número, em **Definições → Integrações**. O agente atende por voz e pode transferir para um telemóvel da equipa. Veja [Chamadas de voz](https://docs.diska.ai/pt/whatsapp/calls). **O agente lembra-se no WhatsApp do que o cliente disse numa chamada?** Ainda não. A [Memória partilhada](https://docs.diska.ai/pt/knowledge-base/shared-memory) é só para chamadas telefónicas; cada conversa de WhatsApp guarda o seu próprio histórico em **Históricos → WhatsApp**. **Posso usar o mesmo agente no telefone e no WhatsApp?** Sim, se for um agente do Prompt Builder: a versão publicada responde nos dois canais, com as mesmas regras e a mesma base de conhecimento. ## Nesta secção ::card-group :::card --- description: Autorizar a Diska na Meta, estados da ligação e mensagem de teste. icon: i-simple-icons-whatsapp title: Ligar o número to: https://docs.diska.ai/pt/whatsapp/connect --- ::: :::card --- description: Sincronizar templates aprovados e enviá-los com consentimento. icon: i-lucide-file-text title: Templates to: https://docs.diska.ai/pt/whatsapp/templates --- ::: :::card --- description: Acompanhar a IA, assumir o atendimento e responder ao cliente. icon: i-lucide-messages-square title: Conversas to: https://docs.diska.ai/pt/whatsapp/conversations --- ::: :::card --- description: O cliente liga pelo WhatsApp e o agente atende, com transferência para a equipa. icon: i-lucide-phone-call title: Chamadas de voz to: https://docs.diska.ai/pt/whatsapp/calls --- ::: :: # Começar com a API A [API da DISKA](https://docs.diska.ai/pt/api/api-channel) é uma API REST para o seu servidor. Lê agentes, chamadas e transcrições, cria e publica agentes, alimenta bases de conhecimento e avisa o seu sistema quando uma chamada termina. Funciona a partir de qualquer ambiente que faça pedidos HTTPS. ::callout{type="info"} Para assistentes de IA e ferramentas de programação, toda a documentação está em texto simples em [`llms.txt`](https://docs.diska.ai/llms.txt){rel=""nofollow""} (índice) e [`llms-full.txt`](https://docs.diska.ai/llms-full.txt){rel=""nofollow""} (conteúdo completo). :: ## Base URL | Ambiente | Base URL | | -------- | ------------------------- | | Produção | `https://api.diska.ai/v1` | Há uma única base URL para todas as organizações, sempre em HTTPS. O prefixo `/api/v1` é a API interna do backoffice e não aceita chaves API. ## O que pode fazer | Grupo | O que faz | Endpoints | | ----------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | Identidade | Confirma a organização e a chave. | `GET /v1/me` | | Agentes | Lista, mostra, cria, edita e publica agentes. | `GET /v1/agents`, `GET /v1/agents/{agent_id}`, `POST /v1/agents`, `PATCH /v1/agents/{agent_id}`, `POST /v1/agents/{agent_id}/publish` | | Chamadas | Histórico com filtros, o detalhe de cada chamada (transcrição, acções executadas e resultado pós-chamada) e a gravação. | `GET /v1/calls`, `GET /v1/calls/{call_id}`, `GET /v1/calls/{call_id}/recording` | | Chamadas de saída | O agente liga a uma pessoa a pedido do seu sistema. | `/v1/outbound-calls` | | Campanhas | Chamadas de saída em lote, com janelas e limites. | `/v1/campaigns` | | Chat | Conversa por texto com um agente, com a resposta no mesmo pedido. | `/v1/chats` | | Análises | Volume, resultados, sentimento e desempenho por agente. | `GET /v1/analytics/overview` | | Números | Os números de telefone da organização. | `GET /v1/phone-numbers` | | Conhecimento | Cria bases de conhecimento e acrescenta texto, páginas web e PDF. | `GET /v1/knowledge-bases`, `POST /v1/knowledge-bases` e os endpoints de documentos | | Webhooks | Regista os endpoints que recebem os dados de cada chamada concluída. | `/v1/webhook-endpoints` | Os parâmetros, corpos, respostas e erros de cada endpoint estão em [Endpoints](https://docs.diska.ai/pt/api/endpoints). O que a API ainda não faz está em [O que a API da DISKA ainda não faz](https://docs.diska.ai/pt/api/api-channel#o-que-a-api-da-diska-ainda-n%C3%A3o-faz). ## Faça o seu primeiro pedido ### 1. Crie uma chave API 1. No backoffice, abra **Definições → Chaves API** (só proprietários e administradores). 2. Clique em **Criar nova chave API** e dê-lhe um nome, por exemplo «Teste da API». 3. Em **Âmbitos**, escolha **Agentes — leitura** e **Chamadas e transcrições** para seguir este guia. Sem nenhum âmbito, a chave tem acesso total. 4. Clique em **Gerar** e copie a chave (`dsk_…`). Só é mostrada esta vez. Guarde a chave numa variável de ambiente do seu servidor: ```bash export DISKA_API_KEY="dsk_…" ``` Mais detalhes em [Autenticação](https://docs.diska.ai/pt/api/authentication). ### 2. Confirme a chave `GET /v1/me` não precisa de âmbito e devolve a organização e a chave: ```bash curl https://api.diska.ai/v1/me \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```json { "organization": { "id": "…", "name": "A Minha Empresa", "slug": "a-minha-empresa" }, "key": { "id": "…", "name": "Teste da API", "key_preview": "dsk_a1b2…F5A4", "scopes": ["agents:read", "calls:read"], "expires_at": null, "created_at": "…", "last_used_at": "…" } } ``` Um `401` quer dizer que a chave falta, está errada, foi revogada ou expirou. Veja os [erros de autenticação](https://docs.diska.ai/pt/api/authentication#erros-de-autentica%C3%A7%C3%A3o). ### 3. Liste os agentes `GET /v1/agents` só lê dados e não tem parâmetros obrigatórios: ::code-group ```bash [cURL] curl https://api.diska.ai/v1/agents \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/agents", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() for agent in response.json()["items"]: print(agent["id"], agent["name"], agent["status"]) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/agents', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) const { items } = await response.json() for (const agent of items) console.log(agent.id, agent.name, agent.status) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status !== 200) { throw new RuntimeException("HTTP $status: $body"); } foreach (json_decode($body, true)['items'] as $agent) { echo $agent['id'], ' ', $agent['name'], ' ', $agent['status'], PHP_EOL; } ``` :: Resposta `200`: ```json { "items": [ { "id": "3f1c2a7e-…", "name": "Recepção", "slug": "recepcao", "description": null, "status": "active", "agent_type": "inbound", "editing_mode": "prompt", "version": 3, "phone_number": null, "public_channel_enabled": false, "created_at": "2026-10-22T19:14:00Z", "updated_at": "2026-10-25T18:40:00Z" } ] } ``` Os agentes arquivados só aparecem com `?status=archived`. Os campos estão descritos em [O objecto agente](https://docs.diska.ai/pt/api/endpoints#o-objecto-agente). ### 4. Leia as chamadas de um agente Com o `id` de um agente, peça as últimas chamadas dele: ```bash curl "https://api.diska.ai/v1/calls?agent_id=3f1c2a7e-…&limit=10" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` Cada chamada traz o canal, o estado, a duração, o resumo e quem ligou. O detalhe, com a transcrição, está em `GET /v1/calls/{call_id}`. Para exportar históricos grandes, use a [paginação por cursor](https://docs.diska.ai/pt/api/api-channel#pagina%C3%A7%C3%A3o). ::callout{type="tip"} O ID de um agente também aparece no backoffice: na página do agente, ao lado do nome, e em **Publicação → API** , com o botão de copiar. :: ## Próximos passos ::card-group :::card --- description: O seu sistema recebe os dados de cada chamada concluída, sem polling. icon: i-lucide-webhook title: Receber webhooks to: https://docs.diska.ai/pt/api/webhooks --- ::: :::card --- description: Crie bases de conhecimento e acrescente texto, páginas web e PDF. icon: i-lucide-book-open title: Alimentar o conhecimento to: https://docs.diska.ai/pt/api/endpoints#conhecimento --- ::: :::card --- description: 120 pedidos por minuto por chave, paginação por cursor e o formato dos erros. icon: i-lucide-gauge title: Paginação, limites e erros to: https://docs.diska.ai/pt/api/api-channel#limites-de-utilização --- ::: :::card --- description: Importe no Postman ou gere um cliente para a sua linguagem. icon: i-lucide-file-json title: Especificação OpenAPI to: https://docs.diska.ai/pt/api/api-channel#especificação-openapi --- ::: :::card --- description: Uma página por endpoint, com esquemas, exemplos em quatro linguagens e Experimentar. icon: i-lucide-book-marked title: Referência da API to: https://docs.diska.ai/pt/api/reference --- ::: :::card --- description: Sincronizar com o CRM, exportar o histórico e alimentar o conhecimento a partir do site. icon: i-lucide-map title: Guias to: https://docs.diska.ai/pt/api/guides --- ::: :: ## Perguntas frequentes **Posso iniciar chamadas ou campanhas pela API?** Sim: [chamadas de saída](https://docs.diska.ai/pt/api/reference/outbound-calls) e [campanhas](https://docs.diska.ai/pt/api/reference/campaigns), com agentes de saída publicados, dentro do horário de contacto. Como têm custo, a Diska activa-as para a organização a pedido. **Posso conversar com o agente pela API?** Por texto, sim: o [chat](https://docs.diska.ai/pt/api/reference/chats) devolve a resposta do agente no mesmo pedido (activado pela Diska a pedido). Por voz, use o widget, o link público, um número de telefone ou o WhatsApp. Veja [Tempo real](https://docs.diska.ai/pt/api/realtime). **Há um ambiente de testes?** Não há sandbox: a API trabalha sempre com os dados da organização da chave. Para testar, use um agente de teste e uma chave só com âmbitos de leitura. **Há SDK oficial?** Ainda não. Gere um cliente a partir da [especificação OpenAPI](https://docs.diska.ai/pt/api/api-channel#especifica%C3%A7%C3%A3o-openapi) ou use HTTP directamente, como nos exemplos acima. Para explorar a API sem escrever código, use a [colecção Postman](https://docs.diska.ai/pt/api/api-channel#postman) ou o **Experimentar** da [Referência da API](https://docs.diska.ai/pt/api/reference). **Como sei se a API está com problemas?** Veja [status.diska.ai](https://status.diska.ai){rel=""nofollow""}: mostra o estado da API, do backoffice e da telefonia, com os incidentes em curso. Pode subscrever as actualizações na própria página. **A API vai mudar?** Dentro da `/v1` só há alterações compatíveis. Veja [Versões e alterações](https://docs.diska.ai/pt/api/changelog). **Quantos pedidos posso fazer?** 120 por minuto, por chave. Acima disso, a API responde `429` com `Retry-After`. Veja [Limites de utilização](https://docs.diska.ai/pt/api/api-channel#limites-de-utiliza%C3%A7%C3%A3o). **Posso usar a chave no browser ou numa aplicação móvel?** Não. A chave dá acesso aos dados da organização: use-a só no seu servidor. # API da DISKA A API da DISKA é a interface REST pública da plataforma, pensada para integrações servidor-a-servidor: sincronizar chamadas e transcrições com o seu CRM, criar e publicar agentes, alimentar bases de conhecimento e receber [webhooks](https://docs.diska.ai/pt/api/webhooks) quando uma chamada termina, sem polling. ## Base URL ```text https://api.diska.ai/v1 ``` A API da DISKA vive em `/v1`. O prefixo `/api/v1` pertence à API interna do backoffice e não aceita chaves API. ## O que pode fazer | Recurso | Operações | Âmbito | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------- | | Identidade | Ver a organização e a chave por trás do token | — (qualquer chave válida) | | Agentes | Listar e ver agentes | `agents:read` | | Agentes | Criar um agente (em branco ou a partir de um modelo), editar o prompt, a saudação, a língua e as bases de conhecimento, e publicá-lo | `agents:write` | | Chamadas | Listar chamadas e ver o detalhe (transcrição, acções executadas, resultado pós-chamada) | `calls:read` | | Gravações | Descarregar a gravação de uma chamada | `recordings:read` | | Chamadas de saída | O agente liga a uma pessoa a pedido do seu sistema | `calls:write` | | Campanhas | Criar campanhas, acrescentar destinatários, iniciar, pausar, retomar, cancelar e ler resultados | `campaigns:read`, `campaigns:write` | | Chat | Conversar por texto com um agente: enviar a mensagem e receber a resposta no mesmo pedido | `chats:write` | | Análises | Resumo de volume, resultados, sentimento e desempenho por agente | `analytics:read` | | Números | Inventário de números de telefone da organização | `phone-numbers:read` | | Conhecimento | Listar bases de conhecimento | `knowledge:read` | | Conhecimento | Criar bases e adicionar documentos (texto, página web, PDF) | `knowledge:write` | | Webhooks | Registar, alterar, testar e remover endpoints de webhook | `webhooks:manage` | A referência completa (parâmetros, corpos, respostas e erros de cada endpoint) está em [Endpoints](https://docs.diska.ai/pt/api/endpoints). ### O que a API da DISKA ainda não faz - **Conversar por voz** pela API: para pôr pessoas a falar com um agente, use o widget, o link público, um número de telefone ou o WhatsApp. Veja [Tempo real](https://docs.diska.ai/pt/api/realtime). - Conversar por texto com agentes do Flow Builder: o chat da API usa agentes em modo prompt. - Listar modelos de agente, editar a voz, o motor, as acções ou os fluxos de um agente, e gerir chaves API — faça-o no backoffice. - Listar, alterar ou apagar documentos de conhecimento. ## Autenticação Crie uma chave em **Definições → Chaves API** (só proprietários e administradores) e envie-a em cada pedido: ```http Authorization: Bearer dsk_… ``` O cabeçalho `X-API-Key: dsk_…` também é aceite. A chave completa só é mostrada uma vez, na criação. Detalhes em [Autenticação](https://docs.diska.ai/pt/api/authentication). ::callout{type="warning"} Use a chave apenas no seu servidor, guardada numa variável de ambiente ou num cofre de segredos. Nunca a coloque em código que corre no browser, numa aplicação móvel ou num repositório. :: ### Âmbitos Na criação da chave pode escolher os **Âmbitos**. **Sem nenhum âmbito seleccionado, a chave tem acesso total** a todos os endpoints. Com âmbitos, só esses endpoints respondem; os outros devolvem `403` com `A chave não tem o âmbito '<âmbito>'.` | Âmbito | Nome no backoffice | Dá acesso a | | -------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------- | | `agents:read` | Agentes — leitura | `GET /v1/agents`, `GET /v1/agents/{agent_id}` | | `agents:write` | Agentes — criar, editar e publicar | `POST /v1/agents`, `PATCH /v1/agents/{agent_id}`, `POST /v1/agents/{agent_id}/publish` | | `calls:read` | Chamadas e transcrições | `GET /v1/calls`, `GET /v1/calls/{call_id}`, `GET /v1/outbound-calls/{outbound_call_id}` | | `calls:write` | Chamadas — ligar a clientes | `POST /v1/outbound-calls`, `POST /v1/outbound-calls/{outbound_call_id}/hangup` | | `recordings:read` | Gravações — descarregar | `GET /v1/calls/{call_id}/recording` | | `campaigns:read` | Campanhas — leitura | `GET /v1/campaigns`, `GET /v1/campaigns/{campaign_id}`, `GET /v1/campaigns/{campaign_id}/recipients` | | `campaigns:write` | Campanhas — gestão | Criar campanhas, acrescentar destinatários, iniciar, pausar, retomar e cancelar | | `chats:write` | Chat com agentes | Todos os endpoints `/v1/chats` | | `analytics:read` | Análises | `GET /v1/analytics/overview` | | `phone-numbers:read` | Números | `GET /v1/phone-numbers` | | `knowledge:read` | Conhecimento — leitura | `GET /v1/knowledge-bases` | | `knowledge:write` | Conhecimento — escrita | `POST /v1/knowledge-bases` e os três endpoints de documentos | | `webhooks:manage` | Webhooks — gestão | Todos os endpoints `/v1/webhook-endpoints` | `GET /v1/me` não exige âmbito. Os âmbitos de uma chave não mudam depois de criada: para mudar o acesso, crie uma chave nova e revogue a antiga. As chamadas de saída, as campanhas e o chat também precisam de estar activos para a organização: têm custo, por isso a Diska activa-os a pedido. Sem isso, respondem `403` mesmo a uma chave com acesso total. ## Primeiro pedido ```bash curl https://api.diska.ai/v1/me \ -H "Authorization: Bearer dsk_…" ``` ```json { "organization": { "id": "…", "name": "A Minha Empresa", "slug": "a-minha-empresa" }, "key": { "id": "…", "name": "Integração CRM", "key_preview": "dsk_a1b2…F5A4", "scopes": [], "expires_at": null, "created_at": "…", "last_used_at": "…" } } ``` `scopes: []` significa acesso total. ## Convenções - Pedidos e respostas em JSON (UTF-8), excepto o envio de PDF, que é `multipart/form-data`. - Datas em ISO 8601. - Tudo pertence à organização da chave: um identificador de outra organização responde `404`, como se não existisse. - Cada resposta traz o cabeçalho `X-Request-Id`. Pode enviar o seu próprio `X-Request-Id` (8 a 64 caracteres: letras, números, `.`, `_`, `:` ou `-`); se não o enviar, a Diska gera um. Indique-o quando contactar o suporte. ## Paginação Só `GET /v1/calls` é paginado; as outras listas devolvem todos os itens de uma vez. A lista de chamadas tem dois modos: **Offset** (por omissão) — `limit` (1–200, padrão 50) e `offset`. A resposta traz `total` com a contagem exacta. Ordena da chamada mais recente para a mais antiga. **Cursor** — recomendado para exportar históricos grandes, porque cada página custa o mesmo a qualquer profundidade: 1. Primeiro pedido: `GET /v1/calls?cursor=start&limit=200`. 2. A resposta traz `next_cursor`; peça a página seguinte com `cursor=`, mantendo os mesmos filtros. 3. Quando `next_cursor` vier `null`, chegou ao fim. Em modo cursor, `total` e `offset` vêm `null` e o parâmetro `search` não é aceite (`400`). Um cursor malformado devolve `400` com `Cursor inválido.` ## Limites de utilização Cada chave pode fazer, por omissão, **120 pedidos por minuto**. O contador é de cada chave — várias chaves da mesma organização não partilham o limite — e a janela de 60 segundos começa no primeiro pedido. Acima do limite, a API responde `429` com os cabeçalhos `Retry-After` (segundos até poder repetir), `X-RateLimit-Limit` e `X-RateLimit-Remaining: 0`: ```json { "detail": { "error": "rate_limited", "retry_after_seconds": 42, "limit": 120, "window_seconds": 60 } } ``` Espere o tempo indicado em `Retry-After` antes de repetir. As respostas com sucesso não trazem cabeçalhos de limite. ## Erros | Código | Quando | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | Pedido recusado: cursor inválido, `search` com `cursor`, URL de webhook ou evento inválido, limite de endpoints atingido, documento de conhecimento inválido (PDF demasiado grande, página sem texto…). | | `401` | Chave em falta, inválida, revogada ou expirada. | | `403` | Organização suspensa, ou a chave não tem o âmbito necessário. | | `404` | O recurso não existe ou pertence a outra organização. | | `409` | Conflito — por exemplo, publicar um agente arquivado. | | `422` | Validação falhou: parâmetros ou corpo com formato inválido, ou um agente que não pode ser publicado (prompt vazio, fluxo inválido). | | `429` | Limite de pedidos excedido — respeite `Retry-After`. | | `500` | Erro inesperado da Diska. | | `502` / `503` | Falha temporária da plataforma — repita com espera crescente e veja o [estado do serviço](https://docs.diska.ai/#estado-do-servi%C3%A7o). | A maioria dos erros vem no formato `{ "detail": "mensagem" }`, com a mensagem em português. Os erros de validação `422` de formato trazem `detail` como uma lista (campo, mensagem) e o `429` traz o objecto mostrado acima. Um `500` vem como: ```json { "error": { "code": "internal_server_error", "message": "Internal server error." }, "request_id": "…" } ``` ## Especificação OpenAPI `GET https://api.diska.ai/v1/openapi.json` devolve a especificação OpenAPI só da API da DISKA. Não exige autenticação e pode ser guardada em cache durante 5 minutos. Pode usá-la para gerar um cliente na sua linguagem; a [Referência da API](https://docs.diska.ai/pt/api/reference) é gerada a partir dela. A versão da especificação (`info.version`) segue a [política de versões](https://docs.diska.ai/pt/api/changelog). ### Postman Há uma colecção Postman pronta, com todos os endpoints, exemplos de corpo e a autenticação já configurada: - [Colecção em português](https://docs.diska.ai/api/diska-canal-api.pt.postman_collection.json){rel=""nofollow""} - [Colecção em inglês](https://docs.diska.ai/api/diska-canal-api.en.postman_collection.json){rel=""nofollow""} 1. No Postman, clique em **Import** e escolha o ficheiro descarregado. 2. Na colecção, abra **Variables** e preencha `apiKey` com a sua chave (`dsk_…`). `baseUrl` já aponta para `https://api.diska.ai`. 3. Preencha também os identificadores que vai usar (`agent_id`, `call_id`, `knowledge_base_id`, `endpoint_id`). Os pedidos `POST`, `PATCH` e `DELETE` alteram dados reais da organização. ## Estado do serviço A página [status.diska.ai](https://status.diska.ai){rel=""nofollow""} mostra o estado da API, do backoffice e da telefonia (SIP/PBX), com os incidentes e as manutenções. Pode subscrever as actualizações na própria página ou seguir o feed [RSS](https://status.diska.ai/feed.rss){rel=""nofollow""}. Se receber `502`, `503` ou tempos de resposta anormais, consulte-a antes de abrir um pedido de suporte. Se a página não mostrar nenhum incidente, contacte o suporte com o `X-Request-Id` do pedido. # Autenticação A [API da DISKA](https://docs.diska.ai/pt/api/api-channel) autentica-se com **chaves API da organização**. Uma chave actua em nome da organização, não de uma pessoa: continua válida se quem a criou sair da organização, até ser revogada ou expirar. ## Criar uma chave Só **proprietários** e **administradores** da organização vêem e gerem chaves API. 1. No backoffice, abra **Definições → Chaves API**. 2. Clique em **Criar nova chave API**. 3. Preencha o **Nome** (obrigatório, até 120 caracteres) e, se quiser, a **Descrição** (até 500). 4. Em **Âmbitos**, escolha o que a chave pode fazer. Sem selecção, a chave tem acesso total. Ver [âmbitos](https://docs.diska.ai/pt/api/api-channel#%C3%A2mbitos). 5. Em **Expira em**, escolha uma data, se quiser que a chave deixe de funcionar sozinha. A chave é válida até ao fim desse dia. 6. Clique em **Gerar**. A janela **A sua chave API** mostra a chave completa (`dsk_…`) **uma única vez**. Copie-a e guarde-a num local seguro: depois de fechar a janela não há forma de a voltar a ver — a Diska guarda apenas um hash da chave, não a chave em si. Se a perder, crie uma nova. Na lista, cada chave aparece com o nome, uma pré-visualização mascarada (`dsk_a1b2…F5A4`), os âmbitos (**Acesso total** quando não tem nenhum), a data de criação, a expiração e o **Último uso**. O último uso é actualizado no máximo de 5 em 5 minutos, por isso uma chave usada agora pode mostrar uma hora ligeiramente anterior. ## Enviar a chave Envie a chave em cada pedido, num destes cabeçalhos: ```http Authorization: Bearer dsk_… ``` ```http X-API-Key: dsk_… ``` Se enviar os dois, vale o `Authorization`. Para confirmar que a chave funciona e a que organização pertence, chame `GET /v1/me`: ```bash curl https://api.diska.ai/v1/me \ -H "Authorization: Bearer dsk_…" ``` ## Expiração e revogação - **Expiração**: depois da data escolhida, a chave responde `401` com `Chave de API expirada.` Uma chave sem data de expiração vale até ser revogada. - **Revogação**: na lista, clique no ícone do caixote do lixo e confirme em **Revogar chave**. A chave deixa de funcionar imediatamente e desaparece da lista. Para trocar uma chave sem interromper a integração: crie a nova, actualize o seu sistema e só depois revogue a antiga. ## Boas práticas - Use uma chave por integração, com os âmbitos mínimos de que essa integração precisa. - Guarde as chaves em variáveis de ambiente ou num cofre de segredos, só no servidor. - Nunca use uma chave em código que corre no browser ou numa aplicação móvel. - Se uma chave for exposta, revogue-a e crie outra. ## Onde a chave não funciona Uma chave API só abre os endpoints da API da DISKA (`https://api.diska.ai/v1`). Não dá acesso ao backoffice nem à API interna que o backoffice usa (`/api/v1`), e não serve para iniciar sessões de voz. O backoffice (`app.diska.ai`) autentica pessoas com a sessão de quem inicia sessão e usa a sua própria API interna. Esses tokens de sessão são de curta duração e pertencem ao produto: não os use em integrações. ## Erros de autenticação | Código | `detail` | Causa | | ------ | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | `401` | `Chave de API em falta. Envie 'Authorization: Bearer dsk_…'.` | O pedido não trouxe nenhuma chave. | | `401` | `Chave de API inválida ou revogada.` | A chave não existe, foi revogada ou não começa por `dsk_` (por exemplo, um token de sessão do backoffice). | | `401` | `Chave de API expirada.` | A data de expiração da chave já passou. | | `403` | `Organização suspensa.` | A organização da chave está suspensa. | | `403` | `A chave não tem o âmbito '…'.` | A chave tem âmbitos e nenhum deles cobre este endpoint. | # Webhooks Um webhook é um pedido `POST` que a Diska faz a um URL seu quando uma chamada termina, com a transcrição e o resultado do processamento pós-chamada. Assim o seu sistema recebe os dados sem ter de perguntar repetidamente. Há duas formas de receber estes dados: | | Webhooks da organização | Acção **Webhook** do agente | | ----------------- | --------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | Onde se configura | Pela [API da DISKA](https://docs.diska.ai/pt/api/api-channel), âmbito `webhooks:manage` | No agente (modo prompt): **Ações** → **Depois da conversa** | | Abrange | Todas as chamadas concluídas da organização | As chamadas desse agente | | Assinatura | Sim — HMAC-SHA256 com o secret do endpoint | Não | | Repetições | Até 3 tentativas | Uma única tentativa | | Teste | `POST /v1/webhook-endpoints/{id}/test` | Fazer uma chamada | Para integrações novas, use os **webhooks da organização**: são assinados, mostram o estado de entrega e são geridos por API. Cada agente pode ainda ter os seus próprios webhooks, assinados, incluindo um que recebe a chamada **antes** de o agente atender: veja [Webhooks do agente](https://docs.diska.ai/pt/telephony/webhooks). ## Webhooks da organização ### Registar um endpoint ```bash curl -X POST https://api.diska.ai/v1/webhook-endpoints \ -H "Authorization: Bearer dsk_…" \ -H "Content-Type: application/json" \ -d '{ "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": ["call.completed"] }' ``` Resposta `201`: ```json { "endpoint": { "id": "…", "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": ["call.completed"], "active": true, "disabled_reason": null, "failure_count": 0, "last_delivery_at": null, "last_delivery_status": null, "secret_preview": "dskw_AbC…wXyZ", "created_at": "…" }, "secret": "dskw_…" } ``` O `secret` (começa por `dskw_`) serve para verificar a assinatura e **só é mostrado nesta resposta**. Guarde-o junto da configuração do seu receptor. Se o perder, remova o endpoint e registe-o de novo. Regras do URL e dos eventos: - O URL tem de ser `https://` completo, com domínio (12 a 2000 caracteres). Endereços privados ou internos são recusados. - `events` é opcional; por omissão é `["call.completed"]`. Tem de ter pelo menos um evento. - Cada organização pode ter até **10** endpoints. ### Eventos | Evento | Quando é enviado | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `call.completed` | Uma chamada termina com o estado `completed` e o processamento pós-chamada (extracções, avaliações, SMS e acções pós-chamada) conclui. Chamadas que falharam, foram canceladas ou abandonadas **não** geram este evento. | | `booking.created` | É aceite na subscrição, mas **a plataforma ainda não envia este evento**. Não dependa dele. | | `ping` | Só é enviado quando chama o endpoint de teste. Não se subscreve. | `call.completed` também é enviado para as [chamadas de saída](https://docs.diska.ai/pt/api/reference/outbound-calls) e as [campanhas](https://docs.diska.ai/pt/api/reference/campaigns) atendidas, e para as conversas do [chat](https://docs.diska.ai/pt/api/reference/chats) quando terminam (canal `web_chat`). ### Conteúdo de `call.completed` O corpo é JSON (UTF-8). Exemplo: ```json { "event": "call.completed", "call_id": "8d0c6a3e-…", "session_id": "…", "organization_id": "…", "agent_id": "…", "ended_at": "2026-10-23T14:05:12.345678+00:00", "caller_contact": "+244923000000", "extracted_data": { "nome": "Ana Silva" }, "evaluations": [], "sentiment": "positive", "post_call_sms": [], "custom_actions": [], "executed_actions": [], "transcript": [ { "role": "assistant", "content": "Bom dia, fala com a assistente da …" }, { "role": "user", "content": "Bom dia, queria marcar uma consulta." } ] } ``` | Campo | Descrição | | ----------------------------- | -------------------------------------------------------------------------------------------------------------------- | | `call_id` | Identificador da chamada. Use-o em `GET /v1/calls/{call_id}` para obter o detalhe completo. | | `session_id` | Identificador da sessão de voz (aparece como `external_ref` nas chamadas da API da DISKA). | | `agent_id`, `organization_id` | Agente que atendeu e organização. | | `ended_at` | Data e hora de fim (ISO 8601). | | `caller_contact` | Contacto de quem ligou, quando conhecido. | | `extracted_data` | Valores dos [extractores de informação](https://docs.diska.ai/pt/actions/information-extractors) do agente. | | `evaluations` | Resultados das [avaliações personalizadas](https://docs.diska.ai/pt/actions/custom-evaluations). | | `sentiment` | `positive`, `neutral`, `negative` ou `null` quando não foi possível classificar. | | `post_call_sms` | Resultado dos [SMS pós-chamada](https://docs.diska.ai/pt/actions/post-call-sms). | | `custom_actions` | Resultado das [acções personalizadas](https://docs.diska.ai/pt/actions/custom-actions) que correm depois da chamada. | | `executed_actions` | Acções executadas durante e depois da chamada. | | `transcript` | Transcrição da conversa, turno a turno. | Num agente com [Ocultar dados pessoais](https://docs.diska.ai/pt/guides/redact-personal-data) activo, `transcript`, `extracted_data`, `evaluations`, `post_call_sms`, `custom_actions` e `executed_actions` chegam com etiquetas como `[NOME]` e `[TELEFONE]` em vez dos dados pessoais. `caller_contact` mantém o número da chamada. O conteúdo pode ganhar campos novos; o seu receptor deve ignorar os que não conhece. Se uma chamada não tiver resultado pós-chamada guardado, o evento traz só `event`, `call_id`, `session_id`, `organization_id`, `agent_id`, `ended_at`, `caller_contact` e `transcript` vazio. ### Cabeçalhos ```text Content-Type: application/json User-Agent: Diska-Webhooks/1.0 X-Diska-Event: call.completed X-Diska-Delivery: X-Diska-Timestamp: X-Diska-Signature: sha256= ``` `X-Diska-Delivery` mantém-se igual nas repetições da mesma entrega: use-o para não processar o mesmo evento duas vezes. ### Verificar a assinatura A assinatura é o HMAC-SHA256, em hexadecimal, do texto `{X-Diska-Timestamp}.{corpo}` com o secret do endpoint. Calcule-a sobre o **corpo bruto**, exactamente como chegou — não sobre o JSON depois de o interpretar e voltar a serializar. ::code-group ```python [Python] import hashlib import hmac import time def is_valid(secret: str, timestamp: str, body: bytes, signature: str) -> bool: if abs(time.time() - int(timestamp)) > 300: # recusa pedidos com mais de 5 minutos return False expected = hmac.new( secret.encode(), f"{timestamp}.".encode() + body, hashlib.sha256 ).hexdigest() return hmac.compare_digest(f"sha256={expected}", signature) ``` ```js [Node.js] import crypto from 'node:crypto' export function isValid(secret, timestamp, rawBody, signature) { if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false const expected = 'sha256=' + crypto .createHmac('sha256', secret) .update(`${timestamp}.`) .update(rawBody) // Buffer com o corpo bruto .digest('hex') const a = Buffer.from(expected) const b = Buffer.from(signature || '') return a.length === b.length && crypto.timingSafeEqual(a, b) } ``` ```php [PHP] 300) { return false; } $expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret); return hash_equals($expected, $signature); } // No receptor: o corpo bruto vem de php://input. $rawBody = file_get_contents('php://input'); $valid = diska_signature_is_valid( getenv('DISKA_WEBHOOK_SECRET'), $_SERVER['HTTP_X_DISKA_TIMESTAMP'] ?? '', $rawBody, $_SERVER['HTTP_X_DISKA_SIGNATURE'] ?? '' ); if (!$valid) { http_response_code(401); exit; } ``` :: O limite de 5 minutos é uma recomendação para evitar que um pedido antigo seja reenviado por terceiros. ### Responder e repetições - Responda com um código `2xx` em menos de 10 segundos. O ideal é guardar o evento numa fila e processá-lo depois. - Qualquer outra resposta conta como falha. Redireccionamentos (`3xx`) não são seguidos e também contam como falha. - Uma entrega falhada é repetida até 3 tentativas no total, com poucos segundos de intervalo. Respostas `4xx` (excepto `408` e `429`) não são repetidas. Em algumas chamadas a Diska faz uma única tentativa. - Depois disso não há reenvio. A entrega é feita no melhor esforço: para reconciliar, `GET /v1/calls` é a fonte de verdade. ### Desactivação automática Ao fim de **20 entregas falhadas seguidas**, o endpoint é desactivado: `active` passa a `false` e `disabled_reason` explica porquê. Uma entrega com sucesso põe o contador a zero. Depois de corrigir o receptor, reactive o endpoint: ```bash curl -X PATCH https://api.diska.ai/v1/webhook-endpoints/ \ -H "Authorization: Bearer dsk_…" \ -H "Content-Type: application/json" \ -d '{ "active": true }' ``` Reactivar põe `failure_count` a zero e limpa `disabled_reason`. Para parar as entregas temporariamente, envie `{ "active": false }`. ### Testar o receptor ```bash curl -X POST https://api.diska.ai/v1/webhook-endpoints//test \ -H "Authorization: Bearer dsk_…" ``` A Diska envia ao seu URL um evento `ping` assinado, com os mesmos cabeçalhos e regras de repetição: ```json { "event": "ping", "organization_id": "…", "endpoint_id": "…" } ``` A resposta diz como correu: `status` (`delivered`, `failed` ou `blocked`), `attempts`, `http_status` e, em caso de falha, `error`. O teste funciona mesmo com o endpoint desactivado e uma falha no teste não conta para a desactivação automática. ### Acompanhar as entregas `GET /v1/webhook-endpoints` mostra, para cada endpoint, `last_delivery_at`, `last_delivery_status` (por exemplo `delivered (200)` ou `failed (HTTP 500)`) e `failure_count`. A referência completa dos endpoints de gestão está em [Endpoints](https://docs.diska.ai/pt/api/endpoints#webhooks). ## Acção Webhook do agente Num agente em modo prompt pode enviar os dados de cada chamada desse agente para um URL, sem usar a API da DISKA: 1. Abra o agente e clique em **Ações**. 2. Em **Depois da conversa**, clique em **Adicionar** e escolha **Webhook** ("Enviar os dados da chamada para um URL."). 3. Introduza o URL. Tem de usar HTTPS e ter um domínio válido. 4. Publique o agente: as chamadas publicadas usam as acções da versão publicada. No fim do processamento pós-chamada de cada chamada desse agente, a Diska faz um `POST` JSON para esse URL com o mesmo conteúdo do evento `call.completed`, excepto `call_id` (use `session_id`, que corresponde a `external_ref` nas chamadas da API da DISKA). Diferenças em relação aos webhooks da organização: - O pedido **não é assinado** e não traz os cabeçalhos `X-Diska-…`. Use um URL difícil de adivinhar e trate o conteúdo como não verificado. - É feita **uma única tentativa**, com um limite de 20 segundos; não há repetições nem desactivação automática. - Não depende do estado final da chamada: também pode ser enviado para chamadas que falharam ou foram canceladas (as abandonadas não). - Se o agente tiver várias acções Webhook, só a primeira com um URL válido é usada. ## Webhooks do agente: Inbound e Data No separador **Telefone** das **Definições de publicação** de cada agente pode configurar dois webhooks desse agente, assinados com o segredo do agente: - **Inbound Webhook**: recebe cada chamada de entrada antes de o agente falar. A resposta pode dar ao agente dados sobre quem liga (nome, plano, saldo…). - **Data Webhook**: recebe os dados de cada chamada concluída do agente — o mesmo conteúdo do `call.completed`, com os campos `call` e `metadata`. Veja [Webhooks do agente](https://docs.diska.ai/pt/telephony/webhooks). # Endpoints ::callout{type="tip"} Cada endpoint tem também uma página própria na [Referência da API](https://docs.diska.ai/pt/api/reference) , com o esquema completo, exemplos em cURL, Python, JavaScript e PHP, e **Experimentar** . :: Todos os endpoints abaixo pertencem à [API da DISKA](https://docs.diska.ai/pt/api/api-channel), em `https://api.diska.ai/v1`, e exigem uma [chave API](https://docs.diska.ai/pt/api/authentication) no cabeçalho `Authorization: Bearer dsk_…` (ou `X-API-Key`). Os erros comuns a todos — `401`, `403`, `422` de formato, `429`, `5xx` — estão descritos em [Erros](https://docs.diska.ai/pt/api/api-channel#erros); aqui ficam só os específicos de cada endpoint. ## Resumo | Método | Caminho | Âmbito | | ------ | ------------------------------------------------------- | -------------------- | | GET | `/v1/me` | — | | GET | `/v1/agents` | `agents:read` | | GET | `/v1/agents/{agent_id}` | `agents:read` | | POST | `/v1/agents` | `agents:write` | | POST | `/v1/agents/{agent_id}/publish` | `agents:write` | | GET | `/v1/calls` | `calls:read` | | GET | `/v1/calls/{call_id}` | `calls:read` | | GET | `/v1/analytics/overview` | `analytics:read` | | GET | `/v1/phone-numbers` | `phone-numbers:read` | | GET | `/v1/knowledge-bases` | `knowledge:read` | | POST | `/v1/knowledge-bases` | `knowledge:write` | | POST | `/v1/knowledge-bases/{knowledge_base_id}/documents` | `knowledge:write` | | POST | `/v1/knowledge-bases/{knowledge_base_id}/documents/url` | `knowledge:write` | | POST | `/v1/knowledge-bases/{knowledge_base_id}/documents/pdf` | `knowledge:write` | | GET | `/v1/webhook-endpoints` | `webhooks:manage` | | POST | `/v1/webhook-endpoints` | `webhooks:manage` | | PATCH | `/v1/webhook-endpoints/{endpoint_id}` | `webhooks:manage` | | DELETE | `/v1/webhook-endpoints/{endpoint_id}` | `webhooks:manage` | | POST | `/v1/webhook-endpoints/{endpoint_id}/test` | `webhooks:manage` | | GET | `/v1/openapi.json` | Sem autenticação | ## Identidade ### `GET /v1/me` Devolve a organização e a chave por trás do token. Não exige âmbito — use-o para confirmar que a chave funciona. Resposta `200`: `organization` (`id`, `name`, `slug`) e `key` (`id`, `name`, `key_preview`, `scopes`, `expires_at`, `created_at`, `last_used_at`). `scopes: []` significa acesso total. Exemplo em [API da DISKA](https://docs.diska.ai/pt/api/api-channel#primeiro-pedido). ## Agentes ### O objecto agente | Campo | Descrição | | ----------------------------- | ------------------------------------------------------------------------------- | | `id` | Identificador do agente. | | `name`, `slug`, `description` | Nome, identificador legível e descrição (pode ser `null`). | | `status` | `draft`, `active`, `inactive` ou `archived`. Um agente publicado fica `active`. | | `agent_type` | `inbound`, `outbound`, `voice_widget` ou `chat`. | | `editing_mode` | `prompt` ou `flow` (Flow Builder). Não muda depois de criado. | | `version` | Número da versão do agente. | | `phone_number` | Número atribuído ao agente, ou `null`. | | `public_channel_enabled` | `true` quando o Link público do agente está activo. | | `created_at`, `updated_at` | Datas de criação e última alteração. | A configuração interna do agente (prompt, fluxos, voz, acções) não é exposta. ### `GET /v1/agents` Lista os agentes da organização, do alterado mais recentemente para o mais antigo. | Parâmetro | Descrição | | ------------ | ------------------------------------------------------------------------------------------------- | | `agent_type` | `inbound`, `outbound`, `voice_widget` ou `chat`. | | `status` | `draft`, `active`, `inactive` ou `archived`. Sem este filtro, os agentes arquivados não aparecem. | | `search` | Texto contido no nome (até 200 caracteres). | Resposta `200`: `{ "items": [ , … ] }`. ### `GET /v1/agents/{agent_id}` Devolve um agente. `404` com `Agente não encontrado.` se não existir na organização. ### `POST /v1/agents` Cria um agente. O agente nasce em rascunho (`status: draft`); publique-o para ficar disponível nos canais. | Campo | Obrigatório | Descrição | | -------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `name` | Não | Até 120 caracteres. Por omissão: `Novo agente`, ou o nome do modelo. | | `agent_type` | Não | `inbound`, `outbound`, `voice_widget` ou `chat`. Por omissão: `inbound`, ou o tipo do modelo. | | `editing_mode` | Não | `prompt` ou `flow`. Por omissão: `prompt` num agente em branco, `flow` a partir de um modelo. | | `template_id` | Não | Identificador de um modelo de agente da Diska (até 64 caracteres). Sem ele, o agente é criado em branco. A API da DISKA não lista modelos. | ```bash curl -X POST https://api.diska.ai/v1/agents \ -H "Authorization: Bearer dsk_…" \ -H "Content-Type: application/json" \ -d '{ "name": "Recepção", "agent_type": "inbound", "editing_mode": "prompt" }' ``` Resposta `201`: o agente criado. Erros: `404` com `Modelo não encontrado.` quando o `template_id` não existe; `422` se o modelo não puder ser instalado. ### `POST /v1/agents/{agent_id}/publish` Publica o rascunho do agente como nova versão e deixa o agente `active`. Em agentes de fluxo, publica também o fluxo principal e os subfluxos que ele usa. Se nada mudou desde a última publicação, não é criada uma versão nova. Corpo opcional: | Campo | Descrição | | ------- | ------------------------------------------------------------ | | `label` | Nome da versão, até 120 caracteres. Por omissão: `Versão N`. | ```bash curl -X POST https://api.diska.ai/v1/agents//publish \ -H "Authorization: Bearer dsk_…" \ -H "Content-Type: application/json" \ -d '{ "label": "Horário de Dezembro" }' ``` Resposta `200`: o agente actualizado. Erros: | Código | Quando | | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `404` | `Agente não encontrado.` | | `409` | `O agente está arquivado. Restaure-o antes de publicar.` | | `422` | O agente não pode ser publicado — por exemplo, `O agente precisa de instruções (prompt) antes de ser publicado.` ou um erro de validação do fluxo. | ## Chamadas ### `GET /v1/calls` Lista as chamadas da organização, das mais recentes para as mais antigas. Ver [paginação](https://docs.diska.ai/pt/api/api-channel#pagina%C3%A7%C3%A3o). | Parâmetro | Descrição | | ---------- | ----------------------------------------------------------------------------------------------------------------------- | | `agent_id` | Só chamadas deste agente. | | `status` | `created`, `active`, `completed`, `failed`, `cancelled` ou `abandoned`. | | `channel` | `browser_demo` (chamada web), `phone`, `whatsapp` ou `web_chat`. | | `search` | Texto no identificador, `external_ref`, nome ou contacto de quem ligou (até 200 caracteres). Não funciona com `cursor`. | | `limit` | 1–200, padrão 50. | | `offset` | Modo offset: quantas chamadas saltar (padrão 0). | | `cursor` | Modo cursor: `start` na primeira página, depois o `next_cursor` recebido. | Resposta `200`: ```json { "items": [ { "id": "…", "agent_name": "Recepção", "channel": "phone", "status": "completed", "…": "…" } ], "limit": 50, "total": 1234, "offset": 0, "next_cursor": null } ``` Em modo offset, `total` e `offset` vêm preenchidos e `next_cursor` é `null`. Em modo cursor, `total` e `offset` vêm `null` e `next_cursor` aponta para a página seguinte (ou `null` no fim). Cada chamada da lista tem: | Campo | Descrição | | -------------------------------------------- | ----------------------------------------------------------------------- | | `id` | Identificador da chamada (é o `call_id` dos webhooks). | | `external_ref` | Identificador da sessão de voz (o `session_id` dos webhooks). | | `agent_id`, `agent_name` | Agente que atendeu. | | `channel` | `browser_demo`, `phone`, `whatsapp` ou `web_chat`. | | `direction` | `inbound`, `outbound`, ou `null` em chamadas web. | | `status` | `created`, `active`, `completed`, `failed`, `cancelled` ou `abandoned`. | | `caller_name`, `caller_contact` | Nome e contacto de quem ligou, quando conhecidos. | | `started_at`, `ended_at`, `duration_seconds` | Início, fim e duração em segundos. | | `end_reason` | Motivo do fim da chamada. | | `summary` | Resumo da chamada, quando gerado. | | `is_simulation` | `true` quando `channel` é `browser_demo`. | | `labels` | Etiquetas da chamada. | | `has_post_call` | `true` quando existe resultado pós-chamada. | | `executed_actions_count` | Número de acções executadas. | ### `GET /v1/calls/{call_id}` Devolve uma chamada com todos os campos da lista e ainda: | Campo | Descrição | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `organization_id` | Organização da chamada. | | `messages` | Transcrição: lista de `{ id, sequence, role, content, created_at }`, por ordem. | | `tool_calls` | Acções executadas: `{ id, tool_name, status, input, output, error_message, latency_ms, called_at, completed_at }`. | | `post_call` | Resultado pós-chamada (o conteúdo do [webhook](https://docs.diska.ai/pt/api/webhooks) `call.completed`, sem `call_id`), ou `null`. | | `has_recording` | `true` quando há gravação disponível. | | `recording_state` | `disabled`, `available`, `failed`, `expired` ou `deleted`. | | `metadata` | Metadados técnicos da chamada. O conteúdo não é estável — não dependa dele. | O áudio da gravação não é devolvido pela API da DISKA. `404` com `Chamada não encontrada.` se a chamada não existir na organização. ## Análises ### `GET /v1/analytics/overview` O mesmo resumo da página **Análises** do backoffice, para uma janela que termina no momento do pedido e comparada com a janela anterior do mesmo tamanho. | Parâmetro | Descrição | | ------------ | --------------------------------------------------------------------------------------------- | | `period` | `daily` (últimas 24 horas), `weekly` (últimos 7 dias, padrão) ou `monthly` (últimos 30 dias). | | `agent_id` | Só este agente. | | `agent_type` | `all` (padrão), `inbound` ou `outbound`. | Resposta `200`: | Campo | Descrição | | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `period`, `start`, `end` | Janela analisada. | | `totals` | `calls`, `minutes` e `avg_duration_seconds`, cada um com `value`, `previous` e `change_pct` (`null` quando a janela anterior não tem dados). | | `daily` | Por dia (UTC): `date`, `calls`, `minutes`, `completed`, `failed`, `cancelled`. | | `by_status`, `by_end_reason` | Distribuição: `key`, `label`, `count`, `pct`. | | `sentiment` | Percentagem de chamadas positivas (`positive_pct`), `classified`, `total`, `breakdown` e evolução diária. | | `agents` | Desempenho por agente: chamadas, minutos, conclusões e variações. | | `actions` | Utilização de cada acção executada, com evolução diária. | | `failed_calls` | Chamadas falhadas recentes: `id`, `started_at`, `contact`, `agent_name`, `end_reason`. | ## Números ### `GET /v1/phone-numbers` Inventário de números de telefone da organização. | Parâmetro | Descrição | | ------------- | --------------------------------------------------------------------- | | `search` | Texto no número, no nome ou no domínio SIP (até 200 caracteres). | | `number_type` | `purchased` (números DISKA) ou `imported` (números próprios por SIP). | Resposta `200`: `{ "items": [ … ], "total": N }`. Cada número inclui `id`, `e164`, `friendly_name`, `number_type`, `status` (`active` ou `inactive`), `country_code`, `capabilities` (`calls`, `sms`), `agent_id` e `agents` (agentes que usam o número: `id`, `name`, `status`). Os números importados por SIP trazem também os campos do trunk (`sip_domain`, `sip_username`, `sip_transport`, `sip_status`…); a palavra-passe SIP nunca é devolvida, só `sip_password_configured`. ## Conhecimento ### O objecto base de conhecimento `id`, `organization_id`, `name`, `instruction` (quando o agente deve usar esta base), `description`, `document_count`, `assigned_agent_count`, `created_at`, `updated_at`. ### O objecto documento `id`, `organization_id`, `knowledge_base_id`, `name`, `source_type` (`manual`, `pdf` ou `url`), `status`, `extraction_status`, `indexing_status` (`indexed` quando a indexação terminou), `content_text`, `original_url`, `mime_type`, `size_bytes`, `error_message`, `has_file`, `created_at`, `updated_at`, entre outros. ### `GET /v1/knowledge-bases` Lista as bases de conhecimento. Parâmetro opcional `search`: texto contido no nome ou na instrução. Resposta `200`: `{ "items": [ , … ] }`. ### `POST /v1/knowledge-bases` | Campo | Obrigatório | Descrição | | ------------- | ----------- | ---------------------------------------------------------------- | | `name` | Sim | 1 a 200 caracteres. | | `instruction` | Sim | Quando e como o agente deve usar esta base. 1 a 4000 caracteres. | | `description` | Não | Até 2000 caracteres. | Resposta `201`: a base criada. Para um agente usar a base, atribua-a no backoffice. ### `POST /v1/knowledge-bases/{knowledge_base_id}/documents` Adiciona um documento de texto. A indexação arranca logo. | Campo | Obrigatório | Descrição | | --------- | ----------- | -------------------------------- | | `name` | Sim | 1 a 200 caracteres. | | `content` | Sim | O texto, até 200 000 caracteres. | ```bash curl -X POST https://api.diska.ai/v1/knowledge-bases//documents \ -H "Authorization: Bearer dsk_…" \ -H "Content-Type: application/json" \ -d '{ "name": "Horários", "content": "Abrimos de segunda a sexta, das 8h às 17h." }' ``` ### `POST /v1/knowledge-bases/{knowledge_base_id}/documents/url` Importa o texto de uma página web pública. | Campo | Obrigatório | Descrição | | ------ | ----------- | --------------------------------------------------------------- | | `name` | Sim | 1 a 200 caracteres. | | `url` | Sim | Endereço `http://` ou `https://` completo, até 2000 caracteres. | A página tem de responder em 15 segundos, ter até 2 MB e ser HTML, texto ou JSON. Endereços privados ou internos são recusados, e são seguidos no máximo 3 redireccionamentos. ### `POST /v1/knowledge-bases/{knowledge_base_id}/documents/pdf` Carrega um PDF em `multipart/form-data`, no campo `file` (até 25 MB). ```bash curl -X POST https://api.diska.ai/v1/knowledge-bases//documents/pdf \ -H "Authorization: Bearer dsk_…" \ -F "file=@tabela-de-precos.pdf;type=application/pdf" ``` ### Respostas e erros dos documentos Os três endpoints de documentos respondem `201` com o documento criado. Erros específicos: | Código | Quando | | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | Conteúdo recusado — por exemplo `Ficheiro vazio.`, `PDF demasiado grande (máx. 25 MB).`, `Apenas ficheiros PDF são aceites.`, `O ficheiro não parece ser um PDF válido.`, `Tempo esgotado ao obter a página.`, `A página não devolveu texto legível.` ou um URL bloqueado por segurança. | | `404` | `Base de conhecimento não encontrada.` | ## Webhooks Como funcionam as entregas, os eventos e a assinatura: ver [Webhooks](https://docs.diska.ai/pt/api/webhooks). ### O objecto endpoint | Campo | Descrição | | ------------------------------------------ | ----------------------------------------------------------- | | `id` | Identificador do endpoint. | | `url`, `description` | Destino e descrição. | | `events` | Eventos subscritos. | | `active` | `false` quando foi desactivado (por si ou automaticamente). | | `disabled_reason` | Motivo da desactivação automática, ou `null`. | | `failure_count` | Entregas falhadas seguidas. | | `last_delivery_at`, `last_delivery_status` | Última entrega e o seu resultado. | | `secret_preview` | Início e fim do secret, para o identificar. | | `created_at` | Data de criação. | ### `GET /v1/webhook-endpoints` Lista os endpoints da organização (activos e inactivos), do mais recente para o mais antigo. Resposta `200`: uma lista de endpoints. ### `POST /v1/webhook-endpoints` | Campo | Obrigatório | Descrição | | ------------- | ----------- | ----------------------------------------------------------------------------------------- | | `url` | Sim | URL `https://` completo, 12 a 2000 caracteres. | | `description` | Não | Até 500 caracteres. | | `events` | Não | Lista de eventos (`call.completed`, `booking.created`). Por omissão `["call.completed"]`. | Resposta `201`: `{ "endpoint": , "secret": "dskw_…" }`. O `secret` só aparece nesta resposta. Erros `400`: `URL inválido: use um endpoint https:// completo.`, `URL bloqueado por segurança: …`, `Subscreva pelo menos um evento.`, `Eventos desconhecidos: …`, `Limite de 10 endpoints por organização atingido.` ### `PATCH /v1/webhook-endpoints/{endpoint_id}` Altera só os campos enviados: | Campo | Descrição | | ------------- | ---------------------------------------------------------------------------------- | | `url` | Novo URL `https://`. | | `description` | Nova descrição; `""` apaga-a. | | `events` | Nova lista de eventos (pelo menos um). | | `active` | `true` reactiva o endpoint e põe `failure_count` a zero; `false` pára as entregas. | Resposta `200`: o endpoint actualizado. Erros: `404` com `Endpoint não encontrado.`; `400` com as mesmas mensagens da criação. O secret não muda. ### `DELETE /v1/webhook-endpoints/{endpoint_id}` Remove o endpoint. Resposta `200`: o endpoint removido. `404` com `Endpoint não encontrado.` ### `POST /v1/webhook-endpoints/{endpoint_id}/test` Envia um evento `ping` assinado para o URL do endpoint, mesmo que esteja desactivado. Resposta `200`: ```json { "status": "delivered", "attempts": 1, "http_status": 200 } ``` `status` pode ser `delivered`, `failed` (com `error`) ou `blocked` (o URL passou a apontar para um endereço não permitido). `404` com `Endpoint não encontrado.` ## API interna do backoffice O backoffice usa outros endpoints, em `https://api.diska.ai/api/v1`, autenticados pela sessão de quem inicia sessão. Não fazem parte da API da DISKA: não aceitam chaves API, não estão documentados e podem mudar sem aviso. Se precisa de algo que só o backoffice faz, [fale connosco](mailto\:hello@diska.ai). # Tempo real As conversas de voz em tempo real acontecem nos canais da Diska. A [API da DISKA](https://docs.diska.ai/pt/api/api-channel) não abre nem controla sessões de voz, e as chaves API não servem para isso: use-a para ler o resultado das chamadas e receba-o por [webhook](https://docs.diska.ai/pt/api/webhooks) quando cada chamada termina. ## Canais de voz | Canal | Para quê | Onde se configura | | ------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------- | | Telefone | Atender chamadas num número DISKA ou num número seu ligado por SIP. | [Telefonia](https://docs.diska.ai/pt/telephony) | | Link público | Uma página com microfone, para qualquer pessoa falar com a versão publicada do agente no browser, sem conta Diska. | [Publicar um agente](https://docs.diska.ai/pt/guides/publish-agent) | | Widget | O botão de chamada no seu site (script ou iframe). | [Incorporar o widget](https://docs.diska.ai/pt/guides/embed-widget) | | Teste no backoffice | Chamadas de teste no browser ou para o seu telemóvel, a partir do agente. | [Testar um agente](https://docs.diska.ai/pt/guides/test-agent) | O número, o link público e o widget de cada agente configuram-se no botão **Publicação** do agente, na janela **Definições de publicação**. ## O endpoint de sessão do link público Quando o **Link público** de um agente está activo, o separador **Link público** das **Definições de publicação** mostra, além do **Endereço para partilhar** e do **Token público**, o **Endpoint de sessão (API)**: ```text https://api.diska.ai/api/v1/public/agents//voice-session ``` Um `POST` a este endereço cria uma sessão de voz anónima sobre a versão publicada do agente. É o que o player web da Diska — a página do link público e o widget — usa para começar cada chamada; o player trata do resto (áudio, transcrição e voz). - Só funciona enquanto o link público estiver activo e o agente tiver uma versão publicada; caso contrário responde `404`. Corre sempre a versão publicada, nunca o rascunho. - **Gerar novo link** troca o token: o endereço antigo deixa de funcionar de imediato. **Desativar** impede novas chamadas e mantém o token para reactivar. - Há limites de sessões por endereço IP e por link. Acima deles, a resposta é `429` com `Demasiadas chamadas de momento. Tente novamente dentro de alguns minutos.` ::callout{type="warning"} O que acontece depois desse `POST` — a ligação de áudio e os pedidos que o player faz durante a chamada — não é um contrato público: depende do motor de voz e pode mudar sem aviso. Para pôr o agente no seu site ou aplicação, use o [widget](https://docs.diska.ai/pt/guides/embed-widget) ou o endereço do link público. :: Nos agentes do tipo **Voice Widget**, o separador **WebSocket** das **Definições de publicação** mostra o mesmo endpoint, como **Canal público**. Com o título **Sessões em tempo real**, explica que é este o pedido que abre a conversa de voz. Não existe um canal WebSocket público para acompanhar o estado da sessão, as transcrições ou os eventos do agente durante a chamada. ## Acompanhar as chamadas Não há um fluxo público de eventos durante a chamada. Para obter os dados das chamadas: - **Webhook `call.completed`** — quando a chamada termina, a Diska envia a transcrição e o resultado pós-chamada para o seu sistema. Ver [Webhooks](https://docs.diska.ai/pt/api/webhooks). - **`GET /v1/calls/{call_id}`** — o detalhe da chamada, quando quiser. Ver [Endpoints](https://docs.diska.ai/pt/api/endpoints#chamadas). - **Históricos** no backoffice — ver [Chamadas](https://docs.diska.ai/pt/history/calls). ## Endpoints de voz da plataforma Os endpoints em `https://api.diska.ai/api/v1/realtime/…` servem as aplicações da própria Diska (o painel de teste, o widget e o link público). São autenticados pela sessão do backoffice ou por credenciais próprias de cada chamada, não aceitam chaves API e não fazem parte da API pública. Não construa integrações sobre eles. # Ver a chave e a organização ```http GET https://api.diska.ai/v1/me ``` **Âmbito:** nenhum — qualquer chave válida Não exige âmbito: use-o para confirmar que a chave funciona. `scopes: []` significa acesso total. ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/me" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/me", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/me', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: [] body-type: none locale: pt method: GET path: /v1/me --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ------------------- | -------------- | ------------------------------------------------------------ | | `organization` | object | A organização da chave. | | `organization.id` | string | Identificador da organização. | | `organization.name` | string | Nome da organização. | | `organization.slug` | string | Identificador legível da organização. | | `key` | object | A chave usada no pedido. | | `key.id` | string | Identificador da chave. | | `key.name` | string | Nome dado à chave. | | `key.key_preview` | string | Início e fim da chave, para a identificar (`dsk_a1b2…F5A4`). | | `key.scopes` | array | Âmbitos da chave. Lista vazia = acesso total. | | `key.expires_at` | string \| null | Data de expiração, ou `null` se não expira. | | `key.created_at` | string \| null | Data de criação (ISO 8601). | | `key.last_used_at` | string \| null | Último uso (actualizado no máximo de 5 em 5 minutos). | ```json { "organization": { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "A Minha Empresa", "slug": "recepcao" }, "key": { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Integração CRM", "key_preview": "dsk_a1b2…F5A4", "scopes": [ "agents:read", "calls:read" ], "expires_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "last_used_at": "2026-10-25T18:40:00Z" } } ``` ## Erros Este endpoint não tem erros próprios. Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Identidade | Método | Endpoint | Descrição | Âmbito | | ------ | ------------------------------------------------------------------------ | --------------------------- | ------ | | `GET` | [`/v1/me`](https://docs.diska.ai/pt/api/reference/identity/get-identity) | Ver a chave e a organização | — | # Listar agentes ```http GET https://api.diska.ai/v1/agents ``` **Âmbito:** `agents:read` Sem o filtro `status`, os agentes arquivados não aparecem. A lista não é paginada. ## Parâmetros ### Na query string | Nome | Tipo | Obrigatório | Descrição | | ------------ | -------------- | ----------- | ----------------------------------------------------------------------------------------------------------------- | | `agent_type` | string \| null | Não | Só agentes deste tipo. Um de: `inbound`, `outbound`, `voice_widget`, `chat`. | | `status` | string \| null | Não | Só agentes neste estado. Use `archived` para ver os arquivados. Um de: `draft`, `active`, `inactive`, `archived`. | | `search` | string \| null | Não | Texto contido no nome. Até 200 caracteres. | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/agents" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/agents", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/agents', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: agent_type in: query options: - inbound - outbound - voice_widget - chat - name: status in: query options: - draft - active - inactive - archived - name: search in: query body-type: none locale: pt method: GET path: /v1/agents --- :: ## Resposta `200` | Campo | Tipo | Descrição | | -------------------------------- | -------------- | ------------------------------------------------------------------------------- | | `items` | array | Os agentes. | | `items[].id` | string | Identificador do agente. | | `items[].name` | string | Nome do agente. | | `items[].slug` | string | Identificador legível do agente. | | `items[].description` | string \| null | Descrição, ou `null`. | | `items[].status` | string | `draft`, `active`, `inactive` ou `archived`. Um agente publicado fica `active`. | | `items[].agent_type` | string | `inbound`, `outbound`, `voice_widget` ou `chat`. | | `items[].editing_mode` | string | `prompt` ou `flow` (Flow Builder). Não muda depois de criado. Padrão: `prompt`. | | `items[].version` | integer | Número da versão do agente. Padrão: `1`. | | `items[].phone_number` | string \| null | Número atribuído ao agente, ou `null`. | | `items[].public_channel_enabled` | boolean | `true` quando o Link público do agente está activo. Padrão: `false`. | | `items[].created_at` | string | Data de criação (ISO 8601). | | `items[].updated_at` | string | Data da última alteração (ISO 8601). | ```json { "items": [ { "id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "name": "Recepção", "slug": "recepcao", "description": "Atende as chamadas da recepção.", "status": "active", "agent_type": "inbound", "editing_mode": "prompt", "version": 3, "phone_number": "+244900000000", "public_channel_enabled": false, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z" } ] } ``` ## Erros Este endpoint não tem erros próprios. Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Ver um agente ```http GET https://api.diska.ai/v1/agents/{agent_id} ``` **Âmbito:** `agents:read` É o rascunho — o que a próxima publicação vai fixar. `has_unpublished_changes` diz se difere da versão publicada. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ---------- | ------ | ----------- | ------------------------ | | `agent_id` | string | Sim | Identificador do agente. | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/agents/" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/agents/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/agents/', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: agent_id in: path required: true body-type: none locale: pt method: GET path: /v1/agents/{agent_id} --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ---------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------- | | `id` | string | Identificador do agente. | | `name` | string | Nome do agente. | | `slug` | string | Identificador legível do agente. | | `description` | string \| null | Descrição, ou `null`. | | `status` | string | `draft`, `active`, `inactive` ou `archived`. Um agente publicado fica `active`. | | `agent_type` | string | `inbound`, `outbound`, `voice_widget` ou `chat`. | | `editing_mode` | string | `prompt` ou `flow` (Flow Builder). Não muda depois de criado. Padrão: `prompt`. | | `version` | integer | Número da versão do agente. Padrão: `1`. | | `phone_number` | string \| null | Número atribuído ao agente, ou `null`. | | `public_channel_enabled` | boolean | `true` quando o Link público do agente está activo. Padrão: `false`. | | `created_at` | string | Data de criação (ISO 8601). | | `updated_at` | string | Data da última alteração (ISO 8601). | | `configuration` | object | A configuração editável (o rascunho). | | `configuration.prompt` | string \| null | As instruções do agente (só agentes em modo prompt; `null` nos do Flow Builder). | | `configuration.greeting` | object | A abertura da conversa. | | `configuration.greeting.mode` | string | `agent_first` (o agente fala primeiro) ou `human_first` (espera pela pessoa). Padrão: `agent_first`. | | `configuration.greeting.message` | string \| null | A saudação, ou `null`. | | `configuration.language` | string \| null | Língua da conversa, por exemplo `pt-PT`. | | `configuration.personality` | string \| null | Personalidade e tom. | | `configuration.objections` | string \| null | Como responder a objecções. | | `configuration.knowledge_notes` | string \| null | Notas de conhecimento escritas no agente. | | `configuration.knowledge_base_ids` | array | Bases de conhecimento atribuídas. | | `has_unpublished_changes` | boolean | `true` quando o rascunho difere da versão publicada. Padrão: `false`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "slug": "recepcao", "description": "CRM — produção", "status": "draft", "agent_type": "inbound", "editing_mode": "prompt", "version": 3, "phone_number": "+244900000000", "public_channel_enabled": false, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z", "configuration": { "prompt": "…", "greeting": { "mode": "agent_first", "message": "…" }, "language": "…", "personality": "…", "objections": "…", "knowledge_notes": "…", "knowledge_base_ids": [ "…" ] }, "has_unpublished_changes": false } ``` ## Erros | Código | Quando | | ------ | ----------------------------------------------------------------- | | `404` | `Agente não encontrado.` — o agente não existe nesta organização. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Editar um agente ```http PATCH https://api.diska.ai/v1/agents/{agent_id} ``` **Âmbito:** `agents:write` As chamadas continuam a usar a versão publicada até [publicar](https://docs.diska.ai/pt/api/reference/agents/publish-agent). A voz, o motor e as acções editam-se no backoffice. Em agentes do Flow Builder o texto vem dos fluxos, por isso `prompt` é recusado. Se duas alterações chegarem ao mesmo tempo, fica a última. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ---------- | ------ | ----------- | ------------------------ | | `agent_id` | string | Sim | Identificador do agente. | ## Corpo do pedido `application/json` | Campo | Tipo | Obrigatório | Descrição | | -------------------- | -------------- | ----------- | ------------------------------------------------------------------- | | `name` | string \| null | Não | Novo nome. Até 120 caracteres. | | `description` | string \| null | Não | Nova descrição; `null` apaga-a. Até 2000 caracteres. | | `prompt` | string \| null | Não | Novas instruções (só agentes em modo prompt). Até 60000 caracteres. | | `greeting` | object \| null | Não | Altera a saudação; só os campos enviados mudam. | | `greeting.mode` | string \| null | Não | `agent_first` ou `human_first`. | | `greeting.message` | string \| null | Não | A saudação; `null` apaga. Até 500 caracteres. | | `language` | string \| null | Não | Língua, no formato `pt-PT`. | | `personality` | string \| null | Não | Personalidade e tom; `null` apaga. Até 10000 caracteres. | | `objections` | string \| null | Não | Como responder a objecções; `null` apaga. Até 10000 caracteres. | | `knowledge_notes` | string \| null | Não | Notas de conhecimento; `null` apaga. Até 10000 caracteres. | | `knowledge_base_ids` | array \| null | Não | Substitui as bases atribuídas pela lista enviada. | ```json { "prompt": "És a recepcionista da Clínica Sol. Marca consultas de segunda a sexta.", "greeting": { "mode": "agent_first", "message": "Clínica Sol, bom dia!" }, "language": "pt-PT" } ``` ## Exemplos ::code-group ```bash [cURL] curl -X PATCH "https://api.diska.ai/v1/agents/" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"prompt":"És a recepcionista da Clínica Sol. Marca consultas de segunda a sexta.","greeting":{"mode":"agent_first","message":"Clínica Sol, bom dia!"},"language":"pt-PT"}' ``` ```python [Python] import os import requests response = requests.patch( "https://api.diska.ai/v1/agents/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "prompt": "És a recepcionista da Clínica Sol. Marca consultas de segunda a sexta.", "greeting": { "mode": "agent_first", "message": "Clínica Sol, bom dia!", }, "language": "pt-PT", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/agents/', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "prompt": "És a recepcionista da Clínica Sol. Marca consultas de segunda a sexta.", "greeting": { "mode": "agent_first", "message": "Clínica Sol, bom dia!" }, "language": "pt-PT" }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'PATCH', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'prompt' => 'És a recepcionista da Clínica Sol. Marca consultas de segunda a sexta.', 'greeting' => [ 'mode' => 'agent_first', 'message' => 'Clínica Sol, bom dia!', ], 'language' => 'pt-PT', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: agent_id in: path required: true body: > { "prompt": "És a recepcionista da Clínica Sol. Marca consultas de segunda a sexta.", "greeting": { "mode": "agent_first", "message": "Clínica Sol, bom dia!" }, "language": "pt-PT" } body-type: json locale: pt method: PATCH path: /v1/agents/{agent_id} --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ---------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------- | | `id` | string | Identificador do agente. | | `name` | string | Nome do agente. | | `slug` | string | Identificador legível do agente. | | `description` | string \| null | Descrição, ou `null`. | | `status` | string | `draft`, `active`, `inactive` ou `archived`. Um agente publicado fica `active`. | | `agent_type` | string | `inbound`, `outbound`, `voice_widget` ou `chat`. | | `editing_mode` | string | `prompt` ou `flow` (Flow Builder). Não muda depois de criado. Padrão: `prompt`. | | `version` | integer | Número da versão do agente. Padrão: `1`. | | `phone_number` | string \| null | Número atribuído ao agente, ou `null`. | | `public_channel_enabled` | boolean | `true` quando o Link público do agente está activo. Padrão: `false`. | | `created_at` | string | Data de criação (ISO 8601). | | `updated_at` | string | Data da última alteração (ISO 8601). | | `configuration` | object | A configuração editável (o rascunho). | | `configuration.prompt` | string \| null | As instruções do agente (só agentes em modo prompt; `null` nos do Flow Builder). | | `configuration.greeting` | object | A abertura da conversa. | | `configuration.greeting.mode` | string | `agent_first` (o agente fala primeiro) ou `human_first` (espera pela pessoa). Padrão: `agent_first`. | | `configuration.greeting.message` | string \| null | A saudação, ou `null`. | | `configuration.language` | string \| null | Língua da conversa, por exemplo `pt-PT`. | | `configuration.personality` | string \| null | Personalidade e tom. | | `configuration.objections` | string \| null | Como responder a objecções. | | `configuration.knowledge_notes` | string \| null | Notas de conhecimento escritas no agente. | | `configuration.knowledge_base_ids` | array | Bases de conhecimento atribuídas. | | `has_unpublished_changes` | boolean | `true` quando o rascunho difere da versão publicada. Padrão: `false`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "slug": "recepcao", "description": "CRM — produção", "status": "draft", "agent_type": "inbound", "editing_mode": "prompt", "version": 3, "phone_number": "+244900000000", "public_channel_enabled": false, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z", "configuration": { "prompt": "…", "greeting": { "mode": "agent_first", "message": "…" }, "language": "…", "personality": "…", "objections": "…", "knowledge_notes": "…", "knowledge_base_ids": [ "…" ] }, "has_unpublished_changes": false } ``` ## Erros | Código | Quando | | ------ | ---------------------------------------------------------------------------------------------------------- | | `404` | `Agente não encontrado.` — o agente não existe nesta organização. | | `404` | `Base de conhecimento não encontrada.` — um dos `knowledge_base_ids` não existe. | | `409` | O agente está arquivado, ou `prompt` foi enviado para um agente do Flow Builder. | | `422` | Um campo desconhecido, um valor fora dos limites, ou `null` em `name`, `prompt`, `greeting` ou `language`. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Criar um agente ```http POST https://api.diska.ai/v1/agents ``` **Âmbito:** `agents:write` O agente nasce em rascunho (`status: draft`): [publique-o](https://docs.diska.ai/pt/api/reference/agents/publish-agent) para ficar disponível nos canais. A API da DISKA não lista modelos. ## Corpo do pedido `application/json` | Campo | Tipo | Obrigatório | Descrição | | -------------- | -------------- | ----------- | ------------------------------------------------------------------------------------------------------------------ | | `name` | string \| null | Não | Nome do agente. Por omissão: `Novo agente`, ou o nome do modelo. Até 120 caracteres. | | `agent_type` | string \| null | Não | Tipo do agente. Por omissão: `inbound`, ou o tipo do modelo. Um de: `inbound`, `outbound`, `voice_widget`, `chat`. | | `editing_mode` | string \| null | Não | Por omissão: `prompt` num agente em branco, `flow` a partir de um modelo. | | `template_id` | string \| null | Não | Modelo de agente da Diska. Sem ele, o agente é criado em branco. Até 64 caracteres. | ```json { "name": "Recepção", "agent_type": "inbound", "editing_mode": "prompt" } ``` ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/agents" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name":"Recepção","agent_type":"inbound","editing_mode":"prompt"}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/agents", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "name": "Recepção", "agent_type": "inbound", "editing_mode": "prompt", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/agents', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "name": "Recepção", "agent_type": "inbound", "editing_mode": "prompt" }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'name' => 'Recepção', 'agent_type' => 'inbound', 'editing_mode' => 'prompt', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: [] body: | { "name": "Recepção", "agent_type": "inbound", "editing_mode": "prompt" } body-type: json locale: pt method: POST path: /v1/agents --- :: ## Resposta `201` | Campo | Tipo | Descrição | | ------------------------ | -------------- | ------------------------------------------------------------------------------- | | `id` | string | Identificador do agente. | | `name` | string | Nome do agente. | | `slug` | string | Identificador legível do agente. | | `description` | string \| null | Descrição, ou `null`. | | `status` | string | `draft`, `active`, `inactive` ou `archived`. Um agente publicado fica `active`. | | `agent_type` | string | `inbound`, `outbound`, `voice_widget` ou `chat`. | | `editing_mode` | string | `prompt` ou `flow` (Flow Builder). Não muda depois de criado. Padrão: `prompt`. | | `version` | integer | Número da versão do agente. Padrão: `1`. | | `phone_number` | string \| null | Número atribuído ao agente, ou `null`. | | `public_channel_enabled` | boolean | `true` quando o Link público do agente está activo. Padrão: `false`. | | `created_at` | string | Data de criação (ISO 8601). | | `updated_at` | string | Data da última alteração (ISO 8601). | ```json { "id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "name": "Recepção", "slug": "recepcao", "description": "Atende as chamadas da recepção.", "status": "active", "agent_type": "inbound", "editing_mode": "prompt", "version": 3, "phone_number": "+244900000000", "public_channel_enabled": false, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z" } ``` ## Erros | Código | Quando | | ------ | ------------------------------------------------------ | | `404` | `Modelo não encontrado.` — o `template_id` não existe. | | `422` | O modelo não pôde ser instalado. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Publicar um agente ```http POST https://api.diska.ai/v1/agents/{agent_id}/publish ``` **Âmbito:** `agents:write` Em agentes de fluxo, publica também o fluxo principal e os subfluxos que ele usa. Se nada mudou desde a última publicação, não é criada uma versão nova. O corpo é opcional. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ---------- | ------ | ----------- | ------------------------ | | `agent_id` | string | Sim | Identificador do agente. | ## Corpo do pedido `application/json` — O corpo é opcional. | Campo | Tipo | Obrigatório | Descrição | | ------- | -------------- | ----------- | ------------------------------------------------------------ | | `label` | string \| null | Não | Nome da versão. Por omissão: `Versão N`. Até 120 caracteres. | ```json { "label": "Horário de Dezembro" } ``` ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/agents//publish" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"label":"Horário de Dezembro"}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/agents//publish", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "label": "Horário de Dezembro", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/agents//publish', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "label": "Horário de Dezembro" }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /publish'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'label' => 'Horário de Dezembro', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: agent_id in: path required: true body: | { "label": "Horário de Dezembro" } body-type: json locale: pt method: POST path: /v1/agents/{agent_id}/publish --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ------------------------ | -------------- | ------------------------------------------------------------------------------- | | `id` | string | Identificador do agente. | | `name` | string | Nome do agente. | | `slug` | string | Identificador legível do agente. | | `description` | string \| null | Descrição, ou `null`. | | `status` | string | `draft`, `active`, `inactive` ou `archived`. Um agente publicado fica `active`. | | `agent_type` | string | `inbound`, `outbound`, `voice_widget` ou `chat`. | | `editing_mode` | string | `prompt` ou `flow` (Flow Builder). Não muda depois de criado. Padrão: `prompt`. | | `version` | integer | Número da versão do agente. Padrão: `1`. | | `phone_number` | string \| null | Número atribuído ao agente, ou `null`. | | `public_channel_enabled` | boolean | `true` quando o Link público do agente está activo. Padrão: `false`. | | `created_at` | string | Data de criação (ISO 8601). | | `updated_at` | string | Data da última alteração (ISO 8601). | ```json { "id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "name": "Recepção", "slug": "recepcao", "description": "Atende as chamadas da recepção.", "status": "active", "agent_type": "inbound", "editing_mode": "prompt", "version": 3, "phone_number": "+244900000000", "public_channel_enabled": false, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z" } ``` ## Erros | Código | Quando | | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `404` | `Agente não encontrado.` — o agente não existe nesta organização. | | `409` | `O agente está arquivado. Restaure-o antes de publicar.` | | `422` | O agente não pode ser publicado — por exemplo `O agente precisa de instruções (prompt) antes de ser publicado.` ou um erro de validação do fluxo. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Agentes A configuração interna do agente (prompt, fluxos, voz e acções) não é exposta: edite-a no backoffice. | Método | Endpoint | Descrição | Âmbito | | ------- | ---------------------------------------------------------------------------------------------- | ------------------ | -------------- | | `GET` | [`/v1/agents`](https://docs.diska.ai/pt/api/reference/agents/list-agents) | Listar agentes | `agents:read` | | `GET` | [`/v1/agents/{agent_id}`](https://docs.diska.ai/pt/api/reference/agents/get-agent) | Ver um agente | `agents:read` | | `PATCH` | [`/v1/agents/{agent_id}`](https://docs.diska.ai/pt/api/reference/agents/update-agent) | Editar um agente | `agents:write` | | `POST` | [`/v1/agents`](https://docs.diska.ai/pt/api/reference/agents/create-agent) | Criar um agente | `agents:write` | | `POST` | [`/v1/agents/{agent_id}/publish`](https://docs.diska.ai/pt/api/reference/agents/publish-agent) | Publicar um agente | `agents:write` | # Listar chamadas ```http GET https://api.diska.ai/v1/calls ``` **Âmbito:** `calls:read` Tem dois modos de [paginação](https://docs.diska.ai/pt/api/api-channel#pagina%C3%A7%C3%A3o): **offset** (por omissão, com `total`) e **cursor** (`cursor=start`, depois o `next_cursor` recebido), melhor para exportar históricos grandes. ## Parâmetros ### Na query string | Nome | Tipo | Obrigatório | Descrição | | ---------- | -------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------- | | `search` | string \| null | Não | Texto no identificador, no `external_ref`, no nome ou no contacto de quem ligou. Não funciona com `cursor`. Até 200 caracteres. | | `agent_id` | string \| null | Não | Só chamadas deste agente. | | `status` | string \| null | Não | Só chamadas neste estado. Um de: `created`, `active`, `completed`, `failed`, `cancelled`, `abandoned`. | | `channel` | string \| null | Não | Só chamadas deste canal: `browser_demo` (chamada web), `phone`, `whatsapp` ou `web_chat`. | | `limit` | integer | Não | Quantas chamadas por página. Entre 1 e 200. Padrão: `50`. | | `offset` | integer | Não | Modo offset: quantas chamadas saltar. Mínimo 0. Padrão: `0`. | | `cursor` | string \| null | Não | Modo cursor: `start` na primeira página, depois o `next_cursor` recebido. Até 200 caracteres. | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/calls?limit=10" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/calls?limit=10", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/calls?limit=10', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: search in: query - name: agent_id in: query - name: status in: query options: - created - active - completed - failed - cancelled - abandoned - name: channel in: query options: - browser_demo - phone - whatsapp - web_chat - name: limit in: query value: "10" - name: offset in: query - name: cursor in: query body-type: none locale: pt method: GET path: /v1/calls --- :: ## Resposta `200` | Campo | Tipo | Descrição | | -------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------ | | `items` | array | As chamadas desta página. | | `items[].id` | string | Identificador da chamada (o `call_id` dos webhooks). | | `items[].external_ref` | string \| null | Identificador da sessão de voz (o `session_id` dos webhooks). | | `items[].agent_id` | string \| null | Agente que atendeu. | | `items[].agent_name` | string \| null | Nome do agente que atendeu. | | `items[].channel` | string | `browser_demo` (chamada web), `phone`, `whatsapp` ou `web_chat`. Padrão: `browser_demo`. | | `items[].direction` | string \| null | `inbound`, `outbound`, ou `null` em chamadas web. | | `items[].status` | string | Estado da chamada. Um de: `created`, `active`, `completed`, `failed`, `cancelled`, `abandoned`. Padrão: `created`. | | `items[].caller_name` | string \| null | Nome de quem ligou, quando conhecido. | | `items[].caller_contact` | string \| null | Contacto de quem ligou, quando conhecido. | | `items[].started_at` | string \| null | Início da chamada. | | `items[].ended_at` | string \| null | Fim da chamada. | | `items[].duration_seconds` | integer \| null | Duração em segundos. | | `items[].end_reason` | string \| null | Motivo do fim da chamada. | | `items[].summary` | string \| null | Resumo da chamada, quando gerado. | | `items[].is_simulation` | boolean | `true` em chamadas web de teste (`browser_demo`). Padrão: `true`. | | `items[].labels` | array | Etiquetas da chamada. | | `items[].has_post_call` | boolean | `true` quando existe resultado pós-chamada. Padrão: `false`. | | `items[].executed_actions_count` | integer | Número de acções executadas. Padrão: `0`. | | `limit` | integer | Tamanho da página pedido. | | `total` | integer \| null | Total de chamadas com estes filtros (modo offset); `null` em modo cursor. | | `offset` | integer \| null | Offset desta página (modo offset); `null` em modo cursor. | | `next_cursor` | string \| null | Cursor da página seguinte (modo cursor), ou `null` no fim. | ```json { "items": [ { "id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "external_ref": "sess_7f3a9c1e", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "channel": "phone", "direction": "inbound", "status": "completed", "caller_name": "Ana Silva", "caller_contact": "+244900000000", "started_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "duration_seconds": 95, "end_reason": "caller_hangup", "summary": "O cliente pediu o horário de abertura e marcou uma visita para sexta-feira.", "is_simulation": false, "labels": [ "urgente" ], "has_post_call": false, "executed_actions_count": 2 } ], "limit": 50, "total": 1, "offset": 0, "next_cursor": "…" } ``` ## Erros | Código | Quando | | ------ | --------------------------------------------------- | | `400` | `Cursor inválido.`, ou `search` usado com `cursor`. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Ver uma chamada ```http GET https://api.diska.ai/v1/calls/{call_id} ``` **Âmbito:** `calls:read` O áudio da gravação não é devolvido: ouça-o em [Históricos](https://docs.diska.ai/pt/history/recordings). ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | --------- | ------ | ----------- | ---------------------------------------------------- | | `call_id` | string | Sim | Identificador da chamada (o `call_id` dos webhooks). | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/calls/" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/calls/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/calls/', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: call_id in: path required: true body-type: none locale: pt method: GET path: /v1/calls/{call_id} --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ---------------------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Identificador da chamada (o `call_id` dos webhooks). | | `external_ref` | string \| null | Identificador da sessão de voz (o `session_id` dos webhooks). | | `agent_id` | string \| null | Agente que atendeu. | | `agent_name` | string \| null | Nome do agente que atendeu. | | `channel` | string | `browser_demo` (chamada web), `phone`, `whatsapp` ou `web_chat`. Padrão: `browser_demo`. | | `direction` | string \| null | `inbound`, `outbound`, ou `null` em chamadas web. | | `status` | string | Estado da chamada. Um de: `created`, `active`, `completed`, `failed`, `cancelled`, `abandoned`. Padrão: `created`. | | `caller_name` | string \| null | Nome de quem ligou, quando conhecido. | | `caller_contact` | string \| null | Contacto de quem ligou, quando conhecido. | | `started_at` | string \| null | Início da chamada. | | `ended_at` | string \| null | Fim da chamada. | | `duration_seconds` | integer \| null | Duração em segundos. | | `end_reason` | string \| null | Motivo do fim da chamada. | | `summary` | string \| null | Resumo da chamada, quando gerado. | | `is_simulation` | boolean | `true` em chamadas web de teste (`browser_demo`). Padrão: `true`. | | `labels` | array | Etiquetas da chamada. | | `has_post_call` | boolean | `true` quando existe resultado pós-chamada. Padrão: `false`. | | `executed_actions_count` | integer | Número de acções executadas. Padrão: `0`. | | `organization_id` | string | Organização da chamada. | | `metadata` | object | Metadados técnicos. O conteúdo não é estável: não dependa dele. | | `messages` | array | Transcrição, por ordem. | | `messages[].id` | string | Identificador da fala. | | `messages[].sequence` | integer | Ordem da fala na conversa. Padrão: `0`. | | `messages[].role` | string | `user` (quem ligou) ou `assistant` (o agente). Padrão: `user`. | | `messages[].content` | string | O que foi dito. | | `messages[].created_at` | string \| null | Quando a fala foi registada. | | `tool_calls` | array | Acções executadas durante a chamada. | | `tool_calls[].id` | string | Identificador da execução. | | `tool_calls[].tool_name` | string | Acção executada. | | `tool_calls[].status` | string | Estado da execução. Padrão: `pending`. | | `tool_calls[].input` | object | Dados enviados à acção. | | `tool_calls[].output` | object \| array \| null | Resultado da acção, ou `null`. | | `tool_calls[].error_message` | string \| null | Erro, quando falhou. | | `tool_calls[].latency_ms` | integer \| null | Tempo de execução em milissegundos. | | `tool_calls[].called_at` | string \| null | Início da execução. | | `tool_calls[].completed_at` | string \| null | Fim da execução. | | `post_call` | object \| null | Resultado pós-chamada (o conteúdo do webhook `call.completed`, sem `call_id`), ou `null`. | | `has_recording` | boolean | `true` quando há gravação disponível. Padrão: `false`. | | `recording_state` | string | Estado da gravação. Um de: `disabled`, `recording`, `uploading`, `available`, `failed`, `expired`, `deleted`. Padrão: `disabled`. | ```json { "id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "external_ref": "sess_7f3a9c1e", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "channel": "phone", "direction": "inbound", "status": "completed", "caller_name": "Ana Silva", "caller_contact": "+244900000000", "started_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "duration_seconds": 95, "end_reason": "caller_hangup", "summary": "O cliente pediu o horário de abertura e marcou uma visita para sexta-feira.", "is_simulation": false, "labels": [ "urgente" ], "has_post_call": true, "executed_actions_count": 2, "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "metadata": {}, "messages": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "sequence": 1, "role": "user", "content": "Bom dia, queria marcar uma consulta.", "created_at": "2026-10-25T18:40:00Z" } ], "tool_calls": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "tool_name": "transfer_call", "status": "completed", "input": {}, "output": {}, "error_message": null, "latency_ms": 820, "called_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z" } ], "post_call": {}, "has_recording": true, "recording_state": "available" } ``` ## Erros | Código | Quando | | ------ | ------------------------- | | `404` | `Chamada não encontrada.` | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Descarregar a gravação ```http GET https://api.diska.ai/v1/calls/{call_id}/recording ``` **Âmbito:** `recordings:read` Por omissão responde `302` para um link assinado que dura 5 minutos (`curl -L -o gravacao.webm …` segue-o e guarda o áudio). Com `?format=json`, devolve o link em JSON. Peça um link novo sempre que precisar do áudio, em vez de o guardar. Cada acesso fica registado na auditoria. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | --------- | ------ | ----------- | ------------------------- | | `call_id` | string | Sim | Identificador da chamada. | ### Na query string | Nome | Tipo | Obrigatório | Descrição | | -------- | ------ | ----------- | ----------------------------------- | | `format` | string | Não | `redirect` (por omissão) ou `json`. | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/calls//recording?format=json" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/calls//recording?format=json", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/calls//recording?format=json', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /recording?format=json'); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: call_id in: path required: true - name: format in: query options: - redirect - json value: json body-type: none locale: pt method: GET path: /v1/calls/{call_id}/recording --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ------------------ | --------------- | ------------------------------------------- | | `call_id` | string | A chamada. | | `url` | string | Link assinado para descarregar o áudio. | | `expires_in` | integer | Segundos até o link expirar. | | `content_type` | string \| null | Formato do áudio, por exemplo `audio/webm`. | | `size_bytes` | integer \| null | Tamanho em bytes. | | `duration_seconds` | integer \| null | Duração em segundos, quando conhecida. | ```json { "call_id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "url": "https://o-seu-sistema.com/hooks/diska", "expires_in": 0, "content_type": "…", "size_bytes": 48213, "duration_seconds": 95 } ``` ## Erros | Código | Quando | | ------ | ---------------------------------------------------------------------------------------------- | | `404` | `Esta chamada não tem gravação.`, ou a gravação já não está disponível (por exemplo, expirou). | | `502` | Não foi possível gerar o link. Tente de novo. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Chamadas Para ser avisado quando uma chamada termina, use [webhooks](https://docs.diska.ai/pt/api/webhooks). | Método | Endpoint | Descrição | Âmbito | | ------ | -------------------------------------------------------------------------------------------------- | ---------------------- | ----------------- | | `GET` | [`/v1/calls`](https://docs.diska.ai/pt/api/reference/calls/list-calls) | Listar chamadas | `calls:read` | | `GET` | [`/v1/calls/{call_id}`](https://docs.diska.ai/pt/api/reference/calls/get-call) | Ver uma chamada | `calls:read` | | `GET` | [`/v1/calls/{call_id}/recording`](https://docs.diska.ai/pt/api/reference/calls/get-call-recording) | Descarregar a gravação | `recordings:read` | # Fazer uma chamada de saída ```http POST https://api.diska.ai/v1/outbound-calls ``` **Âmbito:** `calls:write` A resposta traz o `id` do pedido, com o estado `queued`. Acompanhe-o em [Ver uma chamada de saída](https://docs.diska.ai/pt/api/reference/outbound-calls/get-outbound-call): quando a sessão do agente começa, aparece o `call_id`, o mesmo de `GET /v1/calls` e dos webhooks. O agente recebe da plataforma o contexto da chamada: é uma chamada de saída, o motivo (`purpose`) e o nome do contacto. Envie `Idempotency-Key` para repetir o pedido sem ligar duas vezes. ## Corpo do pedido `application/json` | Campo | Tipo | Obrigatório | Descrição | | -------------- | -------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------- | | `agent_id` | string | Sim | O agente que liga (de saída, publicado, em modo prompt). Até 64 caracteres. | | `to` | string | Sim | Telemóvel angolano: `+244 9XX XXX XXX`, `9XX XXX XXX` ou `00244…`. 9 a 20 caracteres. | | `contact_name` | string \| null | Não | Nome da pessoa, para o agente a tratar pelo nome. Até 120 caracteres. | | `purpose` | string \| null | Não | Motivo da chamada, como o agente o pode dizer. Nunca é lido como instrução. Até 120 caracteres. | | `variables` | object | Não | Variáveis da chamada (`{{nome}}` nos fluxos e nas acções). Até 20; chaves reservadas ou valores com instruções são recusados. | ```json { "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "+244923000000", "contact_name": "Ana Silva", "purpose": "Lembrete da consulta de sexta-feira", "variables": { "consulta": "sexta, 10h" } } ``` ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/outbound-calls" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"agent_id":"3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40","to":"+244923000000","contact_name":"Ana Silva","purpose":"Lembrete da consulta de sexta-feira","variables":{"consulta":"sexta, 10h"}}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/outbound-calls", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "+244923000000", "contact_name": "Ana Silva", "purpose": "Lembrete da consulta de sexta-feira", "variables": { "consulta": "sexta, 10h", }, }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/outbound-calls', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "+244923000000", "contact_name": "Ana Silva", "purpose": "Lembrete da consulta de sexta-feira", "variables": { "consulta": "sexta, 10h" } }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'agent_id' => '3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40', 'to' => '+244923000000', 'contact_name' => 'Ana Silva', 'purpose' => 'Lembrete da consulta de sexta-feira', 'variables' => [ 'consulta' => 'sexta, 10h', ], ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: [] body: | { "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "+244923000000", "contact_name": "Ana Silva", "purpose": "Lembrete da consulta de sexta-feira", "variables": { "consulta": "sexta, 10h" } } body-type: json locale: pt method: POST path: /v1/outbound-calls --- :: ## Resposta `201` | Campo | Tipo | Descrição | | ----------------- | -------------- | ---------------------------------------------------------------------------------------- | | `id` | string | Identificador do pedido de chamada. | | `status` | string | `queued`, `ringing`, `in_progress`, `ended`, `failed` ou `cancelled`. | | `failure_code` | string \| null | Porque falhou, por exemplo `destination_no_answer`. | | `failure_message` | string \| null | O mesmo motivo, em texto. | | `agent_id` | string | O agente que liga. | | `to` | string | Número chamado. | | `from_number` | string | Número DISKA que aparece a quem atende. | | `contact_name` | string \| null | Nome do contacto. | | `purpose` | string \| null | Motivo da chamada. | | `call_id` | string \| null | A chamada em `GET /v1/calls/{call_id}` e nos webhooks, quando a sessão do agente começa. | | `created_at` | string | Quando o pedido foi feito. | | `answered_at` | string \| null | Quando a pessoa atendeu. | | `ended_at` | string \| null | Quando terminou. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "status": "queued", "failure_code": "…", "failure_message": "…", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "…", "from_number": "…", "contact_name": "…", "purpose": "…", "call_id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "created_at": "2026-10-25T18:40:00Z", "answered_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z" } ``` ## Erros | Código | Quando | | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `403` | As chamadas pela API não estão activas para a organização, ou a organização não está habilitada para chamadas de saída. | | `404` | `Agente não encontrado.` | | `409` | O agente não é de saída, não está publicado ou não está em modo prompt; não tem número DISKA activo; fora do horário de contacto; ou o número está na lista de exclusão. | | `422` | O destino não é um telemóvel angolano, é o número do agente, ou há variáveis recusadas. | | `429` | Limite de chamadas simultâneas da organização, ou limite de chamadas pela API desta hora. | | `503` | A linha telefónica não está disponível neste momento. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Ver uma chamada de saída ```http GET https://api.diska.ai/v1/outbound-calls/{outbound_call_id} ``` **Âmbito:** `calls:read` Fica disponível durante 24 horas; depois, use o `call_id`. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------------ | ------ | ----------- | ------------------------------------ | | `outbound_call_id` | string | Sim | O `id` devolvido ao criar a chamada. | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/outbound-calls/" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/outbound-calls/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/outbound-calls/', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: outbound_call_id in: path required: true body-type: none locale: pt method: GET path: /v1/outbound-calls/{outbound_call_id} --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ----------------- | -------------- | ---------------------------------------------------------------------------------------- | | `id` | string | Identificador do pedido de chamada. | | `status` | string | `queued`, `ringing`, `in_progress`, `ended`, `failed` ou `cancelled`. | | `failure_code` | string \| null | Porque falhou, por exemplo `destination_no_answer`. | | `failure_message` | string \| null | O mesmo motivo, em texto. | | `agent_id` | string | O agente que liga. | | `to` | string | Número chamado. | | `from_number` | string | Número DISKA que aparece a quem atende. | | `contact_name` | string \| null | Nome do contacto. | | `purpose` | string \| null | Motivo da chamada. | | `call_id` | string \| null | A chamada em `GET /v1/calls/{call_id}` e nos webhooks, quando a sessão do agente começa. | | `created_at` | string | Quando o pedido foi feito. | | `answered_at` | string \| null | Quando a pessoa atendeu. | | `ended_at` | string \| null | Quando terminou. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "status": "queued", "failure_code": "…", "failure_message": "…", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "…", "from_number": "…", "contact_name": "…", "purpose": "…", "call_id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "created_at": "2026-10-25T18:40:00Z", "answered_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z" } ``` ## Erros | Código | Quando | | ------ | --------------------------------------------------------------------------------------------- | | `404` | `Chamada de saída não encontrada.` — não existe, é de outra organização ou passaram 24 horas. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Desligar uma chamada de saída ```http POST https://api.diska.ai/v1/outbound-calls/{outbound_call_id}/hangup ``` **Âmbito:** `calls:write` Numa chamada já terminada não faz nada. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------------ | ------ | ----------- | ------------------------------------ | | `outbound_call_id` | string | Sim | O `id` devolvido ao criar a chamada. | ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/outbound-calls//hangup" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/outbound-calls//hangup", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/outbound-calls//hangup', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /hangup'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: outbound_call_id in: path required: true body-type: none locale: pt method: POST path: /v1/outbound-calls/{outbound_call_id}/hangup --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ----------------- | -------------- | ---------------------------------------------------------------------------------------- | | `id` | string | Identificador do pedido de chamada. | | `status` | string | `queued`, `ringing`, `in_progress`, `ended`, `failed` ou `cancelled`. | | `failure_code` | string \| null | Porque falhou, por exemplo `destination_no_answer`. | | `failure_message` | string \| null | O mesmo motivo, em texto. | | `agent_id` | string | O agente que liga. | | `to` | string | Número chamado. | | `from_number` | string | Número DISKA que aparece a quem atende. | | `contact_name` | string \| null | Nome do contacto. | | `purpose` | string \| null | Motivo da chamada. | | `call_id` | string \| null | A chamada em `GET /v1/calls/{call_id}` e nos webhooks, quando a sessão do agente começa. | | `created_at` | string | Quando o pedido foi feito. | | `answered_at` | string \| null | Quando a pessoa atendeu. | | `ended_at` | string \| null | Quando terminou. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "status": "queued", "failure_code": "…", "failure_message": "…", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "…", "from_number": "…", "contact_name": "…", "purpose": "…", "call_id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "created_at": "2026-10-25T18:40:00Z", "answered_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z" } ``` ## Erros | Código | Quando | | ------ | ---------------------------------- | | `404` | `Chamada de saída não encontrada.` | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Chamadas de saída Só agentes de saída publicados, em telemóveis angolanos, dentro do horário de contacto (08h–20h) e fora da lista de exclusão. Disponível quando a Diska activa as chamadas pela API para a organização. | Método | Endpoint | Descrição | Âmbito | | ------ | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | ------------- | | `POST` | [`/v1/outbound-calls`](https://docs.diska.ai/pt/api/reference/outbound-calls/create-outbound-call) | Fazer uma chamada de saída | `calls:write` | | `GET` | [`/v1/outbound-calls/{outbound_call_id}`](https://docs.diska.ai/pt/api/reference/outbound-calls/get-outbound-call) | Ver uma chamada de saída | `calls:read` | | `POST` | [`/v1/outbound-calls/{outbound_call_id}/hangup`](https://docs.diska.ai/pt/api/reference/outbound-calls/hang-up-outbound-call) | Desligar uma chamada de saída | `calls:write` | # Listar campanhas ```http GET https://api.diska.ai/v1/campaigns ``` **Âmbito:** `campaigns:read` ## Parâmetros ### Na query string | Nome | Tipo | Obrigatório | Descrição | | -------- | -------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------- | | `status` | string \| null | Não | Só campanhas neste estado. Um de: `draft`, `scheduled`, `running`, `paused`, `completed`, `cancelled`. Até 20 caracteres. | | `limit` | integer | Não | Quantas por página. Entre 1 e 100. Padrão: `50`. | | `offset` | integer | Não | Quantas saltar. Mínimo 0. Padrão: `0`. | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/campaigns" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/campaigns", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/campaigns', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: status in: query options: - draft - scheduled - running - paused - completed - cancelled - name: limit in: query - name: offset in: query body-type: none locale: pt method: GET path: /v1/campaigns --- :: ## Resposta `200` | Campo | Tipo | Descrição | | -------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `items` | array | As campanhas. | | `items[].id` | string | Identificador da campanha. | | `items[].name` | string | Nome. | | `items[].status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` ou `cancelled`. | | `items[].agent_id` | string \| null | Agente. | | `items[].agent_name` | string \| null | Nome do agente. | | `items[].phone_number_id` | string \| null | Linha usada. | | `items[].phone_number` | string \| null | Número da linha. | | `items[].schedule` | object | Horário. | | `items[].schedule.start_at` | string \| null | Início (ISO 8601 com fuso), ou `null` para começar ao iniciar. | | `items[].schedule.timezone` | string | Fuso das janelas. Padrão: `Africa/Luanda`. | | `items[].schedule.windows` | array | Janelas por dia da semana. Sem janelas, liga dentro do horário de contacto. | | `items[].schedule.max_duration_days` | integer | Dias que a campanha pode durar; no fim, o que falta é cancelado. Entre 1 e 90. Padrão: `7`. | | `items[].limits` | object | Limites. | | `items[].limits.max_concurrency` | integer | Chamadas da campanha em simultâneo. Entre 1 e 50. Padrão: `2`. | | `items[].limits.reserved_capacity` | integer | Chamadas simultâneas da organização que ficam livres para outras chamadas. Entre 0 e 50. Padrão: `1`. | | `items[].limits.max_attempts` | integer | Tentativas por destinatário; só não atendidas ou ocupadas são repetidas. Entre 1 e 3. Padrão: `1`. | | `items[].limits.retry_delay_minutes` | integer | Minutos entre tentativas. Entre 15 e 1440. Padrão: `60`. | | `items[].limits.budget_minutes` | integer \| null | Minutos máximos; a campanha pausa antes de os ultrapassar. Entre 1 e 100000. | | `items[].pause_reason` | string \| null | Porque está pausada: `manual`, `budget_exhausted`, `quota_exhausted` ou `emergency_stop`. | | `items[].waiting_reason` | string \| null | Porque não está a ligar agora, por exemplo `outside_window` ou `no_capacity`. Um de: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `items[].next_window_at` | string \| null | Quando abre a próxima janela. | | `items[].deadline_at` | string \| null | Fim do prazo máximo. | | `items[].created_at` | string \| null | Data de criação (ISO 8601). | | `items[].started_at` | string \| null | Quando foi iniciada. | | `items[].completed_at` | string \| null | Quando terminou. | | `items[].cancelled_at` | string \| null | Quando foi cancelada. | | `items[].stats` | object | Indicadores. | | `items[].stats.total` | integer | Destinatários. Padrão: `0`. | | `items[].stats.pending` | integer | Por ligar. Padrão: `0`. | | `items[].stats.in_flight` | integer | A ligar ou em chamada. Padrão: `0`. | | `items[].stats.completed` | integer | Chamada feita (atendida, não atendida ou ocupado). Padrão: `0`. | | `items[].stats.failed` | integer | Não foi possível ligar. Padrão: `0`. | | `items[].stats.cancelled` | integer | Cancelados. Padrão: `0`. | | `items[].stats.excluded` | integer | Na lista de exclusão. Padrão: `0`. | | `items[].stats.calls_started` | integer | Tentativas enviadas (cada repetição conta). Padrão: `0`. | | `items[].stats.answered` | integer | Atendidas. Padrão: `0`. | | `items[].stats.no_answer` | integer | Não atendidas. Padrão: `0`. | | `items[].stats.unavailable` | integer | Ocupado ou indisponível. Padrão: `0`. | | `items[].stats.answer_rate` | number \| null | Atendidas ÷ (atendidas + não atendidas + indisponíveis). | | `items[].stats.total_duration_seconds` | integer | Soma da duração das chamadas atendidas. Padrão: `0`. | | `items[].stats.progress` | number | Destinatários em estado final ÷ total. Padrão: `0`. | | `items[].stats.cost_kz` | number \| null | Custo em kwanzas, só quando há tarifa configurada. | | `items[].stats.with_post_call` | integer | Chamadas com resultado pós-chamada. Padrão: `0`. | | `total` | integer | Total de campanhas. | | `limit` | integer | Tamanho da página. | | `offset` | integer | Offset desta página. | ```json { "items": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ {} ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ], "total": 1, "limit": 50, "offset": 0 } ``` ## Erros Este endpoint não tem erros próprios. Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Criar uma campanha ```http POST https://api.diska.ai/v1/campaigns ``` **Âmbito:** `campaigns:write` O agente tem de ser de saída e publicado, e `phone_number_id` uma linha DISKA activa da organização (veja [Listar números](https://docs.diska.ai/pt/api/reference/phone-numbers/list-phone-numbers)). As janelas têm de ficar dentro do horário de contacto (08h–20h). Depois, [acrescente destinatários](https://docs.diska.ai/pt/api/reference/campaigns/add-campaign-recipients) e [inicie-a](https://docs.diska.ai/pt/api/reference/campaigns/start-campaign). Envie `Idempotency-Key` para repetir o pedido sem criar duas. ## Corpo do pedido `application/json` | Campo | Tipo | Obrigatório | Descrição | | ---------------------------- | --------------- | ----------- | -------------------------------------------------------------------------------------------------------------- | | `name` | string | Sim | Nome da campanha. Até 120 caracteres. | | `agent_id` | string | Sim | Agente de saída publicado que faz as chamadas. | | `phone_number_id` | string | Sim | Linha DISKA de onde se liga (de `GET /v1/phone-numbers`). | | `schedule` | object | Não | Quando a campanha pode ligar. | | `schedule.start_at` | string \| null | Não | Início (ISO 8601 com fuso), ou `null` para começar ao iniciar. | | `schedule.timezone` | string | Não | Fuso das janelas. Padrão: `Africa/Luanda`. | | `schedule.windows` | array | Não | Janelas por dia da semana. Sem janelas, liga dentro do horário de contacto. | | `schedule.windows[].day` | string | Sim | Dia da semana, em inglês. Um de: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Sim | Início, `HH:MM`. | | `schedule.windows[].end` | string | Sim | Fim, `HH:MM`. | | `schedule.max_duration_days` | integer | Não | Dias que a campanha pode durar; no fim, o que falta é cancelado. Entre 1 e 90. Padrão: `7`. | | `limits` | object | Não | Concorrência, tentativas e orçamento. | | `limits.max_concurrency` | integer | Não | Chamadas da campanha em simultâneo. Entre 1 e 50. Padrão: `2`. | | `limits.reserved_capacity` | integer | Não | Chamadas simultâneas da organização que ficam livres para outras chamadas. Entre 0 e 50. Padrão: `1`. | | `limits.max_attempts` | integer | Não | Tentativas por destinatário; só não atendidas ou ocupadas são repetidas. Entre 1 e 3. Padrão: `1`. | | `limits.retry_delay_minutes` | integer | Não | Minutos entre tentativas. Entre 15 e 1440. Padrão: `60`. | | `limits.budget_minutes` | integer \| null | Não | Minutos máximos; a campanha pausa antes de os ultrapassar. Entre 1 e 100000. | ```json { "name": "Lembretes de Novembro", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "schedule": { "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "09:00", "end": "12:00" }, { "day": "monday", "start": "14:00", "end": "18:00" } ] }, "limits": { "max_concurrency": 2, "max_attempts": 2, "retry_delay_minutes": 60 } } ``` ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/campaigns" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name":"Lembretes de Novembro","agent_id":"3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40","phone_number_id":"5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93","schedule":{"timezone":"Africa/Luanda","windows":[{"day":"monday","start":"09:00","end":"12:00"},{"day":"monday","start":"14:00","end":"18:00"}]},"limits":{"max_concurrency":2,"max_attempts":2,"retry_delay_minutes":60}}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/campaigns", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "name": "Lembretes de Novembro", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "schedule": { "timezone": "Africa/Luanda", "windows": [{ "day": "monday", "start": "09:00", "end": "12:00", }, { "day": "monday", "start": "14:00", "end": "18:00", }], }, "limits": { "max_concurrency": 2, "max_attempts": 2, "retry_delay_minutes": 60, }, }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/campaigns', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "name": "Lembretes de Novembro", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "schedule": { "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "09:00", "end": "12:00" }, { "day": "monday", "start": "14:00", "end": "18:00" } ] }, "limits": { "max_concurrency": 2, "max_attempts": 2, "retry_delay_minutes": 60 } }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'name' => 'Lembretes de Novembro', 'agent_id' => '3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40', 'phone_number_id' => '5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93', 'schedule' => [ 'timezone' => 'Africa/Luanda', 'windows' => [[ 'day' => 'monday', 'start' => '09:00', 'end' => '12:00', ], [ 'day' => 'monday', 'start' => '14:00', 'end' => '18:00', ]], ], 'limits' => [ 'max_concurrency' => 2, 'max_attempts' => 2, 'retry_delay_minutes' => 60, ], ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: [] body: | { "name": "Lembretes de Novembro", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "schedule": { "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "09:00", "end": "12:00" }, { "day": "monday", "start": "14:00", "end": "18:00" } ] }, "limits": { "max_concurrency": 2, "max_attempts": 2, "retry_delay_minutes": 60 } } body-type: json locale: pt method: POST path: /v1/campaigns --- :: ## Resposta `201` | Campo | Tipo | Descrição | | ------------------------------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Identificador da campanha. | | `name` | string | Nome. | | `status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` ou `cancelled`. | | `agent_id` | string \| null | Agente. | | `agent_name` | string \| null | Nome do agente. | | `phone_number_id` | string \| null | Linha usada. | | `phone_number` | string \| null | Número da linha. | | `schedule` | object | Horário. | | `schedule.start_at` | string \| null | Início (ISO 8601 com fuso), ou `null` para começar ao iniciar. | | `schedule.timezone` | string | Fuso das janelas. Padrão: `Africa/Luanda`. | | `schedule.windows` | array | Janelas por dia da semana. Sem janelas, liga dentro do horário de contacto. | | `schedule.windows[].day` | string | Dia da semana, em inglês. Um de: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Início, `HH:MM`. | | `schedule.windows[].end` | string | Fim, `HH:MM`. | | `schedule.max_duration_days` | integer | Dias que a campanha pode durar; no fim, o que falta é cancelado. Entre 1 e 90. Padrão: `7`. | | `limits` | object | Limites. | | `limits.max_concurrency` | integer | Chamadas da campanha em simultâneo. Entre 1 e 50. Padrão: `2`. | | `limits.reserved_capacity` | integer | Chamadas simultâneas da organização que ficam livres para outras chamadas. Entre 0 e 50. Padrão: `1`. | | `limits.max_attempts` | integer | Tentativas por destinatário; só não atendidas ou ocupadas são repetidas. Entre 1 e 3. Padrão: `1`. | | `limits.retry_delay_minutes` | integer | Minutos entre tentativas. Entre 15 e 1440. Padrão: `60`. | | `limits.budget_minutes` | integer \| null | Minutos máximos; a campanha pausa antes de os ultrapassar. Entre 1 e 100000. | | `pause_reason` | string \| null | Porque está pausada: `manual`, `budget_exhausted`, `quota_exhausted` ou `emergency_stop`. | | `waiting_reason` | string \| null | Porque não está a ligar agora, por exemplo `outside_window` ou `no_capacity`. Um de: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `next_window_at` | string \| null | Quando abre a próxima janela. | | `deadline_at` | string \| null | Fim do prazo máximo. | | `created_at` | string \| null | Data de criação (ISO 8601). | | `started_at` | string \| null | Quando foi iniciada. | | `completed_at` | string \| null | Quando terminou. | | `cancelled_at` | string \| null | Quando foi cancelada. | | `stats` | object | Indicadores. | | `stats.total` | integer | Destinatários. Padrão: `0`. | | `stats.pending` | integer | Por ligar. Padrão: `0`. | | `stats.in_flight` | integer | A ligar ou em chamada. Padrão: `0`. | | `stats.completed` | integer | Chamada feita (atendida, não atendida ou ocupado). Padrão: `0`. | | `stats.failed` | integer | Não foi possível ligar. Padrão: `0`. | | `stats.cancelled` | integer | Cancelados. Padrão: `0`. | | `stats.excluded` | integer | Na lista de exclusão. Padrão: `0`. | | `stats.calls_started` | integer | Tentativas enviadas (cada repetição conta). Padrão: `0`. | | `stats.answered` | integer | Atendidas. Padrão: `0`. | | `stats.no_answer` | integer | Não atendidas. Padrão: `0`. | | `stats.unavailable` | integer | Ocupado ou indisponível. Padrão: `0`. | | `stats.answer_rate` | number \| null | Atendidas ÷ (atendidas + não atendidas + indisponíveis). | | `stats.total_duration_seconds` | integer | Soma da duração das chamadas atendidas. Padrão: `0`. | | `stats.progress` | number | Destinatários em estado final ÷ total. Padrão: `0`. | | `stats.cost_kz` | number \| null | Custo em kwanzas, só quando há tarifa configurada. | | `stats.with_post_call` | integer | Chamadas com resultado pós-chamada. Padrão: `0`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z" } ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ``` ## Erros | Código | Quando | | ------ | -------------------------------------------------------------------------------------------- | | `403` | As campanhas ou as chamadas pela API não estão activas para a organização. | | `404` | O agente ou o número não existem na organização. | | `409` | O agente não é de saída ou não está publicado, ou o número não é uma linha DISKA activa. | | `422` | Janelas fora do horário de contacto, fuso horário desconhecido ou limites fora do intervalo. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Ver uma campanha ```http GET https://api.diska.ai/v1/campaigns/{campaign_id} ``` **Âmbito:** `campaigns:read` ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------- | ------ | ----------- | -------------------------- | | `campaign_id` | string | Sim | Identificador da campanha. | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/campaigns/" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/campaigns/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/campaigns/', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: campaign_id in: path required: true body-type: none locale: pt method: GET path: /v1/campaigns/{campaign_id} --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ------------------------------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Identificador da campanha. | | `name` | string | Nome. | | `status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` ou `cancelled`. | | `agent_id` | string \| null | Agente. | | `agent_name` | string \| null | Nome do agente. | | `phone_number_id` | string \| null | Linha usada. | | `phone_number` | string \| null | Número da linha. | | `schedule` | object | Horário. | | `schedule.start_at` | string \| null | Início (ISO 8601 com fuso), ou `null` para começar ao iniciar. | | `schedule.timezone` | string | Fuso das janelas. Padrão: `Africa/Luanda`. | | `schedule.windows` | array | Janelas por dia da semana. Sem janelas, liga dentro do horário de contacto. | | `schedule.windows[].day` | string | Dia da semana, em inglês. Um de: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Início, `HH:MM`. | | `schedule.windows[].end` | string | Fim, `HH:MM`. | | `schedule.max_duration_days` | integer | Dias que a campanha pode durar; no fim, o que falta é cancelado. Entre 1 e 90. Padrão: `7`. | | `limits` | object | Limites. | | `limits.max_concurrency` | integer | Chamadas da campanha em simultâneo. Entre 1 e 50. Padrão: `2`. | | `limits.reserved_capacity` | integer | Chamadas simultâneas da organização que ficam livres para outras chamadas. Entre 0 e 50. Padrão: `1`. | | `limits.max_attempts` | integer | Tentativas por destinatário; só não atendidas ou ocupadas são repetidas. Entre 1 e 3. Padrão: `1`. | | `limits.retry_delay_minutes` | integer | Minutos entre tentativas. Entre 15 e 1440. Padrão: `60`. | | `limits.budget_minutes` | integer \| null | Minutos máximos; a campanha pausa antes de os ultrapassar. Entre 1 e 100000. | | `pause_reason` | string \| null | Porque está pausada: `manual`, `budget_exhausted`, `quota_exhausted` ou `emergency_stop`. | | `waiting_reason` | string \| null | Porque não está a ligar agora, por exemplo `outside_window` ou `no_capacity`. Um de: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `next_window_at` | string \| null | Quando abre a próxima janela. | | `deadline_at` | string \| null | Fim do prazo máximo. | | `created_at` | string \| null | Data de criação (ISO 8601). | | `started_at` | string \| null | Quando foi iniciada. | | `completed_at` | string \| null | Quando terminou. | | `cancelled_at` | string \| null | Quando foi cancelada. | | `stats` | object | Indicadores. | | `stats.total` | integer | Destinatários. Padrão: `0`. | | `stats.pending` | integer | Por ligar. Padrão: `0`. | | `stats.in_flight` | integer | A ligar ou em chamada. Padrão: `0`. | | `stats.completed` | integer | Chamada feita (atendida, não atendida ou ocupado). Padrão: `0`. | | `stats.failed` | integer | Não foi possível ligar. Padrão: `0`. | | `stats.cancelled` | integer | Cancelados. Padrão: `0`. | | `stats.excluded` | integer | Na lista de exclusão. Padrão: `0`. | | `stats.calls_started` | integer | Tentativas enviadas (cada repetição conta). Padrão: `0`. | | `stats.answered` | integer | Atendidas. Padrão: `0`. | | `stats.no_answer` | integer | Não atendidas. Padrão: `0`. | | `stats.unavailable` | integer | Ocupado ou indisponível. Padrão: `0`. | | `stats.answer_rate` | number \| null | Atendidas ÷ (atendidas + não atendidas + indisponíveis). | | `stats.total_duration_seconds` | integer | Soma da duração das chamadas atendidas. Padrão: `0`. | | `stats.progress` | number | Destinatários em estado final ÷ total. Padrão: `0`. | | `stats.cost_kz` | number \| null | Custo em kwanzas, só quando há tarifa configurada. | | `stats.with_post_call` | integer | Chamadas com resultado pós-chamada. Padrão: `0`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z" } ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ``` ## Erros | Código | Quando | | ------ | ------------------------ | | `404` | Campanha não encontrada. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Acrescentar destinatários ```http POST https://api.diska.ai/v1/campaigns/{campaign_id}/recipients ``` **Âmbito:** `campaigns:write` Números repetidos e `external_id` repetidos são ignorados, por isso pode repetir o pedido. Números da lista de exclusão ficam `excluded`. A resposta conta os acrescentados, duplicados, excluídos e inválidos (com o motivo de cada um). ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------- | ------ | ----------- | -------------------------- | | `campaign_id` | string | Sim | Identificador da campanha. | ## Corpo do pedido `application/json` | Campo | Tipo | Obrigatório | Descrição | | -------------------------- | -------------- | ----------- | ------------------------------------------------------------------ | | `recipients` | array | Sim | Os destinatários (1 a 1000). | | `recipients[].phone` | string | Sim | Telemóvel angolano. 3 a 40 caracteres. | | `recipients[].name` | string \| null | Não | Nome, para o agente tratar a pessoa pelo nome. Até 120 caracteres. | | `recipients[].email` | string \| null | Não | E-mail. Até 254 caracteres. | | `recipients[].variables` | object | Não | Variáveis da chamada. | | `recipients[].external_id` | string \| null | Não | O seu identificador; repetido é ignorado. Até 120 caracteres. | ```json { "recipients": [ { "phone": "+244923000000", "name": "Ana Silva", "external_id": "crm-1042", "variables": { "consulta": "sexta, 10h" } }, { "phone": "+244924000000", "name": "João Neto", "external_id": "crm-1043" } ] } ``` ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/campaigns//recipients" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"recipients":[{"phone":"+244923000000","name":"Ana Silva","external_id":"crm-1042","variables":{"consulta":"sexta, 10h"}},{"phone":"+244924000000","name":"João Neto","external_id":"crm-1043"}]}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/campaigns//recipients", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "recipients": [{ "phone": "+244923000000", "name": "Ana Silva", "external_id": "crm-1042", "variables": { "consulta": "sexta, 10h", }, }, { "phone": "+244924000000", "name": "João Neto", "external_id": "crm-1043", }], }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/campaigns//recipients', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "recipients": [ { "phone": "+244923000000", "name": "Ana Silva", "external_id": "crm-1042", "variables": { "consulta": "sexta, 10h" } }, { "phone": "+244924000000", "name": "João Neto", "external_id": "crm-1043" } ] }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /recipients'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'recipients' => [[ 'phone' => '+244923000000', 'name' => 'Ana Silva', 'external_id' => 'crm-1042', 'variables' => [ 'consulta' => 'sexta, 10h', ], ], [ 'phone' => '+244924000000', 'name' => 'João Neto', 'external_id' => 'crm-1043', ]], ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: campaign_id in: path required: true body: | { "recipients": [ { "phone": "+244923000000", "name": "Ana Silva", "external_id": "crm-1042", "variables": { "consulta": "sexta, 10h" } }, { "phone": "+244924000000", "name": "João Neto", "external_id": "crm-1043" } ] } body-type: json locale: pt method: POST path: /v1/campaigns/{campaign_id}/recipients --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ------------------- | ------- | ------------------------------------------------------------ | | `added` | integer | Acrescentados. | | `duplicates` | integer | Ignorados por estarem repetidos. | | `excluded` | integer | Na lista de exclusão. | | `invalid` | array | Recusados, com o motivo. | | `invalid[].row` | integer | Posição no pedido (a partir de 1). | | `invalid[].phone` | string | Número enviado. | | `invalid[].reason` | string | Motivo. | | `warnings` | array | Acrescentados com avisos (por exemplo, variáveis ignoradas). | | `warnings[].row` | integer | Posição no pedido (a partir de 1). | | `warnings[].phone` | string | Número enviado. | | `warnings[].reason` | string | Motivo. | | `total` | integer | Destinatários da campanha depois do pedido. | ```json { "added": 0, "duplicates": 0, "excluded": 0, "invalid": [ { "row": 0, "phone": "…", "reason": "…" } ], "warnings": [ { "row": 0, "phone": "…", "reason": "…" } ], "total": 1 } ``` ## Erros | Código | Quando | | ------ | ---------------------------------------- | | `404` | Campanha não encontrada. | | `409` | A campanha já terminou ou foi cancelada. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Listar destinatários ```http GET https://api.diska.ai/v1/campaigns/{campaign_id}/recipients ``` **Âmbito:** `campaigns:read` ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------- | ------ | ----------- | -------------------------- | | `campaign_id` | string | Sim | Identificador da campanha. | ### Na query string | Nome | Tipo | Obrigatório | Descrição | | -------- | -------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `status` | string \| null | Não | Só destinatários neste estado. Um de: `pending`, `reserved`, `calling`, `in_call`, `completed`, `failed`, `cancelled`, `excluded`. Até 20 caracteres. | | `limit` | integer | Não | Quantos por página. Entre 1 e 200. Padrão: `50`. | | `offset` | integer | Não | Quantos saltar. Mínimo 0. Padrão: `0`. | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/campaigns//recipients" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/campaigns//recipients", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/campaigns//recipients', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /recipients'); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: campaign_id in: path required: true - name: status in: query options: - pending - reserved - calling - in_call - completed - failed - cancelled - excluded - name: limit in: query - name: offset in: query body-type: none locale: pt method: GET path: /v1/campaigns/{campaign_id}/recipients --- :: ## Resposta `200` | Campo | Tipo | Descrição | | -------------------------- | --------------- | ---------------------------------------------------------------------------------------------- | | `items` | array | Os destinatários. | | `items[].id` | string | Identificador do destinatário. | | `items[].phone_e164` | string | Número. | | `items[].name` | string \| null | Nome. | | `items[].email` | string \| null | E-mail. | | `items[].variables` | object | Variáveis. | | `items[].external_id` | string \| null | O seu identificador. | | `items[].status` | string | `pending`, `reserved`, `calling`, `in_call`, `completed`, `failed`, `cancelled` ou `excluded`. | | `items[].outcome` | string \| null | `answered`, `no_answer` ou `unavailable`, quando a chamada chegou à rede. | | `items[].attempts` | integer | Tentativas feitas. Padrão: `0`. | | `items[].failure_code` | string \| null | Código da falha. | | `items[].failure_reason` | string \| null | Motivo da falha. | | `items[].call_session_id` | string \| null | A chamada em `GET /v1/calls/{call_id}`. | | `items[].session_id` | string \| null | A sessão de voz (o `session_id` dos webhooks). | | `items[].duration_seconds` | integer \| null | Duração da chamada. | | `items[].next_attempt_at` | string \| null | Próxima tentativa. | | `items[].last_attempt_at` | string \| null | Última tentativa. | | `items[].answered_at` | string \| null | Quando atendeu. | | `items[].ended_at` | string \| null | Quando terminou. | | `items[].created_at` | string \| null | Data de criação (ISO 8601). | | `items[].has_recording` | boolean | `true` quando a chamada tem gravação. Padrão: `false`. | | `total` | integer | Total com este filtro. | | `limit` | integer | Tamanho da página. | | `offset` | integer | Offset desta página. | ```json { "items": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_e164": "…", "name": "Exemplo", "email": "…", "variables": {}, "external_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "status": "pending", "outcome": "answered", "attempts": 0, "failure_code": "…", "failure_reason": "…", "call_session_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "session_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "duration_seconds": 95, "next_attempt_at": "2026-10-25T18:40:00Z", "last_attempt_at": "2026-10-25T18:40:00Z", "answered_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "created_at": "2026-10-25T18:40:00Z", "has_recording": false } ], "total": 1, "limit": 50, "offset": 0 } ``` ## Erros | Código | Quando | | ------ | ------------------------ | | `404` | Campanha não encontrada. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Iniciar uma campanha ```http POST https://api.diska.ai/v1/campaigns/{campaign_id}/start ``` **Âmbito:** `campaigns:write` Precisa de pelo menos um destinatário por ligar. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------- | ------ | ----------- | -------------------------- | | `campaign_id` | string | Sim | Identificador da campanha. | ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/campaigns//start" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/campaigns//start", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/campaigns//start', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /start'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: campaign_id in: path required: true body-type: none locale: pt method: POST path: /v1/campaigns/{campaign_id}/start --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ------------------------------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Identificador da campanha. | | `name` | string | Nome. | | `status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` ou `cancelled`. | | `agent_id` | string \| null | Agente. | | `agent_name` | string \| null | Nome do agente. | | `phone_number_id` | string \| null | Linha usada. | | `phone_number` | string \| null | Número da linha. | | `schedule` | object | Horário. | | `schedule.start_at` | string \| null | Início (ISO 8601 com fuso), ou `null` para começar ao iniciar. | | `schedule.timezone` | string | Fuso das janelas. Padrão: `Africa/Luanda`. | | `schedule.windows` | array | Janelas por dia da semana. Sem janelas, liga dentro do horário de contacto. | | `schedule.windows[].day` | string | Dia da semana, em inglês. Um de: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Início, `HH:MM`. | | `schedule.windows[].end` | string | Fim, `HH:MM`. | | `schedule.max_duration_days` | integer | Dias que a campanha pode durar; no fim, o que falta é cancelado. Entre 1 e 90. Padrão: `7`. | | `limits` | object | Limites. | | `limits.max_concurrency` | integer | Chamadas da campanha em simultâneo. Entre 1 e 50. Padrão: `2`. | | `limits.reserved_capacity` | integer | Chamadas simultâneas da organização que ficam livres para outras chamadas. Entre 0 e 50. Padrão: `1`. | | `limits.max_attempts` | integer | Tentativas por destinatário; só não atendidas ou ocupadas são repetidas. Entre 1 e 3. Padrão: `1`. | | `limits.retry_delay_minutes` | integer | Minutos entre tentativas. Entre 15 e 1440. Padrão: `60`. | | `limits.budget_minutes` | integer \| null | Minutos máximos; a campanha pausa antes de os ultrapassar. Entre 1 e 100000. | | `pause_reason` | string \| null | Porque está pausada: `manual`, `budget_exhausted`, `quota_exhausted` ou `emergency_stop`. | | `waiting_reason` | string \| null | Porque não está a ligar agora, por exemplo `outside_window` ou `no_capacity`. Um de: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `next_window_at` | string \| null | Quando abre a próxima janela. | | `deadline_at` | string \| null | Fim do prazo máximo. | | `created_at` | string \| null | Data de criação (ISO 8601). | | `started_at` | string \| null | Quando foi iniciada. | | `completed_at` | string \| null | Quando terminou. | | `cancelled_at` | string \| null | Quando foi cancelada. | | `stats` | object | Indicadores. | | `stats.total` | integer | Destinatários. Padrão: `0`. | | `stats.pending` | integer | Por ligar. Padrão: `0`. | | `stats.in_flight` | integer | A ligar ou em chamada. Padrão: `0`. | | `stats.completed` | integer | Chamada feita (atendida, não atendida ou ocupado). Padrão: `0`. | | `stats.failed` | integer | Não foi possível ligar. Padrão: `0`. | | `stats.cancelled` | integer | Cancelados. Padrão: `0`. | | `stats.excluded` | integer | Na lista de exclusão. Padrão: `0`. | | `stats.calls_started` | integer | Tentativas enviadas (cada repetição conta). Padrão: `0`. | | `stats.answered` | integer | Atendidas. Padrão: `0`. | | `stats.no_answer` | integer | Não atendidas. Padrão: `0`. | | `stats.unavailable` | integer | Ocupado ou indisponível. Padrão: `0`. | | `stats.answer_rate` | number \| null | Atendidas ÷ (atendidas + não atendidas + indisponíveis). | | `stats.total_duration_seconds` | integer | Soma da duração das chamadas atendidas. Padrão: `0`. | | `stats.progress` | number | Destinatários em estado final ÷ total. Padrão: `0`. | | `stats.cost_kz` | number \| null | Custo em kwanzas, só quando há tarifa configurada. | | `stats.with_post_call` | integer | Chamadas com resultado pós-chamada. Padrão: `0`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z" } ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ``` ## Erros | Código | Quando | | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `409` | A campanha não está em rascunho, não tem destinatários por ligar, a organização não pode fazer chamadas de saída, ou já tem 5 campanhas activas. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Pausar uma campanha ```http POST https://api.diska.ai/v1/campaigns/{campaign_id}/pause ``` **Âmbito:** `campaigns:write` ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------- | ------ | ----------- | -------------------------- | | `campaign_id` | string | Sim | Identificador da campanha. | ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/campaigns//pause" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/campaigns//pause", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/campaigns//pause', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /pause'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: campaign_id in: path required: true body-type: none locale: pt method: POST path: /v1/campaigns/{campaign_id}/pause --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ------------------------------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Identificador da campanha. | | `name` | string | Nome. | | `status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` ou `cancelled`. | | `agent_id` | string \| null | Agente. | | `agent_name` | string \| null | Nome do agente. | | `phone_number_id` | string \| null | Linha usada. | | `phone_number` | string \| null | Número da linha. | | `schedule` | object | Horário. | | `schedule.start_at` | string \| null | Início (ISO 8601 com fuso), ou `null` para começar ao iniciar. | | `schedule.timezone` | string | Fuso das janelas. Padrão: `Africa/Luanda`. | | `schedule.windows` | array | Janelas por dia da semana. Sem janelas, liga dentro do horário de contacto. | | `schedule.windows[].day` | string | Dia da semana, em inglês. Um de: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Início, `HH:MM`. | | `schedule.windows[].end` | string | Fim, `HH:MM`. | | `schedule.max_duration_days` | integer | Dias que a campanha pode durar; no fim, o que falta é cancelado. Entre 1 e 90. Padrão: `7`. | | `limits` | object | Limites. | | `limits.max_concurrency` | integer | Chamadas da campanha em simultâneo. Entre 1 e 50. Padrão: `2`. | | `limits.reserved_capacity` | integer | Chamadas simultâneas da organização que ficam livres para outras chamadas. Entre 0 e 50. Padrão: `1`. | | `limits.max_attempts` | integer | Tentativas por destinatário; só não atendidas ou ocupadas são repetidas. Entre 1 e 3. Padrão: `1`. | | `limits.retry_delay_minutes` | integer | Minutos entre tentativas. Entre 15 e 1440. Padrão: `60`. | | `limits.budget_minutes` | integer \| null | Minutos máximos; a campanha pausa antes de os ultrapassar. Entre 1 e 100000. | | `pause_reason` | string \| null | Porque está pausada: `manual`, `budget_exhausted`, `quota_exhausted` ou `emergency_stop`. | | `waiting_reason` | string \| null | Porque não está a ligar agora, por exemplo `outside_window` ou `no_capacity`. Um de: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `next_window_at` | string \| null | Quando abre a próxima janela. | | `deadline_at` | string \| null | Fim do prazo máximo. | | `created_at` | string \| null | Data de criação (ISO 8601). | | `started_at` | string \| null | Quando foi iniciada. | | `completed_at` | string \| null | Quando terminou. | | `cancelled_at` | string \| null | Quando foi cancelada. | | `stats` | object | Indicadores. | | `stats.total` | integer | Destinatários. Padrão: `0`. | | `stats.pending` | integer | Por ligar. Padrão: `0`. | | `stats.in_flight` | integer | A ligar ou em chamada. Padrão: `0`. | | `stats.completed` | integer | Chamada feita (atendida, não atendida ou ocupado). Padrão: `0`. | | `stats.failed` | integer | Não foi possível ligar. Padrão: `0`. | | `stats.cancelled` | integer | Cancelados. Padrão: `0`. | | `stats.excluded` | integer | Na lista de exclusão. Padrão: `0`. | | `stats.calls_started` | integer | Tentativas enviadas (cada repetição conta). Padrão: `0`. | | `stats.answered` | integer | Atendidas. Padrão: `0`. | | `stats.no_answer` | integer | Não atendidas. Padrão: `0`. | | `stats.unavailable` | integer | Ocupado ou indisponível. Padrão: `0`. | | `stats.answer_rate` | number \| null | Atendidas ÷ (atendidas + não atendidas + indisponíveis). | | `stats.total_duration_seconds` | integer | Soma da duração das chamadas atendidas. Padrão: `0`. | | `stats.progress` | number | Destinatários em estado final ÷ total. Padrão: `0`. | | `stats.cost_kz` | number \| null | Custo em kwanzas, só quando há tarifa configurada. | | `stats.with_post_call` | integer | Chamadas com resultado pós-chamada. Padrão: `0`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z" } ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ``` ## Erros | Código | Quando | | ------ | --------------------------------------------- | | `409` | A campanha não está agendada nem em execução. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Retomar uma campanha ```http POST https://api.diska.ai/v1/campaigns/{campaign_id}/resume ``` **Âmbito:** `campaigns:write` ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------- | ------ | ----------- | -------------------------- | | `campaign_id` | string | Sim | Identificador da campanha. | ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/campaigns//resume" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/campaigns//resume", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/campaigns//resume', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /resume'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: campaign_id in: path required: true body-type: none locale: pt method: POST path: /v1/campaigns/{campaign_id}/resume --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ------------------------------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Identificador da campanha. | | `name` | string | Nome. | | `status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` ou `cancelled`. | | `agent_id` | string \| null | Agente. | | `agent_name` | string \| null | Nome do agente. | | `phone_number_id` | string \| null | Linha usada. | | `phone_number` | string \| null | Número da linha. | | `schedule` | object | Horário. | | `schedule.start_at` | string \| null | Início (ISO 8601 com fuso), ou `null` para começar ao iniciar. | | `schedule.timezone` | string | Fuso das janelas. Padrão: `Africa/Luanda`. | | `schedule.windows` | array | Janelas por dia da semana. Sem janelas, liga dentro do horário de contacto. | | `schedule.windows[].day` | string | Dia da semana, em inglês. Um de: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Início, `HH:MM`. | | `schedule.windows[].end` | string | Fim, `HH:MM`. | | `schedule.max_duration_days` | integer | Dias que a campanha pode durar; no fim, o que falta é cancelado. Entre 1 e 90. Padrão: `7`. | | `limits` | object | Limites. | | `limits.max_concurrency` | integer | Chamadas da campanha em simultâneo. Entre 1 e 50. Padrão: `2`. | | `limits.reserved_capacity` | integer | Chamadas simultâneas da organização que ficam livres para outras chamadas. Entre 0 e 50. Padrão: `1`. | | `limits.max_attempts` | integer | Tentativas por destinatário; só não atendidas ou ocupadas são repetidas. Entre 1 e 3. Padrão: `1`. | | `limits.retry_delay_minutes` | integer | Minutos entre tentativas. Entre 15 e 1440. Padrão: `60`. | | `limits.budget_minutes` | integer \| null | Minutos máximos; a campanha pausa antes de os ultrapassar. Entre 1 e 100000. | | `pause_reason` | string \| null | Porque está pausada: `manual`, `budget_exhausted`, `quota_exhausted` ou `emergency_stop`. | | `waiting_reason` | string \| null | Porque não está a ligar agora, por exemplo `outside_window` ou `no_capacity`. Um de: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `next_window_at` | string \| null | Quando abre a próxima janela. | | `deadline_at` | string \| null | Fim do prazo máximo. | | `created_at` | string \| null | Data de criação (ISO 8601). | | `started_at` | string \| null | Quando foi iniciada. | | `completed_at` | string \| null | Quando terminou. | | `cancelled_at` | string \| null | Quando foi cancelada. | | `stats` | object | Indicadores. | | `stats.total` | integer | Destinatários. Padrão: `0`. | | `stats.pending` | integer | Por ligar. Padrão: `0`. | | `stats.in_flight` | integer | A ligar ou em chamada. Padrão: `0`. | | `stats.completed` | integer | Chamada feita (atendida, não atendida ou ocupado). Padrão: `0`. | | `stats.failed` | integer | Não foi possível ligar. Padrão: `0`. | | `stats.cancelled` | integer | Cancelados. Padrão: `0`. | | `stats.excluded` | integer | Na lista de exclusão. Padrão: `0`. | | `stats.calls_started` | integer | Tentativas enviadas (cada repetição conta). Padrão: `0`. | | `stats.answered` | integer | Atendidas. Padrão: `0`. | | `stats.no_answer` | integer | Não atendidas. Padrão: `0`. | | `stats.unavailable` | integer | Ocupado ou indisponível. Padrão: `0`. | | `stats.answer_rate` | number \| null | Atendidas ÷ (atendidas + não atendidas + indisponíveis). | | `stats.total_duration_seconds` | integer | Soma da duração das chamadas atendidas. Padrão: `0`. | | `stats.progress` | number | Destinatários em estado final ÷ total. Padrão: `0`. | | `stats.cost_kz` | number \| null | Custo em kwanzas, só quando há tarifa configurada. | | `stats.with_post_call` | integer | Chamadas com resultado pós-chamada. Padrão: `0`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z" } ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ``` ## Erros | Código | Quando | | ------ | ---------------------------- | | `409` | A campanha não está pausada. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Cancelar uma campanha ```http POST https://api.diska.ai/v1/campaigns/{campaign_id}/cancel ``` **Âmbito:** `campaigns:write` Não pode ser desfeito. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------- | ------ | ----------- | -------------------------- | | `campaign_id` | string | Sim | Identificador da campanha. | ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/campaigns//cancel" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/campaigns//cancel", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/campaigns//cancel', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /cancel'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: campaign_id in: path required: true body-type: none locale: pt method: POST path: /v1/campaigns/{campaign_id}/cancel --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ------------------------------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Identificador da campanha. | | `name` | string | Nome. | | `status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` ou `cancelled`. | | `agent_id` | string \| null | Agente. | | `agent_name` | string \| null | Nome do agente. | | `phone_number_id` | string \| null | Linha usada. | | `phone_number` | string \| null | Número da linha. | | `schedule` | object | Horário. | | `schedule.start_at` | string \| null | Início (ISO 8601 com fuso), ou `null` para começar ao iniciar. | | `schedule.timezone` | string | Fuso das janelas. Padrão: `Africa/Luanda`. | | `schedule.windows` | array | Janelas por dia da semana. Sem janelas, liga dentro do horário de contacto. | | `schedule.windows[].day` | string | Dia da semana, em inglês. Um de: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Início, `HH:MM`. | | `schedule.windows[].end` | string | Fim, `HH:MM`. | | `schedule.max_duration_days` | integer | Dias que a campanha pode durar; no fim, o que falta é cancelado. Entre 1 e 90. Padrão: `7`. | | `limits` | object | Limites. | | `limits.max_concurrency` | integer | Chamadas da campanha em simultâneo. Entre 1 e 50. Padrão: `2`. | | `limits.reserved_capacity` | integer | Chamadas simultâneas da organização que ficam livres para outras chamadas. Entre 0 e 50. Padrão: `1`. | | `limits.max_attempts` | integer | Tentativas por destinatário; só não atendidas ou ocupadas são repetidas. Entre 1 e 3. Padrão: `1`. | | `limits.retry_delay_minutes` | integer | Minutos entre tentativas. Entre 15 e 1440. Padrão: `60`. | | `limits.budget_minutes` | integer \| null | Minutos máximos; a campanha pausa antes de os ultrapassar. Entre 1 e 100000. | | `pause_reason` | string \| null | Porque está pausada: `manual`, `budget_exhausted`, `quota_exhausted` ou `emergency_stop`. | | `waiting_reason` | string \| null | Porque não está a ligar agora, por exemplo `outside_window` ou `no_capacity`. Um de: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `next_window_at` | string \| null | Quando abre a próxima janela. | | `deadline_at` | string \| null | Fim do prazo máximo. | | `created_at` | string \| null | Data de criação (ISO 8601). | | `started_at` | string \| null | Quando foi iniciada. | | `completed_at` | string \| null | Quando terminou. | | `cancelled_at` | string \| null | Quando foi cancelada. | | `stats` | object | Indicadores. | | `stats.total` | integer | Destinatários. Padrão: `0`. | | `stats.pending` | integer | Por ligar. Padrão: `0`. | | `stats.in_flight` | integer | A ligar ou em chamada. Padrão: `0`. | | `stats.completed` | integer | Chamada feita (atendida, não atendida ou ocupado). Padrão: `0`. | | `stats.failed` | integer | Não foi possível ligar. Padrão: `0`. | | `stats.cancelled` | integer | Cancelados. Padrão: `0`. | | `stats.excluded` | integer | Na lista de exclusão. Padrão: `0`. | | `stats.calls_started` | integer | Tentativas enviadas (cada repetição conta). Padrão: `0`. | | `stats.answered` | integer | Atendidas. Padrão: `0`. | | `stats.no_answer` | integer | Não atendidas. Padrão: `0`. | | `stats.unavailable` | integer | Ocupado ou indisponível. Padrão: `0`. | | `stats.answer_rate` | number \| null | Atendidas ÷ (atendidas + não atendidas + indisponíveis). | | `stats.total_duration_seconds` | integer | Soma da duração das chamadas atendidas. Padrão: `0`. | | `stats.progress` | number | Destinatários em estado final ÷ total. Padrão: `0`. | | `stats.cost_kz` | number \| null | Custo em kwanzas, só quando há tarifa configurada. | | `stats.with_post_call` | integer | Chamadas com resultado pós-chamada. Padrão: `0`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z" } ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ``` ## Erros | Código | Quando | | ------ | ---------------------------------------- | | `409` | A campanha já terminou ou foi cancelada. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Campanhas A Diska liga dentro das janelas e dos limites que definir, e cada chamada aparece em [Chamadas](https://docs.diska.ai/pt/api/reference/calls) e nos webhooks. Funciona como as [Campanhas](https://docs.diska.ai/pt/telephony/campaigns) do backoffice. | Método | Endpoint | Descrição | Âmbito | | ------ | --------------------------------------------------------------------------------------------------------------------- | ------------------------- | ----------------- | | `GET` | [`/v1/campaigns`](https://docs.diska.ai/pt/api/reference/campaigns/list-campaigns) | Listar campanhas | `campaigns:read` | | `POST` | [`/v1/campaigns`](https://docs.diska.ai/pt/api/reference/campaigns/create-campaign) | Criar uma campanha | `campaigns:write` | | `GET` | [`/v1/campaigns/{campaign_id}`](https://docs.diska.ai/pt/api/reference/campaigns/get-campaign) | Ver uma campanha | `campaigns:read` | | `POST` | [`/v1/campaigns/{campaign_id}/recipients`](https://docs.diska.ai/pt/api/reference/campaigns/add-campaign-recipients) | Acrescentar destinatários | `campaigns:write` | | `GET` | [`/v1/campaigns/{campaign_id}/recipients`](https://docs.diska.ai/pt/api/reference/campaigns/list-campaign-recipients) | Listar destinatários | `campaigns:read` | | `POST` | [`/v1/campaigns/{campaign_id}/start`](https://docs.diska.ai/pt/api/reference/campaigns/start-campaign) | Iniciar uma campanha | `campaigns:write` | | `POST` | [`/v1/campaigns/{campaign_id}/pause`](https://docs.diska.ai/pt/api/reference/campaigns/pause-campaign) | Pausar uma campanha | `campaigns:write` | | `POST` | [`/v1/campaigns/{campaign_id}/resume`](https://docs.diska.ai/pt/api/reference/campaigns/resume-campaign) | Retomar uma campanha | `campaigns:write` | | `POST` | [`/v1/campaigns/{campaign_id}/cancel`](https://docs.diska.ai/pt/api/reference/campaigns/cancel-campaign) | Cancelar uma campanha | `campaigns:write` | # Criar uma conversa ```http POST https://api.diska.ai/v1/chats ``` **Âmbito:** `chats:write` Se o agente fala primeiro e tem saudação, a resposta já traz essa mensagem. A conversa aparece também em `GET /v1/calls`, com o canal `web_chat`. `metadata` é seu: é guardada e devolvida, mas o agente nunca a vê. Envie `Idempotency-Key` para repetir o pedido sem abrir duas conversas. ## Corpo do pedido `application/json` | Campo | Tipo | Obrigatório | Descrição | | ----------- | -------------- | ----------- | --------------------------------------------------------------------------- | | `agent_id` | string | Sim | Agente publicado em modo prompt. Até 64 caracteres. | | `variables` | object | Não | Variáveis da conversa (até 20), como nas chamadas. | | `metadata` | object | Não | Até 20 pares texto → texto (500 caracteres por valor), só para si. | | `contact` | string \| null | Não | Quem conversa: telefone, e-mail ou o seu identificador. Até 120 caracteres. | ```json { "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "contact": "+244923000000", "variables": { "nome": "Ana" }, "metadata": { "crm_ticket": "T-1042" } } ``` ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/chats" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"agent_id":"3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40","contact":"+244923000000","variables":{"nome":"Ana"},"metadata":{"crm_ticket":"T-1042"}}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/chats", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "contact": "+244923000000", "variables": { "nome": "Ana", }, "metadata": { "crm_ticket": "T-1042", }, }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/chats', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "contact": "+244923000000", "variables": { "nome": "Ana" }, "metadata": { "crm_ticket": "T-1042" } }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'agent_id' => '3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40', 'contact' => '+244923000000', 'variables' => [ 'nome' => 'Ana', ], 'metadata' => [ 'crm_ticket' => 'T-1042', ], ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: [] body: | { "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "contact": "+244923000000", "variables": { "nome": "Ana" }, "metadata": { "crm_ticket": "T-1042" } } body-type: json locale: pt method: POST path: /v1/chats --- :: ## Resposta `201` | Campo | Tipo | Descrição | | ----------------------- | -------------- | ----------------------------------------------------------------- | | `id` | string | Identificador da conversa (o mesmo de `GET /v1/calls/{call_id}`). | | `agent_id` | string | O agente. | | `status` | string | `active` ou `ended`. | | `contact` | string \| null | Quem conversa, como o indicou. | | `metadata` | object | Os seus metadados, devolvidos tal como os enviou. | | `created_at` | string | Data de criação (ISO 8601). | | `ended_at` | string \| null | Quando terminou. | | `end_reason` | string \| null | `ended_by_api`, `agent_ended` ou `inactivity`. | | `messages` | array | As mensagens, por ordem. | | `messages[].id` | string | Identificador da mensagem. | | `messages[].role` | string | `user` (a pessoa) ou `assistant` (o agente). | | `messages[].content` | string | O texto. | | `messages[].created_at` | string \| null | Quando foi escrita. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "status": "active", "contact": "+244900000000", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "end_reason": "caller_hangup", "messages": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "role": "user", "content": "Bom dia, queria marcar uma consulta.", "created_at": "2026-10-25T18:40:00Z" } ] } ``` ## Erros | Código | Quando | | ------ | ----------------------------------------------------------------- | | `403` | O chat pela API não está activo para a organização. | | `404` | `Agente não encontrado.` | | `409` | O agente não está publicado, está inactivo ou usa o Flow Builder. | | `422` | Variáveis recusadas ou metadados acima dos limites. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Enviar uma mensagem ```http POST https://api.diska.ai/v1/chats/{chat_id}/messages ``` **Âmbito:** `chats:write` Uma mensagem de cada vez por conversa. Se o agente concluir a conversa, `chat.status` passa a `ended`. As acções do agente (por exemplo, marcar uma reunião) correm a sério e pedem confirmação como nas chamadas. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | --------- | ------ | ----------- | -------------------------- | | `chat_id` | string | Sim | Identificador da conversa. | ## Corpo do pedido `application/json` | Campo | Tipo | Obrigatório | Descrição | | --------- | ------ | ----------- | ------------------------------------------ | | `message` | string | Sim | A mensagem da pessoa. Até 4000 caracteres. | ```json { "message": "Queria marcar uma consulta para sexta-feira." } ``` ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/chats//messages" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"message":"Queria marcar uma consulta para sexta-feira."}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/chats//messages", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "message": "Queria marcar uma consulta para sexta-feira.", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/chats//messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "message": "Queria marcar uma consulta para sexta-feira." }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /messages'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'message' => 'Queria marcar uma consulta para sexta-feira.', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: chat_id in: path required: true body: | { "message": "Queria marcar uma consulta para sexta-feira." } body-type: json locale: pt method: POST path: /v1/chats/{chat_id}/messages --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ----------------------- | -------------- | ----------------------------------------------------------------- | | `chat` | object | A conversa, com o estado actualizado. | | `chat.id` | string | Identificador da conversa (o mesmo de `GET /v1/calls/{call_id}`). | | `chat.agent_id` | string | O agente. | | `chat.status` | string | `active` ou `ended`. | | `chat.contact` | string \| null | Quem conversa, como o indicou. | | `chat.metadata` | object | Os seus metadados, devolvidos tal como os enviou. | | `chat.created_at` | string | Data de criação (ISO 8601). | | `chat.ended_at` | string \| null | Quando terminou. | | `chat.end_reason` | string \| null | `ended_by_api`, `agent_ended` ou `inactivity`. | | `reply` | string \| null | A resposta do agente, ou `null`. | | `messages` | array | As mensagens novas: a da pessoa e a do agente. | | `messages[].id` | string | Identificador da mensagem. | | `messages[].role` | string | `user` (a pessoa) ou `assistant` (o agente). | | `messages[].content` | string | O texto. | | `messages[].created_at` | string \| null | Quando foi escrita. | ```json { "chat": { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "status": "active", "contact": "+244900000000", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "end_reason": "caller_hangup" }, "reply": "…", "messages": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "role": "user", "content": "Bom dia, queria marcar uma consulta.", "created_at": "2026-10-25T18:40:00Z" } ] } ``` ## Erros | Código | Quando | | ------ | ----------------------------------------------------------------------------------------- | | `403` | O chat pela API não está activo para a organização. | | `404` | `Chat não encontrado.` | | `409` | A conversa terminou, ou a mensagem anterior ainda está a ser respondida. | | `502` | O agente não conseguiu responder a tempo. A mensagem não ficou guardada: envie-a de novo. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Ver uma conversa ```http GET https://api.diska.ai/v1/chats/{chat_id} ``` **Âmbito:** `chats:write` ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | --------- | ------ | ----------- | -------------------------- | | `chat_id` | string | Sim | Identificador da conversa. | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/chats/" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/chats/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/chats/', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: chat_id in: path required: true body-type: none locale: pt method: GET path: /v1/chats/{chat_id} --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ----------------------- | -------------- | ----------------------------------------------------------------- | | `id` | string | Identificador da conversa (o mesmo de `GET /v1/calls/{call_id}`). | | `agent_id` | string | O agente. | | `status` | string | `active` ou `ended`. | | `contact` | string \| null | Quem conversa, como o indicou. | | `metadata` | object | Os seus metadados, devolvidos tal como os enviou. | | `created_at` | string | Data de criação (ISO 8601). | | `ended_at` | string \| null | Quando terminou. | | `end_reason` | string \| null | `ended_by_api`, `agent_ended` ou `inactivity`. | | `messages` | array | As mensagens, por ordem. | | `messages[].id` | string | Identificador da mensagem. | | `messages[].role` | string | `user` (a pessoa) ou `assistant` (o agente). | | `messages[].content` | string | O texto. | | `messages[].created_at` | string \| null | Quando foi escrita. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "status": "active", "contact": "+244900000000", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "end_reason": "caller_hangup", "messages": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "role": "user", "content": "Bom dia, queria marcar uma consulta.", "created_at": "2026-10-25T18:40:00Z" } ] } ``` ## Erros | Código | Quando | | ------ | --------------------------------------------------- | | `403` | O chat pela API não está activo para a organização. | | `404` | `Chat não encontrado.` | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Listar conversas ```http GET https://api.diska.ai/v1/chats ``` **Âmbito:** `chats:write` ## Parâmetros ### Na query string | Nome | Tipo | Obrigatório | Descrição | | ---------- | -------------- | ----------- | ------------------------------------------------ | | `agent_id` | string \| null | Não | Só conversas deste agente. Até 64 caracteres. | | `status` | string \| null | Não | `active` ou `ended`. | | `limit` | integer | Não | Quantas por página. Entre 1 e 100. Padrão: `50`. | | `offset` | integer | Não | Quantas saltar. Mínimo 0. Padrão: `0`. | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/chats" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/chats", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/chats', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: agent_id in: query - name: status in: query options: - active - ended - name: limit in: query - name: offset in: query body-type: none locale: pt method: GET path: /v1/chats --- :: ## Resposta `200` | Campo | Tipo | Descrição | | -------------------- | -------------- | ----------------------------------------------------------------- | | `items` | array | As conversas. | | `items[].id` | string | Identificador da conversa (o mesmo de `GET /v1/calls/{call_id}`). | | `items[].agent_id` | string | O agente. | | `items[].status` | string | `active` ou `ended`. | | `items[].contact` | string \| null | Quem conversa, como o indicou. | | `items[].metadata` | object | Os seus metadados, devolvidos tal como os enviou. | | `items[].created_at` | string | Data de criação (ISO 8601). | | `items[].ended_at` | string \| null | Quando terminou. | | `items[].end_reason` | string \| null | `ended_by_api`, `agent_ended` ou `inactivity`. | | `total` | integer | Total com estes filtros. | | `limit` | integer | Tamanho da página. | | `offset` | integer | Offset desta página. | ```json { "items": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "status": "active", "contact": "+244900000000", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "end_reason": "caller_hangup" } ], "total": 1, "limit": 50, "offset": 0 } ``` ## Erros | Código | Quando | | ------ | --------------------------------------------------- | | `403` | O chat pela API não está activo para a organização. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Terminar uma conversa ```http POST https://api.diska.ai/v1/chats/{chat_id}/end ``` **Âmbito:** `chats:write` Corre então o mesmo processamento de uma chamada concluída — extracções, avaliações e resumo — e é enviado o webhook `call.completed`. Uma conversa sem mensagens durante 30 minutos termina sozinha, da mesma forma. Terminar uma conversa já terminada não faz nada. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | --------- | ------ | ----------- | -------------------------- | | `chat_id` | string | Sim | Identificador da conversa. | ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/chats//end" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/chats//end", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/chats//end', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /end'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: chat_id in: path required: true body-type: none locale: pt method: POST path: /v1/chats/{chat_id}/end --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ----------------------- | -------------- | ----------------------------------------------------------------- | | `id` | string | Identificador da conversa (o mesmo de `GET /v1/calls/{call_id}`). | | `agent_id` | string | O agente. | | `status` | string | `active` ou `ended`. | | `contact` | string \| null | Quem conversa, como o indicou. | | `metadata` | object | Os seus metadados, devolvidos tal como os enviou. | | `created_at` | string | Data de criação (ISO 8601). | | `ended_at` | string \| null | Quando terminou. | | `end_reason` | string \| null | `ended_by_api`, `agent_ended` ou `inactivity`. | | `messages` | array | As mensagens, por ordem. | | `messages[].id` | string | Identificador da mensagem. | | `messages[].role` | string | `user` (a pessoa) ou `assistant` (o agente). | | `messages[].content` | string | O texto. | | `messages[].created_at` | string \| null | Quando foi escrita. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "status": "active", "contact": "+244900000000", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "end_reason": "caller_hangup", "messages": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "role": "user", "content": "Bom dia, queria marcar uma consulta.", "created_at": "2026-10-25T18:40:00Z" } ] } ``` ## Erros | Código | Quando | | ------ | --------------------------------------------------- | | `403` | O chat pela API não está activo para a organização. | | `404` | `Chat não encontrado.` | | `409` | A mensagem anterior ainda está a ser respondida. | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Chat O agente usa as mesmas instruções, conhecimento e acções que nas chamadas. Disponível quando a Diska activa o chat pela API para a organização. | Método | Endpoint | Descrição | Âmbito | | ------ | ------------------------------------------------------------------------------------------------ | --------------------- | ------------- | | `POST` | [`/v1/chats`](https://docs.diska.ai/pt/api/reference/chats/create-chat) | Criar uma conversa | `chats:write` | | `POST` | [`/v1/chats/{chat_id}/messages`](https://docs.diska.ai/pt/api/reference/chats/send-chat-message) | Enviar uma mensagem | `chats:write` | | `GET` | [`/v1/chats/{chat_id}`](https://docs.diska.ai/pt/api/reference/chats/get-chat) | Ver uma conversa | `chats:write` | | `GET` | [`/v1/chats`](https://docs.diska.ai/pt/api/reference/chats/list-chats) | Listar conversas | `chats:write` | | `POST` | [`/v1/chats/{chat_id}/end`](https://docs.diska.ai/pt/api/reference/chats/end-chat) | Terminar uma conversa | `chats:write` | # Resumo das análises ```http GET https://api.diska.ai/v1/analytics/overview ``` **Âmbito:** `analytics:read` As datas diárias estão em UTC. ## Parâmetros ### Na query string | Nome | Tipo | Obrigatório | Descrição | | ------------ | -------------- | ----------- | ------------------------------------------------------------------------------------------------------- | | `period` | string | Não | `daily` (últimas 24 horas), `weekly` (últimos 7 dias) ou `monthly` (últimos 30 dias). Padrão: `weekly`. | | `agent_id` | string \| null | Não | Só este agente. | | `agent_type` | string | Não | `all`, `inbound` ou `outbound`. Padrão: `all`. | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/analytics/overview?period=weekly" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/analytics/overview?period=weekly", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/analytics/overview?period=weekly', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: period in: query options: - daily - weekly - monthly value: weekly - name: agent_id in: query - name: agent_type in: query options: - all - inbound - outbound body-type: none locale: pt method: GET path: /v1/analytics/overview --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ---------------------------------------- | -------------- | ---------------------------------------------------------------------------------------------- | | `period` | string | Janela analisada. Um de: `daily`, `weekly`, `monthly`. Padrão: `weekly`. | | `start` | string | Início da janela. | | `end` | string | Fim da janela (o momento do pedido). | | `totals` | object | Totais da janela, comparados com a anterior. | | `totals.calls` | object | Número de chamadas. | | `totals.calls.value` | number | Valor na janela actual. Padrão: `0`. | | `totals.calls.previous` | number | Valor na janela anterior. Padrão: `0`. | | `totals.calls.change_pct` | number \| null | Variação em percentagem, ou `null` quando a janela anterior não tem dados. | | `totals.minutes` | object | Minutos de chamada. | | `totals.minutes.value` | number | Valor na janela actual. Padrão: `0`. | | `totals.minutes.previous` | number | Valor na janela anterior. Padrão: `0`. | | `totals.minutes.change_pct` | number \| null | Variação em percentagem, ou `null` quando a janela anterior não tem dados. | | `totals.avg_duration_seconds` | object | Duração média em segundos. | | `totals.avg_duration_seconds.value` | number | Valor na janela actual. Padrão: `0`. | | `totals.avg_duration_seconds.previous` | number | Valor na janela anterior. Padrão: `0`. | | `totals.avg_duration_seconds.change_pct` | number \| null | Variação em percentagem, ou `null` quando a janela anterior não tem dados. | | `daily` | array | Evolução por dia. | | `daily[].date` | string | Dia, em UTC (AAAA-MM-DD). | | `daily[].calls` | integer | Chamadas nesse dia. Padrão: `0`. | | `daily[].minutes` | number | Minutos nesse dia. Padrão: `0`. | | `daily[].completed` | integer | Chamadas concluídas. Padrão: `0`. | | `daily[].failed` | integer | Chamadas falhadas. Padrão: `0`. | | `daily[].cancelled` | integer | Chamadas canceladas. Padrão: `0`. | | `by_status` | array | Distribuição por estado da chamada. | | `by_status[].key` | string | Valor (código). | | `by_status[].label` | string | Nome legível. | | `by_status[].count` | integer | Número de chamadas. Padrão: `0`. | | `by_status[].pct` | number | Percentagem do total. Padrão: `0`. | | `by_end_reason` | array | Distribuição por motivo de fim. | | `by_end_reason[].key` | string | Valor (código). | | `by_end_reason[].label` | string | Nome legível. | | `by_end_reason[].count` | integer | Número de chamadas. Padrão: `0`. | | `by_end_reason[].pct` | number | Percentagem do total. Padrão: `0`. | | `sentiment` | object | Sentimento das chamadas. | | `sentiment.positive_pct` | object | Percentagem de chamadas positivas. | | `sentiment.positive_pct.value` | number | Valor na janela actual. Padrão: `0`. | | `sentiment.positive_pct.previous` | number | Valor na janela anterior. Padrão: `0`. | | `sentiment.positive_pct.change_pct` | number \| null | Variação em percentagem, ou `null` quando a janela anterior não tem dados. | | `sentiment.classified` | integer | Chamadas com sentimento classificado. Padrão: `0`. | | `sentiment.total` | integer | Total de chamadas. Padrão: `0`. | | `sentiment.breakdown` | array | Distribuição por sentimento. | | `sentiment.breakdown[].key` | string | Valor (código). | | `sentiment.breakdown[].label` | string | Nome legível. | | `sentiment.breakdown[].count` | integer | Número de chamadas. Padrão: `0`. | | `sentiment.breakdown[].pct` | number | Percentagem do total. Padrão: `0`. | | `sentiment.daily` | array | Evolução diária. | | `sentiment.daily[].date` | string | Dia, em UTC (AAAA-MM-DD). | | `sentiment.daily[].positive` | integer | Chamadas positivas. Padrão: `0`. | | `sentiment.daily[].neutral` | integer | Chamadas neutras. Padrão: `0`. | | `sentiment.daily[].negative` | integer | Chamadas negativas. Padrão: `0`. | | `agents` | array | Desempenho por agente. | | `agents[].agent_id` | string \| null | Agente. | | `agents[].name` | string | Nome do agente. Padrão: `—`. | | `agents[].calls` | integer | Chamadas. Padrão: `0`. | | `agents[].minutes` | number | Minutos. Padrão: `0`. | | `agents[].completed` | integer | Chamadas concluídas. Padrão: `0`. | | `agents[].completion_pct` | number | Percentagem de chamadas concluídas (conclusão técnica, não resultado de negócio). Padrão: `0`. | | `agents[].completion_change_pct` | number \| null | Variação da conclusão face à janela anterior. | | `agents[].goal_achieved_pct` | number \| null | Percentagem de chamadas com o objectivo atingido, ou `null` quando não se sabe. | | `agents[].calls_change_pct` | number \| null | Variação das chamadas. | | `agents[].minutes_change_pct` | number \| null | Variação dos minutos. | | `agents[].goal_change_pct` | number \| null | Variação do objectivo atingido. | | `actions` | array | Utilização de cada acção executada. | | `actions[].tool_name` | string | Acção (código). | | `actions[].label` | string | Nome da acção. | | `actions[].usage` | object | Execuções na janela, com a variação. | | `actions[].usage.value` | number | Valor na janela actual. Padrão: `0`. | | `actions[].usage.previous` | number | Valor na janela anterior. Padrão: `0`. | | `actions[].usage.change_pct` | number \| null | Variação em percentagem, ou `null` quando a janela anterior não tem dados. | | `actions[].daily` | array | Execuções por dia. | | `actions[].daily[].date` | string | Dia, em UTC (AAAA-MM-DD). | | `actions[].daily[].count` | integer | Execuções nesse dia. Padrão: `0`. | | `failed_calls` | array | Chamadas falhadas recentes. | | `failed_calls[].id` | string | Identificador da chamada. | | `failed_calls[].started_at` | string \| null | Início da chamada. | | `failed_calls[].contact` | string \| null | Contacto de quem ligou. | | `failed_calls[].agent_name` | string \| null | Agente. | | `failed_calls[].end_reason` | string \| null | Motivo da falha. | ```json { "period": "weekly", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z", "totals": { "calls": { "value": 42, "previous": 38, "change_pct": 10.5 }, "minutes": { "value": 42, "previous": 38, "change_pct": 10.5 }, "avg_duration_seconds": { "value": 42, "previous": 38, "change_pct": 10.5 } }, "daily": [ { "date": "2026-10-25", "calls": 42, "minutes": 63.5, "completed": 38, "failed": 3, "cancelled": 1 } ], "by_status": [ { "key": "completed", "label": "Concluída", "count": 38, "pct": 90.5 } ], "by_end_reason": [ { "key": "completed", "label": "Concluída", "count": 38, "pct": 90.5 } ], "sentiment": { "positive_pct": { "value": 42, "previous": 38, "change_pct": 10.5 }, "classified": 40, "total": 1, "breakdown": [ { "key": "completed", "label": "Concluída", "count": 38, "pct": 90.5 } ], "daily": [ { "date": "2026-10-25", "positive": 30, "neutral": 8, "negative": 2 } ] }, "agents": [ { "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "name": "Recepção", "calls": 42, "minutes": 63.5, "completed": 38, "completion_pct": 90.5, "completion_change_pct": 0, "goal_achieved_pct": 0, "calls_change_pct": 0, "minutes_change_pct": 0, "goal_change_pct": 0 } ], "actions": [ { "tool_name": "transfer_call", "label": "Concluída", "usage": { "value": 42, "previous": 38, "change_pct": 10.5 }, "daily": [ { "date": "2026-10-25", "count": 38 } ] } ], "failed_calls": [ { "id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "started_at": "2026-10-25T18:40:00Z", "contact": "+244900000000", "agent_name": "Recepção", "end_reason": "caller_hangup" } ] } ``` ## Erros Este endpoint não tem erros próprios. Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Análises | Método | Endpoint | Descrição | Âmbito | | ------ | ----------------------------------------------------------------------------------------- | ------------------- | ---------------- | | `GET` | [`/v1/analytics/overview`](https://docs.diska.ai/pt/api/reference/analytics/get-overview) | Resumo das análises | `analytics:read` | # Listar números ```http GET https://api.diska.ai/v1/phone-numbers ``` **Âmbito:** `phone-numbers:read` Os números importados por SIP trazem também os campos do trunk; a palavra-passe SIP nunca é devolvida, só `sip_password_configured`. ## Parâmetros ### Na query string | Nome | Tipo | Obrigatório | Descrição | | ------------- | -------------- | ----------- | --------------------------------------------------------------------- | | `search` | string \| null | Não | Texto no número, no nome ou no domínio SIP. Até 200 caracteres. | | `number_type` | string \| null | Não | `purchased` (números DISKA) ou `imported` (números próprios por SIP). | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/phone-numbers" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/phone-numbers", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/phone-numbers', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: search in: query - name: number_type in: query options: - purchased - imported body-type: none locale: pt method: GET path: /v1/phone-numbers --- :: ## Resposta `200` | Campo | Tipo | Descrição | | --------------------------------- | -------------- | -------------------------------------------------------------------------------------------- | | `items` | array | Os números. | | `items[].id` | string | Identificador. | | `items[].organization_id` | string | Organização a que pertence. | | `items[].e164` | string | O número em formato E.164. | | `items[].friendly_name` | string \| null | Nome dado ao número. | | `items[].number_type` | string | `purchased` (número DISKA) ou `imported` (número próprio por SIP). Padrão: `purchased`. | | `items[].status` | string | `active` ou `inactive`. Padrão: `active`. | | `items[].country_code` | string | País do número (ISO 3166). Padrão: `AO`. | | `items[].capabilities` | object | O que o número suporta. | | `items[].capabilities.calls` | boolean | Faz e recebe chamadas. Padrão: `true`. | | `items[].capabilities.sms` | boolean | Envia SMS. Padrão: `true`. | | `items[].monthly_price_kz` | number \| null | Preço mensal em kwanzas, quando aplicável. | | `items[].provider` | string \| null | Operador do número. | | `items[].provider_sid` | string \| null | Identificador do número no operador. | | `items[].agent_id` | string \| null | Agente principal do número. | | `items[].agents` | array | Agentes que usam o número. | | `items[].agents[].id` | string | Agente. | | `items[].agents[].name` | string | Nome do agente. | | `items[].agents[].status` | string \| null | Estado do agente. | | `items[].sip_domain` | string \| null | Trunk SIP: domínio do servidor. | | `items[].sip_username` | string \| null | Trunk SIP: utilizador. | | `items[].sip_password_configured` | boolean | `true` quando a palavra-passe SIP está definida (nunca é devolvida). Padrão: `false`. | | `items[].sip_outbound_proxy` | string \| null | Trunk SIP: proxy de saída. | | `items[].sip_auth_username` | string \| null | Trunk SIP: utilizador de autenticação, se diferente. | | `items[].sip_outbound_register` | boolean | `true` quando a Diska se regista no servidor SIP. Padrão: `false`. | | `items[].origination_uri` | string \| null | Endereço SIP para onde o operador envia as chamadas recebidas. | | `items[].sip_status` | string \| null | Estado do trunk SIP. Um de: `pending_credentials`, `pending_provisioning`, `ready`, `error`. | | `items[].sip_status_detail` | string \| null | Detalhe do estado do trunk. | | `items[].sip_transport` | string | Transporte SIP. Um de: `udp`, `tcp`. Padrão: `udp`. | | `items[].sip_allowed_ips` | array | Endereços IP autorizados a enviar chamadas. | | `items[].created_at` | string \| null | Data de criação (ISO 8601). | | `items[].updated_at` | string \| null | Data da última alteração (ISO 8601). | | `total` | integer | Quantos números. | ```json { "items": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "e164": "+244900000000", "friendly_name": "Linha principal", "number_type": "purchased", "status": "active", "country_code": "AO", "capabilities": { "calls": true, "sms": true }, "monthly_price_kz": 0, "provider": "africell", "provider_sid": null, "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agents": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Recepção", "status": "active" } ], "sip_domain": null, "sip_username": null, "sip_password_configured": false, "sip_outbound_proxy": null, "sip_auth_username": null, "sip_outbound_register": false, "origination_uri": null, "sip_status": null, "sip_status_detail": null, "sip_transport": "udp", "sip_allowed_ips": [], "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z" } ], "total": 1 } ``` ## Erros Este endpoint não tem erros próprios. Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Números | Método | Endpoint | Descrição | Âmbito | | ------ | ---------------------------------------------------------------------------------------------- | -------------- | -------------------- | | `GET` | [`/v1/phone-numbers`](https://docs.diska.ai/pt/api/reference/phone-numbers/list-phone-numbers) | Listar números | `phone-numbers:read` | # Listar bases de conhecimento ```http GET https://api.diska.ai/v1/knowledge-bases ``` **Âmbito:** `knowledge:read` ## Parâmetros ### Na query string | Nome | Tipo | Obrigatório | Descrição | | -------- | -------------- | ----------- | ---------------------------------------------------------- | | `search` | string \| null | Não | Texto contido no nome ou na instrução. Até 200 caracteres. | ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/knowledge-bases" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/knowledge-bases", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/knowledge-bases', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: search in: query body-type: none locale: pt method: GET path: /v1/knowledge-bases --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ------------------------------ | -------------- | ------------------------------------------- | | `items` | array | As bases de conhecimento. | | `items[].id` | string | Identificador. | | `items[].organization_id` | string | Organização a que pertence. | | `items[].name` | string | Nome da base. | | `items[].instruction` | string | Quando e como o agente deve usar esta base. | | `items[].description` | string \| null | Descrição, ou `null`. | | `items[].document_count` | integer | Número de documentos. Padrão: `0`. | | `items[].assigned_agent_count` | integer | Agentes que usam esta base. Padrão: `0`. | | `items[].created_at` | string \| null | Data de criação (ISO 8601). | | `items[].updated_at` | string \| null | Data da última alteração (ISO 8601). | ```json { "items": [ { "id": "b2e4c6d8-1a3f-4e5b-9c7d-0f2a4b6c8e10", "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Produtos e preços", "instruction": "Use esta base para responder a perguntas sobre produtos, preços e horários.", "description": "Tabela de preços e horários de 2026.", "document_count": 3, "assigned_agent_count": 1, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z" } ] } ``` ## Erros Este endpoint não tem erros próprios. Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Criar uma base de conhecimento ```http POST https://api.diska.ai/v1/knowledge-bases ``` **Âmbito:** `knowledge:write` Acrescente documentos com os três endpoints seguintes e atribua a base a um agente no backoffice. ## Corpo do pedido `application/json` | Campo | Tipo | Obrigatório | Descrição | | ------------- | -------------- | ----------- | ---------------------------------------------------------------- | | `name` | string | Sim | Nome da base. Até 200 caracteres. | | `instruction` | string | Sim | Quando e como o agente deve usar esta base. Até 4000 caracteres. | | `description` | string \| null | Não | Descrição. Até 2000 caracteres. | ```json { "name": "Produtos e preços", "instruction": "Use esta base para responder a perguntas sobre produtos, preços e horários.", "description": "Tabela de preços e horários de 2026." } ``` ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/knowledge-bases" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name":"Produtos e preços","instruction":"Use esta base para responder a perguntas sobre produtos, preços e horários.","description":"Tabela de preços e horários de 2026."}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/knowledge-bases", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "name": "Produtos e preços", "instruction": "Use esta base para responder a perguntas sobre produtos, preços e horários.", "description": "Tabela de preços e horários de 2026.", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/knowledge-bases', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "name": "Produtos e preços", "instruction": "Use esta base para responder a perguntas sobre produtos, preços e horários.", "description": "Tabela de preços e horários de 2026." }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'name' => 'Produtos e preços', 'instruction' => 'Use esta base para responder a perguntas sobre produtos, preços e horários.', 'description' => 'Tabela de preços e horários de 2026.', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: [] body: > { "name": "Produtos e preços", "instruction": "Use esta base para responder a perguntas sobre produtos, preços e horários.", "description": "Tabela de preços e horários de 2026." } body-type: json locale: pt method: POST path: /v1/knowledge-bases --- :: ## Resposta `201` | Campo | Tipo | Descrição | | ---------------------- | -------------- | ------------------------------------------- | | `id` | string | Identificador. | | `organization_id` | string | Organização a que pertence. | | `name` | string | Nome da base. | | `instruction` | string | Quando e como o agente deve usar esta base. | | `description` | string \| null | Descrição, ou `null`. | | `document_count` | integer | Número de documentos. Padrão: `0`. | | `assigned_agent_count` | integer | Agentes que usam esta base. Padrão: `0`. | | `created_at` | string \| null | Data de criação (ISO 8601). | | `updated_at` | string \| null | Data da última alteração (ISO 8601). | ```json { "id": "b2e4c6d8-1a3f-4e5b-9c7d-0f2a4b6c8e10", "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Produtos e preços", "instruction": "Use esta base para responder a perguntas sobre produtos, preços e horários.", "description": "Tabela de preços e horários de 2026.", "document_count": 3, "assigned_agent_count": 1, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z" } ``` ## Erros Este endpoint não tem erros próprios. Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Adicionar um documento de texto ```http POST https://api.diska.ai/v1/knowledge-bases/{knowledge_base_id}/documents ``` **Âmbito:** `knowledge:write` A indexação arranca logo; o documento fica pronto quando `indexing_status` for `indexed`. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------------- | ------ | ----------- | -------------------------------------- | | `knowledge_base_id` | string | Sim | Identificador da base de conhecimento. | ## Corpo do pedido `application/json` | Campo | Tipo | Obrigatório | Descrição | | --------- | ------ | ----------- | -------------------------------------- | | `name` | string | Sim | Nome do documento. Até 200 caracteres. | | `content` | string | Sim | O texto. Até 200000 caracteres. | ```json { "name": "Horários", "content": "Abrimos de segunda a sexta, das 8h às 17h." } ``` ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/knowledge-bases//documents" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name":"Horários","content":"Abrimos de segunda a sexta, das 8h às 17h."}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/knowledge-bases//documents", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "name": "Horários", "content": "Abrimos de segunda a sexta, das 8h às 17h.", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/knowledge-bases//documents', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "name": "Horários", "content": "Abrimos de segunda a sexta, das 8h às 17h." }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /documents'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'name' => 'Horários', 'content' => 'Abrimos de segunda a sexta, das 8h às 17h.', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: knowledge_base_id in: path required: true body: | { "name": "Horários", "content": "Abrimos de segunda a sexta, das 8h às 17h." } body-type: json locale: pt method: POST path: /v1/knowledge-bases/{knowledge_base_id}/documents --- :: ## Resposta `201` | Campo | Tipo | Descrição | | ------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Identificador. | | `organization_id` | string | Organização a que pertence. | | `knowledge_base_id` | string | Base a que o documento pertence. | | `name` | string | Nome do documento. | | `source_type` | string | `manual` (texto), `pdf` ou `url`. | | `status` | string | Estado geral do documento. Um de: `pending`, `uploading`, `processing`, `ready`, `failed`, `indexing_pending`. Padrão: `pending`. | | `extraction_status` | string | Estado da extracção do texto. Um de: `pending`, `extracted`, `skipped`, `failed`. Padrão: `pending`. | | `indexing_status` | string | Estado da indexação: `indexed` quando o agente já o pode usar. Um de: `pending`, `indexing_pending`, `indexed`, `skipped`, `failed`. Padrão: `indexing_pending`. | | `content_text` | string \| null | O texto extraído. | | `original_url` | string \| null | Endereço importado (documentos `url`). | | `storage_path` | string \| null | Localização interna do ficheiro. | | `mime_type` | string \| null | Tipo do ficheiro. | | `size_bytes` | integer \| null | Tamanho em bytes. | | `error_message` | string \| null | Erro, quando falhou. | | `metadata` | object | Metadados técnicos. | | `created_at` | string \| null | Data de criação (ISO 8601). | | `updated_at` | string \| null | Data da última alteração (ISO 8601). | | `has_file` | boolean | `true` quando há um ficheiro guardado. Padrão: `false`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "knowledge_base_id": "b2e4c6d8-1a3f-4e5b-9c7d-0f2a4b6c8e10", "name": "Horários", "source_type": "manual", "status": "ready", "extraction_status": "extracted", "indexing_status": "indexed", "content_text": "Abrimos de segunda a sexta, das 8h às 17h.", "original_url": null, "storage_path": null, "mime_type": "text/plain", "size_bytes": 48213, "error_message": "…", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z", "has_file": false } ``` ## Erros | Código | Quando | | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | Conteúdo recusado — por exemplo `Ficheiro vazio.`, `PDF demasiado grande (máx. 25 MB).`, `Apenas ficheiros PDF são aceites.`, `O ficheiro não parece ser um PDF válido.`, `Tempo esgotado ao obter a página.`, `A página não devolveu texto legível.` ou um URL bloqueado por segurança. | | `404` | `Base de conhecimento não encontrada.` | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Importar uma página web ```http POST https://api.diska.ai/v1/knowledge-bases/{knowledge_base_id}/documents/url ``` **Âmbito:** `knowledge:write` A página tem de responder em 15 segundos, ter até 2 MB e ser HTML, texto ou JSON. Endereços privados ou internos são recusados, e são seguidos no máximo 3 redireccionamentos. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------------- | ------ | ----------- | -------------------------------------- | | `knowledge_base_id` | string | Sim | Identificador da base de conhecimento. | ## Corpo do pedido `application/json` | Campo | Tipo | Obrigatório | Descrição | | ------ | ------ | ----------- | ------------------------------------------------------------------------- | | `name` | string | Sim | Nome do documento. Até 200 caracteres. | | `url` | string | Sim | Endereço `http://` ou `https://` completo da página. 8 a 2000 caracteres. | ```json { "name": "Página de preços", "url": "https://www.exemplo.ao/precos" } ``` ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/knowledge-bases//documents/url" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name":"Página de preços","url":"https://www.exemplo.ao/precos"}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/knowledge-bases//documents/url", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "name": "Página de preços", "url": "https://www.exemplo.ao/precos", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/knowledge-bases//documents/url', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "name": "Página de preços", "url": "https://www.exemplo.ao/precos" }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /documents/url'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'name' => 'Página de preços', 'url' => 'https://www.exemplo.ao/precos', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: knowledge_base_id in: path required: true body: | { "name": "Página de preços", "url": "https://www.exemplo.ao/precos" } body-type: json locale: pt method: POST path: /v1/knowledge-bases/{knowledge_base_id}/documents/url --- :: ## Resposta `201` | Campo | Tipo | Descrição | | ------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Identificador. | | `organization_id` | string | Organização a que pertence. | | `knowledge_base_id` | string | Base a que o documento pertence. | | `name` | string | Nome do documento. | | `source_type` | string | `manual` (texto), `pdf` ou `url`. | | `status` | string | Estado geral do documento. Um de: `pending`, `uploading`, `processing`, `ready`, `failed`, `indexing_pending`. Padrão: `pending`. | | `extraction_status` | string | Estado da extracção do texto. Um de: `pending`, `extracted`, `skipped`, `failed`. Padrão: `pending`. | | `indexing_status` | string | Estado da indexação: `indexed` quando o agente já o pode usar. Um de: `pending`, `indexing_pending`, `indexed`, `skipped`, `failed`. Padrão: `indexing_pending`. | | `content_text` | string \| null | O texto extraído. | | `original_url` | string \| null | Endereço importado (documentos `url`). | | `storage_path` | string \| null | Localização interna do ficheiro. | | `mime_type` | string \| null | Tipo do ficheiro. | | `size_bytes` | integer \| null | Tamanho em bytes. | | `error_message` | string \| null | Erro, quando falhou. | | `metadata` | object | Metadados técnicos. | | `created_at` | string \| null | Data de criação (ISO 8601). | | `updated_at` | string \| null | Data da última alteração (ISO 8601). | | `has_file` | boolean | `true` quando há um ficheiro guardado. Padrão: `false`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "knowledge_base_id": "b2e4c6d8-1a3f-4e5b-9c7d-0f2a4b6c8e10", "name": "Horários", "source_type": "manual", "status": "ready", "extraction_status": "extracted", "indexing_status": "indexed", "content_text": "Abrimos de segunda a sexta, das 8h às 17h.", "original_url": null, "storage_path": null, "mime_type": "text/plain", "size_bytes": 48213, "error_message": "…", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z", "has_file": false } ``` ## Erros | Código | Quando | | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | Conteúdo recusado — por exemplo `Ficheiro vazio.`, `PDF demasiado grande (máx. 25 MB).`, `Apenas ficheiros PDF são aceites.`, `O ficheiro não parece ser um PDF válido.`, `Tempo esgotado ao obter a página.`, `A página não devolveu texto legível.` ou um URL bloqueado por segurança. | | `404` | `Base de conhecimento não encontrada.` | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Carregar um PDF ```http POST https://api.diska.ai/v1/knowledge-bases/{knowledge_base_id}/documents/pdf ``` **Âmbito:** `knowledge:write` ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------------- | ------ | ----------- | -------------------------------------- | | `knowledge_base_id` | string | Sim | Identificador da base de conhecimento. | ## Corpo do pedido `multipart/form-data` | Campo | Tipo | Obrigatório | Descrição | | ------ | ---- | ----------- | ------------------ | | `file` | file | Sim | O PDF (até 25 MB). | ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/knowledge-bases//documents/pdf" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -F "file=@tabela-de-precos.pdf;type=application/pdf" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/knowledge-bases//documents/pdf", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, files={"file": ("tabela-de-precos.pdf", open("tabela-de-precos.pdf", "rb"), "application/pdf")}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 20 ou superior, num ficheiro .mjs import { openAsBlob } from 'node:fs' const form = new FormData() form.append('file', await openAsBlob('tabela-de-precos.pdf', { type: 'application/pdf' }), 'tabela-de-precos.pdf') const response = await fetch('https://api.diska.ai/v1/knowledge-bases//documents/pdf', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` }, body: form }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /documents/pdf'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_POSTFIELDS => ['file' => new CURLFile('tabela-de-precos.pdf', 'application/pdf')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. No Experimentar escolha um PDF do seu computador. ::api-playground --- params: - name: knowledge_base_id in: path required: true body-type: multipart locale: pt method: POST path: /v1/knowledge-bases/{knowledge_base_id}/documents/pdf --- :: ## Resposta `201` | Campo | Tipo | Descrição | | ------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Identificador. | | `organization_id` | string | Organização a que pertence. | | `knowledge_base_id` | string | Base a que o documento pertence. | | `name` | string | Nome do documento. | | `source_type` | string | `manual` (texto), `pdf` ou `url`. | | `status` | string | Estado geral do documento. Um de: `pending`, `uploading`, `processing`, `ready`, `failed`, `indexing_pending`. Padrão: `pending`. | | `extraction_status` | string | Estado da extracção do texto. Um de: `pending`, `extracted`, `skipped`, `failed`. Padrão: `pending`. | | `indexing_status` | string | Estado da indexação: `indexed` quando o agente já o pode usar. Um de: `pending`, `indexing_pending`, `indexed`, `skipped`, `failed`. Padrão: `indexing_pending`. | | `content_text` | string \| null | O texto extraído. | | `original_url` | string \| null | Endereço importado (documentos `url`). | | `storage_path` | string \| null | Localização interna do ficheiro. | | `mime_type` | string \| null | Tipo do ficheiro. | | `size_bytes` | integer \| null | Tamanho em bytes. | | `error_message` | string \| null | Erro, quando falhou. | | `metadata` | object | Metadados técnicos. | | `created_at` | string \| null | Data de criação (ISO 8601). | | `updated_at` | string \| null | Data da última alteração (ISO 8601). | | `has_file` | boolean | `true` quando há um ficheiro guardado. Padrão: `false`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "knowledge_base_id": "b2e4c6d8-1a3f-4e5b-9c7d-0f2a4b6c8e10", "name": "Horários", "source_type": "manual", "status": "ready", "extraction_status": "extracted", "indexing_status": "indexed", "content_text": "Abrimos de segunda a sexta, das 8h às 17h.", "original_url": null, "storage_path": null, "mime_type": "text/plain", "size_bytes": 48213, "error_message": "…", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z", "has_file": false } ``` ## Erros | Código | Quando | | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | Conteúdo recusado — por exemplo `Ficheiro vazio.`, `PDF demasiado grande (máx. 25 MB).`, `Apenas ficheiros PDF são aceites.`, `O ficheiro não parece ser um PDF válido.`, `Tempo esgotado ao obter a página.`, `A página não devolveu texto legível.` ou um URL bloqueado por segurança. | | `404` | `Base de conhecimento não encontrada.` | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Conhecimento Para um agente usar uma base, atribua-a no backoffice. | Método | Endpoint | Descrição | Âmbito | | ------ | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | ----------------- | | `GET` | [`/v1/knowledge-bases`](https://docs.diska.ai/pt/api/reference/knowledge/list-knowledge-bases) | Listar bases de conhecimento | `knowledge:read` | | `POST` | [`/v1/knowledge-bases`](https://docs.diska.ai/pt/api/reference/knowledge/create-knowledge-base) | Criar uma base de conhecimento | `knowledge:write` | | `POST` | [`/v1/knowledge-bases/{knowledge_base_id}/documents`](https://docs.diska.ai/pt/api/reference/knowledge/add-text-document) | Adicionar um documento de texto | `knowledge:write` | | `POST` | [`/v1/knowledge-bases/{knowledge_base_id}/documents/url`](https://docs.diska.ai/pt/api/reference/knowledge/import-url) | Importar uma página web | `knowledge:write` | | `POST` | [`/v1/knowledge-bases/{knowledge_base_id}/documents/pdf`](https://docs.diska.ai/pt/api/reference/knowledge/upload-pdf) | Carregar um PDF | `knowledge:write` | # Listar endpoints de webhook ```http GET https://api.diska.ai/v1/webhook-endpoints ``` **Âmbito:** `webhooks:manage` ## Exemplos ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/webhook-endpoints" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/webhook-endpoints", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/webhook-endpoints', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: [] body-type: none locale: pt method: GET path: /v1/webhook-endpoints --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ------------------------- | -------------- | --------------------------------------------------------------------------- | | `[].id` | string | Identificador do endpoint. | | `[].url` | string | Destino das entregas. | | `[].description` | string \| null | Descrição. | | `[].events` | array | Eventos subscritos. | | `[].active` | boolean | `false` quando foi desactivado (por si ou automaticamente). Padrão: `true`. | | `[].disabled_reason` | string \| null | Motivo da desactivação automática, ou `null`. | | `[].failure_count` | integer | Entregas falhadas seguidas. Padrão: `0`. | | `[].last_delivery_at` | string \| null | Última entrega. | | `[].last_delivery_status` | string \| null | Resultado da última entrega, por exemplo `delivered (200)`. | | `[].secret_preview` | string | Início e fim do secret, para o identificar. | | `[].created_at` | string \| null | Data de criação (ISO 8601). | ```json [ { "id": "e7a1c3f5-9b2d-4f6e-8a0c-3d5f7b9e1c24", "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ], "active": true, "disabled_reason": null, "failure_count": 0, "last_delivery_at": "2026-10-25T18:40:00Z", "last_delivery_status": "delivered (200)", "secret_preview": "dskw_AbC…wXyZ", "created_at": "2026-10-25T18:40:00Z" } ] ``` ## Erros Este endpoint não tem erros próprios. Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Registar um endpoint de webhook ```http POST https://api.diska.ai/v1/webhook-endpoints ``` **Âmbito:** `webhooks:manage` A resposta traz o `secret` (`dskw_…`) para verificar a assinatura: **só aparece nesta resposta**. Cada organização pode ter até 10 endpoints. ## Corpo do pedido `application/json` | Campo | Tipo | Obrigatório | Descrição | | ------------- | -------------- | ----------- | ------------------------------------------------------------------------------------------------------------ | | `url` | string | Sim | URL `https://` completo do seu receptor. Endereços privados ou internos são recusados. 12 a 2000 caracteres. | | `description` | string \| null | Não | Descrição. Até 500 caracteres. | | `events` | array | Não | Eventos a subscrever: `call.completed`, `booking.created`. Por omissão `["call.completed"]`. | ```json { "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ] } ``` ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/webhook-endpoints" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"url":"https://o-seu-sistema.com/hooks/diska","description":"CRM — produção","events":["call.completed"]}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/webhook-endpoints", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": ["call.completed"], }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/webhook-endpoints', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ] }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'url' => 'https://o-seu-sistema.com/hooks/diska', 'description' => 'CRM — produção', 'events' => ['call.completed'], ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: [] body: | { "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ] } body-type: json locale: pt method: POST path: /v1/webhook-endpoints --- :: ## Resposta `201` | Campo | Tipo | Descrição | | ------------------------------- | -------------- | --------------------------------------------------------------------------- | | `endpoint` | object | O endpoint criado. | | `endpoint.id` | string | Identificador do endpoint. | | `endpoint.url` | string | Destino das entregas. | | `endpoint.description` | string \| null | Descrição. | | `endpoint.events` | array | Eventos subscritos. | | `endpoint.active` | boolean | `false` quando foi desactivado (por si ou automaticamente). Padrão: `true`. | | `endpoint.disabled_reason` | string \| null | Motivo da desactivação automática, ou `null`. | | `endpoint.failure_count` | integer | Entregas falhadas seguidas. Padrão: `0`. | | `endpoint.last_delivery_at` | string \| null | Última entrega. | | `endpoint.last_delivery_status` | string \| null | Resultado da última entrega, por exemplo `delivered (200)`. | | `endpoint.secret_preview` | string | Início e fim do secret, para o identificar. | | `endpoint.created_at` | string \| null | Data de criação (ISO 8601). | | `secret` | string | O secret (`dskw_…`) para verificar a assinatura. Só aparece nesta resposta. | ```json { "endpoint": { "id": "e7a1c3f5-9b2d-4f6e-8a0c-3d5f7b9e1c24", "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ], "active": true, "disabled_reason": null, "failure_count": 0, "last_delivery_at": "2026-10-25T18:40:00Z", "last_delivery_status": "delivered (200)", "secret_preview": "dskw_AbC…wXyZ", "created_at": "2026-10-25T18:40:00Z" }, "secret": "dskw_…" } ``` ## Erros | Código | Quando | | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | `URL inválido: use um endpoint https:// completo.`, `URL bloqueado por segurança: …`, `Subscreva pelo menos um evento.`, `Eventos desconhecidos: …` ou `Limite de 10 endpoints por organização atingido.` | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Alterar um endpoint de webhook ```http PATCH https://api.diska.ai/v1/webhook-endpoints/{endpoint_id} ``` **Âmbito:** `webhooks:manage` `active: true` reactiva um endpoint desactivado e põe `failure_count` a zero; `active: false` pára as entregas. O secret não muda. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------- | ------ | ----------- | -------------------------- | | `endpoint_id` | string | Sim | Identificador do endpoint. | ## Corpo do pedido `application/json` | Campo | Tipo | Obrigatório | Descrição | | ------------- | --------------- | ----------- | ----------------------------------------------------------------------- | | `url` | string \| null | Não | Novo URL `https://`. 12 a 2000 caracteres. | | `description` | string \| null | Não | Nova descrição; `""` apaga-a. Até 500 caracteres. | | `events` | array \| null | Não | Nova lista de eventos (pelo menos um). | | `active` | boolean \| null | Não | `true` reactiva e põe `failure_count` a zero; `false` pára as entregas. | ```json { "active": true } ``` ## Exemplos ::code-group ```bash [cURL] curl -X PATCH "https://api.diska.ai/v1/webhook-endpoints/" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"active":true}' ``` ```python [Python] import os import requests response = requests.patch( "https://api.diska.ai/v1/webhook-endpoints/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "active": True, }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/webhook-endpoints/', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "active": true }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'PATCH', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'active' => true, ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: endpoint_id in: path required: true body: | { "active": true } body-type: json locale: pt method: PATCH path: /v1/webhook-endpoints/{endpoint_id} --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ---------------------- | -------------- | --------------------------------------------------------------------------- | | `id` | string | Identificador do endpoint. | | `url` | string | Destino das entregas. | | `description` | string \| null | Descrição. | | `events` | array | Eventos subscritos. | | `active` | boolean | `false` quando foi desactivado (por si ou automaticamente). Padrão: `true`. | | `disabled_reason` | string \| null | Motivo da desactivação automática, ou `null`. | | `failure_count` | integer | Entregas falhadas seguidas. Padrão: `0`. | | `last_delivery_at` | string \| null | Última entrega. | | `last_delivery_status` | string \| null | Resultado da última entrega, por exemplo `delivered (200)`. | | `secret_preview` | string | Início e fim do secret, para o identificar. | | `created_at` | string \| null | Data de criação (ISO 8601). | ```json { "id": "e7a1c3f5-9b2d-4f6e-8a0c-3d5f7b9e1c24", "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ], "active": true, "disabled_reason": null, "failure_count": 0, "last_delivery_at": "2026-10-25T18:40:00Z", "last_delivery_status": "delivered (200)", "secret_preview": "dskw_AbC…wXyZ", "created_at": "2026-10-25T18:40:00Z" } ``` ## Erros | Código | Quando | | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | `URL inválido: use um endpoint https:// completo.`, `URL bloqueado por segurança: …`, `Subscreva pelo menos um evento.`, `Eventos desconhecidos: …` ou `Limite de 10 endpoints por organização atingido.` | | `404` | `Endpoint não encontrado.` | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Remover um endpoint de webhook ```http DELETE https://api.diska.ai/v1/webhook-endpoints/{endpoint_id} ``` **Âmbito:** `webhooks:manage` As entregas param de imediato. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------- | ------ | ----------- | -------------------------- | | `endpoint_id` | string | Sim | Identificador do endpoint. | ## Exemplos ::code-group ```bash [cURL] curl -X DELETE "https://api.diska.ai/v1/webhook-endpoints/" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.delete( "https://api.diska.ai/v1/webhook-endpoints/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/webhook-endpoints/', { method: 'DELETE', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'DELETE', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: endpoint_id in: path required: true body-type: none locale: pt method: DELETE path: /v1/webhook-endpoints/{endpoint_id} --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ---------------------- | -------------- | --------------------------------------------------------------------------- | | `id` | string | Identificador do endpoint. | | `url` | string | Destino das entregas. | | `description` | string \| null | Descrição. | | `events` | array | Eventos subscritos. | | `active` | boolean | `false` quando foi desactivado (por si ou automaticamente). Padrão: `true`. | | `disabled_reason` | string \| null | Motivo da desactivação automática, ou `null`. | | `failure_count` | integer | Entregas falhadas seguidas. Padrão: `0`. | | `last_delivery_at` | string \| null | Última entrega. | | `last_delivery_status` | string \| null | Resultado da última entrega, por exemplo `delivered (200)`. | | `secret_preview` | string | Início e fim do secret, para o identificar. | | `created_at` | string \| null | Data de criação (ISO 8601). | ```json { "id": "e7a1c3f5-9b2d-4f6e-8a0c-3d5f7b9e1c24", "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ], "active": true, "disabled_reason": null, "failure_count": 0, "last_delivery_at": "2026-10-25T18:40:00Z", "last_delivery_status": "delivered (200)", "secret_preview": "dskw_AbC…wXyZ", "created_at": "2026-10-25T18:40:00Z" } ``` ## Erros | Código | Quando | | ------ | -------------------------- | | `404` | `Endpoint não encontrado.` | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Testar um endpoint de webhook ```http POST https://api.diska.ai/v1/webhook-endpoints/{endpoint_id}/test ``` **Âmbito:** `webhooks:manage` Funciona mesmo com o endpoint desactivado, e uma falha no teste não conta para a desactivação automática. ## Parâmetros ### No caminho | Nome | Tipo | Obrigatório | Descrição | | ------------- | ------ | ----------- | -------------------------- | | `endpoint_id` | string | Sim | Identificador do endpoint. | ## Exemplos ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/webhook-endpoints//test" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/webhook-endpoints//test", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 ou superior, num ficheiro .mjs const response = await fetch('https://api.diska.ai/v1/webhook-endpoints//test', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /test'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Experimentar Envie o pedido a partir desta página, com a sua chave. A chave fica só nesta página: não é guardada e só é enviada para `api.diska.ai`. Use uma chave de teste com os âmbitos mínimos. ::api-playground --- params: - name: endpoint_id in: path required: true body-type: none locale: pt method: POST path: /v1/webhook-endpoints/{endpoint_id}/test --- :: ## Resposta `200` | Campo | Tipo | Descrição | | ------------- | --------------- | ------------------------------------------------------------------------------------------- | | `status` | string | `delivered`, `failed` ou `blocked` (o URL passou a apontar para um endereço não permitido). | | `attempts` | integer | Tentativas feitas. | | `http_status` | integer \| null | Código HTTP que o seu receptor devolveu. | | `error` | string | Motivo da falha, só quando `status` não é `delivered`. | ```json { "status": "delivered", "attempts": 1, "http_status": 200 } ``` ## Erros | Código | Quando | | ------ | -------------------------- | | `404` | `Endpoint não encontrado.` | Os erros comuns a todos os endpoints (`401`, `403`, `422`, `429` e `5xx`) estão em [Erros](https://docs.diska.ai/pt/api/api-channel#erros). # Webhooks As entregas, os eventos e a assinatura estão em [Webhooks](https://docs.diska.ai/pt/api/webhooks). | Método | Endpoint | Descrição | Âmbito | | -------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------- | ----------------- | | `GET` | [`/v1/webhook-endpoints`](https://docs.diska.ai/pt/api/reference/webhooks/list-webhook-endpoints) | Listar endpoints de webhook | `webhooks:manage` | | `POST` | [`/v1/webhook-endpoints`](https://docs.diska.ai/pt/api/reference/webhooks/create-webhook-endpoint) | Registar um endpoint de webhook | `webhooks:manage` | | `PATCH` | [`/v1/webhook-endpoints/{endpoint_id}`](https://docs.diska.ai/pt/api/reference/webhooks/update-webhook-endpoint) | Alterar um endpoint de webhook | `webhooks:manage` | | `DELETE` | [`/v1/webhook-endpoints/{endpoint_id}`](https://docs.diska.ai/pt/api/reference/webhooks/delete-webhook-endpoint) | Remover um endpoint de webhook | `webhooks:manage` | | `POST` | [`/v1/webhook-endpoints/{endpoint_id}/test`](https://docs.diska.ai/pt/api/reference/webhooks/test-webhook-endpoint) | Testar um endpoint de webhook | `webhooks:manage` | # Referência da API Cada endpoint da [API da DISKA](https://docs.diska.ai/pt/api/api-channel) tem uma página com os parâmetros, o esquema do corpo e da resposta, exemplos em cURL, Python, JavaScript e PHP, e um formulário **Experimentar** que envia o pedido a partir da página. Esta referência é gerada da [especificação OpenAPI](https://api.diska.ai/v1/openapi.json){rel=""nofollow""}. ## Antes de começar - Base URL: `https://api.diska.ai/v1`. Todos os pedidos levam a chave no cabeçalho `Authorization: Bearer dsk_…` — veja [Começar com a API](https://docs.diska.ai/pt/api/getting-started). - **Experimentar** usa a sua chave só nesta página: não a guarda e só a envia para `api.diska.ai`. Os pedidos `POST`, `PATCH` e `DELETE` alteram dados reais da organização. Use uma chave de teste com os âmbitos mínimos e revogue-a quando terminar. - Prefere o Postman? Descarregue a colecção ([português](https://docs.diska.ai/api/diska-canal-api.pt.postman_collection.json){rel=""nofollow""} ou [inglês](https://docs.diska.ai/api/diska-canal-api.en.postman_collection.json){rel=""nofollow""}), importe-a em **Import** e preencha a variável `apiKey`. ## Endpoints ### Identidade | Método | Endpoint | Descrição | Âmbito | | ------ | ------------------------------------------------------------------------ | --------------------------- | ------ | | `GET` | [`/v1/me`](https://docs.diska.ai/pt/api/reference/identity/get-identity) | Ver a chave e a organização | — | ### Agentes | Método | Endpoint | Descrição | Âmbito | | ------- | ---------------------------------------------------------------------------------------------- | ------------------ | -------------- | | `GET` | [`/v1/agents`](https://docs.diska.ai/pt/api/reference/agents/list-agents) | Listar agentes | `agents:read` | | `GET` | [`/v1/agents/{agent_id}`](https://docs.diska.ai/pt/api/reference/agents/get-agent) | Ver um agente | `agents:read` | | `PATCH` | [`/v1/agents/{agent_id}`](https://docs.diska.ai/pt/api/reference/agents/update-agent) | Editar um agente | `agents:write` | | `POST` | [`/v1/agents`](https://docs.diska.ai/pt/api/reference/agents/create-agent) | Criar um agente | `agents:write` | | `POST` | [`/v1/agents/{agent_id}/publish`](https://docs.diska.ai/pt/api/reference/agents/publish-agent) | Publicar um agente | `agents:write` | ### Chamadas | Método | Endpoint | Descrição | Âmbito | | ------ | -------------------------------------------------------------------------------------------------- | ---------------------- | ----------------- | | `GET` | [`/v1/calls`](https://docs.diska.ai/pt/api/reference/calls/list-calls) | Listar chamadas | `calls:read` | | `GET` | [`/v1/calls/{call_id}`](https://docs.diska.ai/pt/api/reference/calls/get-call) | Ver uma chamada | `calls:read` | | `GET` | [`/v1/calls/{call_id}/recording`](https://docs.diska.ai/pt/api/reference/calls/get-call-recording) | Descarregar a gravação | `recordings:read` | ### Chamadas de saída | Método | Endpoint | Descrição | Âmbito | | ------ | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | ------------- | | `POST` | [`/v1/outbound-calls`](https://docs.diska.ai/pt/api/reference/outbound-calls/create-outbound-call) | Fazer uma chamada de saída | `calls:write` | | `GET` | [`/v1/outbound-calls/{outbound_call_id}`](https://docs.diska.ai/pt/api/reference/outbound-calls/get-outbound-call) | Ver uma chamada de saída | `calls:read` | | `POST` | [`/v1/outbound-calls/{outbound_call_id}/hangup`](https://docs.diska.ai/pt/api/reference/outbound-calls/hang-up-outbound-call) | Desligar uma chamada de saída | `calls:write` | ### Campanhas | Método | Endpoint | Descrição | Âmbito | | ------ | --------------------------------------------------------------------------------------------------------------------- | ------------------------- | ----------------- | | `GET` | [`/v1/campaigns`](https://docs.diska.ai/pt/api/reference/campaigns/list-campaigns) | Listar campanhas | `campaigns:read` | | `POST` | [`/v1/campaigns`](https://docs.diska.ai/pt/api/reference/campaigns/create-campaign) | Criar uma campanha | `campaigns:write` | | `GET` | [`/v1/campaigns/{campaign_id}`](https://docs.diska.ai/pt/api/reference/campaigns/get-campaign) | Ver uma campanha | `campaigns:read` | | `POST` | [`/v1/campaigns/{campaign_id}/recipients`](https://docs.diska.ai/pt/api/reference/campaigns/add-campaign-recipients) | Acrescentar destinatários | `campaigns:write` | | `GET` | [`/v1/campaigns/{campaign_id}/recipients`](https://docs.diska.ai/pt/api/reference/campaigns/list-campaign-recipients) | Listar destinatários | `campaigns:read` | | `POST` | [`/v1/campaigns/{campaign_id}/start`](https://docs.diska.ai/pt/api/reference/campaigns/start-campaign) | Iniciar uma campanha | `campaigns:write` | | `POST` | [`/v1/campaigns/{campaign_id}/pause`](https://docs.diska.ai/pt/api/reference/campaigns/pause-campaign) | Pausar uma campanha | `campaigns:write` | | `POST` | [`/v1/campaigns/{campaign_id}/resume`](https://docs.diska.ai/pt/api/reference/campaigns/resume-campaign) | Retomar uma campanha | `campaigns:write` | | `POST` | [`/v1/campaigns/{campaign_id}/cancel`](https://docs.diska.ai/pt/api/reference/campaigns/cancel-campaign) | Cancelar uma campanha | `campaigns:write` | ### Chat | Método | Endpoint | Descrição | Âmbito | | ------ | ------------------------------------------------------------------------------------------------ | --------------------- | ------------- | | `POST` | [`/v1/chats`](https://docs.diska.ai/pt/api/reference/chats/create-chat) | Criar uma conversa | `chats:write` | | `POST` | [`/v1/chats/{chat_id}/messages`](https://docs.diska.ai/pt/api/reference/chats/send-chat-message) | Enviar uma mensagem | `chats:write` | | `GET` | [`/v1/chats/{chat_id}`](https://docs.diska.ai/pt/api/reference/chats/get-chat) | Ver uma conversa | `chats:write` | | `GET` | [`/v1/chats`](https://docs.diska.ai/pt/api/reference/chats/list-chats) | Listar conversas | `chats:write` | | `POST` | [`/v1/chats/{chat_id}/end`](https://docs.diska.ai/pt/api/reference/chats/end-chat) | Terminar uma conversa | `chats:write` | ### Análises | Método | Endpoint | Descrição | Âmbito | | ------ | ----------------------------------------------------------------------------------------- | ------------------- | ---------------- | | `GET` | [`/v1/analytics/overview`](https://docs.diska.ai/pt/api/reference/analytics/get-overview) | Resumo das análises | `analytics:read` | ### Números | Método | Endpoint | Descrição | Âmbito | | ------ | ---------------------------------------------------------------------------------------------- | -------------- | -------------------- | | `GET` | [`/v1/phone-numbers`](https://docs.diska.ai/pt/api/reference/phone-numbers/list-phone-numbers) | Listar números | `phone-numbers:read` | ### Conhecimento | Método | Endpoint | Descrição | Âmbito | | ------ | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | ----------------- | | `GET` | [`/v1/knowledge-bases`](https://docs.diska.ai/pt/api/reference/knowledge/list-knowledge-bases) | Listar bases de conhecimento | `knowledge:read` | | `POST` | [`/v1/knowledge-bases`](https://docs.diska.ai/pt/api/reference/knowledge/create-knowledge-base) | Criar uma base de conhecimento | `knowledge:write` | | `POST` | [`/v1/knowledge-bases/{knowledge_base_id}/documents`](https://docs.diska.ai/pt/api/reference/knowledge/add-text-document) | Adicionar um documento de texto | `knowledge:write` | | `POST` | [`/v1/knowledge-bases/{knowledge_base_id}/documents/url`](https://docs.diska.ai/pt/api/reference/knowledge/import-url) | Importar uma página web | `knowledge:write` | | `POST` | [`/v1/knowledge-bases/{knowledge_base_id}/documents/pdf`](https://docs.diska.ai/pt/api/reference/knowledge/upload-pdf) | Carregar um PDF | `knowledge:write` | ### Webhooks | Método | Endpoint | Descrição | Âmbito | | -------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------- | ----------------- | | `GET` | [`/v1/webhook-endpoints`](https://docs.diska.ai/pt/api/reference/webhooks/list-webhook-endpoints) | Listar endpoints de webhook | `webhooks:manage` | | `POST` | [`/v1/webhook-endpoints`](https://docs.diska.ai/pt/api/reference/webhooks/create-webhook-endpoint) | Registar um endpoint de webhook | `webhooks:manage` | | `PATCH` | [`/v1/webhook-endpoints/{endpoint_id}`](https://docs.diska.ai/pt/api/reference/webhooks/update-webhook-endpoint) | Alterar um endpoint de webhook | `webhooks:manage` | | `DELETE` | [`/v1/webhook-endpoints/{endpoint_id}`](https://docs.diska.ai/pt/api/reference/webhooks/delete-webhook-endpoint) | Remover um endpoint de webhook | `webhooks:manage` | | `POST` | [`/v1/webhook-endpoints/{endpoint_id}/test`](https://docs.diska.ai/pt/api/reference/webhooks/test-webhook-endpoint) | Testar um endpoint de webhook | `webhooks:manage` | # Sincronizar chamadas com o CRM Neste guia, cada chamada concluída chega ao seu servidor por [webhook](https://docs.diska.ai/pt/api/webhooks), sem polling. O receptor: 1. verifica a assinatura; 2. ignora repetições; 3. responde logo; 4. numa fila, lê o detalhe da chamada e cria ou actualiza o contacto e a actividade no CRM. Uma reconciliação diária apanha o que se tenha perdido. ## Antes de começar - Uma [chave API](https://docs.diska.ai/pt/api/authentication) com os âmbitos **Webhooks — gestão** (`webhooks:manage`) e **Chamadas e transcrições** (`calls:read`). - Um servidor acessível da internet por `https://`. - Python 3.11 ou superior com `flask` e `requests`, ou Node.js 18 ou superior. ## 1. Escreva o receptor ::code-group ```python [Python] import hashlib import hmac import json import os import queue import threading import time import requests from flask import Flask, request API = "https://api.diska.ai/v1" API_KEY = os.environ["DISKA_API_KEY"] SECRET = os.environ["DISKA_WEBHOOK_SECRET"] app = Flask(__name__) jobs: queue.Queue = queue.Queue() seen: set[str] = set() # em produção: uma tabela com X-Diska-Delivery como chave única def is_valid(timestamp: str, body: bytes, signature: str) -> bool: if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300: return False expected = hmac.new(SECRET.encode(), f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest() return hmac.compare_digest(f"sha256={expected}", signature) @app.post("/hooks/diska") def receive(): body = request.get_data() # o corpo bruto, antes de interpretar o JSON timestamp = request.headers.get("X-Diska-Timestamp", "") if not is_valid(timestamp, body, request.headers.get("X-Diska-Signature", "")): return "", 401 delivery = request.headers.get("X-Diska-Delivery", "") if delivery in seen: return "", 200 # repetição de uma entrega que já recebeu seen.add(delivery) event = json.loads(body) if event.get("event") == "call.completed": jobs.put(event) # processe fora do pedido: responda em menos de 10 segundos return "", 200 def crm_upsert(phone: str | None, name: str | None, activity: dict) -> None: # Substitua pela chamada à API do seu CRM: procure o contacto pelo telefone, # crie-o se não existir e acrescente a actividade com o id da chamada. print("CRM", phone, name, activity) def sync_call(event: dict) -> None: response = requests.get( f"{API}/calls/{event['call_id']}", headers={"Authorization": f"Bearer {API_KEY}"}, timeout=30, ) response.raise_for_status() call = response.json() crm_upsert( phone=event.get("caller_contact"), name=call.get("caller_name"), activity={ "diska_call_id": call["id"], "started_at": call["started_at"], "duration_seconds": call["duration_seconds"], "agent": call["agent_name"], "summary": call["summary"], "sentiment": event.get("sentiment"), "data": event.get("extracted_data", {}), }, ) def worker() -> None: while True: event = jobs.get() try: sync_call(event) except Exception as exc: # a reconciliação diária apanha o que falhar aqui print("sincronização falhou", event["call_id"], exc) finally: jobs.task_done() threading.Thread(target=worker, daemon=True).start() ``` ```js [Node.js] // Node.js 18 ou superior, num ficheiro .mjs import crypto from 'node:crypto' import http from 'node:http' const API = 'https://api.diska.ai/v1' const { DISKA_API_KEY, DISKA_WEBHOOK_SECRET } = process.env const seen = new Set() // em produção: uma tabela com X-Diska-Delivery como chave única function isValid(timestamp, rawBody, signature) { if (!/^\d+$/.test(timestamp || '') || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false const expected = 'sha256=' + crypto.createHmac('sha256', DISKA_WEBHOOK_SECRET) .update(`${timestamp}.`).update(rawBody).digest('hex') const a = Buffer.from(expected) const b = Buffer.from(signature || '') return a.length === b.length && crypto.timingSafeEqual(a, b) } async function crmUpsert(phone, name, activity) { // Substitua pela chamada à API do seu CRM: procure o contacto pelo telefone, // crie-o se não existir e acrescente a actividade com o id da chamada. console.log('CRM', phone, name, activity) } async function syncCall(event) { const response = await fetch(`${API}/calls/${event.call_id}`, { headers: { Authorization: `Bearer ${DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`HTTP ${response.status}`) const call = await response.json() await crmUpsert(event.caller_contact, call.caller_name, { diska_call_id: call.id, started_at: call.started_at, duration_seconds: call.duration_seconds, agent: call.agent_name, summary: call.summary, sentiment: event.sentiment, data: event.extracted_data ?? {} }) } http.createServer((req, res) => { if (req.method !== 'POST' || req.url !== '/hooks/diska') return res.writeHead(404).end() const chunks = [] req.on('data', chunk => chunks.push(chunk)) req.on('end', () => { const rawBody = Buffer.concat(chunks) // o corpo bruto, antes de interpretar o JSON if (!isValid(req.headers['x-diska-timestamp'], rawBody, req.headers['x-diska-signature'])) return res.writeHead(401).end() res.writeHead(200).end() // responda já; processe a seguir const delivery = req.headers['x-diska-delivery'] if (seen.has(delivery)) return // repetição de uma entrega que já recebeu seen.add(delivery) const event = JSON.parse(rawBody) if (event.event === 'call.completed') { syncCall(event).catch(err => console.error('sincronização falhou', event.call_id, err)) // a reconciliação apanha o que falhar } }) }).listen(Number(process.env.PORT || 3000)) ``` :: O que o receptor faz, por ordem: - **Verifica a assinatura** sobre o corpo bruto, com o secret do endpoint. Um pedido sem assinatura válida recebe `401`. Veja [Verificar a assinatura](https://docs.diska.ai/pt/api/webhooks#verificar-a-assinatura). - **Ignora repetições.** Uma entrega repetida traz o mesmo `X-Diska-Delivery`. - **Responde logo** com `200`, e processa a seguir: a Diska espera no máximo 10 segundos. - **Lê o detalhe da chamada** em [`GET /v1/calls/{call_id}`](https://docs.diska.ai/pt/api/reference/calls/get-call), para ter o resumo, a duração e o nome de quem ligou. O evento já traz o sentimento e os dados extraídos. - **Chama o CRM** em `crm_upsert` / `crmUpsert`. Substitua o `print` pela API do seu CRM, e use o `diska_call_id` como chave única da actividade, para nunca a criar duas vezes. O evento de teste (`ping`) também recebe `200`, para o passo 3 funcionar. Para correr o receptor, com as variáveis `DISKA_API_KEY` e `DISKA_WEBHOOK_SECRET` definidas: ```bash pip install flask requests flask --app receiver run --port 3000 # Python node receiver.mjs # Node.js (porta 3000) ``` Em produção, ponha-o atrás do seu servidor web ou do seu proxy, com HTTPS. ## 2. Registe o endpoint ```bash curl -X POST https://api.diska.ai/v1/webhook-endpoints \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM", "events": ["call.completed"]}' ``` A resposta traz o `secret` (`dskw_…`) **só desta vez**. Guarde-o em `DISKA_WEBHOOK_SECRET` e reinicie o receptor. Guarde também o `endpoint.id`. ## 3. Teste ```bash curl -X POST https://api.diska.ai/v1/webhook-endpoints//test \ -H "Authorization: Bearer $DISKA_API_KEY" ``` A resposta deve trazer `"status": "delivered"`. Se trouxer `failed`, o campo `error` diz porquê: URL inacessível, certificado inválido, ou o receptor respondeu `401` porque o secret não é o certo. Depois, ligue para o número do agente e termine a chamada normalmente. Quando o processamento pós-chamada acabar, o receptor recebe `call.completed` e o contacto aparece no CRM. ## 4. Reconcilie uma vez por dia As entregas são feitas no melhor esforço: se o seu servidor estiver em baixo durante as repetições, o evento perde-se. A fonte de verdade é [`GET /v1/calls`](https://docs.diska.ai/pt/api/reference/calls/list-calls). Este script percorre as chamadas concluídas dos últimos dias: ::code-group ```python [Python] import os import time from datetime import datetime, timedelta, timezone import requests API = "https://api.diska.ai/v1" session = requests.Session() session.headers["Authorization"] = f"Bearer {os.environ['DISKA_API_KEY']}" def get(path: str, params: dict | None = None) -> dict: while True: response = session.get(f"{API}{path}", params=params, timeout=60) if response.status_code == 429: # limite de pedidos: espere o que a API indica time.sleep(int(response.headers.get("Retry-After", "5"))) continue response.raise_for_status() return response.json() def calls_since(since: datetime): """Chamadas concluídas desde `since`, da mais recente para a mais antiga.""" params = {"cursor": "start", "limit": 200, "status": "completed"} while True: page = get("/calls", params) for call in page["items"]: if call["started_at"] and datetime.fromisoformat(call["started_at"]) < since: return # a lista vem da mais recente para a mais antiga: pode parar yield call if not page["next_cursor"]: return params["cursor"] = page["next_cursor"] since = datetime.now(timezone.utc) - timedelta(days=2) # um pouco mais do que o intervalo entre execuções for call in calls_since(since): print("verificar no CRM:", call["id"], call["started_at"]) # crie a actividade se ainda não existir ``` :: Corra-o uma vez por dia, por exemplo com `cron`, e crie no CRM a actividade das chamadas que lá não estejam. Como a lista vem da mais recente para a mais antiga, o script pára na primeira chamada anterior à data de corte. ## Para produção - Guarde os `X-Diska-Delivery` processados numa tabela, não em memória: o receptor pode reiniciar. - Use uma fila persistente (por exemplo Redis ou SQS) em vez da fila em memória. - Registe as falhas de sincronização: a reconciliação recupera-as, mas convém saber que aconteceram. - Vigie o endpoint: [`GET /v1/webhook-endpoints`](https://docs.diska.ai/pt/api/reference/webhooks/list-webhook-endpoints) mostra `failure_count` e `active`. Ao fim de 20 falhas seguidas o endpoint é desactivado; depois de corrigir, reactive-o com `{"active": true}`. # Exportar o histórico de chamadas Este guia exporta as chamadas da organização com [`GET /v1/calls`](https://docs.diska.ai/pt/api/reference/calls/list-calls). Usa a [paginação por cursor](https://docs.diska.ai/pt/api/api-channel#pagina%C3%A7%C3%A3o), que custa o mesmo em qualquer página, mesmo com centenas de milhares de chamadas. ## Antes de começar - Uma [chave API](https://docs.diska.ai/pt/api/authentication) com o âmbito **Chamadas e transcrições** (`calls:read`). - Python 3.11 ou superior com `requests`, ou Node.js 18 ou superior. ## Exportar para CSV ::code-group ```python [Python] import csv import os import time import requests API = "https://api.diska.ai/v1" FIELDS = [ "id", "started_at", "ended_at", "duration_seconds", "channel", "direction", "status", "agent_name", "caller_name", "caller_contact", "end_reason", "summary", ] session = requests.Session() session.headers["Authorization"] = f"Bearer {os.environ['DISKA_API_KEY']}" def get(path: str, params: dict | None = None) -> dict: while True: response = session.get(f"{API}{path}", params=params, timeout=60) if response.status_code == 429: # limite de pedidos: espere o que a API indica time.sleep(int(response.headers.get("Retry-After", "5"))) continue response.raise_for_status() return response.json() params = {"cursor": "start", "limit": 200} # filtros opcionais: agent_id, status, channel total = 0 with open("chamadas.csv", "w", newline="", encoding="utf-8") as file: writer = csv.DictWriter(file, fieldnames=FIELDS, extrasaction="ignore") writer.writeheader() while True: page = get("/calls", params) writer.writerows(page["items"]) total += len(page["items"]) if not page["next_cursor"]: break params["cursor"] = page["next_cursor"] print(f"{total} chamadas exportadas para chamadas.csv") ``` ```js [Node.js] // Node.js 18 ou superior, num ficheiro .mjs import { createWriteStream } from 'node:fs' import { setTimeout as sleep } from 'node:timers/promises' const API = 'https://api.diska.ai/v1' const FIELDS = ['id', 'started_at', 'ended_at', 'duration_seconds', 'channel', 'direction', 'status', 'agent_name', 'caller_name', 'caller_contact', 'end_reason', 'summary'] async function get(path, params) { for (;;) { const response = await fetch(`${API}${path}?${new URLSearchParams(params)}`, { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (response.status === 429) { // limite de pedidos: espere o que a API indica await sleep(1000 * Number(response.headers.get('retry-after') || 5)) continue } if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) return response.json() } } const cell = value => `"${String(value ?? '').replaceAll('"', '""')}"` const out = createWriteStream('chamadas.csv') out.write(FIELDS.join(',') + '\n') const params = { cursor: 'start', limit: 200 } // filtros opcionais: agent_id, status, channel let total = 0 for (;;) { const page = await get('/calls', params) for (const call of page.items) out.write(FIELDS.map(f => cell(call[f])).join(',') + '\n') total += page.items.length if (!page.next_cursor) break params.cursor = page.next_cursor } out.end() console.log(`${total} chamadas exportadas para chamadas.csv`) ``` :: - A primeira página pede `cursor=start`; as seguintes usam o `next_cursor` recebido. Quando `next_cursor` vem `null`, chegou ao fim. - `limit=200` é o máximo por página. - Se a API responder `429`, o script espera o que o cabeçalho `Retry-After` indica e repete o pedido. - Para exportar só parte, acrescente filtros a `params`: `agent_id`, `status` ou `channel`. Veja os [parâmetros](https://docs.diska.ai/pt/api/reference/calls/list-calls#par%C3%A2metros). ## Incluir as transcrições A lista não traz a transcrição. Para a ter, peça o detalhe de cada chamada e guarde uma linha JSON por chamada: ::code-group ```python [Python] import json import os import time import requests API = "https://api.diska.ai/v1" session = requests.Session() session.headers["Authorization"] = f"Bearer {os.environ['DISKA_API_KEY']}" def get(path: str, params: dict | None = None) -> dict: while True: response = session.get(f"{API}{path}", params=params, timeout=60) if response.status_code == 429: time.sleep(int(response.headers.get("Retry-After", "5"))) continue response.raise_for_status() return response.json() params = {"cursor": "start", "limit": 200, "status": "completed"} with open("chamadas.jsonl", "w", encoding="utf-8") as file: while True: page = get("/calls", params) for call in page["items"]: detail = get(f"/calls/{call['id']}") # transcrição, acções e resultado pós-chamada file.write(json.dumps(detail, ensure_ascii=False) + "\n") time.sleep(0.5) # no máximo 120 pedidos por minuto por chave if not page["next_cursor"]: break params["cursor"] = page["next_cursor"] ``` :: Cada linha tem o mesmo conteúdo de [`GET /v1/calls/{call_id}`](https://docs.diska.ai/pt/api/reference/calls/get-call): transcrição (`messages`), acções executadas e resultado pós-chamada. O script faz um pedido por chamada e espera meio segundo entre eles, para ficar abaixo dos 120 pedidos por minuto: 10 000 chamadas demoram cerca de hora e meia. ## Exportar só o que é novo A API não filtra por data, mas a lista vem da mais recente para a mais antiga. Para exportar só desde a última execução, pare quando `started_at` for anterior a essa data, como a função `calls_since` de [Sincronizar chamadas com o CRM](https://docs.diska.ai/pt/api/guides/sync-calls-crm#4-reconcilie-uma-vez-por-dia). ## Cuidados - As exportações têm dados pessoais: contactos, nomes e o que foi dito. Guarde-as com o mesmo cuidado que o resto dos dados dos seus clientes. - O áudio das gravações não é exportado pela API. Ouça as gravações em [Históricos](https://docs.diska.ai/pt/history/recordings). # Alimentar o conhecimento a partir do site Este guia cria uma [base de conhecimento](https://docs.diska.ai/pt/knowledge-base) com o conteúdo do seu site. O script lê o `sitemap.xml`, importa cada página pelo endereço e carrega os PDF. No fim, diz quantos documentos importou e quais falharam. ## Antes de começar - Uma [chave API](https://docs.diska.ai/pt/api/authentication) com o âmbito **Conhecimento — escrita** (`knowledge:write`). - O endereço do `sitemap.xml` do seu site. - Python 3.11 ou superior com `requests`, ou Node.js 18 ou superior. ## O script ::code-group ```python [Python] import os import re import time from urllib.parse import urlparse import requests API = "https://api.diska.ai/v1" SITEMAP = "https://www.exemplo.ao/sitemap.xml" # o sitemap do seu site MAX_PAGES = 100 session = requests.Session() session.headers["Authorization"] = f"Bearer {os.environ['DISKA_API_KEY']}" def post(path: str, **kwargs) -> requests.Response: while True: response = session.post(f"{API}{path}", timeout=60, **kwargs) if response.status_code == 429: # limite de pedidos: espere o que a API indica time.sleep(int(response.headers.get("Retry-After", "5"))) continue return response # 1. Uma base nova para o conteúdo do site. response = post("/knowledge-bases", json={ "name": "Site", "instruction": "Use esta base para responder a perguntas sobre a empresa, os produtos e os preços, com a informação do site.", }) response.raise_for_status() base_id = response.json()["id"] # 2. As páginas do sitemap. sitemap = requests.get(SITEMAP, timeout=30) sitemap.raise_for_status() urls = re.findall(r"\s*([^<\s]+)\s*", sitemap.text)[:MAX_PAGES] # 3. Cada página como documento: páginas web por URL, PDF por upload. imported, failed = 0, [] for url in urls: name = urlparse(url).path.strip("/") or "Página inicial" if url.lower().endswith(".pdf"): pdf = requests.get(url, timeout=60) result = post(f"/knowledge-bases/{base_id}/documents/pdf", files={"file": (name, pdf.content, "application/pdf")}) else: result = post(f"/knowledge-bases/{base_id}/documents/url", json={"name": name[:200], "url": url}) if result.status_code == 201: imported += 1 else: failed.append((url, result.json().get("detail"))) time.sleep(0.5) # no máximo 120 pedidos por minuto por chave print(f"Base {base_id}: {imported} documentos importados") for url, detail in failed: print("falhou:", url, "—", detail) ``` ```js [Node.js] // Node.js 18 ou superior, num ficheiro .mjs import { setTimeout as sleep } from 'node:timers/promises' const API = 'https://api.diska.ai/v1' const SITEMAP = 'https://www.exemplo.ao/sitemap.xml' // o sitemap do seu site const MAX_PAGES = 100 const auth = { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } async function post(path, init) { for (;;) { const response = await fetch(`${API}${path}`, { method: 'POST', ...init, headers: { ...auth, ...init.headers } }) if (response.status !== 429) return response await sleep(1000 * Number(response.headers.get('retry-after') || 5)) // limite de pedidos } } const json = body => ({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) // 1. Uma base nova para o conteúdo do site. const created = await post('/knowledge-bases', json({ name: 'Site', instruction: 'Use esta base para responder a perguntas sobre a empresa, os produtos e os preços, com a informação do site.' })) if (!created.ok) throw new Error(`${created.status} ${await created.text()}`) const base = await created.json() // 2. As páginas do sitemap. const xml = await (await fetch(SITEMAP)).text() const urls = [...xml.matchAll(/\s*([^<\s]+)\s*<\/loc>/g)].map(m => m[1]).slice(0, MAX_PAGES) // 3. Cada página como documento: páginas web por URL, PDF por upload. let imported = 0 const failed = [] for (const url of urls) { const name = new URL(url).pathname.replace(/^\/+|\/+$/g, '') || 'Página inicial' let result if (url.toLowerCase().endsWith('.pdf')) { const form = new FormData() form.append('file', new Blob([await (await fetch(url)).arrayBuffer()], { type: 'application/pdf' }), name) result = await post(`/knowledge-bases/${base.id}/documents/pdf`, { body: form }) } else { result = await post(`/knowledge-bases/${base.id}/documents/url`, json({ name: name.slice(0, 200), url })) } if (result.status === 201) imported++ else failed.push([url, (await result.json()).detail]) await sleep(500) // no máximo 120 pedidos por minuto por chave } console.log(`Base ${base.id}: ${imported} documentos importados`) for (const [url, detail] of failed) console.log('falhou:', url, '—', detail) ``` :: - Cada página é importada com [Importar uma página web](https://docs.diska.ai/pt/api/reference/knowledge/import-url). A página tem de responder em 15 segundos, ter até 2 MB e ser HTML, texto ou JSON. Endereços privados ou internos são recusados. - Os PDF são descarregados e carregados com [Carregar um PDF](https://docs.diska.ai/pt/api/reference/knowledge/upload-pdf), até 25 MB. - O nome de cada documento é o caminho da página (`produtos/telemoveis`), para o reconhecer no backoffice. - `MAX_PAGES` limita quantas páginas importa. Comece com poucas e veja o resultado. - Se o seu sitemap for um índice (lista outros sitemaps em vez de páginas), corra o script para cada sitemap da lista. As páginas que falham aparecem no fim, com o motivo — por exemplo `A página não devolveu texto legível.` quando a página só mostra conteúdo com JavaScript. ## Ligue a base ao agente A API cria a base, mas não a atribui a um agente. No backoffice: 1. Abra a base em **Conhecimento** e confirme que os documentos ficaram indexados. 2. Atribua-a ao agente, como em [Atribuir bases a um agente](https://docs.diska.ai/pt/knowledge-base#atribuir-bases-a-um-agente). 3. Publique o agente, no backoffice ou com [Publicar um agente](https://docs.diska.ai/pt/api/reference/agents/publish-agent). As chamadas só usam uma base nova depois de publicar. ## Actualize o conteúdo A API da DISKA ainda não lista, altera nem apaga documentos. Para acrescentar páginas novas, importe-as para a mesma base: um documento novo numa base já atribuída tem efeito imediato. Para refazer tudo, corra o script para uma base nova, troque a base do agente e publique-o, e depois elimine a base antiga em **Conhecimento**. # Guias da API Cada guia resolve um caso real do princípio ao fim, com código pronto a adaptar. O código foi testado contra uma réplica da API com as mesmas respostas da [referência](https://docs.diska.ai/pt/api/reference). ::card-group :::card --- description: Cada chamada concluída chega ao seu servidor por webhook e cria ou actualiza o contacto e a actividade no CRM. icon: i-lucide-refresh-cw title: Sincronizar chamadas com o CRM to: https://docs.diska.ai/pt/api/guides/sync-calls-crm --- ::: :::card --- description: Todo o histórico para CSV, ou com as transcrições para JSONL, com paginação por cursor. icon: i-lucide-download title: Exportar o histórico de chamadas to: https://docs.diska.ai/pt/api/guides/export-call-history --- ::: :::card --- description: Lê o sitemap do site e importa cada página e cada PDF para uma base de conhecimento. icon: i-lucide-globe title: Alimentar o conhecimento a partir do site to: https://docs.diska.ai/pt/api/guides/knowledge-from-website --- ::: :: # Versões e alterações ## Política de versões A versão principal está no caminho: `https://api.diska.ai/v1`. Dentro da `/v1`, a Diska só faz alterações compatíveis: uma integração que funciona hoje continua a funcionar sem mudanças. ### Alterações compatíveis Podem acontecer a qualquer momento e ficam registadas no [histórico](https://docs.diska.ai/#hist%C3%B3rico): - novos endpoints; - novos campos nas respostas e nos webhooks; - novos parâmetros ou campos opcionais nos pedidos; - novos valores em campos de estado ou de tipo (por exemplo, um novo `channel` ou `status`); - novos eventos de webhook (só os recebe se os subscrever); - outro texto nas mensagens de erro (`detail`); - limites de utilização mais generosos. Para a sua integração aguentar estas alterações: - ignore os campos que não conhece; - trate valores desconhecidos de estado ou de tipo sem falhar; - decida pelo código HTTP, não pelo texto das mensagens de erro; - não dependa da ordem dos campos; - trate os identificadores como texto opaco. ### Alterações incompatíveis Remover ou mudar o nome de um endpoint ou de um campo, mudar um tipo, tornar obrigatório um parâmetro opcional ou mudar a forma de autenticar só acontece numa nova versão principal (`/v2`). Nesse caso: - a nova versão é anunciada nesta página, com o que muda e como migrar; - a `/v1` continua a funcionar durante pelo menos **6 meses** depois do anúncio. A excepção são as correcções de segurança urgentes, que podem mudar um comportamento sem aviso prévio. Ficam também registadas aqui. ### Versão da especificação O campo `info.version` da [especificação OpenAPI](https://docs.diska.ai/pt/api/api-channel#especifica%C3%A7%C3%A3o-openapi) segue o formato `MAJOR.MINOR.PATCH`: | Parte | Sobe quando | | ------- | ---------------------------------------------------------------------------------- | | `MAJOR` | Há uma nova versão principal no caminho (`/v2`). | | `MINOR` | Há funcionalidades novas ou mudanças visíveis na especificação, todas compatíveis. | | `PATCH` | Há correcções sem efeito no contrato. | ## Histórico ### 1.4.0 — Novembro de 2026 - **OAuth para plataformas parceiras** (piloto): uma plataforma liga-se a empresas DISKA com authorization code + PKCE; o token (`dsk_oat_…`) usa os mesmos endpoints `/v1`, só na empresa e com as permissões concedidas. Novos endpoints `/oauth/token`, `/oauth/revoke`, `/.well-known/oauth-authorization-server` e `GET /v1/oauth/token-info`. Veja [OAuth para plataformas parceiras](https://docs.diska.ai/pt/api/oauth). - `GET /v1/me` com um token OAuth devolve `app` (e `key` a `null`). Com uma chave API, a resposta não muda. ### 1.3.0 — 1 de Novembro de 2026 - **Editar agentes:** `PATCH /v1/agents/{agent_id}` altera o rascunho (prompt, saudação, língua, personalidade, objecções, notas e bases de conhecimento). `GET /v1/agents/{agent_id}` passa a trazer `configuration` e `has_unpublished_changes`. - **Gravações:** `GET /v1/calls/{call_id}/recording` redirecciona para um link assinado de 5 minutos, ou devolve-o em JSON. Novo âmbito `recordings:read`. - **Chamadas de saída:** `POST /v1/outbound-calls`, `GET /v1/outbound-calls/{outbound_call_id}` e `…/hangup`. Novo âmbito `calls:write`. - **Campanhas:** `/v1/campaigns` — criar, acrescentar e listar destinatários, iniciar, pausar, retomar e cancelar. Novos âmbitos `campaigns:read` e `campaigns:write`. - **Chat:** `/v1/chats` — conversa por texto com um agente, com a resposta no mesmo pedido. Terminar a conversa envia `call.completed`. Novo âmbito `chats:write`. As conversas aparecem em `GET /v1/calls` com o canal `web_chat`. - As chamadas de saída, as campanhas e o chat são activados pela Diska para cada organização. As chaves com acesso total ganham os âmbitos novos. ### 1.2.0 — 1 de Novembro de 2026 - A especificação OpenAPI declara a autenticação como esquemas de segurança (`bearerAuth` e `apiKeyHeader`), em vez de repetir o cabeçalho `X-API-Key` como parâmetro em cada operação. A API funciona como antes: as duas formas de enviar a chave continuam válidas. - A API aceita pedidos do browser vindos de `docs.diska.ai`, para o **Experimentar** da [Referência da API](https://docs.diska.ai/pt/api/reference). - A descrição da especificação aponta para [Começar com a API](https://docs.diska.ai/pt/api/getting-started) e para a referência. ### 11 de Setembro de 2026 - A transcrição de `GET /v1/calls/{call_id}` (`messages`) passa a vir agrupada em falas completas. Antes, nas chamadas web em tempo real, cada fragmento transmitido — às vezes uma só palavra — era uma entrada. O formato de cada entrada não muda. ### 1.1.0 — 6 de Agosto de 2026 Lançamento da API da DISKA: - chaves API da organização, com âmbitos e data de expiração; - agentes: listar, ver, criar e publicar; - chamadas: lista com paginação por offset e por cursor, e detalhe com transcrição, acções executadas e resultado pós-chamada; - análises, números de telefone e bases de conhecimento (texto, página web e PDF); - webhooks `call.completed` assinados, com repetições e desactivação automática; - limite de 120 pedidos por minuto por chave; - especificação OpenAPI em `/v1/openapi.json`. # OAuth para plataformas parceiras Se a sua plataforma (um sistema de vendas, um CRM ou um ERP) precisa de utilizar a DISKA **em nome dos seus clientes**, utilize OAuth 2.0. O cliente selecciona «Ligar com a DISKA», escolhe a empresa e as permissões num ecrã da DISKA, e a sua plataforma recebe um token válido apenas para essa empresa. | | Chave API | OAuth | | ------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | Indicado para | Uma empresa que integra os seus próprios sistemas | Uma plataforma que serve várias empresas | | Como é obtida | O cliente copia a chave em **Definições → Chaves API** e introdu-la na sua plataforma | O cliente autoriza o acesso num ecrã da DISKA | | Âmbito | Os âmbitos definidos na chave; uma chave sem âmbitos tem acesso total | Apenas as permissões que o cliente concedeu | | Revogação | O cliente elimina a chave | O cliente desliga a aplicação em **Definições → Aplicações ligadas**, ou a própria aplicação revoga o acesso | ::callout{type="info"} As aplicações OAuth estão em fase **piloto** . Para registar a sua plataforma, contacte a DISKA: activamos a funcionalidade para a sua organização. :: O fluxo segue o padrão OAuth 2.1: **authorization code com PKCE** (método S256, obrigatório), tokens de acesso válidos durante uma hora e refresh tokens com **rotação**. ## Endpoints | Função | URL | | ------------------------ | -------------------------------------------------------------------------------------------------------------- | | Metadados (RFC 8414) | `https://api.diska.ai/.well-known/oauth-authorization-server` | | Autorização (no browser) | `https://app.diska.ai/oauth/authorize` | | Emissão de tokens | `POST https://api.diska.ai/oauth/token` | | Revogação (RFC 7009) | `POST https://api.diska.ai/oauth/revoke` | | Informação do token | `GET https://api.diska.ai/v1/oauth/token-info` | | API | `https://api.diska.ai/v1`, com os mesmos endpoints da [API da DISKA](https://docs.diska.ai/pt/api/api-channel) | ## 1. Registar a aplicação O registo é feito em **Definições → Apps OAuth**, por um proprietário ou administrador da sua organização. Indique: - **Nome, descrição, site, política de privacidade e logótipo**, apresentados ao cliente no ecrã de autorização. O site, a política de privacidade e o logótipo têm de ser endereços `https://`. - **Ambiente**: - **Teste**: apenas os membros da sua organização podem autorizar a aplicação, e só para a própria organização; são aceites endereços `http://localhost` nos redirect URIs. Destina-se ao desenvolvimento. - **Produção**: qualquer empresa DISKA pode autorizar a aplicação. Enquanto não for **verificada pela DISKA**, o ecrã de autorização apresenta um aviso e a aplicação fica limitada a 100 empresas ligadas. Alterar o nome, a descrição, o logótipo, o site, a política de privacidade ou os redirect URIs de uma aplicação verificada, ou acrescentar permissões, devolve-a ao estado de não verificada até nova revisão da DISKA. - **Redirect URIs**: até 10 endereços `https://` (ou `http://localhost` no ambiente de teste). O `redirect_uri` de cada pedido tem de coincidir **exactamente** com um deles. - **Permissões** que a aplicação pode pedir (consulte [Permissões](https://docs.diska.ai/#permiss%C3%B5es)). Após o registo, recebe o `client_id` (`dsk_app_…`) e o `client_secret` (`dsk_cs_…`). O secret **é apresentado uma única vez**: guarde-o no servidor da sua plataforma e nunca o exponha no browser nem numa aplicação móvel. Pode gerar um novo secret a qualquer momento. O anterior deixa de funcionar de imediato, mas os tokens já emitidos continuam válidos. ## 2. Encaminhar o cliente para a DISKA Em cada pedido de ligação, gere: - um valor `state` aleatório, guardado na sessão do utilizador, que protege contra ataques CSRF; - um `code_verifier` aleatório, com 43 a 128 caracteres do conjunto `A-Z a-z 0-9 - . _ ~`, e o respectivo `code_challenge`, calculado como base64url(SHA-256(`code_verifier`)) sem o carácter `=` final. Em seguida, redireccione o browser para: ```text https://app.diska.ai/oauth/authorize ?response_type=code &client_id=dsk_app_… &redirect_uri=https://app.exemplo.ao/integracoes/diska/callback &scope=organization:read agents:read calls:read calls:write &state=… &code_challenge=… &code_challenge_method=S256 ``` | Parâmetro | Descrição | | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | `response_type` | Tem sempre o valor `code`. | | `client_id` | Identificador da sua aplicação. | | `redirect_uri` | Um dos endereços registados, exactamente igual. | | `scope` | Permissões pedidas, separadas por espaços. Se for omitido, são pedidas todas as permissões configuradas na aplicação. | | `state` | Obrigatório. É devolvido sem alterações. | | `code_challenge`, `code_challenge_method` | Parâmetros PKCE. Só é aceite o método `S256`. | No ecrã da DISKA, o cliente inicia sessão (caso ainda não o tenha feito), escolhe a empresa e pode **desmarcar permissões**. Apenas proprietários e administradores podem ligar aplicações a uma empresa. O ecrã indica também as operações que a aplicação **nunca** poderá realizar: consultar chaves API, gerir membros, consultar faturação e minutos, alterar números, telefonia ou WhatsApp, e eliminar a empresa. ## 3. Receber o código de autorização Se o cliente autorizar o acesso, o browser regressa ao seu `redirect_uri`: ```text https://app.exemplo.ao/integracoes/diska/callback?code=dsk_ac_…&state=… ``` Confirme que o `state` recebido é igual ao que guardou. O código é válido durante **60 segundos** e pode ser utilizado **uma única vez**. Se o cliente recusar o pedido, ou se o pedido contiver um erro detectado depois da validação do `client_id` e do `redirect_uri`, o browser regressa com um código de erro: ```text …/callback?error=access_denied&error_description=O+utilizador+recusou+o+pedido.&state=… ``` Um `client_id` desconhecido ou um `redirect_uri` não registado **não** provocam o regresso à sua aplicação. Nesses casos, o erro é apresentado no ecrã da DISKA. ## 4. Trocar o código por tokens A troca é feita a partir do seu servidor, com autenticação HTTP Basic (`client_id:client_secret`) e o corpo no formato `application/x-www-form-urlencoded`: ```bash curl -X POST https://api.diska.ai/oauth/token \ -u "dsk_app_…:dsk_cs_…" \ -d grant_type=authorization_code \ -d code=dsk_ac_… \ -d redirect_uri=https://app.exemplo.ao/integracoes/diska/callback \ -d code_verifier=… ``` Em alternativa à autenticação Basic, pode enviar o `client_id` e o `client_secret` no corpo do pedido. Não utilize os dois métodos em simultâneo. Resposta `200`: ```json { "access_token": "dsk_oat_…", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "dsk_ort_…", "scope": "organization:read agents:read calls:read calls:write", "organization": { "id": "6f1c…", "name": "Loja Kianda", "nif": "5000000000" } } ``` - `scope` contém as permissões **concedidas** pelo cliente, que podem ser menos do que as pedidas. - `organization` identifica a empresa. O `nif` só é enviado com a permissão `organization:read`; sem ela, vem `null`. Guarde os tokens associados a este identificador: um cliente pode ligar várias empresas, e cada uma tem os seus próprios tokens. - Se a mesma empresa voltar a autorizar a aplicação, as novas permissões substituem as anteriores e os tokens antigos deixam de ser válidos. ## 5. Utilizar a API O access token é enviado da mesma forma que uma chave API, no cabeçalho `Authorization`: ```bash curl https://api.diska.ai/v1/me \ -H "Authorization: Bearer dsk_oat_…" ``` ```json { "organization": { "id": "6f1c…", "name": "Loja Kianda", "slug": "loja-kianda" }, "key": null, "app": { "client_id": "dsk_app_…", "name": "Vende", "scopes": ["organization:read", "agents:read", "calls:read", "calls:write"] } } ``` Todos os endpoints da [API da DISKA](https://docs.diska.ai/pt/api/reference) estão disponíveis, sempre no contexto da empresa associada ao token e dentro das permissões concedidas. Aplicam-se os minutos de voz, os limites e as funcionalidades activas dessa empresa (chamadas de saída, campanhas e chat). O endpoint `GET /v1/oauth/token-info` devolve a aplicação, a empresa, as permissões e a data de expiração do token utilizado. ## 6. Renovar os tokens O access token é válido durante **uma hora**. Antes de expirar, ou ao receber uma resposta `401`, troque o refresh token por um novo par de tokens: ```bash curl -X POST https://api.diska.ai/oauth/token \ -u "dsk_app_…:dsk_cs_…" \ -d grant_type=refresh_token \ -d refresh_token=dsk_ort_… ``` A resposta tem o mesmo formato do passo 4. Guarde **ambos** os tokens recebidos: o refresh token é substituído em cada renovação (**rotação**) e o access token anterior deixa de ser válido. ::callout{type="warning"} Cada refresh token só pode ser utilizado **uma vez** . Se um refresh token já utilizado for apresentado de novo, a DISKA considera-o comprometido, **desliga a empresa** e a aplicação terá de pedir nova autorização. Garanta que cada renovação é feita por um único processo (por exemplo, com um bloqueio por empresa) e guarde o novo par de tokens antes de o utilizar. Se o mesmo refresh token chegar duas vezes em menos de 10 segundos (dois processos a renovar ao mesmo tempo), o segundo pedido recebe `invalid_grant` e a empresa **não** é desligada: use o par de tokens que o primeiro pedido recebeu. :: Um refresh token que não seja utilizado expira ao fim de **90 dias**, contados a partir da última renovação. Na renovação, o parâmetro `scope` é opcional. Se for enviado, tem de ser igual às permissões concedidas. ## 7. Revogar o acesso Quando o cliente desliga a DISKA na sua plataforma, revogue o acesso: ```bash curl -X POST https://api.diska.ai/oauth/revoke \ -u "dsk_app_…:dsk_cs_…" \ -d token=dsk_ort_… ``` - A revogação do **refresh token** desliga a empresa e invalida todos os tokens associados. - A revogação de um **access token** invalida apenas esse token. - A resposta é sempre `200`, mesmo para um token desconhecido. O cliente também pode desligar a aplicação, ou retirar-lhe permissões, em **Definições → Aplicações ligadas**. A alteração produz efeito no pedido seguinte da aplicação, que é notificada por [webhook](https://docs.diska.ai/#webhooks-da-aplica%C3%A7%C3%A3o). ## Permissões | Permissão | Acesso concedido | | ----------------------------------- | --------------------------------------------------------------------------------------------- | | `organization:read` | NIF da empresa. O identificador e o nome da empresa são sempre enviados na resposta do token. | | `agents:read` | Listar e consultar agentes. | | `agents:write` | Criar, editar e publicar agentes. | | `calls:read` | Chamadas, transcrições, resultados pós-chamada e o evento `call.completed`. | | `calls:write` | [Chamadas de saída](https://docs.diska.ai/pt/api/reference/outbound-calls). | | `analytics:read` | Análises. | | `phone-numbers:read` | Números. | | `knowledge:read`, `knowledge:write` | Bases de conhecimento. | | `recordings:read` | Gravações. | | `campaigns:read`, `campaigns:write` | [Campanhas](https://docs.diska.ai/pt/api/reference/campaigns). | | `chats:write` | [Chat](https://docs.diska.ai/pt/api/reference/chats) com agentes. | Não existe uma permissão para gerir os webhooks da empresa (`/v1/webhook-endpoints`). A aplicação recebe os eventos através do seu próprio [webhook](https://docs.diska.ai/#webhooks-da-aplica%C3%A7%C3%A3o). Um token sem a permissão necessária recebe `403`, mesmo que a empresa tenha essa permissão noutras chaves API. ## Erros Nos endpoints de emissão e de revogação de tokens, os erros seguem o formato OAuth (`{"error", "error_description"}`): | HTTP | `error` | Causa | | ---- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 401 | `invalid_client` | `client_id` ou `client_secret` incorrectos, ou autenticação em falta. | | 400 | `invalid_request` | Parâmetro em falta ou `code_verifier` inválido. | | 400 | `invalid_grant` | Código ou refresh token inválido, expirado, já utilizado ou emitido para outra aplicação; ou `redirect_uri` ou `code_verifier` que não correspondem ao pedido original. | | 400 | `invalid_scope` | Na renovação, `scope` diferente das permissões concedidas. | | 400 | `unsupported_grant_type` | `grant_type` diferente de `authorization_code` e de `refresh_token`. | | 400 | `unauthorized_client` | A aplicação foi suspensa pela DISKA. | | 403 | `app_connection_limit` | A aplicação, ainda não verificada, atingiu o limite de empresas ligadas. | | 403 | `organization_suspended` | A empresa está suspensa. A ligação mantém-se e a renovação volta a funcionar quando a empresa for reactivada. | Nos pedidos à API (`/v1`) com um token: | HTTP | Causa | | ---- | ----------------------------------------------------------------------------------------------------------------------------------- | | 401 | Token inválido, expirado ou revogado (`WWW-Authenticate: Bearer error="invalid_token"`). Renove os tokens ou peça nova autorização. | | 403 | Permissão em falta (`WWW-Authenticate: Bearer error="insufficient_scope", scope="…"`). | | 403 | `Organização suspensa.` | | 402 | A empresa esgotou os minutos de voz. Aplica-se apenas a pedidos que utilizam voz. | ## Webhooks da aplicação Cada aplicação tem **um único** URL de webhook, configurado em **Definições → Apps OAuth**, que recebe os eventos de todas as empresas ligadas. Ao configurar o URL, é gerado um secret de assinatura (`dskw_…`), apresentado uma única vez. | Evento | Enviado quando | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `app.authorization.created` | Uma empresa liga a aplicação, ou volta a ligá-la. | | `app.authorization.updated` | A empresa retira permissões. O campo `data.scopes` indica as permissões que se mantêm. | | `app.authorization.revoked` | A ligação termina por decisão da empresa, por decisão da DISKA ou por reutilização de um refresh token. Não é enviado quando é a própria aplicação a revogar o acesso. | | `call.completed` | Uma chamada termina, nas empresas que concederam `calls:read`. O campo `data` tem o mesmo conteúdo do [evento `call.completed`](https://docs.diska.ai/pt/api/webhooks). Se a empresa desligar a aplicação ou retirar `calls:read`, as entregas pendentes são canceladas. | | `ping` | É utilizado o botão **Enviar ping**. | Exemplo de corpo: ```json { "id": "0b6f…", "event": "app.authorization.revoked", "created_at": "2026-11-19T10:15:02.123456+00:00", "organization_id": "6f1c…", "data": { "connection_id": "a1b2…", "reason": "member", "revoked_at": "2026-11-19T10:15:02.120000+00:00" } } ``` Os cabeçalhos e a assinatura seguem o mesmo modelo dos [webhooks da API](https://docs.diska.ai/pt/api/webhooks#verificar-a-assinatura): `X-Diska-Event`, `X-Diska-Delivery` (igual ao campo `id`), `X-Diska-Timestamp` e `X-Diska-Signature`. A assinatura tem o formato `sha256=` e é calculada com o secret do webhook da aplicação. O seu servidor deve responder com `2xx` em menos de 10 segundos. Uma entrega falhada é repetida após **1 minuto, 5 minutos, 30 minutos, 2 horas e 8 horas**, num total de seis tentativas. Uma resposta `410` interrompe as repetições. Utilize o campo `id` para ignorar entregas repetidas. A opção **Ver entregas** apresenta as últimas 25 entregas, com o respectivo estado e erro. ## Exemplo completo ::code-group ```python [Python] import base64, hashlib, os, secrets import requests CLIENT_ID = os.environ["DISKA_CLIENT_ID"] CLIENT_SECRET = os.environ["DISKA_CLIENT_SECRET"] REDIRECT_URI = "https://app.exemplo.ao/integracoes/diska/callback" def start(session: dict) -> str: """Devolve o URL para onde redireccionar o browser.""" verifier = secrets.token_urlsafe(48) challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode() session["diska_state"] = secrets.token_urlsafe(24) session["diska_verifier"] = verifier params = { "response_type": "code", "client_id": CLIENT_ID, "redirect_uri": REDIRECT_URI, "scope": "organization:read agents:read calls:read", "state": session["diska_state"], "code_challenge": challenge, "code_challenge_method": "S256", } return requests.Request("GET", "https://app.diska.ai/oauth/authorize", params=params).prepare().url def callback(session: dict, query: dict) -> dict: """Troca o código por tokens; guarde-os associados a tokens['organization']['id'].""" if query.get("error"): raise RuntimeError(query.get("error_description") or query["error"]) if query.get("state") != session.pop("diska_state", None): raise RuntimeError("state inválido") response = requests.post( "https://api.diska.ai/oauth/token", auth=(CLIENT_ID, CLIENT_SECRET), data={ "grant_type": "authorization_code", "code": query["code"], "redirect_uri": REDIRECT_URI, "code_verifier": session.pop("diska_verifier"), }, timeout=15, ) response.raise_for_status() return response.json() def refresh(refresh_token: str) -> dict: response = requests.post( "https://api.diska.ai/oauth/token", auth=(CLIENT_ID, CLIENT_SECRET), data={"grant_type": "refresh_token", "refresh_token": refresh_token}, timeout=15, ) response.raise_for_status() return response.json() # guarde o novo par antes de o utilizar ``` ```js [Node.js] import crypto from 'node:crypto' const CLIENT_ID = process.env.DISKA_CLIENT_ID const CLIENT_SECRET = process.env.DISKA_CLIENT_SECRET const REDIRECT_URI = 'https://app.exemplo.ao/integracoes/diska/callback' const basic = 'Basic ' + Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64') export function start(session) { const verifier = crypto.randomBytes(48).toString('base64url') const challenge = crypto.createHash('sha256').update(verifier).digest('base64url') session.diskaState = crypto.randomBytes(24).toString('base64url') session.diskaVerifier = verifier const url = new URL('https://app.diska.ai/oauth/authorize') url.search = new URLSearchParams({ response_type: 'code', client_id: CLIENT_ID, redirect_uri: REDIRECT_URI, scope: 'organization:read agents:read calls:read', state: session.diskaState, code_challenge: challenge, code_challenge_method: 'S256' }) return url.toString() } async function token(body) { const response = await fetch('https://api.diska.ai/oauth/token', { method: 'POST', headers: { 'Authorization': basic, 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(body) }) const json = await response.json() if (!response.ok) throw new Error(json.error_description || json.error) return json } export async function callback(session, query) { if (query.error) throw new Error(query.error_description || query.error) if (query.state !== session.diskaState) throw new Error('state inválido') delete session.diskaState return token({ grant_type: 'authorization_code', code: query.code, redirect_uri: REDIRECT_URI, code_verifier: session.diskaVerifier }) // guarde os tokens associados a organization.id } export const refresh = refreshToken => token({ grant_type: 'refresh_token', refresh_token: refreshToken }) ``` :: ## Limites de utilização - `POST /oauth/token` e `POST /oauth/revoke`: 60 pedidos por minuto, por aplicação e por endereço IP. - Pedidos à API (`/v1`) com um token: 120 pedidos por minuto **por empresa ligada**. O consumo de uma empresa nunca afecta o limite de outra. - Chamadas de saída (`POST /v1/outbound-calls`): até 200 por dia (UTC) **por empresa ligada**. Destinatários de campanhas (`POST /v1/campaigns/{id}/recipients`): até 2000 por dia por empresa ligada. Estes limites somam-se aos da própria empresa; acima deles a API responde `429` e a empresa vê o registo na auditoria. Se precisar de mais, fale com a DISKA. # API A Diska tem uma API pública para integrações servidor-a-servidor: a **[API da DISKA](https://docs.diska.ai/pt/api/api-channel)**. Com uma chave API da organização, o seu sistema pode consultar agentes, chamadas, transcrições, análises, números e bases de conhecimento, criar e publicar agentes, alimentar bases de conhecimento e registar webhooks que avisam quando uma chamada termina. ## Base URL ```text https://api.diska.ai/v1 ``` Primeiro pedido — confirma a organização e a chave por trás do token: ```bash curl https://api.diska.ai/v1/me \ -H "Authorization: Bearer dsk_…" ``` Passo a passo, com exemplos em cURL, Python, JavaScript e PHP: [Começar com a API](https://docs.diska.ai/pt/api/getting-started). A especificação OpenAPI da API da DISKA está em `https://api.diska.ai/v1/openapi.json` (sem autenticação). Pode importá-la no Postman ou usá-la para gerar um cliente. ::callout{type="info"} O backoffice ( `app.diska.ai` ) usa uma API interna própria, autenticada pela sessão de quem inicia sessão. Essa API não é um contrato de integração: pode mudar sem aviso e não aceita chaves API. Para integrações, use apenas a API da DISKA. :: ## Conteúdo ::card-group :::card --- description: Crie uma chave e faça o primeiro pedido, com exemplos em várias linguagens. icon: i-lucide-rocket title: Começar com a API to: https://docs.diska.ai/pt/api/getting-started --- ::: :::card --- description: O que pode fazer, âmbitos, paginação, limites e erros. icon: i-lucide-plug title: API da DISKA to: https://docs.diska.ai/pt/api/api-channel --- ::: :::card --- description: Criar, usar, expirar e revogar chaves API. icon: i-lucide-key-round title: Autenticação to: https://docs.diska.ai/pt/api/authentication --- ::: :::card --- description: Receba os dados de cada chamada concluída no seu sistema. icon: i-lucide-webhook title: Webhooks to: https://docs.diska.ai/pt/api/webhooks --- ::: :::card --- description: Plataformas que servem muitas empresas: ligação com um clique, tokens por empresa. to: /pt/api/oauth icon: i-lucide-key-square title: OAuth para parceiros --- ::: :::card --- description: Referência completa de cada endpoint da API da DISKA. icon: i-lucide-list title: Endpoints to: https://docs.diska.ai/pt/api/endpoints --- ::: :::card --- description: Como pôr pessoas a falar com um agente e o que não é API pública. icon: i-lucide-audio-waveform title: Tempo real to: https://docs.diska.ai/pt/api/realtime --- ::: :::card --- description: Cada endpoint numa página: esquemas, exemplos e Experimentar. to: /pt/api/reference icon: i-lucide-book-marked title: Referência da API --- ::: :::card --- description: Integrações completas com código testado. icon: i-lucide-map title: Guias to: https://docs.diska.ai/pt/api/guides --- ::: :::card --- description: Política de versões e histórico de alterações. icon: i-lucide-history title: Versões e alterações to: https://docs.diska.ai/pt/api/changelog --- ::: :: # Cal.com Com o Cal.com ligado, o agente pode marcar uma reunião no seu calendário durante a conversa. A ligação é da organização: uma conta Cal.com serve todos os agentes. ![Painel do Cal.com ligado, com a conta autorizada e o botão Desligar](https://docs.diska.ai/images/docs/integrations/calcom-drawer.png) ## Ligar 1. No Cal.com, gere uma chave API nas definições da aplicação. 2. Na Diska, aceda a **Definições → Integrações** e clique em **Cal.com**. 3. Em **Ligar com Cal.com**, cole a chave no campo **Chave API**. 4. Clique em **Ligar**. Aparece *Cal.com ligado* e o painel mostra **Autorizado por** (o email da conta) e **Ligado em**. A chave é validada no Cal.com e guardada cifrada no servidor; nunca fica no browser. Só o **Proprietário** e os **Administradores** podem ligar ou desligar. ## Usar nas marcações 1. Em **Acções → Agendamento em tempo real**, crie uma acção. A secção **Conta Cal.com** mostra o estado da ligação. 2. Em **Evento**, escolha o tipo de evento da sua conta Cal.com (use o botão de actualizar se acabou de criar um). 3. Atribua a acção ao agente, ou use-a no nó [Agendamento](https://docs.diska.ai/pt/nodes/booking) de um fluxo. O email de confirmação da marcação vai para a variável ``: mapeie-a ao anexar a acção ao agente. A sugestão automática de horários livres ainda está *em breve*: por agora, o agente marca a hora pedida pelo cliente e o Cal.com valida a disponibilidade. Veja [Agendamento em tempo real](https://docs.diska.ai/pt/actions/real-time-booking) e o guia [Marcar reuniões](https://docs.diska.ai/pt/guides/book-meetings). ## Desligar No painel do Cal.com, clique em **Desligar**. Aparece *Cal.com desligado*. As acções de agendamento deixam de conseguir marcar até voltar a ligar, e a publicação de um fluxo com o nó **Agendamento** pode ser bloqueada com *Marcação (calendário) ainda não está ligada a um fornecedor.* ## Problemas | Mensagem | Causa | | -------------------------------------------------------- | ------------------------------------------------------------------------------- | | *Chave API do Cal.com inválida ou sem permissão.* | A chave está errada, foi revogada ou não tem permissões. Gere outra no Cal.com. | | *Não foi possível contactar o Cal.com. Tente novamente.* | Falha de rede temporária. | | *Nenhum tipo de evento encontrado na conta Cal.com.* | Crie um tipo de evento no Cal.com. | Mais em [Integração não liga](https://docs.diska.ai/pt/troubleshooting/integration-not-connecting). # Integrações As integrações dão aos agentes acesso a serviços fora da Diska. Gerem-se em **Definições → Integrações** (Proprietário e Administradores) — veja [Integrações nas Definições](https://docs.diska.ai/pt/settings/integrations). ## Disponíveis | Integração | Para quê | Quem configura | | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | | [Cal.com](https://docs.diska.ai/pt/integrations/calcom) | O agente marca reuniões no seu calendário durante a chamada. | A organização, com uma chave API do Cal.com. | | **SMS (Ombala)** | SMS durante e depois da chamada. Veja [SMS durante a chamada](https://docs.diska.ai/pt/actions/during-call-sms) e [SMS pós-chamada](https://docs.diska.ai/pt/actions/post-call-sms). | A Diska (selo **Gerido pela Diska**). | | [WhatsApp](https://docs.diska.ai/pt/whatsapp) | Os clientes conversam por WhatsApp com um agente. | A organização, autorizando a Diska na Meta. | | [API da DISKA e webhooks](https://docs.diska.ai/pt/api/api-channel) | O seu CRM ou sistema lê dados e recebe eventos da Diska. | A organização, com [chaves API](https://docs.diska.ai/pt/settings/api-keys). | | [Acções personalizadas](https://docs.diska.ai/pt/actions/custom-actions) | O agente chama uma API sua durante a chamada. | A organização, em **Acções**. | Para ligar números de telefone, veja [Telefonia](https://docs.diska.ai/pt/telephony). ## Fora da lista A página **Integrações** só lista o que já pode usar. Outros serviços (por exemplo, CRMs) ainda não têm integração dedicada; até lá, use a API da DISKA e as acções personalizadas para ligar a Diska aos seus sistemas. # Números de telefone A página **Números** (menu lateral) lista os números de telefone da organização. Todos os membros a podem consultar; só o **Proprietário** e os **Administradores** podem comprar, importar, eliminar e atribuir números. ## A lista de números O botão **Número** abre duas opções: - **Comprar um número DISKA** — reserve um número da rede DISKA; fica activo quando o pagamento for confirmado. - **Importar um número personalizado** — ligue à Diska um número que já utiliza, por trunk SIP. Veja [Ligar por SIP](https://docs.diska.ai/pt/telephony/sip-trunk). A tabela mostra: | Coluna | O que mostra | | ------------ | ----------------------------------------------------------------------------------- | | **Número** | O número em formato +244 959 000 000. | | **Nome** | O nome amigável, se lhe deu um. | | **Tipo** | **Comprado** (número DISKA) ou **Importado** (trunk SIP próprio). | | **Chamadas** | Se o número recebe chamadas. | | **Estado** | O estado de configuração (ver abaixo). Passe o rato por cima para ler a explicação. | | **SMS** | Se o número tem capacidade de SMS. | | **Agentes** | Quantos agentes usam o número. | | **Preço** | A mensalidade em Kz/mês (— nos números importados). | No menu **⋮** de cada linha tem **Copiar** e **Eliminar**. A página actualiza-se sozinha a cada poucos segundos, por isso uma encomenda confirmada ou um trunk que acabou de ficar pronto aparecem sem recarregar. ## Estado do número | Estado | Significado | | ------------------------- | --------------------------------------------------------------------------------------------------- | | **Configurado** | O número tem um agente associado. A disponibilidade e o encaminhamento dependem também do operador. | | **Sem agente** | Nenhum agente usa o número. Atribua-o a um agente para atender. | | **A ativar** | Número importado à espera de ser activado no servidor SIP. | | **Credenciais pendentes** | Número importado com a configuração SIP por concluir (por exemplo, à espera do registo SIP). | | **Não confirmado** | O servidor ainda não confirmou a configuração SIP. | | **Erro SIP** | A configuração SIP falhou. Consulte o detalhe do número. | | **Desativado** | O número está desactivado (por exemplo, suspenso pela DISKA). | | **Sem chamadas** | O número não tem capacidade de chamadas. | ::callout{type="warning"} **Configurado** só confirma que há um agente associado. Para atender chamadas, esse agente tem de ser do tipo **Inbound** e estar **publicado** com o número. Veja [Agente não atende](https://docs.diska.ai/pt/troubleshooting/agent-not-answering) . :: ## Comprar um número DISKA Os números DISKA são números angolanos da rede DISKA, na rede Africell. O pagamento é confirmado pela equipa DISKA. 1. Em **Números**, clique em **Número → Comprar um número DISKA**. 2. A janela lista os números à venda, com a mensalidade (Kz/mês) e a taxa de activação. Clique em **Reservar** no número que quer. 3. A janela passa a **Número reservado** e mostra **Reservado até**, **Mensalidade**, **Taxa de ativação** e **Primeiro pagamento** (activação + 1.º mês), com as instruções de pagamento. 4. Clique em **Concluir** e pague conforme as instruções (por omissão, a equipa DISKA envia os dados de pagamento por email). 5. Quando a DISKA confirma o pagamento, o número aparece na lista como **Comprado**, com o estado **Sem agente**. Falta [atribuí-lo a um agente](https://docs.diska.ai/#atribuir-a-um-agente). Se a lista estiver vazia, verá *"De momento não há números DISKA à venda."* — pode, entretanto, importar um número com um trunk SIP do seu operador. ### Encomendas por pagar Enquanto o pagamento não é confirmado, a encomenda aparece no topo da página: o número, a data até à qual está reservado, o primeiro pagamento, a mensalidade seguinte e as instruções de pagamento. - **Cancelar encomenda** pede confirmação (**Cancelar a encomenda?**) e devolve o número à venda. - Se o pagamento não for confirmado até **Reservado até**, a encomenda expira e o número volta a estar à venda. - Quando a encomenda é concluída, cancelada ou expira, deixa de aparecer na página. Mensagens que pode ver ao reservar: | Mensagem | O que fazer | | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | | *Já tem N encomendas por pagar. Conclua ou cancele uma antes.* | Há um limite de encomendas abertas ao mesmo tempo. Pague ou cancele uma. | | *A organização atingiu o limite de N números DISKA (X em uso e Y por pagar).* | A DISKA definiu um máximo de números para a organização. Contacte a DISKA para o aumentar. | | *Este número já não está disponível.* | Outra organização reservou-o primeiro. Escolha outro. | ## Detalhe de um número Clique numa linha para abrir o detalhe: - o **estado**, com a explicação; - **Nome amigável** (opcional) — guardado ao carregar em Enter ou ao sair do campo; - **Tipo**, **Chamadas** e **SMS**; - **Usado em agentes** — a lista de agentes com este número, com ligação para cada um; - nos números importados, a secção **SIP trunk** (veja [Ligar por SIP](https://docs.diska.ai/pt/telephony/sip-trunk#acompanhar-o-estado)). ## Atribuir a um agente 1. Abra o agente e clique em **Publicação** na barra de ferramentas. Abre **Definições de publicação**. 2. No separador **Telefone**, clique em **Adicionar número de telefone**. 3. Escolha o número. A lista mostra o estado de cada número e tem pesquisa; o botão **Importar** abre a importação de um trunk SIP. 4. Aparece *Número anexado*. 5. **Publique o agente** (botão **Publicar**). As chamadas são atendidas pela versão publicada, por isso a atribuição só conta depois de publicar. Para trocar de número use o lápis (**Alterar número**); para o retirar use **×** (**Remover número**). Volte a publicar depois de qualquer alteração. Regras: - Cada número recebe chamadas num **único agente Inbound**. Se já estiver noutro, verá *Número já anexado a um agente inbound*. - Um agente **Outbound** pode usar o mesmo número que o agente Inbound, como identificação de quem liga. - Um número DISKA só pode ser atribuído quando está activo na organização; caso contrário verá *Este número DISKA não está ativo na organização*. - Só aparecem números activos. Sem permissão, o separador mostra *Apenas proprietários e administradores podem atribuir números.* - A lista de verificação do agente avisa **Número de telefone** quando falta um número. Não impede a publicação, mas sem número o agente não atende chamadas telefónicas nem faz a chamada de teste. ## Eliminar ou devolver um número - **Número importado**: **⋮ → Eliminar** e confirme em **Eliminar número?**. O número deixa a organização. - **Número DISKA**: não se elimina na página. Ao tentar, verá *Este número é uma linha da rede DISKA. Para o devolver, contacte o suporte.* - Um número DISKA com o estado **Desativado** foi suspenso pela DISKA. Contacte o suporte. ## Consultar por API Os números também podem ser lidos pela API da DISKA: `GET /v1/phone-numbers`, com uma chave com o âmbito `phone-numbers:read`. Veja [API da DISKA](https://docs.diska.ai/pt/api/api-channel). # Ligar por SIP Um **trunk SIP** liga o seu operador ou a sua central telefónica (PBX) à Diska, para que os agentes atendam as chamadas de um número angolano que já tem. Este guia serve para qualquer operador ou central compatível com SIP. As chamadas para o número passam a ser atendidas pelo agente **Inbound** publicado com ele. Importar um número exige o papel de **Proprietário** ou **Administrador**. Se ainda não tem número, compre um número DISKA em [Números de telefone](https://docs.diska.ai/pt/telephony/numbers): não precisa de configurar SIP. ::callout{type="info"} **O que a ligação por SIP suporta hoje** - Números angolanos (+244 seguido de 9 dígitos), para **chamadas recebidas**. - Transporte **UDP** ou **TCP** num endereço **IPv4 público**. TLS e SRTP não estão disponíveis. - As transferências saem pelo seu trunk. O número importado não envia SMS. - A chamada de teste do painel **Testar** só funciona com números DISKA: valide um número importado com uma chamada real. :: ## Pré-requisitos - O papel de **Proprietário** ou **Administrador** na organização. - O **domínio SIP** do operador ou da central: um domínio ou IPv4 público, com porta se não for a habitual. - Os **IPs públicos de sinalização** de onde as chamadas saem para a Diska. Podem ser diferentes do domínio de registo. - **Utilizador** e **password** SIP, se o operador exigir registo (REGISTER); caso contrário, autenticação por IP. - Regras de firewall, do seu lado, que deixem passar a sinalização e o áudio da Diska (ver [Endereços SIP da Diska](https://docs.diska.ai/#endere%C3%A7os-sip-da-diska)). - Um agente do tipo **Inbound** para atender o número. ## Endereços SIP da Diska Envie as chamadas para o nome `sip.diska.ai`, na porta **5080**. Use o IP só nas regras de firewall. | Uso | Endereço | Porta | Protocolo | | -------------------------- | -------------------------------- | ----------- | ---------- | | Sinalização SIP dos trunks | `sip.diska.ai` (102.219.124.234) | 5080 | UDP ou TCP | | Áudio (RTP) | 102.219.124.234 | 16384–16639 | UDP | | SIP com TLS | Não disponível | — | — | Cada chamada é endereçada ao número importado, em formato internacional (E.164): ```text sip:+244923456789@sip.diska.ai:5080 ``` É o **Origination URI** que o detalhe do número mostra quando o trunk fica pronto. A porta 5060 da Diska não recebe trunks de operadores: use sempre a 5080. ## Definições do trunk | Definição | Valores aceites | Recomendação | | ---------------- | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | **Transporte** | UDP ou TCP | UDP, salvo se o operador exigir TCP. | | **Codecs** | G.711 A-law (PCMA), G.711 μ-law (PCMU) ou Opus | G.711 A-law a 20 ms, o padrão das redes angolanas. G.729 e G.723 não são aceites. | | **DTMF** | RFC 2833 / RFC 4733 (`telephone-event`, payload 101) | Aceite RFC 2833 do lado do operador ou da central: a Diska não envia teclas por SIP INFO. | | **Autenticação** | Por IP (estática) ou SIP REGISTER com autenticação digest | Por IP, se o operador permitir: não depende de um registo activo. | | **Rede** | IPv4 público | Uma central numa rede privada precisa de um IP público ou de conectividade adicional combinada com a DISKA. | Para uma ligação estável: - Declare **todos** os IPs de onde o operador envia chamadas, ou a rede inteira (de /16 a /32). A Diska recusa chamadas de IPs que não declarou. - Se o operador usar endereços diferentes para o áudio, a firewall do seu lado tem de aceitar o áudio de e para 102.219.124.234, nas portas UDP 16384–16639. - Com registo SIP, a Diska regista-se no operador e mantém o registo activo. O registo confirma a ligação, mas não prova que o número está encaminhado: faça sempre uma chamada real. ## Importar o número 1. Em **Números**, clique em **Número → Importar um número personalizado**. Abre **Importar número de telefone**. 2. Preencha os campos: | Campo | Obrigatório | Notas | | ----------------------------------- | ------------------ | ------------------------------------------------------------------------------------------- | | **Phone Provider** | Sim | **Custom**. *Twilio (em breve)* está desactivado. | | **Phone Number** | Sim | Número angolano em formato +244, por exemplo +244923456789. | | **Friendly Name** | Não | Nome para reconhecer o número na lista. | | **SIP Domain** | Sim | Domínio ou IP, com porta opcional (1–65535). Sem `sip:` nem `http://`. | | **Username** / **Password** | Só com registo SIP | Obrigatórios quando activa o registo SIP; caso contrário, preencha se o operador os exigir. | | **IPs de sinalização da operadora** | Sim | IPv4 públicos ou redes de /16 a /32, um por linha ou separados por vírgulas. | | **Transporte SIP** | Sim | **UDP** (por omissão) ou **TCP**. | | **Outbound Proxy** | Não | Domínio ou IP com porta, por exemplo `proxy.operador.ao:5060`. | | **Auth Username** | Não | Utilizador de autenticação, se for diferente do **Username**. | | **Ativar registo SIP outbound** | Não | Marque se o operador ou a central exigem SIP REGISTER. | 3. Clique em **Importar**. Se o servidor já confirmou a configuração, aparece *Número importado*; se ainda a está a aplicar, aparece *Configuração guardada* com o estado actual. Erros ao importar: | Mensagem | Causa | | -------------------------------------------------------------------------- | ----------------------------------------------------------------- | | *A sua organização já possui este número.* | O número já está na sua lista. | | *Este número pertence à rede DISKA.* | É um número DISKA: não se importa, compra-se. | | *Username e password são obrigatórios quando o registo SIP está activado.* | Activou o registo SIP sem credenciais. | | *Use IPs públicos da operadora ou redes IPv4 /16 a /32.* | Indicou IPs privados ou uma rede demasiado larga. | | *Use um domínio ou IP, sem esquema SIP/HTTP, e uma porta entre 1 e 65535.* | O **SIP Domain** ou o **Outbound Proxy** têm um formato inválido. | ## Acompanhar o estado A coluna **Estado** da lista e o detalhe do número (secção **SIP trunk**) mostram a evolução. A página actualiza-se sozinha; a configuração demora normalmente menos de um minuto a chegar ao servidor SIP. | Estado na lista | Estado SIP no detalhe | O que significa | | -------------------------------- | --------------------- | ----------------------------------------------------------------------- | | **A ativar** | Activação pendente | A configuração está a ser aplicada no servidor SIP. | | **Credenciais pendentes** | Credenciais pendentes | Falta concluir a configuração SIP, por exemplo à espera do registo SIP. | | **Erro SIP** | Erro | A configuração falhou. Leia a mensagem no detalhe. | | **Sem agente** / **Configurado** | Configurado | O trunk está pronto. Falta, ou já tem, um agente. | O detalhe mostra também a mensagem do servidor, por exemplo: - *Trunk configurado. Publique o agente associado e teste uma chamada de entrada com a operadora.* - *Registo SIP confirmado. Publique o agente associado e valide uma chamada real.* - *A aguardar registo SIP. Verifique credenciais, domínio e acesso de rede com a operadora.* Na secção **SIP trunk** do detalhe encontra ainda: **Provider**, **SIP Domain**, **Username**, **Password** (oculta), **Outbound Proxy**, **Auth Username**, **Solicitar registo SIP**, o transporte, os **IPs de entrada** e, quando pronto, o **Origination URI**. ## Encaminhar o número para a Diska Quando o trunk fica pronto, copie o **Origination URI** no detalhe do número e envie-o ao operador (ou configure-o na sua central). As chamadas para o número devem chegar a esse destino: - a partir dos IPs que declarou; - com o transporte escolhido; - com o número importado como destino (no formato `+244…`). A Diska só aceita uma chamada do trunk quando vem de um dos IPs declarados **e** é para o número importado. ## Pôr o número a atender 1. Atribua o número a um agente **Inbound** em **Publicação → Telefone** — veja [Atribuir a um agente](https://docs.diska.ai/pt/telephony/numbers#atribuir-a-um-agente). 2. **Publique** o agente. Só a versão publicada atende. 3. Faça uma chamada real para o número e confirme que o agente atende, que ouve e é ouvido nos dois sentidos e que a chamada aparece em [Históricos](https://docs.diska.ai/pt/history/calls). ## Transferências pelo trunk Numa chamada recebida pelo seu trunk, a transferência sai pelo mesmo trunk, com o seu número como identificação de quem liga. O destino pode ser um número de telefone ou um SIP URI no domínio do trunk. Para as transferências saírem, o operador ou a central têm de aceitar chamadas da Diska (102.219.124.234, porta 5080) com as credenciais do registo SIP ou por IP, e de as encaminhar para o destino. Veja [Transferências por telefone e SIP](https://docs.diska.ai/pt/telephony/transfers). ## Encriptação A ligação por SIP usa sinalização SIP por UDP ou TCP e áudio RTP, sem encriptação. TLS e SRTP ainda não estão disponíveis. Se a sua política exigir chamadas encriptadas, fale com a DISKA antes de ligar o trunk. ## Resumo de compatibilidade | Definição | Suportado | Não suportado | | ------------ | ------------------------------------ | --------------------------------------------------------------------- | | Transporte | UDP, TCP | TLS | | Codecs | G.711 A-law, G.711 μ-law, Opus | G.729, G.723 | | DTMF | RFC 2833 / RFC 4733 | SIP INFO, DTMF em banda | | Autenticação | Por IP, SIP REGISTER com digest | — | | Rede | IPv4 público | IPv6, IP privado sem conectividade adicional, destinos só por DNS SRV | | Números | Angolanos (+244) | Outros países | | Chamadas | Recebidas; transferências pelo trunk | Chamadas de saída do agente, SMS, chamada de teste do painel | ## Alterar a configuração No detalhe só pode alterar o **Nome amigável**. Para mudar os dados SIP, elimine o número (**⋮ → Eliminar**), importe-o de novo com os dados correctos e confirme a atribuição no agente. ## Resolução de problemas | Sintoma | Causas prováveis | O que fazer | | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | A chamada não chega à Diska ou o operador recebe uma recusa | O número não está encaminhado para o **Origination URI**; a chamada sai de um IP que não declarou; o operador envia para a porta 5060. | Confirme o encaminhamento e a porta 5080 com o operador; acrescente o IP em falta e importe de novo. | | A chamada chega mas ninguém atende | O número não está atribuído a um agente **Inbound** publicado; a organização atingiu o limite de chamadas em simultâneo. | Atribua e publique — veja [Chamadas recebidas](https://docs.diska.ai/pt/telephony/phone-calls#chamadas-recebidas) e [Chamadas em simultâneo](https://docs.diska.ai/pt/telephony/concurrency). | | O estado fica em **Credenciais pendentes** | O registo SIP não foi aceite. | Verifique utilizador, password, **Auth Username**, domínio e porta com o operador. | | O estado mostra **Erro SIP** | A configuração foi recusada pelo servidor SIP. | Leia a mensagem no detalhe e corrija o dado indicado. | | O agente atende mas não se ouve num dos sentidos | O áudio (RTP) está bloqueado por uma firewall ou por NAT. | Autorize UDP 16384–16639 de e para 102.219.124.234 e confirme que o operador anuncia um IP público no SDP. | | Áudio com cortes ou ruído | Codec ou rede instáveis. | Use G.711 A-law a 20 ms e verifique a perda de pacotes na ligação do operador. | | As teclas marcadas pelo agente não são reconhecidas | O destino espera DTMF por SIP INFO ou em banda. | Configure o destino para RFC 2833 / RFC 4733. | | As transferências falham num número importado | O operador recusa as chamadas que a Diska envia pelo trunk, ou não encaminha o destino. | Peça ao operador para aceitar chamadas de 102.219.124.234 e confirme o formato do destino. | Veja também [Erros e motivos de fim](https://docs.diska.ai/pt/telephony/errors) para ler o motivo de fim de cada chamada em **Históricos**. ## Perguntas frequentes **Posso ligar um número de outro país?** Não. A importação aceita apenas números angolanos (+244). **Preciso de registo SIP?** Só se o operador o exigir. Com autenticação por IP, basta declarar os IPs de sinalização. **Quantas chamadas em simultâneo aceita o trunk?** O limite é da organização, para todos os números juntos. Veja [Chamadas em simultâneo](https://docs.diska.ai/pt/telephony/concurrency). **O agente pode fazer chamadas de saída pelo meu trunk?** Não. As chamadas de saída (agentes Outbound, campanhas e chamada de teste) usam números DISKA. Pelo trunk saem apenas as transferências. **Posso usar o mesmo número em dois agentes?** Não. Cada número atende com **um** agente Inbound publicado. # Chamadas telefónicas Esta página descreve o que acontece numa chamada telefónica: como chega ao agente, o que a pessoa ouve, as transferências e o IVR, o fim da chamada e o processamento que se segue. Explica também a chamada de teste pelo telefone e os limites que a DISKA pode definir para a organização. ## Chamadas recebidas Uma chamada para um número da organização é atendida quando **todas** estas condições se verificam: 1. O número está activo na organização. Num trunk SIP, o estado SIP está pronto e a chamada vem de um IP declarado. 2. Há **exactamente um** agente do tipo **Inbound** com esse número. 3. Esse agente está publicado, não está arquivado, e **a versão publicada tem o número** — publique depois de atribuir ou trocar o número. 4. A organização não atingiu o seu limite de chamadas em simultâneo (ver [Limites](https://docs.diska.ai/#limites)). Se alguma falhar, a chamada não é atendida por nenhum agente. Uma chamada nunca é desviada para outro agente nem para outra organização. ### O que a pessoa ouve - O agente atende com a **saudação** da versão publicada. - Se **Gravar chamadas** estiver activo, o agente lê a mensagem de consentimento configurada. Veja [Gravar chamadas](https://docs.diska.ai/pt/guides/record-calls). - Se a pessoa ficar em silêncio, o agente pergunta se ainda está em linha; se o silêncio continuar, despede-se e termina a chamada. - Se o agente não puder ser contactado no início da chamada, a chamada termina sem conversa (com uma breve mensagem automática ou um sinal de chamada falhada). O número de quem liga fica associado à chamada e pode ser usado pelas acções do agente, por exemplo para enviar um SMS. ## Durante a chamada ### Transferências O agente pode transferir a pessoa para alguém da sua equipa, com uma acção de [Transferências de chamada](https://docs.diska.ai/pt/actions/call-transfers) ou com o nó [Transferência](https://docs.diska.ai/pt/nodes/transfer) do fluxo. - **Transferência direta**: o destino toca e, quando atende, a pessoa é ligada sem aviso prévio. - **Transferência assistida com mensagem** ou **com resumo contextual**: quem atende ouve primeiro, na voz do agente, o motivo ou um resumo da chamada; só depois a pessoa é ligada. Regras por tipo de número: | | Número DISKA | Trunk SIP próprio | | -------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------- | | Destino | Só telemóveis angolanos (Africell ou Unitel) | Número de telefone ou SIP URI do domínio do trunk | | Origem do destino | Um número fixo na acção ou na **Lista telefónica** — nunca um número dito durante a conversa | Fixo, ou preenchido com variáveis da conversa | | Autorização | A organização tem de estar autorizada a fazer chamadas de saída | Não é necessária | | Identificação de quem liga | O número DISKA que a pessoa marcou | O seu número importado | Um nó **Transferência** para uma **fila** ou **equipa** não existe nas linhas telefónicas: o fluxo não publica com esse destino (veja [Fluxo não publica](https://docs.diska.ai/pt/troubleshooting/flow-not-publishing)). Numa chamada web não há linha para transferir, e o nó segue o caminho de falha. Se o destino estiver ocupado, desligado, rejeitar ou não atender em cerca de 20 segundos, a transferência falha e a pessoa continua com o agente, que lhe diz «Infelizmente o número está indisponível neste momento.». Noutras falhas (por exemplo, um destino não permitido), o agente diz a mensagem de falha que configurou na acção. Depois de a pessoa ser ligada ao destino, o agente sai da chamada. A partir daí: - a conversa com a pessoa da equipa **não é gravada**; - o limite de duração do agente **não corta** a chamada. ### IVR Com a acção **Tratamento IVR**, o agente marca teclas (DTMF) na linha para navegar menus de voz — por exemplo, quando liga para um número atendido por um menu automático. Depois de uma transferência concluída o agente já saiu da chamada, por isso não marca teclas. Numa chamada web, o agente continua a conversa. Veja [IVR](https://docs.diska.ai/pt/actions/ivr). ### SMS e marcações O agente pode enviar SMS durante a chamada e marcar reuniões no Cal.com. Veja [SMS durante a chamada](https://docs.diska.ai/pt/actions/during-call-sms) e [Agendamento em tempo real](https://docs.diska.ai/pt/actions/real-time-booking). ## Fim da chamada Uma chamada telefónica termina quando: - a pessoa desliga; - o agente termina a chamada depois de se despedir (por exemplo, a pedido da pessoa ou com a tarefa concluída), ou o fluxo chega a um nó [Terminar chamada](https://docs.diska.ai/pt/nodes/end-call); - o silêncio se prolonga (o agente despede-se antes); - é atingida a duração máxima definida em [Configuração de chamada](https://docs.diska.ai/pt/telephony/call-settings) — a linha desliga sem despedida; - a transferência é concluída: a chamada continua entre a pessoa e o destino, sem o agente. ## Depois da chamada A chamada fica registada em **Históricos** com a transcrição, o resumo e o motivo de fim. Se a gravação estiver activa, o áudio aparece quando o envio terminar: numa chamada telefónica ficam gravados os primeiros 27 minutos da parte com o agente. Veja [Chamadas](https://docs.diska.ai/pt/history/calls) e [Gravações](https://docs.diska.ai/pt/history/recordings). A seguir, a plataforma corre as acções pós-chamada do agente: - [Extratores de Informação](https://docs.diska.ai/pt/actions/information-extractors); - [Avaliações Personalizadas](https://docs.diska.ai/pt/actions/custom-evaluations); - [SMS pós-chamada](https://docs.diska.ai/pt/actions/post-call-sms); - o webhook `call.completed` da API da DISKA, se o tiver configurado. Veja [Webhooks](https://docs.diska.ai/pt/api/webhooks); - o Data Webhook do agente, se o tiver configurado. Veja [Webhooks do agente](https://docs.diska.ai/pt/telephony/webhooks). ## Chamada de teste pelo telefone No painel de teste, o agente liga do seu número DISKA para o seu telemóvel. É uma chamada real, com minutos reais da linha DISKA. Antes de começar: - o agente tem um **número DISKA** atribuído e foi **publicado** com ele pelo menos uma vez; - a organização está autorizada a fazer chamadas de saída (ver [Limites](https://docs.diska.ai/#limites)); - tem um telemóvel angolano (Africell ou Unitel). Passos: 1. No agente, clique em **Testar → Chamada telefónica**. 2. Em **Versão do agente**, escolha: - **Rascunho — ações simuladas**: SMS, marcações e transferências são simulados; - **V*n* publicada — ações reais**: as acções são executadas a sério, como numa chamada real. 3. **Chamada de** mostra o número do agente. 4. Em **Ligar para**, escreva o seu telemóvel com 9 dígitos, por exemplo 923 000 000 (o prefixo é +244). 5. Se o agente tiver variáveis antes da chamada, preencha-as. 6. Clique em **Ligar-me** e atenda. O painel mostra o estado: *A preparar a chamada…*, *A tocar no …*, *Em chamada · m\:ss*, *Chamada terminada · m\:ss* ou *Chamada cancelada*. Use **Desligar** para terminar. Na chamada de teste aplicam-se a **Duração do toque** e o limite de duração da versão escolhida, e a gravação se estiver activa. Cada pessoa só tem uma chamada de teste de cada vez, e há um número máximo de chamadas de teste por hora na organização. A chamada aparece em **Históricos**. Mensagens que pode ver: | Mensagem | O que fazer | | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | *Atribua um número DISKA ao agente e publique-o.* | O agente não tem número. Atribua um número DISKA e publique. | | *Publique o agente uma vez para testar por telefone.* | O agente nunca foi publicado. | | *Atribua ao agente um número DISKA activo e publique-o para testar por telefone.* | A versão publicada não tem um número DISKA activo (por exemplo, é um número importado, ou atribuiu o número depois de publicar). | | *Indique um telemóvel angolano (Africell ou Unitel), por exemplo 923 000 000.* | O número indicado não é um telemóvel angolano. | | *Indique o seu telemóvel, não o número do agente.* | Marcou o número do próprio agente. | | *Esta organização ainda não está habilitada para chamadas telefónicas de saída.* | Peça à DISKA para autorizar a organização. | | *A organização atingiu o limite de chamadas em simultâneo.* | Espere que termine outra chamada. | | *Já tem uma chamada de teste em curso. Termine-a antes de ligar de novo.* | Desligue a chamada anterior. | | *Atingiu o limite de chamadas de teste desta hora. Tente mais tarde.* | Aguarde até à hora seguinte. | | *O número está ocupado, desligado ou rejeitou a chamada.* | Confirme que o telemóvel está ligado e com rede. | | *A chamada não foi atendida.* | Atenda antes de o toque terminar, ou aumente a **Duração do toque**. | | *O agente não conseguiu atender a chamada. Tente novamente.* | Tente de novo; se persistir, contacte o suporte. | | *A linha telefónica não está disponível neste momento.* | Tente mais tarde. | | *Não foi possível confirmar o estado da chamada.* | Veja o resultado em **Históricos** e tente de novo. | Para os outros modos de teste (chamada web, chat e simulação) veja [Testar o agente](https://docs.diska.ai/pt/guides/test-agent). ## Limites A DISKA configura, por organização, as autorizações e limites seguintes. Não são alterados no backoffice: fale com a DISKA para os ajustar. | Limite | O que abrange | Quando é atingido | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Chamadas de saída** | A chamada de teste, as transferências em números DISKA e as chamadas de agentes Outbound. Não afecta chamadas recebidas nem transferências pelo seu trunk SIP. | A chamada de teste mostra *Esta organização ainda não está habilitada para chamadas telefónicas de saída.*; a transferência falha e a pessoa continua com o agente. | | **Chamadas em simultâneo** | Todas as chamadas telefónicas abertas da organização: recebidas, de teste e de saída. | Novas chamadas não são atendidas até terminar uma; a chamada de teste mostra *A organização atingiu o limite de chamadas em simultâneo.* | | **Números DISKA** | Números DISKA em uso mais encomendas por pagar. | *A organização atingiu o limite de N números DISKA (X em uso e Y por pagar).* | As chamadas nos números DISKA usam minutos reais do operador — incluindo a chamada de teste e a ligação aberta numa transferência. Para saber o que conta para o limite de chamadas em simultâneo e como planear a capacidade, veja [Chamadas em simultâneo](https://docs.diska.ai/pt/telephony/concurrency). Os motivos de fim de cada chamada estão em [Erros e motivos de fim](https://docs.diska.ai/pt/telephony/errors). # Configuração de chamada Cada agente tem uma secção **Configuração de chamada** com o tempo de toque e o limite de duração das suas chamadas telefónicas. ## Onde encontrar 1. Abra o agente. 2. Clique em **Definições** na barra de ferramentas. 3. Abra a secção **Configuração de chamada**. As alterações guardam-se sozinhas no rascunho. As chamadas reais usam a versão publicada, por isso **publique** para que passem a valer. No painel **Testar → Chamada telefónica**, a chamada usa a configuração da versão que escolher (rascunho ou publicada). Alterar estas definições exige o papel de **Proprietário**, **Administrador** ou **Membro**. ## Duração do toque (segundos) Quanto tempo o telemóvel do cliente toca nas chamadas que o agente faz — hoje, a [chamada de teste pelo telefone](https://docs.diska.ai/pt/telephony/phone-calls#chamada-de-teste-pelo-telefone) — antes de a linha desistir. - Valores: **10 a 60 segundos** (por omissão, 30). - Não se aplica às chamadas recebidas nem ao toque do destino de uma transferência. ## Limitar duração da chamada Com o interruptor **Limitar duração da chamada** activo, indique o **Máximo (minutos)**, de **1 a 240** (por omissão, 15). - A chamada telefónica é desligada automaticamente quando atinge o máximo, contado a partir do atendimento. O agente não se despede antes: se as conversas costumam ser longas, deixe margem. - Uma chamada já transferida para uma pessoa **não é cortada**. - Aplica-se às chamadas telefónicas da versão publicada e à chamada de teste da versão escolhida no painel de teste. Não se aplica a chamadas web (widget, link público ou teste web). Com o interruptor desligado, a duração não tem limite definido pelo agente. ## Deixar mensagem de voz O interruptor **Deixar mensagem de voz** está desactivado. A UI explica: *Quando cair em voicemail (outbound). Indisponível: as linhas ainda não detectam atendedores automáticos.* ## Motivos de fim de chamada A secção **Motivos de fim de chamada** mostra, só para leitura (*Definido no sistema*), os motivos que o agente pode indicar quando termina a chamada: | Motivo | Quando | | -------------------- | ------------------------------------ | | `user_requested_end` | A pessoa pediu para terminar. | | `task_completed` | O objectivo da chamada foi cumprido. | | `inactivity` | A pessoa deixou de responder. | | `error` | O agente não conseguiu continuar. | Estes motivos, e os restantes fins de chamada (a pessoa desligou, silêncio, limite de duração), aparecem em [Históricos](https://docs.diska.ai/pt/history/calls). Veja também [Fim da chamada](https://docs.diska.ai/pt/telephony/phone-calls#fim-da-chamada). ## Gravação A gravação configura-se na secção **Segurança e conformidade** das mesmas **Definições**: ao activar **Gravar chamadas**, o agente avisa o cliente no início da chamada (a menos que desligue **Avisar que a chamada é gravada**). Nas chamadas telefónicas (incluindo a chamada de teste do painel) ficam gravados os primeiros 27 minutos da parte com o agente. Veja [Gravar chamadas](https://docs.diska.ai/pt/guides/record-calls). # Campanhas Uma **campanha** liga, um a um, para uma lista de contactos com um agente do tipo **Outbound** (chamadas de saída), a partir de um número DISKA da sua organização. A Diska respeita os horários que definir, nunca ocupa toda a capacidade telefónica e regista o resultado de cada chamada. As chamadas aparecem em **Históricos** como qualquer outra, com gravação e transcrição quando estão activas. Encontra-a no menu **Campanhas**, logo abaixo de **Números**. Se o menu não aparecer, a funcionalidade ainda não está activa na sua organização: peça-a à DISKA. ## Antes de começar - A organização tem de estar habilitada para **chamadas de saída** (activado pela DISKA). - Um agente do tipo **Outbound**, publicado (do Prompt Builder ou do Flow Designer). As campanhas usam sempre a versão publicada. - Um **número DISKA** activo da organização, que será o número de origem. - Contactos que **autorizaram** ser contactados pela sua empresa. Antes de iniciar, a Diska pede-lhe que o confirme. ## Criar uma campanha Em **Campanhas**, clique em **Nova campanha**. O assistente tem quatro passos: 1. **Configuração** — o nome, o agente de voz e o número de origem. 2. **Destinatários** — importe um ficheiro ou adicione contactos à mão (ver abaixo). A Diska mostra quantos são elegíveis, inválidos, repetidos ou excluídos antes de os adicionar. 3. **Agendamento e limites** — quando e quanto pode ligar (ver abaixo). 4. **Revisão** — o resumo, a estimativa de custo (quando há dados para a calcular) e a confirmação de que os contactos autorizaram a chamada. **Iniciar campanha** ou **Agendar campanha** põe-na em marcha; quem só pode preparar campanhas guarda-a como **Rascunho**. ## O ficheiro de destinatários Aceita **.csv** (separado por vírgulas ou ponto e vírgula) e **.xlsx** (a primeira folha), até 5 MB e 10 000 linhas por ficheiro. A primeira linha é o cabeçalho: | Coluna | Para quê | | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | `telefone` (ou `phone`, `número`, `telemóvel`) | Obrigatória. Formato internacional (+244 923 000 000) ou nacional angolano (923 000 000). | | `nome` (ou `name`) | Opcional. O agente recebe-o como o nome do contacto. | | `email` | Opcional. | | `id` (ou `external_id`) | Opcional. O seu identificador do contacto: enviar a mesma linha duas vezes não a duplica. | | qualquer outra coluna | Uma **variável** por destinatário, com o nome do cabeçalho (`Produto favorito` → `produto_favorito`). | Exemplo (CSV separado por ponto e vírgula): ```text telefone;nome;email;id;produto;cidade 923 000 001;Ana Silva;ana@exemplo.ao;crm-001;Iogurte de morango;Luanda +244 934 000 002;João Paulo;;crm-002;Leite magro;Benguela ``` Aqui, `produto` e `cidade` passam a ser variáveis de cada destinatário: o agente recebe-as como informação sobre o contacto, tal como as variáveis pré-chamada do agente. Regras: - Só **telemóveis angolanos** (Africell e Unitel) podem ser marcados; outros números são assinalados como «fora da matriz». - Um número repetido na lista, ou que já está na campanha, entra uma só vez. - Os números da **lista de exclusão** são ignorados. - As variáveis são **informação** para o agente, nunca instruções: textos que tentam dar ordens ao agente e nomes reservados pela plataforma são ignorados. - Cada campanha aceita até 5 000 destinatários (limite configurável pela DISKA). ## Horários e limites | Opção | O que faz | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Início** | Agora, ou numa data e hora. | | **Fuso horário** | O fuso das janelas (por defeito, Africa/Luanda). | | **Janelas de chamadas** | Por dia da semana, uma ou várias janelas por dia (por exemplo, 09:00–12:00 e 14:00–18:00). Fora delas a campanha espera; os contactos **não** são dados como falhados. As janelas têm de ficar dentro do horário legal de contacto (08:00–20:00, hora local). | | **Prazo máximo** | Dias que a campanha pode durar (por defeito 7, até 30). No fim do prazo, os contactos ainda por ligar são cancelados e a campanha fica concluída. O tempo em pausa conta para o prazo. | | **Chamadas simultâneas** | Quantas chamadas a campanha pode ter ao mesmo tempo. | | **Capacidade reservada** | Quantas das chamadas simultâneas da organização ficam sempre livres para chamadas recebidas e outras chamadas. | | **Tentativas** | 1 a 3. Só uma chamada **não atendida** ou **ocupada** é repetida, depois do intervalo que escolher. Uma falha técnica nunca é repetida sozinha. | | **Orçamento de minutos** | Opcional. A campanha pausa sozinha antes de o ultrapassar. | Além destes limites, a Diska nunca ultrapassa a capacidade telefónica da plataforma e da organização, conta **todas** as chamadas em curso (recebidas, de teste e de outras campanhas) e nunca desliga uma chamada para libertar capacidade. ## Boas práticas - **Comece pequeno.** Faça uma primeira campanha com poucos números da sua equipa, uma chamada de cada vez, e ouça as gravações antes de alargar. - **Prepare o agente para chamadas de saída.** O agente recebe o contexto da campanha (que é a empresa a ligar, o nome da campanha e o nome do contacto), mas o guião deve dizer o motivo da chamada e o que fazer se a pessoa não puder falar. - **Escolha janelas em que as pessoas atendem.** Evite o início da manhã e a hora de almoço; use o fuso horário dos contactos. - **Use poucas tentativas.** Duas tentativas, com algumas horas de intervalo, costumam chegar. Mais do que isso incomoda quem não quer atender. - **Mantenha a lista limpa.** Use a coluna `id` para poder reenviar o ficheiro sem duplicados e acrescente à lista de exclusão quem pedir para não ser contactado. - **Defina um orçamento de minutos** nas primeiras campanhas, para saber o que cada uma consome. ## Estados da campanha | Estado | Significado | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | **Rascunho** | Em preparação; ainda não liga. | | **Agendada** | Pronta; espera a data de início, a janela ou capacidade livre. | | **Em execução** | A ligar. Por baixo do estado aparece o motivo quando está à espera (por exemplo, «Fora do horário — retoma às 09:00»). | | **Pausada** | Não inicia novas chamadas; as chamadas em curso continuam. Pausa manual, orçamento ou quota mensal esgotados, ou paragem de emergência. | | **Concluída** | Todos os contactos chegaram a um estado final, ou o prazo terminou. | | **Cancelada** | Parada definitivamente; os contactos ainda por ligar foram cancelados. | - **Pausar** impede novas chamadas e mantém as que estão a decorrer. - **Retomar** continua com os contactos por ligar, respeitando horários e capacidade. - **Cancelar** cancela os contactos por ligar, sem desligar chamadas já estabelecidas. Não pode ser desfeito. - **Pausar todas** (na lista de campanhas) é a paragem de emergência da organização. ## Destinatários e resultados Cada destinatário tem um estado: **Pendente**, **Reservado**, **A ligar**, **Em chamada**, **Realizado**, **Falhado**, **Cancelado** ou **Excluído**. A Diska separa o **resultado da chamada** de uma **falha técnica**: - **Realizado** quer dizer que a chamada chegou à rede: **Atendida**, **Não atendida** ou **Ocupado/indisponível**. Uma chamada atendida sem venda é um resultado, não uma falha. - **Falhado** quer dizer que a chamada não pôde ser feita (linha indisponível, agente indisponível) ou que não foi possível confirmar o resultado. O motivo aparece na lista. Na página da campanha pode filtrar por estado, abrir a chamada de cada contacto em **Históricos** (com gravação e transcrição, quando existem), **Exportar resultados** em CSV, **Adicionar destinatários** e **Repetir falhadas** (opcionalmente também as não atendidas). Se uma pessoa pedir na chamada para não voltar a ser contactada («não me liguem mais»), o número entra na lista de exclusão da organização e deixa de ser marcado em todas as campanhas. ## Indicadores | Indicador | Como se calcula | | ----------------------- | ---------------------------------------------------------------------------------------------------------------------- | | **Progresso** | Destinatários em estado final (realizado, falhado, cancelado, excluído) ÷ total de destinatários. | | **Chamadas iniciadas** | Tentativas enviadas ao servidor telefónico (cada repetição conta). | | **Taxa de atendimento** | Atendidas ÷ (atendidas + não atendidas + ocupado/indisponível). Falhas técnicas não entram. | | **Duração total** | Soma da duração das chamadas atendidas. | | **Custo acumulado** | Duração × tarifa por minuto, só quando a DISKA configurou uma tarifa; caso contrário aparece «Sem tarifa configurada». | ## Lista de exclusão Em **Campanhas → Lista de exclusão** gere os números que a organização nunca deve contactar. Um número acrescentado é retirado de imediato de todas as campanhas por ligar. ## Permissões | Acção | Papéis | | -------------------------------------------------- | ----------------------------------- | | Ver campanhas e resultados | Todos | | Criar, editar, importar, pausar, lista de exclusão | Proprietário, Administrador, Editor | | Iniciar, retomar, repetir, cancelar, pausar todas | Proprietário, Administrador | ## Resolução de problemas | O que vê | O que quer dizer | O que fazer | | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | **Fora do horário** | A janela de chamadas está fechada. | Nada: a campanha retoma sozinha na janela seguinte, à hora indicada. | | **Aguarda a data de início** | A campanha foi agendada. | Nada, ou mude a data em **Editar**. | | **A aguardar capacidade livre** | Estão a decorrer tantas chamadas que não há espaço sem tirar capacidade às chamadas recebidas. | Espere, ou aumente as chamadas simultâneas da campanha se a organização tiver margem. | | **Capacidade telefónica por configurar** | A capacidade de chamadas de saída da plataforma ainda não foi configurada. | Contacte a Diska. | | **Chamadas de saída não activas na organização** | A organização não está habilitada para chamadas de saída. | Contacte a Diska. | | **Agente indisponível** | O agente foi arquivado, deixou de ser Outbound ou não tem versão publicada. | Publique o agente. | | **Número de origem indisponível** | O número deixou de ser uma linha DISKA activa. | Escolha outro número ou contacte a Diska. | | **Pausada — orçamento de minutos esgotado** | A campanha gastou o orçamento definido. | Aumente o orçamento e clique em **Retomar**. | | Um destinatário **Falhado — sem resultado** | O servidor telefónico recebeu o pedido mas não confirmou o resultado. A Diska não repete a chamada sozinha, para não ligar duas vezes. | Veja a chamada em **Históricos** e, se for caso, use **Repetir falhadas**. | ## Perguntas frequentes **Posso alterar uma campanha depois de iniciar?** Pode alterar o nome, os horários e os limites com a campanha agendada ou pausada. O agente e o número de origem não mudam depois de criada. **As chamadas da campanha contam como chamadas normais?** Sim. São chamadas do agente como as outras: aparecem em **Históricos** (pode filtrar pela campanha), com gravação e transcrição quando estão activas, e usam a [Memória partilhada](https://docs.diska.ai/pt/knowledge-base/shared-memory) se o agente tiver um grupo. **O que acontece a quem não atende?** Fica **Realizado — Não atendida**. Se configurou mais do que uma tentativa, a Diska volta a ligar depois do intervalo escolhido, dentro das janelas. **Posso pausar no meio de uma chamada?** Sim. Pausar e cancelar nunca desligam chamadas em curso: só impedem novas chamadas. **Posso ligar para números estrangeiros ou fixos?** Ainda não. Por agora só telemóveis angolanos (Africell e Unitel). ## Privacidade e retenção - Cada organização só vê as suas campanhas. - O registo de auditoria guarda quem fez o quê, sem números, nomes nem variáveis. - Os destinatários de uma campanha terminada há mais de 180 dias são apagados; a campanha mantém os totais. ## API As campanhas também se gerem pela API: criar, acrescentar destinatários (até 1000 por pedido, com `external_id` para evitar duplicados), iniciar, pausar, retomar, cancelar e ler os resultados. Veja [Campanhas na referência da API](https://docs.diska.ai/pt/api/reference/campaigns). A API de campanhas é activada pela Diska a pedido. Para importar contactos sem programar, exporte-os para CSV ou Excel e use **Adicionar destinatários**, com a coluna `id` para evitar duplicados. # Chamadas em simultâneo A Diska limita quantas chamadas de voz (telefone e WhatsApp) cada organização pode ter abertas ao mesmo tempo. O limite protege a qualidade das chamadas e a capacidade das linhas, e é definido pela DISKA para cada organização. São dois limites diferentes: - **Chamadas em simultâneo** — quantas chamadas de voz da organização podem estar abertas ao mesmo tempo. - **Chamadas de saída** — se a organização está autorizada a fazer chamadas pelas linhas DISKA (chamada de teste, agentes Outbound, campanhas e transferências em números DISKA ou em chamadas WhatsApp). Veja [Limites](https://docs.diska.ai/pt/telephony/phone-calls#limites). ## O que conta Contam **todas** as chamadas de voz abertas da organização, em números DISKA, em números importados por [SIP](https://docs.diska.ai/pt/telephony/sip-trunk) ou no WhatsApp: - chamadas recebidas; - chamadas de teste pelo telefone; - chamadas feitas por agentes Outbound, incluindo as de [Campanhas](https://docs.diska.ai/pt/telephony/campaigns); - [chamadas de voz WhatsApp](https://docs.diska.ai/pt/whatsapp/calls). Não contam: - chamadas web (widget, link público e teste no browser); - mensagens de WhatsApp e conversas de chat; - a ligação que uma transferência abre para o destino: a transferência não ocupa uma chamada nova no limite. O limite é da **organização**, não de cada número nem de cada agente: todos os números e agentes partilham a mesma capacidade. ## O seu limite A DISKA define o limite de cada organização. Não se altera no backoffice: para saber qual é o seu, ou para o mudar, fale com a DISKA. Uma organização sem limite próprio fica sujeita apenas à capacidade da plataforma. ## Quando o limite é atingido | Chamada | O que acontece | | -------------------- | ---------------------------------------------------------------------------------------------------------------------- | | **Recebida** | O agente não atende. Quem liga ouve o sinal de chamada falhada da rede e pode voltar a ligar quando houver capacidade. | | **Chamada de teste** | O painel **Testar** mostra *A organização atingiu o limite de chamadas em simultâneo.* | | **Campanha** | A campanha espera, com o aviso *A aguardar capacidade livre*, e continua sozinha quando uma chamada termina. | | **Em curso** | Nunca é desligada para libertar capacidade. | O limite é verificado quando a chamada começa. Duas chamadas que cheguem no mesmo instante podem passar as duas, por isso o limite pode ser ultrapassado por uma chamada. ## Campanhas e capacidade reservada As campanhas partilham a capacidade com as chamadas recebidas. Para que uma campanha não ocupe as linhas de que precisa para atender: - **Chamadas simultâneas** limita quantas chamadas a campanha tem ao mesmo tempo; - **Capacidade reservada** (por omissão, 1) fica sempre livre para chamadas recebidas e outras chamadas. Uma campanha só inicia uma chamada nova quando cabe em todos os limites ao mesmo tempo: o da campanha, o da organização (descontando a capacidade reservada e todas as chamadas abertas) e o da plataforma. Veja [Campanhas](https://docs.diska.ai/pt/telephony/campaigns). Exemplo: com um limite de 5 chamadas na organização, capacidade reservada 1 e 2 chamadas recebidas em curso, a campanha pode ter no máximo 2 chamadas ao mesmo tempo (5 − 1 − 2). ## Planear a capacidade Para pedir um limite à DISKA, estime: 1. quantas chamadas recebe na hora de maior movimento; 2. quanto tempo duram, em média; 3. quantas chamadas de campanha quer em paralelo, e em que horário; 4. quantas pessoas da equipa fazem chamadas de teste. Para aproveitar melhor a capacidade: - defina uma **duração máxima** em [Configuração de chamada](https://docs.diska.ai/pt/telephony/call-settings), para que uma chamada esquecida não ocupe uma linha; - corra as campanhas fora das horas em que recebe mais chamadas; - mantenha pelo menos 1 de **Capacidade reservada** nas campanhas. ## Perguntas frequentes **As chamadas web contam para o limite?** Não. Só as chamadas telefónicas. **O limite é por número?** Não. É da organização, para todos os números e agentes juntos. **O que ouve quem liga quando o limite está esgotado?** O sinal de chamada falhada da rede: o agente não chega a atender. **Uma campanha pode bloquear as chamadas recebidas?** Não, se mantiver capacidade reservada: a campanha nunca usa esses lugares. **Como aumento o limite?** Fale com a DISKA com a estimativa de volume da secção anterior. # Transferências por telefone e SIP Uma transferência passa a chamada telefónica do agente para uma pessoa da sua equipa: um telemóvel, um número do seu operador ou uma extensão da sua central por SIP. Esta página explica o que acontece na linha. Para criar a acção, os modos e as mensagens, veja [Transferências de chamada](https://docs.diska.ai/pt/actions/call-transfers). Numa chamada de voz WhatsApp, a transferência funciona de outra forma: veja [Chamadas de voz](https://docs.diska.ai/pt/whatsapp/calls#transferir-para-uma-pessoa). ## Como funciona na linha 1. O agente decide transferir, quando a condição da acção se verifica, e avisa o cliente. 2. A Diska liga para o destino pela **mesma linha** por onde passa a chamada: a rede DISKA ou o seu trunk SIP. 3. Enquanto o destino toca (até cerca de 20 segundos), o cliente continua com o agente, sem música de espera. 4. Quando o destino atende, a Diska liga as duas chamadas e o agente sai. Nas transferências assistidas, quem atende ouve primeiro o aviso na voz do agente. 5. Se o destino não atender, estiver ocupado, desligado ou rejeitar, o agente diz «Infelizmente o número está indisponível neste momento.» e continua a conversa. A Diska faz uma **chamada nova** ao destino e junta-a à chamada do cliente; não entrega a chamada ao operador (SIP REFER). Por isso: - o destino não precisa de suportar SIP REFER; - o destino vê o número da linha, não o do cliente (ver [Identificação de quem liga](https://docs.diska.ai/#identifica%C3%A7%C3%A3o-de-quem-liga)); - a chamada continua a passar pela Diska até alguém desligar. Depois de ligadas as duas chamadas, a conversa com a pessoa da equipa não é gravada e o limite de duração do agente deixa de se aplicar. ## Destinos por tipo de número | | Número DISKA | Número importado por SIP | | ---------------------------------- | -------------------------------------------------------------------------------------------- | --------------------------------------------------- | | **Destinos aceites** | Só telemóveis angolanos (Africell ou Unitel) | Números de telefone ou SIP URIs no domínio do trunk | | **De onde vem o destino** | Um número fixo na acção ou na **Lista telefónica** — nunca um número dito durante a conversa | Fixo, ou preenchido com variáveis da conversa | | **Autorização** | A organização tem de estar autorizada a fazer chamadas de saída | Não é necessária | | **Por onde sai** | Pela rede DISKA | Pelo seu trunk SIP | | **Quem paga a ligação ao destino** | Minutos da linha DISKA | O seu operador | Numa linha DISKA não é possível transferir para o próprio número da linha, para números fixos, para números internacionais nem para SIP URIs. ## SIP URIs aceites Num número importado, um SIP URI tem de usar um **número** e o **SIP Domain** do trunk, exactamente como foi importado (incluindo a porta, se a indicou). | Formato | Exemplo | Aceite | | -------------------------- | --------------------------------------- | -------------------------------------------------- | | Número no domínio do trunk | `sip:+244222000000@pbx.empresa.ao` | Sim, se `pbx.empresa.ao` for o SIP Domain do trunk | | Extensão numérica | `sip:2001@pbx.empresa.ao` | Sim (3 a 20 algarismos) | | Utilizador com letras | `sip:vendas@pbx.empresa.ao` | Não | | Outro domínio | `sip:2001@outra-central.ao` | Não | | Com parâmetros | `sip:2001@pbx.empresa.ao;transport=tcp` | Não: o transporte é o do trunk | Um número de telefone também pode ter 3 a 20 algarismos, com `+` opcional: o seu operador ou a sua central decidem para onde o encaminham. ## Identificação de quem liga | A chamada passa por | O destino vê | | ------------------- | --------------------------------------------------------------- | | Um número DISKA | O número DISKA que o cliente marcou (ou de onde o agente ligou) | | Um número importado | O seu número importado | O número do cliente nunca é enviado ao destino. Para a pessoa da equipa saber de quem se trata: - use uma transferência **assistida**, para ouvir o motivo ou um resumo antes de falar com o cliente; - peça ao agente que recolha o nome e o motivo antes de transferir, com [Extratores de Informação](https://docs.diska.ai/pt/actions/information-extractors) para os ver depois em **Históricos**. ## Horário e disponibilidade Com **Activar horário de disponibilidade**, fora do horário a Diska não liga para o destino: o agente diz a mensagem *Humano indisponível* e continua a conversa. O horário usa o fuso indicado na acção (por omissão `Africa/Luanda`). Veja [Disponibilidade humana](https://docs.diska.ai/pt/actions/call-transfers#disponibilidade-humana). ## O que não está disponível - Entregar a chamada ao operador por SIP REFER. - Enviar headers SIP personalizados (X-headers) ou User-to-User (UUI). Os headers do separador **Simulação** só se usam no botão **Simular**. - Música de espera enquanto o destino toca. - Transferir para uma fila ou equipa. - Transferências em chamadas web: não há linha telefónica, e o agente continua a conversa. ## Resolução de problemas | Sintoma | Causas prováveis | O que fazer | | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | O agente diz «Infelizmente o número está indisponível neste momento.» | O destino não atendeu em cerca de 20 segundos, estava ocupado, desligado ou rejeitou. | Confirme que o destino tem rede e atende; considere uma [Lista telefónica](https://docs.diska.ai/pt/actions/call-transfers#listas-telef%C3%B3nicas) com alternativas. | | O agente diz a mensagem de falha da acção | O destino não é permitido nessa linha: não é um telemóvel angolano, é um SIP URI noutro domínio, ou a organização não tem chamadas de saída autorizadas. | Corrija o destino na acção, ou peça à DISKA para autorizar as chamadas de saída. | | O agente diz a mensagem *Humano indisponível* | A chamada foi fora do horário de disponibilidade. | Reveja o horário e o fuso da acção. | | O agente não transfere | A condição da acção não se verificou, ou a acção não está ligada à versão publicada do agente. | Reveja a **Descrição da condição** e publique o agente. | | A transferência funciona no teste mas não nas chamadas reais | Testou com o rascunho, em que a transferência é simulada. | Teste com **Testar → Chamada telefónica** escolhendo a versão publicada. | ## Perguntas frequentes **Porque é que o destino vê o número da Diska e não o do cliente?** Porque a Diska faz uma chamada nova ao destino, pela linha da chamada. O número mostrado é o dessa linha. **Posso transferir para uma extensão da minha central?** Sim, se a chamada entrou por um número importado: use `sip:extensão@domínio-do-trunk` ou o número da extensão. **Posso transferir para um número fixo numa linha DISKA?** Não. Numa linha DISKA só se transfere para telemóveis angolanos. **O agente ouve a conversa depois da transferência?** Não. O agente sai quando o destino atende, e essa parte não é gravada. **A transferência conta para o limite de chamadas em simultâneo?** Não abre uma chamada nova no limite. Veja [Chamadas em simultâneo](https://docs.diska.ai/pt/telephony/concurrency). # Webhooks do agente Cada agente pode ter dois webhooks, em **Publicação → Telefone**: | | Inbound Webhook | Data Webhook | | ----------------- | ---------------------------------------------------------------- | --------------------------------------------------------------------------------- | | Quando | Quando uma chamada chega ao agente, antes de ele falar | Quando a chamada termina, depois do processamento pós-chamada | | Chamadas | De entrada, por telefone ou WhatsApp (só agentes **Inbound**) | De entrada e de saída, por telefone ou WhatsApp, e as do link público e do widget | | O seu sistema | Responde com dados sobre quem liga, que o agente usa na conversa | Guarda a transcrição, os dados recolhidos, as avaliações e as acções | | Evento | `call.inbound` | `call.completed` | | Tempo de resposta | Até 5 segundos | Até 10 segundos | | Repetições | Nenhuma: a chamada não espera | Até 3 tentativas | Os dois pedidos são `POST` com corpo JSON e são **assinados** com o segredo do agente (ver [Verificar a assinatura](https://docs.diska.ai/#verificar-a-assinatura)). ## Configurar 1. Abra o agente e clique em **Publicação**. 2. No separador **Telefone**, escreva o URL em **Inbound Webhook** e/ou **Data Webhook**. O URL tem de começar por `https://` e ser um endereço público. 3. Clique fora do campo ou carregue em Enter para guardar. 4. Clique em **Inicializar** para enviar um pedido de teste ao URL (ver [Testar](https://docs.diska.ai/#testar-com-inicializar)). 5. **Publique** o agente. Como as restantes definições da chamada, os webhooks valem a partir da versão publicada. Para deixar de usar um webhook, apague o URL (botão **×**) e publique de novo. Quem pode editar o agente (proprietários, administradores e membros) altera os webhooks e vê o segredo de assinatura. ## Inbound Webhook Quando uma chamada de entrada chega ao agente, a Diska envia-a ao Inbound Webhook **antes de o agente falar**. A resposta pode trazer: - **`variables`**: dados sobre quem liga (nome, plano, saldo, última encomenda…). O agente recebe-os como factos sobre esta chamada e usa-os na conversa. Num agente em modo fluxo, ficam disponíveis como variáveis (`{{nome}}`). - **`metadata`**: referências do seu sistema (o ID do cliente no CRM, um ID de sessão…). O agente não as vê; voltam no [Data Webhook](https://docs.diska.ai/#data-webhook), no campo `metadata`. ### Pedido ```json { "event": "call.inbound", "test": false, "agent_id": "61e5f9d7-06eb-43ad-a8a5-056ff7b448fd", "organization_id": "0ba43fdf-…", "channel": "phone", "direction": "inbound", "from_number": "+244923000001", "to_number": "+244959092450", "created_at": "2026-11-08T10:15:02.418Z" } ``` | Campo | Descrição | | ------------- | --------------------------------------------------------------------------------------------- | | `channel` | `phone` (número DISKA ou trunk SIP) ou `whatsapp` | | `from_number` | O número de quem liga, como a rede o entregou. Pode ser `null` se a pessoa esconder o número. | | `to_number` | O número do agente. Numa chamada WhatsApp é `null`. | | `test` | `true` só nos pedidos de **Inicializar** | ### Resposta Responda `200` com um JSON: ```json { "variables": { "nome": "Ana Silva", "plano": "Gold", "saldo": "12 500 Kz" }, "metadata": { "crm_id": "CL-48213" } } ``` - Os nomes das variáveis são normalizados para minúsculas, sem acentos nem espaços (`Nome do cliente` → `nome_do_cliente`). - No máximo 20 variáveis, até 200 caracteres cada. Os valores ficam numa só linha. - Uma variável cujo valor pareça uma instrução (por exemplo «ignora as instruções anteriores») é ignorada. O agente recebe as variáveis como **factos**, nunca como ordens. - `metadata`: até 20 pares, 500 caracteres por valor. - Uma resposta `200` ou `204` sem corpo é válida: o agente atende sem dados extra. - Também aceitamos o formato `{"call_inbound": {"custom_variables": {…}, "metadata": {…}}}`, para quem migra de outra plataforma. ### Se o seu sistema não responder A chamada **nunca é recusada** por causa do Inbound Webhook. Se o seu sistema demorar mais de 5 segundos, responder com um erro, um redireccionamento ou algo que não seja JSON, o agente atende na mesma, sem esses dados. Não há repetições: quem liga está à espera. Responda depressa: cada segundo que o seu sistema demora é um segundo a mais de toque para quem liga. ### Exemplo de receptor ::code-group ```python [Python (FastAPI)] from fastapi import FastAPI, Request app = FastAPI() @app.post("/diska/inbound") async def inbound(request: Request): call = await request.json() cliente = await procurar_cliente(call["from_number"]) # o seu CRM if cliente is None: return {} return { "variables": {"nome": cliente.nome, "plano": cliente.plano}, "metadata": {"crm_id": cliente.id}, } ``` ```js [Node.js (Express)] app.post('/diska/inbound', express.json(), async (req, res) => { const cliente = await procurarCliente(req.body.from_number) // o seu CRM if (!cliente) return res.json({}) res.json({ variables: { nome: cliente.nome, plano: cliente.plano }, metadata: { crm_id: cliente.id } }) }) ``` :: Verifique a assinatura antes de responder com dados do cliente (ver [Verificar a assinatura](https://docs.diska.ai/#verificar-a-assinatura)). ## Data Webhook Quando uma chamada termina e o processamento pós-chamada acaba (transcrição, extracção de dados, avaliações, SMS e acções), a Diska envia os dados ao Data Webhook. O corpo é o mesmo do evento `call.completed` dos [webhooks da organização](https://docs.diska.ai/pt/api/webhooks), com mais dois campos: `call` e `metadata`. ```json { "event": "call.completed", "test": false, "call_id": "8f1c2d3e-…", "session_id": "sess_…", "agent_id": "61e5f9d7-06eb-43ad-a8a5-056ff7b448fd", "organization_id": "0ba43fdf-…", "ended_at": "2026-11-08T10:18:44.120Z", "caller_contact": "+244923000001", "extracted_data": { "nome": "Ana Silva", "motivo": "Alterar o plano" }, "evaluations": [], "sentiment": "positive", "post_call_sms": [], "custom_actions": [], "executed_actions": [], "transcript": [ { "role": "assistant", "content": "Olá Ana, em que posso ajudar?" }, { "role": "user", "content": "Queria mudar para o plano Gold." } ], "call": { "id": "8f1c2d3e-…", "channel": "phone", "direction": "inbound", "status": "completed", "end_reason": "user_requested_end", "started_at": "2026-11-08T10:15:03.002Z", "ended_at": "2026-11-08T10:18:41.870Z", "duration_seconds": 219, "from_number": "+244923000001", "to_number": "+244959092450" }, "metadata": { "crm_id": "CL-48213" } } ``` | Campo | Descrição | | ----------------- | ---------------------------------------------------------------------------------------------------------------- | | `call_id` | O ID da chamada em [Históricos](https://docs.diska.ai/pt/history/calls) e na API da DISKA (`GET /v1/calls/{id}`) | | `extracted_data` | Os valores dos [extractores de informação](https://docs.diska.ai/pt/actions/information-extractors) do agente | | `evaluations` | As avaliações pós-chamada configuradas | | `transcript` | A conversa, por turnos | | `call.end_reason` | O motivo de fim (ver [Erros e motivos de fim](https://docs.diska.ai/pt/telephony/errors)) | | `metadata` | O que o Inbound Webhook devolveu em `metadata` (vazio se não houver) | Com [Ocultar dados pessoais](https://docs.diska.ai/pt/guides/redact-personal-data) activo, a transcrição e os dados extraídos chegam já mascarados (por exemplo `[TELEFONE]`). O número da linha de quem liga mantém-se. ### Que chamadas são enviadas - Chamadas **concluídas** de agentes publicados: por telefone (número DISKA ou trunk SIP), WhatsApp, link público e widget, de entrada e de saída (incluindo campanhas e chamadas pela API da DISKA). - Não são enviadas: as chamadas de teste do painel **Testar** e do Centro de Testes, as conversas de texto da API da DISKA, e as chamadas que falharam ou foram canceladas. ### Respostas e repetições - Responda `2xx` em menos de 10 segundos. Guarde o evento numa fila e processe-o depois. - Um erro `5xx`, `408`, `429` ou a falta de resposta é repetido até 3 tentativas, com 1 e 2 segundos de intervalo. - Um `4xx` (outro que não `408`/`429`) não é repetido: o seu sistema recusou o pedido. - Redireccionamentos (`3xx`) não são seguidos. - `X-Diska-Delivery` é igual em todas as tentativas da mesma chamada: use-o para não processar a mesma chamada duas vezes. ## Testar com Inicializar O botão **Inicializar** envia um pedido de teste ao URL escrito no campo, mesmo antes de o guardar: - **Inbound Webhook**: envia um `call.inbound` com `"test": true` e números fictícios. A Diska mostra o código de resposta, o tempo, e as variáveis que o agente receberia, ou o motivo de uma variável ser ignorada. - **Data Webhook**: envia um `call.completed` com `"test": true`, uma conversa de exemplo e IDs a zero. Os pedidos de teste são assinados como os reais. Para separar testes de chamadas reais, veja o campo `test`. ## Verificar a assinatura Cada pedido traz estes cabeçalhos: ```text Content-Type: application/json User-Agent: Diska-Webhooks/1.0 X-Diska-Event: call.inbound | call.completed X-Diska-Delivery: X-Diska-Timestamp: X-Diska-Signature: sha256= ``` A assinatura é o HMAC-SHA256, em hexadecimal, do texto `{X-Diska-Timestamp}.{corpo}` com o **segredo de assinatura** do agente. Encontra o segredo em **Publicação → Telefone → Segredo de assinatura** (começa por `whsec_`). Cada agente tem o seu; o mesmo segredo assina os dois webhooks. Calcule a assinatura sobre o **corpo bruto**, exactamente como chegou. O código é o mesmo dos webhooks da organização: veja os exemplos em Python, Node.js e PHP em [Webhooks › Verificar a assinatura](https://docs.diska.ai/pt/api/webhooks#verificar-a-assinatura). Recuse pedidos com mais de 5 minutos. ## Webhooks do agente ou da organização? | | Webhooks do agente | [Webhooks da organização](https://docs.diska.ai/pt/api/webhooks) | | ----------------- | --------------------------------------- | ---------------------------------------------------------------- | | Onde se configura | **Publicação → Telefone**, por agente | Pela API da DISKA (`webhooks:manage`) | | Antes da chamada | Sim: Inbound Webhook | Não | | Depois da chamada | Data Webhook, das chamadas deste agente | `call.completed` de todas as chamadas da organização | | Assinatura | Segredo do agente (`whsec_…`) | Secret de cada endpoint (`dskw_…`) | Pode usar os dois: uma chamada concluída é enviada a cada webhook configurado. ## Resolução de problemas | Sintoma | O que verificar | | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | O agente não usa os dados do Inbound Webhook | O agente foi publicado depois de guardar o URL? Use **Inicializar** e veja se as variáveis aparecem e se alguma foi ignorada. | | **Inicializar** diz «Sem resposta a tempo» | O seu sistema demora mais de 5 segundos. Responda primeiro com o que tiver e faça o resto depois. | | «Este endereço não é público» | O URL aponta para um endereço privado (rede interna, `localhost`). Use um endereço público com `https://`. | | O Data Webhook não chega | A chamada foi uma chamada de teste? O agente foi publicado com o URL? A chamada terminou como concluída? | | A assinatura não confere | Use o corpo bruto, sem voltar a serializar o JSON, e o segredo do agente certo. | # Erros e motivos de fim Cada chamada telefónica em [Históricos](https://docs.diska.ai/pt/history/calls) tem um **motivo de fim**. Esta página explica cada motivo e o que fazer quando uma chamada falha. Em **Históricos** aparece o nome do motivo ou o seu código, por isso a tabela mostra os dois. ## Fins normais | Motivo | Código | O que significa | | ------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Cliente desligou** | `caller_hangup`, `user_hangup` | A pessoa desligou. | | **Agente terminou a chamada** | `end_call` | O agente despediu-se e desligou (tarefa concluída, pedido da pessoa ou fim do fluxo). | | **Agente terminou a conversa** | `live_end_call` | O agente terminou a conversa depois de se despedir. | | **Transferida para uma pessoa** | `transferred` | A transferência foi concluída e o agente saiu da chamada. Veja [Transferências por telefone e SIP](https://docs.diska.ai/pt/telephony/transfers). | | **Terminada por silêncio** | `silence_timeout` | A pessoa deixou de responder; o agente perguntou se ainda estava em linha e despediu-se. | | **Limite de duração atingido** | `max_duration` | A chamada chegou ao **Máximo (minutos)** de [Configuração de chamada](https://docs.diska.ai/pt/telephony/call-settings). A linha desliga sem despedida. | | **Cliente desligou antes de atender** | `abandoned_before_answer` | A pessoa desligou enquanto a linha tocava, antes de o agente falar. | | **Cancelada** | `cancelled` | A chamada de teste foi cancelada no painel antes de ser atendida. | ## Fins da linha telefónica | Motivo | Código | O que significa | O que fazer | | ----------------------------- | ------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------- | | **Desligada pela linha** | `gateway_hangup` | A linha telefónica terminou a chamada. | Se for frequente, veja se coincide com o limite de duração ou com cortes de rede. | | **Linha telefónica terminou** | `freeswitch_hangup` | O servidor telefónico terminou a chamada. | Igual ao anterior. | | **Linha sem resposta** | `timeout_hangup` | A linha deixou de responder durante a chamada. | Tente de novo; se persistir, contacte o suporte com a hora da chamada. | | **Chamada terminada** | `other_hangup` | A chamada terminou por um motivo que a linha não especificou. | Nada, se for pontual. | ## Falhas do agente ou do áudio Nestes casos, a pessoa ouve uma breve mensagem automática ou o sinal de chamada falhada, e a chamada termina. | Motivo | Código | O que significa | | ---------------------------------------------- | ------------------------------------ | ------------------------------------------------------ | | **Agente indisponível** | `runtime_unavailable` | O agente não pôde ser contactado no início da chamada. | | **Ligação ao agente perdida** | `runtime_disconnect` | A ligação ao agente caiu durante a chamada. | | **Desligada pelo motor de voz** | `runtime_hangup` | O motor de voz terminou a sessão. | | **Falha a iniciar o áudio** | `media_start_failed` | O áudio da chamada não arrancou. | | **Falha no áudio** | `media_stream_failed` | O áudio da chamada falhou durante a conversa. | | **Falha a atender** | `startup_answer_or_media_failed` | A chamada não pôde ser atendida. | | **Falha técnica** / **Falha técnica na linha** | `exception`, `gateway_worker_exited` | Erro interno da Diska. | O que fazer: volte a ligar. Se a falha se repetir, contacte a DISKA com a hora da chamada e o número. Veja também [Chamadas caem](https://docs.diska.ai/pt/troubleshooting/calls-drop). ## Chamadas que não chegam ao agente Algumas chamadas nunca chegam a um agente, e por isso não têm conversa em **Históricos**. Quem liga ouve o sinal de chamada falhada ou ninguém atende. | Causa | O que fazer | | ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | O número não está atribuído a um agente **Inbound**, ou o agente não foi publicado depois de receber o número. | Atribua o número e publique — veja [Chamadas recebidas](https://docs.diska.ai/pt/telephony/phone-calls#chamadas-recebidas). | | A organização atingiu o limite de chamadas em simultâneo. | Veja [Chamadas em simultâneo](https://docs.diska.ai/pt/telephony/concurrency). | | Num número importado: a chamada veio de um IP que não declarou, para a porta errada, ou o trunk ainda não está pronto. | Veja a [resolução de problemas de Ligar por SIP](https://docs.diska.ai/pt/telephony/sip-trunk#resolu%C3%A7%C3%A3o-de-problemas). | | O número está **Desativado** (por exemplo, suspenso pela DISKA) ou **Sem chamadas**. | Veja o [Estado do número](https://docs.diska.ai/pt/telephony/numbers#estado-do-n%C3%BAmero) e contacte a DISKA. | ## Falhas de transferência e da chamada de teste - Uma transferência que falha não termina a chamada: o agente continua com a pessoa. As causas estão em [Transferências por telefone e SIP](https://docs.diska.ai/pt/telephony/transfers#resolu%C3%A7%C3%A3o-de-problemas). - As mensagens do painel **Testar → Chamada telefónica** estão em [Chamada de teste pelo telefone](https://docs.diska.ai/pt/telephony/phone-calls#chamada-de-teste-pelo-telefone). # Telefonia A Diska liga os seus agentes de voz à rede telefónica. Uma pessoa liga para um número angolano e é atendida pelo agente publicado nesse número. Durante a chamada, o agente pode transferir a pessoa para alguém da sua equipa, marcar teclas num menu IVR, enviar SMS, marcar reuniões e gravar a conversa. ## Duas formas de ter um número | | Número DISKA | Trunk SIP próprio | | ------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | O que é | Um número angolano da rede DISKA, na rede Africell | Um número angolano (+244) que já tem noutro operador ou na sua central (PBX) | | Como se obtém | **Números → Número → Comprar um número DISKA**: reserva e pagamento confirmado pela DISKA | **Números → Número → Importar um número personalizado**: liga o seu trunk SIP à Diska | | Chamadas recebidas | Sim | Sim | | Chamada de teste do painel **Testar** | Sim | Não | | Transferências | Para telemóveis angolanos fixados na acção ou na lista telefónica | Pelo seu trunk, para números ou para SIP URIs do domínio do trunk | | Detalhes | [Números de telefone](https://docs.diska.ai/pt/telephony/numbers) | [Ligar por SIP](https://docs.diska.ai/pt/telephony/sip-trunk) | ## Como uma chamada chega ao agente Uma chamada para o seu número é atendida quando: 1. o número está activo na organização (e, num trunk SIP, a configuração SIP está pronta); 2. o número está atribuído a **um** agente do tipo **Inbound**, em **Publicação → Telefone**; 3. esse agente foi **publicado** depois de receber o número — é a versão publicada que atende; 4. a organização não atingiu o seu limite de [chamadas em simultâneo](https://docs.diska.ai/pt/telephony/concurrency). Se alguma destas condições falhar, ninguém atende a chamada. Veja o percurso completo em [Chamadas telefónicas](https://docs.diska.ai/pt/telephony/phone-calls). ## Chamadas que o agente faz - **Chamada de teste**: no painel **Testar → Chamada telefónica**, o botão **Ligar-me** faz o agente ligar do seu número DISKA para o seu telemóvel. Veja [Chamadas telefónicas](https://docs.diska.ai/pt/telephony/phone-calls#chamada-de-teste-pelo-telefone). - **Agentes Outbound**: um agente do tipo **Outbound** pode ter um número DISKA, que usa como identificação de quem liga. - **Campanhas**: ligam automaticamente para uma lista de contactos com um agente Outbound, dentro dos horários e limites que definir. Veja [Campanhas](https://docs.diska.ai/pt/telephony/campaigns). As chamadas de saída só estão disponíveis para organizações habilitadas pela DISKA. ## Durante a chamada - **Transferências** para uma pessoa — directas ou assistidas, em que quem atende ouve primeiro o motivo ou um resumo na voz do agente. Veja [Transferências por telefone e SIP](https://docs.diska.ai/pt/telephony/transfers), [Transferências de chamada](https://docs.diska.ai/pt/actions/call-transfers) e o nó [Transferência](https://docs.diska.ai/pt/nodes/transfer). - **IVR**: o agente marca teclas (DTMF) na linha para navegar menus de voz. Veja [IVR](https://docs.diska.ai/pt/actions/ivr). - **SMS** durante e depois da chamada. Veja [SMS durante a chamada](https://docs.diska.ai/pt/actions/during-call-sms) e [SMS pós-chamada](https://docs.diska.ai/pt/actions/post-call-sms). - **Gravação**: com **Gravar chamadas** activo, as chamadas telefónicas também são gravadas (os primeiros 27 minutos). Veja [Gravar chamadas](https://docs.diska.ai/pt/guides/record-calls). - **Limites**: duração máxima da chamada e tempo de toque, por agente — veja [Configuração de chamada](https://docs.diska.ai/pt/telephony/call-settings); e chamadas em simultâneo, por organização — veja [Chamadas em simultâneo](https://docs.diska.ai/pt/telephony/concurrency). - **Webhooks do agente**: o seu sistema recebe cada chamada antes de o agente atender e pode dar-lhe dados sobre quem liga; no fim, recebe os dados da chamada. Veja [Webhooks do agente](https://docs.diska.ai/pt/telephony/webhooks). ## Quem pode fazer o quê | Acção | Proprietário | Administrador | Membro | Visualizador | | ----------------------------------------------- | :----------: | :-----------: | :----: | :----------: | | Ver a página **Números** | ✓ | ✓ | ✓ | ✓ | | Comprar, importar e eliminar números | ✓ | ✓ | | | | Atribuir um número a um agente | ✓ | ✓ | | | | Alterar a **Configuração de chamada** do agente | ✓ | ✓ | ✓ | | | Fazer a chamada de teste pelo telefone | ✓ | ✓ | ✓ | ✓ | ## Nesta secção ::card-group :::card --- description: Comprar um número DISKA, estados e atribuição a um agente. icon: i-lucide-phone title: Números de telefone to: https://docs.diska.ai/pt/telephony/numbers --- ::: :::card --- description: Ligar o trunk do seu operador ou central à Diska — endereços, codecs e importação. icon: i-lucide-cable title: Ligar por SIP to: https://docs.diska.ai/pt/telephony/sip-trunk --- ::: :::card --- description: Da chegada ao agente ao fim da chamada, teste e limites. icon: i-lucide-phone-call title: Chamadas telefónicas to: https://docs.diska.ai/pt/telephony/phone-calls --- ::: :::card --- description: Duração do toque, duração máxima e motivos de fim. icon: i-lucide-timer title: Configuração de chamada to: https://docs.diska.ai/pt/telephony/call-settings --- ::: :::card --- description: Ligar automaticamente para uma lista de contactos com um agente Outbound. icon: i-lucide-megaphone title: Campanhas to: https://docs.diska.ai/pt/telephony/campaigns --- ::: :::card --- description: O limite de chamadas abertas da organização e como planear a capacidade. icon: i-lucide-layers title: Chamadas em simultâneo to: https://docs.diska.ai/pt/telephony/concurrency --- ::: :::card --- description: O que acontece na linha ao passar uma chamada para uma pessoa, por telefone ou SIP. icon: i-lucide-phone-forwarded title: Transferências to: https://docs.diska.ai/pt/telephony/transfers --- ::: :::card --- description: Inbound Webhook antes de atender e Data Webhook no fim de cada chamada. icon: i-lucide-webhook title: Webhooks do agente to: https://docs.diska.ai/pt/telephony/webhooks --- ::: :::card --- description: O que significa cada motivo de fim em Históricos e o que fazer. icon: i-lucide-triangle-alert title: Erros e motivos de fim to: https://docs.diska.ai/pt/telephony/errors --- ::: :: # Perfil pessoal Em **Definições → Conta → Perfil** gere a informação pessoal da sua conta. Também lá chega pelo menu do utilizador, no fundo do menu lateral (**Ver perfil pessoal**). O perfil é seu: não altera os dados da organização. ## Avatar 1. Clique em **Alterar avatar**. 2. Escolha uma imagem JPG, PNG ou WebP, com 2 MB no máximo. 3. O avatar é guardado de imediato (*Avatar atualizado*). ## Informação do perfil | Campo | Notas | | -------------------- | ---------------------------------------------------- | | **Nome completo** | O nome mostrado na plataforma e na lista de membros. | | **Username** | Opcional. | | **Cargo** | Opcional. | | **Telefone** | Opcional. | | **Idioma preferido** | Português ou English. | | **Fuso horário** | Africa/Luanda, Africa/Maputo, Europe/Lisbon ou UTC. | | **Biografia** | Texto livre. | Depois de editar, clique em **Guardar perfil**. Aparece *Perfil atualizado*. O email da conta não se altera aqui: veja [Credenciais](https://docs.diska.ai/pt/settings/credentials). # Credenciais A página **Definições → Conta → Credenciais** reúne a segurança da sua conta. Estas definições acompanham-no em todas as organizações a que pertence. A página tem quatro cartões: - **Email** — o endereço da conta e o seu estado; - **Password** — ver [Password](https://docs.diska.ai/pt/settings/password); - **Autenticação de dois fatores** — ainda *Em breve*, ver [Autenticação de dois fatores](https://docs.diska.ai/pt/settings/two-factor); - **Sessões ativas** — ver [Sessões ativas](https://docs.diska.ai/pt/settings/sessions). ## Email O cartão mostra o email e o selo **Verificado** ou **Por verificar**. - **Reenviar verificação** volta a enviar o email de verificação (só quando o email está por verificar). - **Alterar email** pede o **Novo email** e a **Password atual**. Clique em **Enviar confirmação** e siga as instruções enviadas para o endereço actual e para o novo. ## Contas com acesso Google Se entrou com Google, a página mostra *Acesso com Google*: o email e a password são geridos na sua conta Google, e os botões **Alterar email** e **Alterar password** não aparecem. Para gerir uma password Diska, entre com email e palavra-passe. # Password ## Alterar a password 1. Aceda a **Definições → Conta → Credenciais**. 2. No cartão **Password**, clique em **Alterar password**. 3. Preencha **Password atual**, **Nova password** e **Confirmar nova password**. Pode usar **Mostrar passwords** para ver o que escreveu. 4. Clique em **Alterar password**. Aparece *Password alterada*. A nova password tem de ter: - 10 caracteres no mínimo; - uma letra maiúscula; - um número; - um carácter especial. O indicador por baixo do campo mostra os requisitos cumpridos. Se a password actual estiver errada, verá *Password atual incorreta.* ## Esqueceu-se da password No ecrã de entrada, clique em **Esqueceu-se da palavra-passe?**, indique o seu email e siga as instruções recebidas. ## Contas com acesso Google Se entra com Google, a password é gerida na sua conta Google e o botão **Alterar password** não aparece. # Autenticação de dois fatores ::callout{type="warning"} **Ainda não está disponível.** O cartão **Autenticação de dois fatores** em **Definições → Conta → Credenciais** mostra *Em breve* e não tem botão de activação. :: O cartão anuncia a protecção adicional com uma aplicação autenticadora (Google Authenticator, 1Password, Authy ou Microsoft Authenticator). Fica *Em breve* até o início de sessão passar a exigir o segundo factor. ## Enquanto isso A sua conta fica protegida por: - uma **password** com regras de força — veja [Password](https://docs.diska.ai/pt/settings/password); - o **início de sessão com Google**, se o usar; - as **sessões activas**, que pode terminar a qualquer momento — veja [Sessões ativas](https://docs.diska.ai/pt/settings/sessions). # Sessões ativas O cartão **Sessões ativas**, em **Definições → Conta → Credenciais**, lista os dispositivos onde a sua conta foi usada recentemente. Cada sessão mostra: - o browser e o sistema operativo (por exemplo, *Chrome em Windows*); - o país, ou *Localização indisponível*, e o IP; - **Última atividade**; - o selo **Sessão atual** no dispositivo que está a usar. ## Terminar uma sessão Clique em **Terminar** junto de um dispositivo que não reconhece. Esse dispositivo deixa de conseguir usar a Diska e tem de voltar a entrar. A sessão actual não tem o botão **Terminar**: para sair deste dispositivo use **Terminar sessão** no menu do utilizador. ## Terminar todas as outras sessões **Terminar todas as outras sessões** mantém apenas o dispositivo actual. As outras sessões terminam de imediato. Se suspeitar de acesso indevido, termine as outras sessões e altere a [password](https://docs.diska.ai/pt/settings/password). # Empresa A página **Definições → Empresa** (**Preferências da empresa**) mostra e edita os dados da empresa activa. Só o **Proprietário** e os **Administradores** a vêem e podem guardar alterações. ## Campos | Campo | Notas | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome** | Nome da empresa mostrado na plataforma e em comunicações. Entre 2 e 120 caracteres. | | **Website** | URL público da empresa, começado por `http://` ou `https://`. Pode ficar vazio. | | **NIF** | Número de identificação fiscal: 9 ou 10 dígitos para uma empresa, ou o número do BI para um empresário em nome individual. Espaços, pontos e hífenes são ignorados. Pode ficar vazio. | | **Tipo de negócio** | Saúde, Imobiliário, Educação, Restauração, Retalho, Serviços, Seguros, Recrutamento, Hotelaria, Call Center ou Outro. Os modelos de agente abrem filtrados por este tipo. | | **Região do cliente** | Só leitura. A região é definida na configuração e não pode ser alterada. | Clique em **Guardar alterações** (activo quando há alterações). Aparece *Preferências guardadas*. O nome, o tipo de negócio, o website e o NIF são pedidos uma vez no ecrã **Bem-vindo à Diska**, no primeiro acesso do proprietário. Os agentes criados depois de a empresa ter nome usam-no como o nome da empresa que representam. No topo da página, **ID da empresa** mostra o identificador da organização; clique para o copiar (útil ao falar com o suporte). ## Retenção das gravações O período máximo durante o qual as gravações de chamadas são guardadas é definido para toda a organização: por omissão, **90 dias**. Em cada agente, na secção **Segurança e conformidade** das **Definições**, pode encurtar esse período (7, 30, 90, 180 ou 365 dias, nunca acima do da organização). Esta página ainda não mostra o período da organização. Veja [Gravar chamadas](https://docs.diska.ai/pt/guides/record-calls). ## Trocar de empresa Se pertence a várias organizações, escolha a empresa no selector no topo do menu lateral. Aparece *Empresa alterada para …* e os agentes, números, fluxos e históricos passam a ser os da empresa seleccionada. # Organização A página **Definições → Organização** mostra um resumo da organização activa. Só o **Proprietário** e os **Administradores** a vêem. Mostra: - o nome da organização; - **Slug** e **Estado**; - **A sua função** nesta organização. Os botões levam às páginas onde a gestão se faz: - **Preferências da empresa** → [Empresa](https://docs.diska.ai/pt/settings/company); - **Membros da empresa** → [Membros](https://docs.diska.ai/pt/settings/members). Para trocar de organização use o selector no topo do menu lateral. O que é uma organização, e o que lhe pertence, está em [Organização](https://docs.diska.ai/pt/concepts/organization). # Membros A página **Definições → Membros** gere quem tem acesso à organização. Só o **Proprietário** e os **Administradores** a vêem. ## Funções | Função | O que pode fazer | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Proprietário** | Tudo o que um Administrador faz, e atribuir a função de Proprietário. | | **Administrador** | Gerir membros, convites, empresa, integrações e chaves API; comprar, importar e atribuir números; arquivar agentes; eliminar documentos de conhecimento e gravações. Também cria, edita e publica. | | **Membro** | Criar, editar e publicar agentes e fluxos; adicionar e editar conhecimento; criar e editar acções e testes. Não vê as páginas de organização das Definições nem atribui números. | | **Visualizador** | Consultar agentes, conhecimento, acções, históricos e análises, e testar agentes. Não altera nada. | ::callout{type="info"} Os testes estão abertos a todas as funções, incluindo o **Visualizador** . Uma chamada de teste da versão publicada executa acções reais (SMS, marcações, transferências) — veja [Chamadas telefónicas](https://docs.diska.ai/pt/telephony/phone-calls#chamada-de-teste-pelo-telefone) . :: ## Convidar um utilizador 1. Clique em **Convidar utilizador**. 2. Em **Convidar para a minha empresa**, indique o **Endereço de email**. 3. Escolha a **Função**: **Membro** ou **Admin**. 4. Clique em: - **Enviar convite** — a Diska envia o convite por email (*Email de convite enviado*); ou - **Gerar link** — gera um link único, que copia e envia como quiser (*Link de convite gerado*). Se o email não puder ser enviado, aparece *Convite criado* com o link para copiar. O convite é válido durante **14 dias**. Quem o recebe abre o link, vê a **Empresa**, o **Email** e a **Função**, e clica em **Aceitar convite**; tem de entrar com o email convidado. Para dar a função de **Visualizador** ou **Proprietário**, convide como Membro e altere a função depois de aceitar. ## Convites pendentes O separador **Convites** lista os convites com **Email**, **Função** e **Estado**. Pode copiar o link de um convite ou **Revogar** o convite. ## Gerir membros No separador **Utilizadores**: - **Alterar a função**: escolha a nova função na coluna **Função** e confirme em **Alterar função?**. Se alterar a sua própria função, pode perder o acesso a esta página. - **Remover**: clique em **Remover** e confirme em **Remover membro?**. A pessoa perde de imediato o acesso à organização. Regras: - Só um **Proprietário** pode atribuir a função de Proprietário. - A organização mantém sempre pelo menos um Proprietário: não é possível remover nem despromover o último. # Integrações A página **Definições → Integrações** (*Ligue serviços externos e canais à sua organização.*) lista os serviços que pode usar com os seus agentes. Só o **Proprietário** e os **Administradores** a vêem. ## O que aparece na página | Categoria | Serviço | Estado | O que faz | | ----------------------------- | ---------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | **Calendário e agendamentos** | **Cal.com** | **Ligado** quando ligou a sua conta | Marcações durante a chamada. Clique para ligar ou desligar — veja [Cal.com](https://docs.diska.ai/pt/integrations/calcom). | | **Mensagens** | **SMS (Ombala)** | **Ligado** ou **Não configurado**, com o selo **Gerido pela Diska** | Envio de SMS durante e depois da chamada. É configurado pela Diska; não há nada a ligar do seu lado. | Por baixo, a secção **WhatsApp** liga o número WhatsApp Business da organização e escolhe os agentes que atendem as mensagens e as chamadas. Veja [Ligar o WhatsApp](https://docs.diska.ai/pt/whatsapp/connect). Só aparecem os serviços que já pode usar. Outros serviços ainda não estão disponíveis e não são listados. ## Estados - **Ligado** — a integração está configurada e pode ser usada pelas acções e pelos fluxos. - **Não configurado** — num serviço **Gerido pela Diska**, o serviço não está configurado na plataforma. Contacte a DISKA. - Sem selo — o Cal.com ainda não foi ligado. ## Ver também - [Integrações](https://docs.diska.ai/pt/integrations) — o que cada integração permite fazer. - [Integração não liga](https://docs.diska.ai/pt/troubleshooting/integration-not-connecting). # Chaves API As chaves API autenticam a [API da DISKA](https://docs.diska.ai/pt/api/api-channel): o acesso programático aos dados da organização (agentes, chamadas, análises, números, conhecimento e webhooks) em `https://api.diska.ai/v1`. Só o **Proprietário** e os **Administradores** vêem a página **Definições → Chaves API**. ## Criar uma chave 1. Clique em **Criar nova chave API**. 2. Preencha: - **Nome** (obrigatório); - **Descrição** (opcional); - **Âmbitos** — sem selecção, a chave tem acesso total; - **Expira em** (opcional). 3. Clique em **Gerar**. 4. Na janela **A sua chave API**, copie a chave e guarde-a num local seguro. *Não voltará a ser mostrado.* Âmbitos disponíveis: | Âmbito | Na UI | | -------------------- | ------------------------ | | `agents:read` | Agentes — leitura | | `agents:write` | Agentes — criar/publicar | | `calls:read` | Chamadas e transcrições | | `analytics:read` | Análises | | `phone-numbers:read` | Números | | `knowledge:read` | Conhecimento — leitura | | `knowledge:write` | Conhecimento — escrita | | `webhooks:manage` | Webhooks — gestão | ## A lista de chaves | Coluna | O que mostra | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | **Nome** | Nome e descrição. | | **Chave** | Uma pré-visualização (começa por `dsk_`). O botão copiar copia só a pré-visualização: o valor completo só é mostrado na criação. | | **Âmbitos** | *Acesso total* ou os âmbitos escolhidos. | | **Data de criação** | | | **Expira** | — quando não expira. | | **Último uso** | Ajuda a encontrar chaves esquecidas. | ## Usar a chave ```bash curl https://api.diska.ai/v1/me \ -H "Authorization: Bearer dsk_…" ``` Os endpoints estão em [Endpoints](https://docs.diska.ai/pt/api/endpoints) e a autenticação em [Autenticação](https://docs.diska.ai/pt/api/authentication). ## Revogar uma chave Clique no ícone do caixote do lixo e confirme em **Revogar chave API** → **Revogar chave**. A chave fica imediatamente desactivada e deixa de poder aceder à API. ## Boas práticas - Guarde as chaves em variáveis de ambiente ou num cofre de segredos, nunca no código ou no frontend. - Dê a cada integração a sua chave, só com os âmbitos de que precisa. - Se uma chave for comprometida, gere uma nova e revogue a antiga. # Aplicações ligadas e Apps OAuth Outras plataformas (um sistema de vendas, um CRM) podem usar a DISKA em nome da sua empresa sem lhes dar uma chave API: na plataforma, carrega em «Ligar com a DISKA», escolhe a empresa e as permissões num ecrã da DISKA, e a plataforma fica ligada. Para quem desenvolve a integração, veja [OAuth para plataformas parceiras](https://docs.diska.ai/pt/api/oauth). ## Ligar uma aplicação No ecrã de autorização da DISKA: 1. Confirme o nome da aplicação e quem a publica. Uma aplicação **ainda não verificada pela DISKA** mostra um aviso: ligue-a só se a conhece. 2. Escolha a empresa. Só o **Proprietário** e os **Administradores** de uma empresa a podem ligar. 3. Desmarque as permissões que não quer dar. 4. Clique em **Ligar**. Volta à plataforma, já ligada. Nenhuma aplicação pode, seja qual for a permissão: ver ou criar chaves API, gerir membros e convites, ver faturação e minutos, alterar números, telefonia ou WhatsApp, ou apagar a empresa. ## Aplicações ligadas Em **Definições → Aplicações ligadas** (Proprietário e Administradores) vê, para cada aplicação: quem a publica, quem a ligou e quando, e quando a usou pela última vez. - **Retirar permissões**: desmarque e clique em **Retirar permissões**. Aplica-se já ao pedido seguinte da aplicação. Para dar mais permissões, a aplicação tem de as pedir de novo. - **Desligar**: a aplicação perde o acesso imediatamente. Para voltar a usá-la, autorize-a de novo. Ligar, retirar permissões e desligar ficam no registo de actividade. ## Apps OAuth (parceiros) Se a sua organização é uma plataforma parceira da DISKA, a página **Definições → Apps OAuth** permite registar a aplicação que os seus clientes vão ligar. A página aparece quando a DISKA activa a funcionalidade para a sua organização. 1. Clique em **Registar aplicação** e preencha o nome, o ambiente (**Teste** ou **Produção**), os redirect URIs e as permissões que a aplicação pode pedir. 2. Copie o **Client ID** e o **Client secret**. O secret só é mostrado uma vez; com **Gerar novo secret** cria outro e o anterior deixa de funcionar. 3. Opcional: em **Webhook**, configure o URL que recebe os eventos de todas as empresas ligadas, envie um **ping** e consulte as últimas entregas. Cada aplicação mostra quantas empresas a ligaram e o estado: **Não verificada** (até 100 empresas), **Verificada** ou **Suspensa**. Uma aplicação verificada volta a não verificada se mudar o nome, a descrição, o logótipo, as páginas ou os redirect URIs, ou se pedir novas permissões. Apagar uma aplicação desliga todas as empresas. # Definições A área **Definições** (menu lateral) reúne a configuração da sua conta e da organização activa. | Grupo no menu | Páginas | Quem vê | | ------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------ | | **Conta** | **Perfil**, **Credenciais** | Todos os membros | | Organização | **Empresa**, **Organização**, **Integrações**, **Chaves API**, **Aplicações ligadas** (e **Apps OAuth** para parceiros) | Proprietário e Administradores | | Pessoas | **Membros** | Proprietário e Administradores | As páginas da conta acompanham-no em todas as organizações a que pertence. As restantes aplicam-se só à organização seleccionada no topo do menu lateral. ::card-group :::card --- description: Nome, avatar, cargo, idioma e fuso horário. icon: i-lucide-user title: Perfil to: https://docs.diska.ai/pt/settings/personal-profile --- ::: :::card --- description: Email, password, autenticação de dois fatores e sessões. icon: i-lucide-key-round title: Credenciais to: https://docs.diska.ai/pt/settings/credentials --- ::: :::card --- description: Nome, website e região da empresa. icon: i-lucide-building-2 title: Empresa to: https://docs.diska.ai/pt/settings/company --- ::: :::card --- description: Resumo da organização activa e a sua função. icon: i-lucide-users title: Organização to: https://docs.diska.ai/pt/settings/organization --- ::: :::card --- description: Convites, funções e acessos. icon: i-lucide-user-plus title: Membros to: https://docs.diska.ai/pt/settings/members --- ::: :::card --- description: Cal.com, SMS e WhatsApp. icon: i-lucide-puzzle title: Integrações to: https://docs.diska.ai/pt/settings/integrations --- ::: :::card --- description: Crie e revogue chaves da API da DISKA. icon: i-lucide-code-xml title: Chaves API to: https://docs.diska.ai/pt/settings/api-keys --- ::: :::card --- description: Plataformas que usam a DISKA em nome da empresa; Apps OAuth para parceiros. icon: i-lucide-plug title: Aplicações ligadas to: https://docs.diska.ai/pt/settings/connected-apps --- ::: :: # Agente não atende ## Chamadas telefónicas Verifique pela ordem: ### 1. O número está pronto Em **Números**, veja a coluna **Estado** do número: | Estado | O que fazer | | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | **Sem agente** | Atribua o número a um agente (passo 2). | | **A ativar**, **Credenciais pendentes**, **Não confirmado** | Número importado ainda sem configuração SIP pronta. Veja [Ligar por SIP](https://docs.diska.ai/pt/telephony/sip-trunk#acompanhar-o-estado). | | **Erro SIP** | Leia a mensagem no detalhe do número e corrija os dados com o operador. | | **Desativado** | O número foi suspenso. Contacte o suporte DISKA. | | **Configurado** | Continue: este estado não confirma que o agente está publicado. | Uma encomenda de número DISKA ainda por pagar não atende: o número só entra na lista quando a DISKA confirma o pagamento. ### 2. O número está num agente Inbound No agente, abra **Publicação → Telefone** e confirme o número. Só um agente do tipo **Inbound** atende chamadas; um agente **Outbound** usa o número apenas para ligar. Cada número atende num único agente Inbound. ### 3. O agente foi publicado depois de receber o número As chamadas são atendidas pela **versão publicada**. Se atribuiu ou trocou o número depois da última publicação, clique em **Publicar**. Confirme também que o agente não está arquivado. ### 4. O trunk SIP encaminha para a Diska (números importados) - O operador encaminha o número para o **Origination URI** mostrado no detalhe do número. - As chamadas saem de um dos **IPs de sinalização da operadora** que indicou. - O transporte (UDP ou TCP) é o mesmo dos dois lados. A Diska recusa chamadas do trunk que venham de outros IPs. ### 5. A organização não atingiu o limite de chamadas em simultâneo Se a DISKA definiu um limite, novas chamadas não são atendidas enquanto houver esse número de chamadas abertas. Veja [Limites](https://docs.diska.ai/pt/telephony/phone-calls#limites). ### Ouviu uma mensagem automática e a chamada terminou O agente não pôde ser contactado no início da chamada. Tente de novo; se repetir, contacte o suporte com a hora da chamada. ## Chamadas web, widget e link público - O agente tem uma versão **publicada**. O widget e o link público usam sempre a versão publicada. - O **Link público** está activo em **Publicação → Link público**. - O browser tem permissão para usar o microfone. - Para isolar o problema, teste o agente em **Testar → Chamada web** ou **Testar → Chat**. Veja [Testar o agente](https://docs.diska.ai/pt/guides/test-agent). ## O agente atende mas não responde bem - A lista de verificação do editor do agente mostra os erros e avisos por resolver. - Republique depois de alterar o prompt, o fluxo, as acções ou o conhecimento. - Veja [Conhecimento não responde](https://docs.diska.ai/pt/troubleshooting/kb-not-answering) e [Fluxo não publica](https://docs.diska.ai/pt/troubleshooting/flow-not-publishing). # Chamadas caem Comece por abrir a chamada em [Históricos](https://docs.diska.ai/pt/history/calls): o motivo de fim, a duração e a transcrição dizem quase sempre porque terminou. ## A chamada telefónica termina sempre ao fim do mesmo tempo O agente tem **Limitar duração da chamada** activo. Ao atingir o **Máximo (minutos)**, a linha desliga sem despedida. Aumente o máximo ou desligue o limite em **Definições → Configuração de chamada** e publique. Veja [Configuração de chamada](https://docs.diska.ai/pt/telephony/call-settings). ## O agente despediu-se e desligou - **Silêncio**: a pessoa deixou de falar; o agente perguntou se ainda estava em linha e depois despediu-se. - **Fim pedido ou tarefa concluída**: o agente terminou a chamada com um dos motivos de fim (por exemplo, `user_requested_end` ou `task_completed`). Se termina cedo demais, reveja o prompt ou o nó **Terminar chamada** do fluxo. ## A chamada caiu numa transferência - **A transferência correu bem**: depois de a pessoa ser ligada ao destino, o agente sai da chamada. Isto é normal; a conversa com a pessoa da equipa continua e não é gravada. - **A transferência falhou**: se o destino estava ocupado, desligado ou não atendeu em cerca de 20 segundos, a pessoa continua com o agente. Confirme o destino em [Transferências de chamada](https://docs.diska.ai/pt/actions/call-transfers). - **Num número DISKA**, a transferência só liga para telemóveis angolanos (Africell ou Unitel) fixados na acção ou na lista telefónica, e a organização tem de estar autorizada a fazer chamadas de saída. Um número dito durante a conversa, ou um número de rede fixa, é recusado. Veja [Transferências](https://docs.diska.ai/pt/telephony/phone-calls#transfer%C3%AAncias). ## A chamada terminou logo no início O agente não pôde ser contactado no arranque: a chamada termina com uma breve mensagem automática ou um sinal de chamada falhada. Tente de novo; se repetir, contacte o suporte com a hora da chamada. ## Corte de áudio ou queda a meio, sem motivo aparente - **Rede de quem liga**: teste a partir de outro telemóvel ou de outra rede. - **Trunk SIP próprio**: confirme com o operador os IPs, o transporte e os codecs acordados, e que não há equipamentos de rede a fechar sessões longas. - **Chamada web**: uma ligação de internet instável, fechar o separador do browser ou o microfone deixar de responder terminam a chamada. O motivo aparece em Históricos (por exemplo, *Ligação perdida* ou *Página fechada*). Se a queda se repetir sem causa visível, contacte o suporte com a hora e o número de cada chamada. ## A gravação parou mas a chamada continuou Não é uma queda: numa chamada telefónica só ficam gravados os primeiros 27 minutos da parte com o agente. Veja [Gravar chamadas](https://docs.diska.ai/pt/guides/record-calls). # Fluxo não publica Quando clica em **Publicar** e o fluxo tem erros, a publicação é recusada com o aviso **Fluxo inválido** e a descrição do primeiro erro. Se aparecer só *Não foi possível publicar*, tente de novo; se repetir, contacte o suporte. ## Onde ver todos os erros Abra a **Lista de verificação** no editor do agente. Mostra *N problemas · X erros · Y avisos*: - **erros** de fluxo bloqueiam a publicação; - **avisos** (por exemplo, falta de número de telefone) não bloqueiam. Clique num item para ir ao nó com o problema. Os erros também aparecem no próprio nó, no canvas. Veja [Validação e publicação](https://docs.diska.ai/pt/flow-builder/validation-publishing). ## Erros frequentes | Mensagem | Como resolver | | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | *O fluxo precisa de pelo menos um nó End alcançável para terminar a chamada.* | Ligue pelo menos um caminho a um nó **Terminar chamada**. | | *O ciclo … não tem saída: nenhum caminho a partir dele termina a chamada.* | Dê ao ciclo uma saída que chegue a **Terminar chamada**. | | *A ligação referencia um nó que não existe.* | Apague a ligação partida e volte a ligar os nós. | | *Conversation precisa de uma instrução clara para o agente.* | Escreva a instrução do nó **Conversação**. | | *End precisa de um motivo de fim de chamada.* / *End precisa de uma despedida antes de terminar a chamada.* | Complete o nó **Terminar chamada**. | | *Cada caminho do Branch precisa de variável e operador.* / *Cada caminho LLM Prompt precisa de uma descrição da condição.* | Complete as condições do nó **Dividir o caminho**. | | *Jump precisa de um nó de destino.* / *O destino do Jump já não existe.* | Escolha um destino válido no nó **Saltar para**. | | *Trigger Subflow precisa de um subflow de destino.* / *Este subflow ainda não tem triggers de entrada ativos.* | Escolha o subfluxo e active um trigger de entrada nele. | | *Este nó não tem nenhuma acção anexada. Anexe uma acção para o usar.* | Anexe ao agente a acção que o nó usa (por exemplo, uma acção personalizada). | | *There are no during-call SMS actions attached to this agent.* | Anexe uma acção de [SMS durante a chamada](https://docs.diska.ai/pt/actions/during-call-sms) ao agente. | | *Transfer para telefone precisa de um número.* (e equivalentes para SIP URI, lista telefónica ou acção) | Complete o destino do nó **Transferência**. | | *Transferir para uma fila ou equipa não existe nas linhas telefónicas. Escolha um telefone, SIP URI, lista telefónica ou acção de transferência.* | Mude o destino do nó **Transferência**: as linhas telefónicas transferem para um número, não para uma fila. | | *Seleccione uma acção de Agendamento em tempo real (Acções → Agendamento em tempo real).* | Crie ou escolha a acção de agendamento no nó **Agendamento**. | | *Booking deve receber uma variável de contacto antes de publicar.* | Recolha o contacto (por exemplo, o email) antes do nó **Agendamento**. | | *Marcação (calendário) ainda não está ligada a um fornecedor. …* | Ligue o [Cal.com](https://docs.diska.ai/pt/integrations/calcom) em **Definições → Integrações**, ou remova o nó. | | *… ainda não implementado. Remova-o antes de publicar.* | O nó é de um canal ainda não disponível. Remova-o. | | *A transferência de chamadas não está disponível neste servidor …* | A telefonia não está disponível neste ambiente. Contacte o suporte. | ::callout{type="tip"} Alguns destes erros só bloqueiam a publicação. No painel **Testar** com o **Rascunho** , pode experimentar um fluxo ainda incompleto (sem **Terminar chamada** , com transferência para fila ou com marcação sem calendário ligado). :: ## Depois de publicar - O número de telefone e as bases de conhecimento também ficam na versão publicada: se os alterar, publique de novo. - Uma transferência que publica pode, mesmo assim, falhar numa chamada real se o destino não for permitido na linha. Veja [Transferências](https://docs.diska.ai/pt/telephony/phone-calls#transfer%C3%AAncias). # Conhecimento não responde Verifique pela ordem: ## 1. A base está atribuída ao agente 1. Abra o agente → **Definições** → secção **Conhecimento e memória**. 2. Em **Bases de conhecimento atribuídas**, marque as bases que o agente deve usar. 3. Clique em **Guardar atribuições**. ## 2. O agente foi publicado depois As chamadas reais usam as bases que estavam atribuídas quando publicou. Se atribuiu ou retirou uma base depois, clique em **Publicar**. No painel **Testar** com o **Rascunho**, as alterações valem logo. ## 3. Os documentos estão prontos Abra a base em **Conhecimento** e veja o estado de cada documento: | Estado | O que fazer | | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | **Indexado** / **Pronto** | O documento está disponível. | | **A carregar** / **A processar** / **Indexação pendente** | Aguarde. | | **Sem texto / indexação pendente** | O PDF não tem texto seleccionável (por exemplo, é digitalizado). Carregue uma versão com texto ou copie o conteúdo para um documento em branco. | | **Extração falhou** / **Indexação falhou** / **Falhou** | Leia a mensagem do documento e use **Reindexar** no menu do documento. | | **Sem indexação** | O documento não tem texto suficiente para indexar. | **Reindexar tudo** reprocessa todos os documentos da base. Veja [Fontes](https://docs.diska.ai/pt/knowledge-base/sources). ## 4. A pergunta está coberta - Confirme que a resposta está mesmo nos documentos, escrita de forma clara. - Para páginas web, confirme que a página tem texto (e não só imagens ou conteúdo carregado por scripts). - Use a instrução da base para dizer ao agente quando a deve consultar. - Diga no prompt do agente para responder com base no conhecimento e admitir quando não sabe. ## 5. Teste e veja o diagnóstico Corra um caso no [Centro de Testes](https://docs.diska.ai/pt/test-center) com uma pergunta cuja resposta está nos documentos. No histórico de execuções, o detalhe do caso pode mostrar o **Diagnóstico da base de conhecimento**, com o que o agente encontrou. # Integração não liga As integrações gerem-se em **Definições → Integrações**, que só o **Proprietário** e os **Administradores** vêem. Se não encontra a página, peça a um deles. ## Cal.com | Sintoma ou mensagem | O que fazer | | --------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | *Chave API do Cal.com inválida ou sem permissão.* | Gere uma nova chave nas definições da aplicação Cal.com e volte a ligar. | | *Não foi possível contactar o Cal.com. Tente novamente.* | Falha temporária. Tente de novo dentro de momentos. | | *Ligação não confirmada* no painel | A Diska não conseguiu ler o estado. Clique em **Tentar novamente**. | | *Nenhum tipo de evento encontrado na conta Cal.com.* ou a lista **Evento** está vazia | Crie um tipo de evento no Cal.com e use o botão de actualizar junto a **Evento** na acção de agendamento. | | A acção de agendamento diz *Ligue o Cal.com em Definições → Integrações para seleccionar tipos de evento.* | O Cal.com não está ligado. Veja [Cal.com](https://docs.diska.ai/pt/integrations/calcom). | | O fluxo não publica com *Marcação (calendário) ainda não está ligada a um fornecedor.* | Ligue o Cal.com, ou remova o nó **Agendamento**. | | A marcação falha na chamada | A hora pedida pode não estar livre no Cal.com, ou faltar o email do cliente (``). Veja a acção em [Agendamento em tempo real](https://docs.diska.ai/pt/actions/real-time-booking). | Para trocar de conta Cal.com, clique em **Desligar** e ligue com a chave da outra conta. ## SMS (Ombala) O SMS é **Gerido pela Diska**: não há nada para ligar do seu lado. - Se o cartão **SMS (Ombala)** mostrar **Não configurado**, o envio de SMS não está disponível na plataforma. Contacte a DISKA. - Se mostrar **Ligado** e um SMS não chega, confirme o número de destino e as variáveis da acção em [SMS durante a chamada](https://docs.diska.ai/pt/actions/during-call-sms) ou [SMS pós-chamada](https://docs.diska.ai/pt/actions/post-call-sms). ## WhatsApp A secção **WhatsApp**, na mesma página, mostra o estado das ligações: - *WhatsApp ainda não configurado* — ainda não ligou nenhuma conta. - *Novas ligações em preparação* — a ligação de novas contas ainda não está disponível; a mensagem indica o motivo. Veja [Ligar o WhatsApp](https://docs.diska.ai/pt/whatsapp/connect). ## Outros serviços A página só lista as integrações disponíveis. Para ligar outros sistemas (por exemplo, um CRM), use a [API da DISKA](https://docs.diska.ai/pt/api/api-channel) ou [Acções personalizadas](https://docs.diska.ai/pt/actions/custom-actions). # Testes falham ## Suites do Centro de Testes Abra a execução em **Centro de Testes → Histórico** e o caso que falhou. ### Como ler o resultado - Cada critério mostra **Passou** ou **Falhou**, com a explicação do avaliador. - **Erro** num caso significa que a execução do caso não terminou (por exemplo, falha técnica), não que o agente respondeu mal. Corra de novo. - A execução é uma **Simulação de texto**: não usa voz nem executa ferramentas reais. A linha *Não exercitado nesta simulação: …* diz o que ficou de fora. - **Pronto para publicar** ou **Publicação com pendências** resume o estado do agente no momento do teste. - Nos agentes de fluxo, **Percurso do fluxo** mostra os nós visitados e se a conversa **Chegou ao fim**. ### Causas frequentes | Sintoma | O que fazer | | -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Os critérios falham mas a conversa parece boa | Reescreva critérios vagos de forma observável ("o agente pede o email" em vez de "o agente é prestável"). | | O agente não sabe responder | Confirme a base de conhecimento — veja [Conhecimento não responde](https://docs.diska.ai/pt/troubleshooting/kb-not-answering). | | O resultado não reflecte as últimas alterações | A suite corre contra o rascunho ou contra a versão publicada, conforme **Correr por defeito contra o rascunho (não o publicado)**. Publique, ou ajuste esta opção da suite. | | O fluxo **Não terminou** | Siga o **Percurso do fluxo** até ao último nó e corrija o caminho que não chega a **Terminar chamada**. | | *Perdemos a ligação ao teste — atualize a página.* | Recarregue a página; a execução continua no servidor. | Veja [Centro de Testes](https://docs.diska.ai/pt/test-center) e [Avaliações](https://docs.diska.ai/pt/test-center/evaluations). ## Chamada de teste pelo telefone No painel **Testar → Chamada telefónica**, o botão **Ligar-me** faz o agente ligar para o seu telemóvel. Se não funcionar: ### O botão Ligar-me está desactivado | Indicação | O que fazer | | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | *Atribua um número DISKA ao agente e publique-o.* | Atribua um número DISKA em **Publicação → Telefone** e publique. | | *Publique o agente uma vez para testar por telefone.* | Publique o agente. | | *Indique um telemóvel angolano (Africell ou Unitel) com 9 dígitos, ex.: 923 000 000.* | Corrija o número em **Ligar para**. Só telemóveis angolanos (+244). | ### A chamada não começa | Mensagem | O que fazer | | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | *Atribua ao agente um número DISKA activo e publique-o para testar por telefone.* | A versão publicada não tem um número DISKA activo. Os números importados por trunk SIP não fazem chamadas de teste. Atribua um número DISKA e publique. | | *Esta organização ainda não está habilitada para chamadas telefónicas de saída.* | Peça à DISKA para autorizar a organização. | | *A organização atingiu o limite de chamadas em simultâneo.* | Espere que termine outra chamada. | | *Já tem uma chamada de teste em curso. Termine-a antes de ligar de novo.* | Desligue a chamada anterior. | | *Atingiu o limite de chamadas de teste desta hora. Tente mais tarde.* | Aguarde até à hora seguinte. | | *Indique o seu telemóvel, não o número do agente.* | Marque o seu telemóvel. | ### A chamada começa mas falha | Mensagem no painel | O que fazer | | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | | *O número está ocupado, desligado ou rejeitou a chamada.* | Confirme que o telemóvel está ligado, com rede e sem chamada em curso. | | *A chamada não foi atendida.* | Atenda mais depressa, ou aumente a **Duração do toque** em [Configuração de chamada](https://docs.diska.ai/pt/telephony/call-settings). | | *O agente não conseguiu atender a chamada. Tente novamente.* | Tente de novo. Se repetir, teste em **Chamada web** para confirmar que o agente arranca. | | *A linha telefónica não está disponível neste momento.* | A linha está temporariamente indisponível. Tente mais tarde. | | *Não foi possível confirmar o estado da chamada.* | Veja a chamada em **Históricos** e tente de novo. | ### A chamada correu mas as acções não aconteceram Com **Rascunho — ações simuladas**, SMS, marcações e transferências são simulados. Escolha **V*n* publicada — ações reais** para as executar a sério. Veja [Chamadas telefónicas](https://docs.diska.ai/pt/telephony/phone-calls#chamada-de-teste-pelo-telefone). # Resolução de problemas Cada página parte do sintoma, lista as causas pela ordem em que vale a pena verificá-las e indica o que fazer. As mensagens entre aspas são as que o backoffice mostra. Antes de tudo, abra a chamada em [Históricos](https://docs.diska.ai/pt/history/calls): a transcrição, as acções executadas e o motivo de fim mostram até onde a conversa chegou. Se o problema começou de repente ou afecta todos os agentes, veja primeiro [status.diska.ai](https://status.diska.ai){rel=""nofollow""}: mostra o estado da API, do backoffice e da telefonia, com os incidentes em curso e as manutenções previstas. ::card-group :::card --- description: Ninguém atende quando liga para o número. icon: i-lucide-phone-off title: Agente não atende to: https://docs.diska.ai/pt/troubleshooting/agent-not-answering --- ::: :::card --- description: A chamada termina antes do esperado. icon: i-lucide-phone-missed title: Chamadas caem to: https://docs.diska.ai/pt/troubleshooting/calls-drop --- ::: :::card --- description: A publicação é recusada com erros do fluxo. icon: i-lucide-alert-triangle title: Fluxo não publica to: https://docs.diska.ai/pt/troubleshooting/flow-not-publishing --- ::: :::card --- description: O agente ignora a base de conhecimento. icon: i-lucide-book-x title: Conhecimento não responde to: https://docs.diska.ai/pt/troubleshooting/kb-not-answering --- ::: :::card --- description: Cal.com, SMS ou WhatsApp não funcionam. icon: i-lucide-unplug title: Integração não liga to: https://docs.diska.ai/pt/troubleshooting/integration-not-connecting --- ::: :::card --- description: Suites do Centro de Testes e chamadas de teste com erro. icon: i-lucide-x-circle title: Testes falham to: https://docs.diska.ai/pt/troubleshooting/tests-failing --- ::: :: # Política de Privacidade ::alert{type="warning"} **Documento em revisão jurídica.** Este texto descreve fielmente como a plataforma funciona hoje, mas ainda não foi validado por advogado. Antes de o apresentar a clientes ou reguladores como compromisso contratual, submeta-o a revisão legal — sobretudo as secções de retenção, transferências internacionais e direitos dos titulares. :: **Última actualização:** 24 de Outubro de 2026 A Diska desenvolve agentes de voz com inteligência artificial que atendem chamadas, qualificam contactos e executam processos por telefone. Esta política explica que dados pessoais tratamos, com que fundamento, durante quanto tempo e a quem os transmitimos. Está escrita para ser lida. Onde a prática técnica é relevante — por exemplo, que uma chamada só é gravada mediante aviso — dizemo-lo em concreto, em vez de usar fórmulas genéricas. ## Quem somos A Diska é a responsável pelo tratamento dos dados descritos nesta política. - **Contacto de privacidade:** - **Âmbito:** o site `diska.ai`, a aplicação em `app.diska.ai`, a API em `api.diska.ai`, o widget de voz incorporável e as chamadas conduzidas pelos agentes que os nossos clientes configuram. ## Dois papéis diferentes, duas responsabilidades Esta distinção determina a quem deve dirigir-se para exercer os seus direitos. **Quando é nosso cliente** (criou conta, configurou agentes), somos **responsáveis pelo tratamento** dos seus dados de conta, faturação e utilização. **Quando fala com um agente de um cliente nosso**, é esse cliente quem decide porquê e para quê a chamada acontece. Nesse caso a Diska actua como **subcontratante**: tratamos os dados da chamada por instrução do cliente e nos limites que ele define. Se pretende aceder ou apagar o que foi dito numa chamada, o pedido deve ser dirigido à empresa que o atendeu; nós apoiamos essa empresa a responder-lhe. ## Que dados tratamos ### Dados de conta Nome, endereço de e-mail, palavra-passe (guardada apenas como *hash*), empresa, cargo, telefone, idioma e fuso horário. Se entrar com Google, recebemos do Google o nome, o e-mail e a fotografia de perfil — nunca a sua palavra-passe Google. ### Dados de configuração dos agentes Instruções, fluxos de conversa, variáveis, ações e documentos que carrega para a base de conhecimento. Estes documentos são divididos em excertos e convertidos em representações numéricas (*embeddings*) para que o agente possa consultá-los durante uma chamada. ### Dados de chamada Isto é o núcleo do serviço, e vale a pena ser preciso: - **Áudio em tempo real.** Enquanto a chamada decorre, o áudio é transmitido ao fornecedor de voz para ser transcrito e respondido. É tratado em trânsito. - **Transcrição.** O texto do que foi dito, guardado no histórico da chamada. - **Metadados.** Início, duração, estado, resultado, o agente envolvido e — em chamadas telefónicas — o número de telefone. - **Variáveis recolhidas.** Aquilo que o agente foi configurado para perguntar: nome, contacto, motivo do contacto, preferências de horário. - **Gravação áudio**, apenas quando aplicável — ver a secção seguinte. ### Gravações: nunca em silêncio A gravação **não está ligada por omissão**. É uma decisão por agente, tomada pelo cliente, e a plataforma impõe duas garantias técnicas: 1. Um agente sem mensagem de aviso configurada **não grava**, mesmo que a gravação esteja activada. Não existe a possibilidade de gravar sem aviso. 2. O aviso é dito pelo agente no início da chamada. Em modo **explícito**, o agente espera uma confirmação falada antes de continuar. A frase exacta usada fica registada junto da gravação, para que mais tarde seja possível saber o que lhe foi comunicado — e não apenas que "houve consentimento". ### Dados do site e do widget - **Formulário de contacto:** nome, e-mail, empresa e telefone que nos envia. - **Demonstração pública:** pode falar com a Ísis, a nossa agente de demonstração, sem criar conta. Essa conversa é tratada como qualquer chamada. - **Analítica:** usamos Google Analytics para perceber como o site é usado. Os parâmetros são filtrados antes do envio — endereços de e-mail, telefones, identificadores e cadeias opacas são removidos, e os caminhos com identificadores são anonimizados. - **Dados técnicos:** endereço IP e agente de utilizador, usados para segurança e limitação de abuso. ## Com que fundamento tratamos | Finalidade | Fundamento | | ------------------------------------------------ | ---------------------------------------------------------- | | Prestar o serviço a quem tem conta | Execução do contrato | | Conduzir chamadas em nome de clientes | Instruções do cliente (como subcontratante) | | Gravar chamadas | Consentimento do interlocutor, obtido no início da chamada | | Segurança, prevenção de abuso, registos técnicos | Interesse legítimo | | Responder a pedidos de contacto | Diligências pré-contratuais | | Cumprir obrigações legais e fiscais | Obrigação jurídica | ## Com quem partilhamos Não vendemos dados pessoais. Recorremos a fornecedores que os tratam por nossa conta, sob contrato, e apenas para as funções indicadas: | Fornecedor | Função | Dados envolvidos | | -------------- | --------------------------------------------------------- | ---------------------------------------------------------- | | **OpenAI** | Voz em tempo real, transcrição, síntese e *embeddings* | Áudio e texto da chamada, excertos da base de conhecimento | | **Inworld AI** | Voz em tempo real (fala‑para‑fala), transcrição e síntese | Áudio e texto da chamada | | **xAI** | Voz em tempo real (fala‑para‑fala), transcrição e síntese | Áudio e texto da chamada | | **ElevenLabs** | Síntese de voz | Texto a ser falado pelo agente | | **Cartesia** | Síntese de voz | Texto a ser falado pelo agente | | **Supabase** | Base de dados, armazenamento e autenticação | Conta, configuração, transcrições, gravações | | **Google** | Início de sessão e analítica do site | E-mail e perfil; eventos de navegação | | **Twilio** | Telefonia, quando o cliente activa chamadas telefónicas | Número de telefone e áudio da chamada | Podemos ainda divulgar dados quando a lei o exigir, ou para defender direitos em processo judicial. ## Transferências internacionais Os fornecedores acima operam maioritariamente fora de Angola, o que significa que os dados são transferidos para outras jurisdições — sobretudo Estados Unidos e União Europeia. Exigimos garantias contratuais adequadas a essas transferências. ## Durante quanto tempo guardamos - **Dados de conta:** enquanto a conta existir, e até 12 meses depois para efeitos contabilísticos e legais. - **Transcrições e metadados de chamada:** enquanto a conta do cliente estiver activa, salvo instrução de eliminação anterior. - **Gravações áudio:** pelo período que o cliente definir; se não definir, seguem o mesmo prazo das transcrições. - **Registos técnicos e de segurança:** até 12 meses. - **Contactos do formulário:** até 24 meses após o último contacto. Um cliente pode pedir a eliminação antecipada de qualquer chamada. ## Os seus direitos Ao abrigo da Lei n.º 22/11, de 17 de Junho (Lei da Protecção de Dados Pessoais de Angola) e, quando aplicável, do RGPD, tem direito a aceder aos seus dados, corrigi-los, apagá-los, opor-se ao tratamento, pedir a sua limitação e recebê-los em formato portável. Pode ainda retirar o consentimento de gravação a qualquer momento, sem afetar o que já foi gravado licitamente. Escreva para . Respondemos no prazo legal. Se falarmos com o titular por conta de um cliente nosso, encaminhamos o pedido para esse cliente e ajudamo-lo a responder. Tem também o direito de apresentar reclamação junto da **Agência de Protecção de Dados (APD)** de Angola. ## Segurança A segurança é tratada em detalhe na [documentação de segurança](https://docs.diska.ai/pt/concepts). Em resumo: as ligações são cifradas em trânsito, as credenciais de terceiros ficam sempre do lado do servidor e nunca chegam ao navegador, o acesso aos dados de cada organização é isolado, e as credenciais de sessão das chamadas anónimas são de curta duração e limitadas à própria sessão. Nenhum sistema é imune. Se detectarmos um incidente que o afecte, notificamos os clientes envolvidos e, quando a lei o exigir, a autoridade competente. ## Menores O serviço não se destina a menores de 18 anos e não recolhemos os seus dados conscientemente. Se souber que um menor nos forneceu dados, contacte-nos para eliminação. ## Alterações Podemos actualizar esta política. Alterações materiais são comunicadas aos clientes por e-mail ou através da aplicação, com antecedência razoável. A data no topo indica a versão em vigor. # Termos e Condições ::alert{type="warning"} **Documento em revisão jurídica.** Descreve com rigor o funcionamento e as regras da plataforma, mas ainda não foi validado por advogado. Antes de o usar como contrato vinculativo — sobretudo as secções de responsabilidade, pagamentos e rescisão — submeta-o a revisão legal. :: **Última actualização:** 9 de Agosto de 2026 Estes termos regulam a utilização da plataforma Diska: o site `diska.ai`, a aplicação `app.diska.ai`, a API `api.diska.ai`, o widget de voz e tudo o que lhes está associado. Ao criar conta ou usar o serviço, aceita-os. Se aceitar em nome de uma empresa, declara ter poderes para a vincular. Nesse caso, "você" significa essa empresa. ## O que a Diska faz A Diska permite criar agentes de voz que atendem chamadas, conduzem conversas segundo instruções que você define, consultam documentos que você carrega e executam ações que você configura — marcar compromissos, enviar mensagens, chamar sistemas externos. O agente é seu. Nós fornecemos a plataforma que o faz funcionar. ## Conta e acesso Precisa de uma conta para usar o serviço. É responsável por manter as credenciais em segurança e por tudo o que acontece na sua conta. Avise-nos assim que suspeitar de acesso não autorizado. Não pode partilhar credenciais entre pessoas: convide os membros da sua equipa para a organização, com o nível de acesso adequado. Precisa de ter pelo menos 18 anos. ## O conteúdo é seu As instruções que escreve, os fluxos que desenha, os documentos que carrega e os dados das suas chamadas continuam seus. Não reclamamos propriedade sobre eles. Concede-nos apenas a licença necessária para operar o serviço: alojar, processar e transmitir esse conteúdo aos fornecedores indicados na [Política de Privacidade](https://docs.diska.ai/pt/legal/privacy), para que o agente funcione. Garante que tem direito a usar o que carrega e que isso não viola direitos de terceiros. ## O que espera de si A responsabilidade pelas conversas dos seus agentes é sua. Em concreto, compromete-se a: - **Cumprir a lei sobre gravação e comunicações.** As regras variam por jurisdição. A plataforma dá-lhe as ferramentas — aviso falado, consentimento explícito — mas a decisão de as usar corretamente é sua. - **Não usar a Diska para chamadas não solicitadas em massa** nem para campanhas que violem as regras aplicáveis a marketing telefónico. - **Não fazer o agente passar por humano** quando a lei exigir que se identifique como sistema automatizado. - **Não usar o serviço para fraude, assédio, conteúdos ilegais, ou para tentar extrair credenciais ou dados de terceiros.** - **Não tentar contornar limites técnicos**, sondar a infraestrutura, aceder a dados de outras organizações ou submeter a plataforma a carga artificial. - **Obter as autorizações necessárias** dos titulares dos dados que os seus agentes recolhem. Podemos suspender uma conta que esteja a causar dano — a terceiros, à plataforma ou a outros clientes — e, sempre que seja razoável, avisamos antes. ## Serviços de terceiros O serviço depende de fornecedores externos (modelos de linguagem, síntese e transcrição de voz, telefonia, alojamento). Uma falha, alteração ou indisponibilidade desses fornecedores pode afetar o serviço. Escolhemos e gerimos esses fornecedores com cuidado, mas não controlamos a sua disponibilidade. ## Limites da inteligência artificial Isto merece ser dito sem rodeios: um agente de voz gera respostas probabilísticas. Pode interpretar mal, pode responder de forma incorreta e pode falhar numa chamada importante. Não garantimos que as respostas sejam exactas, completas ou adequadas a um fim específico. Cabe-lhe testar os agentes antes de os pôr a atender clientes reais — o Centro de Testes existe para isso — e supervisionar os resultados. Não use a Diska como único mecanismo em decisões críticas de saúde, segurança, questões jurídicas ou financeiras sem revisão humana. ## Pagamentos As condições comerciais — preço, ciclo de faturação, limites de utilização — são as acordadas no seu plano ou proposta. Salvo indicação em contrário, os valores não incluem impostos, que ficam a seu cargo. A falta de pagamento pode levar à suspensão do serviço, após aviso. ## Disponibilidade Empenhamo-nos em manter o serviço disponível, mas não o prestamos sem interrupções. Pode haver manutenção planeada, falhas e degradações. Salvo se tiver um acordo de nível de serviço escrito, o serviço é prestado "tal como está". ## Responsabilidade Na medida máxima permitida pela lei, a Diska não responde por lucros cessantes, perda de dados, perda de oportunidades de negócio ou danos indirectos resultantes do uso do serviço. A nossa responsabilidade total, por qualquer causa, está limitada ao valor que nos pagou nos 12 meses anteriores ao facto que a originou. Nada nestes termos exclui responsabilidade que a lei não permita excluir. ## Suspensão e rescisão Pode encerrar a conta quando quiser. Podemos rescindir ou suspender o acesso se violar estes termos, se a utilização puser em risco a plataforma ou terceiros, ou por falta de pagamento. Terminado o contrato, pode exportar os seus dados durante **30 dias**. Após esse período, eliminamo-los conforme os prazos da [Política de Privacidade](https://docs.diska.ai/pt/legal/privacy). ## Alterações Podemos alterar estes termos. Alterações materiais são comunicadas com antecedência razoável, por e-mail ou na aplicação. Continuar a usar o serviço depois da entrada em vigor significa aceitá-las; se não concordar, pode encerrar a conta. ## Lei aplicável Estes termos regem-se pela lei da República de Angola. Os litígios que não sejam resolvidos por acordo serão submetidos aos tribunais competentes de Luanda. ## Contacto Dúvidas sobre estes termos: . # Build voice agents with Diska Diska is the platform where your company builds, tests and publishes **AI voice agents**. An agent answers customers by phone, on your website or through a link, speaks Portuguese, looks things up in your knowledge base and takes real actions: it books meetings, sends SMS, transfers the call to a person or calls your APIs. Everything is managed in the Diska backoffice, without code. ![Diska overview with call statistics, daily volume and call outcomes](https://docs.diska.ai/images/docs/dashboard/dashboard-overview.png) ## What you can do today - **Build voice agents** from an industry template or from scratch, in two editing modes: **Prompt Builder** (one system instruction) or **Flow Designer** (a visual flow of nodes and conditions). - **Answer on several channels**: web call in the browser, voice widget on your website, public link, phone numbers (a DISKA number or your own number over SIP) and WhatsApp, for Prompt-mode agents. - **Give the agent actions**: real-time booking, call transfer (including warm transfer), IVR menu handling, SMS during and after the call, custom actions that call your APIs, information extractors and custom evaluations. - **Answer from your own knowledge**: assign knowledge bases (documents and web pages) to the agent. - **Test before you publish**: web call, chat, a phone call to your mobile and simulations with test suites (in the editor or the Test Center), on the draft or the published version. - **Follow the results**: **Históricos** (History) lists calls with transcript, summary and recording (when enabled), plus WhatsApp conversations. **Análises** (Analytics) shows metrics per agent. - **Integrate with your systems** through the [DISKA API](https://docs.diska.ai/en/api/api-channel), webhooks and the Cal.com integration. ## How the backoffice is organised The backoffice is in Portuguese. Menu names are quoted as they appear, with an English gloss. | Menu | What it is for | Documentation | | ---------------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | **Visão geral** (Overview) | Call metrics and, in a new organization, the first steps. | [Initial setup](https://docs.diska.ai/en/getting-started/initial-setup) | | **Agentes** (Agents) | Create, edit, test and publish agents. | [Create your first agent](https://docs.diska.ai/en/getting-started/first-agent) | | **Conhecimento** (Knowledge) | Knowledge bases the agents consult. | [Knowledge base](https://docs.diska.ai/en/knowledge-base) | | **Acções** (Actions) | Bookings, transfers, IVR, SMS, custom actions, extractors and evaluations. | [Actions](https://docs.diska.ai/en/actions) | | **Números** (Numbers) | Buy a DISKA number or import your own number over SIP. | [Telephony](https://docs.diska.ai/en/telephony) | | **Históricos** (History) | Calls and WhatsApp conversations, with transcript, summary and recording. | [History](https://docs.diska.ai/en/history) | | **Análises** (Analytics) | Volume, duration, outcomes and executed actions, per agent. | [Analytics](https://docs.diska.ai/en/history/analytics) | | **Centro de Testes** (Test Center) | Test suites to validate agents before publishing. | [Test Center](https://docs.diska.ai/en/test-center) | | **Definições** (Settings) | Profile, company, members, integrations (including WhatsApp) and API keys. | [Settings](https://docs.diska.ai/en/settings) | What each person sees depends on their role in the organization: for example, only owners and administrators see **Empresa** (Company), **Membros** (Members) and **Chaves API** (API keys). See [Organization and permissions](https://docs.diska.ai/en/concepts/organization). ## Where to start ::card-group :::card --- description: Create your account, invite the team, build your first agent and run a test call. icon: i-lucide-rocket title: Getting started to: https://docs.diska.ai/en/getting-started --- ::: :::card --- description: Agents, flows, versions, channels and permissions, explained before you build. icon: i-lucide-lightbulb title: Concepts to: https://docs.diska.ai/en/concepts --- ::: :::card --- description: Let the agent book, transfer, send SMS and call your APIs. icon: i-lucide-zap title: Actions to: https://docs.diska.ai/en/actions --- ::: :::card --- description: Design the conversation with nodes, conditions, subflows and actions. icon: i-lucide-workflow title: Flow Builder to: https://docs.diska.ai/en/flow-builder --- ::: :::card --- description: DISKA numbers, your own number over SIP, phone calls and call limits. icon: i-lucide-phone title: Telephony to: https://docs.diska.ai/en/telephony --- ::: :::card --- description: Connect your WhatsApp Business account and let an agent answer messages. icon: i-lucide-message-circle title: WhatsApp to: https://docs.diska.ai/en/whatsapp --- ::: :::card --- description: Review calls, transcripts, recordings and conversations, and follow the metrics. icon: i-lucide-history title: History to: https://docs.diska.ai/en/history --- ::: :::card --- description: Publish, test, transfer to a human, book meetings, send SMS and record calls. icon: i-lucide-book-open title: Guides to: https://docs.diska.ai/en/guides --- ::: :: # Initial setup Before building your first agent, create your account, confirm the company details and bring the team into the organization. The backoffice is in Portuguese; labels are quoted as they appear, with an English gloss. ## 1. Create an account 1. Open the Diska backoffice and click **Criar conta** (Create account). 2. Fill in **Nome** (first name), **Apelido** (last name), **Email** and **Palavra-passe** (password, at least 8 characters). **Telefone** (phone, +244) is optional. 3. Tick **Aceito os termos de serviço da Diska** (I accept the terms of service) and click **Criar conta**. 4. Open the confirmation email (check your spam folder too) and click the link. The backoffice confirms the account and opens **Bem-vindo à Diska** (Welcome to Diska). Alternatively, use **Criar conta com Google** (Sign up with Google). ### Welcome to Diska On your first visit, Diska asks for your company details, once: - **Nome da empresa** (Company name) — required; it appears to your team, in invitations and in the agents you create; - **Tipo de negócio** (Business type) — optional; Diska uses it to suggest agent templates; - **Website** and **NIF** (tax ID) — optional. Click **Continuar** (Continue) to open **Visão geral** (Overview). You are the organization's **Proprietário** (Owner) and can change these details later under **Definições → Empresa** (Settings → Company), step 4. Accounts created before this screen existed see it once, titled **Complete os dados da sua empresa** (Complete your company details). ::callout{type="tip"} Invited by a colleague? You don't need a company of your own: open the invitation link and follow step 6. If you created the account without going back to the link, the welcome screen shows the open invitation with **Aceitar convite** (Accept invitation). :: ## 2. Sign in On **Entre na sua conta** (Sign in to your account), use your email and password, or **Continuar com Google** (Continue with Google). - If the account isn't confirmed yet, the backoffice says so and shows **Reenviar email de confirmação** (Resend confirmation email). - If you forgot your password, click **Esqueceu-se da palavra-passe?** (Forgot your password?) and enter your email to receive a recovery link. - If you belong to more than one organization, switch organization in the menu at the top of the sidebar, which shows the active organization's name. ## 3. First steps on the Overview While the organization has no calls yet, **Visão geral** (Overview) shows the **Primeiros passos** (First steps) list, with progress (“2 de 4 concluídos”, 2 of 4 done) and a button for each step: | Step | What it means | Button | | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | Criar o primeiro agente (Create the first agent) | Pick a ready-made template or start from scratch. If you gave a business type, the button opens that type's templates. | **Ir aos agentes** (Go to agents) or **Ver modelos** (See templates) | | Fazer uma chamada de teste (Run a test call) | The web call runs in the browser, no number needed. | **Testar agente** (Test agent) | | Publicar o agente (Publish the agent) | Publishing fixes the version that answers real calls. | **Abrir o agente** (Open the agent) | | Atribuir um número (Assign a number) | Only needed for phone calls; the web test works without a number. | **Ver números** (See numbers) | The list only shows the steps your role can carry out (a **Membro** (Member) doesn't see “Assign a number”, for example). Once the first calls come in, the list gives way to the metrics: total calls, minutes, average duration and call outcomes. ## 4. Confirm the company details Under **Definições → Empresa** (**Preferências da empresa**, company preferences) review: - **Nome** (Name) — the company name shown in the platform and in communications; - **Website** — the company's public URL; it can stay empty; - **NIF** — the tax identification number; it can stay empty; - **Tipo de negócio** (Business type) — used to suggest agent templates; - **Região do cliente** (Customer region) — set in the account configuration; it can't be changed here; - **ID da empresa** (Company ID) — click to copy it; it is useful for support requests. Click **Guardar alterações** (Save changes). Only owners and administrators see and edit this page. More in [Company](https://docs.diska.ai/en/settings/company). ## 5. Invite the team Under **Definições → Membros** (Settings → Members), click **Convidar utilizador** (Invite user): 1. Enter the colleague's **Endereço de email** (email address). 2. Choose the **Função** (role): **Membro** (Member — standard access to the company, limited administration) or **Admin** (inviting users and main administration). 3. Click **Enviar convite** (Send invitation) to send the invitation by email, or **Gerar link** (Generate link) to get a link you share some other way. If the email can't be sent, the invitation is still created and the link appears on screen so you can copy it. - Pending invitations are in the **Convites** (Invitations) tab, where you can copy the link or click **Revogar** (Revoke). - An invitation expires after 14 days. - Active members are in the **Utilizadores** (Users) tab, where you can change the **Função** or click **Remover** (Remove). The backoffice asks for confirmation first. Only owners and administrators can open **Membros**. More in [Members](https://docs.diska.ai/en/settings/members). ## 6. Accept an invitation 1. Open the invitation link. The **Junte-se à sua equipa** (Join your team) page shows the organization, the invited email and the role. 2. Click **Iniciar sessão** (Sign in) and sign in with **the same email** as the invitation. If you don't have an account yet, create one with that email. 3. Click **Aceitar convite** (Accept invitation). The backoffice switches to the new organization and opens **Visão geral**. If you created the account only to accept the invitation, the organization signup created for you, still unnamed and without any data, is archived when you accept. If you already used it (for example, you created an agent), it stays available in the organization switcher. If you are signed in with a different email, the page shows **Conta diferente da convidada** (Different account from the invited one) and an **Entrar com outra conta** (Sign in with another account) button. ::callout{type="info"} If after signing in you see **Conta por associar** (Account not linked), your session isn't linked to a Diska profile yet. Click **Tentar novamente** (Try again); if you were invited, accept the invitation from the email you received, or ask an administrator to invite you with the same email address. :: ## 7. Roles | Role | What it can do | | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | **Proprietário** (Owner) | Everything an Administrator does, plus assigning the Owner role. | | **Administrador** (Administrator) | Manage the company, members, integrations and API keys; assign phone numbers to agents; archive agents; delete knowledge bases and recordings. | | **Membro** (Member) | Create, edit, test and publish agents; manage knowledge, actions and test suites. | | **Visualizador** (Viewer) | View agents, knowledge, actions, history and analytics; test agents and run tests. Can't edit or publish. | - Invitations only offer **Membro** and **Admin**. To give someone the **Visualizador** role, invite them as Membro and then change the role in the **Utilizadores** tab. - Only an Owner can assign the Owner role, and the organization always keeps at least one Owner. The full permission table is in [Organization and permissions](https://docs.diska.ai/en/concepts/organization). ::callout{type="tip"} Invite each person with the most restrictive role that does the job; you can always change it later. :: ## Next step With the organization ready, [create your first agent](https://docs.diska.ai/en/getting-started/first-agent). # Create your first agent This page is the overview. For the full walkthrough, screen by screen, follow the [Create your first agent](https://docs.diska.ai/en/guides/create-first-agent) guide. Under **Agentes** (Agents), click **Novo agente** (New agent). The menu offers four options: | Option | What for | | ----------------------------------------- | ----------------------------------------------------------------- | | **Voice Agent** | For voice calls and conversations. Creates an agent from scratch. | | **Chat Agent** | For messaging and live chat. Creates an agent from scratch. | | **Importar de JSON** (Import from JSON) | Load a configuration file exported from another agent. | | **Explorar templates** (Browse templates) | Start from a ready-made Diska template. | ## From a template ![Template gallery by industry, with industry and agent type filters](https://docs.diska.ai/images/docs/agents/agent-create-template.png) 1. Click **Novo agente → Explorar templates**. 2. In **Escolher template** (Choose template), filter by **Setor** (industry: Saúde, Imobiliário, Educação, Restauração, Retalho, Serviços, Seguros, Recrutamento, Hotelaria, Call Center), by **Inbound** or **Outbound**, or search by name. 3. Open a template to see its description, what the agent does, the persona and flow it includes and the tools it uses. 4. Under **Modo de edição** (Editing mode), choose **Prompt** (persona and instructions as text, no canvas) or **Flow Designer** (steps and connections in a visual flow). 5. Click **Instalar template** (Install template). The agent is created as a draft and the editor opens. ## From scratch 1. Click **Novo agente → Voice Agent**. 2. In **Escolha o tipo de agente** (Choose the agent type), choose **Inbound** (incoming calls), **Outbound** (outgoing calls) or **Voice Widget** (voice widget for your website) and click **Continuar** (Continue). 3. In **Escolha o modo de edição** (Choose the editing mode), choose **Prompt Builder** (a single prompt defines the behaviour) or **Flow Designer** (flows with nodes and conditions). 4. Click **Criar agente** (Create agent). The editor opens with the **Definições globais** (Global settings) panel open. **Chat Agent** skips the type choice and goes straight to the editing mode. ::callout{type="info"} The editing mode is chosen when you create the agent and can't be changed later in the editor. If in doubt, start with **Prompt Builder** : it is the quickest way to get an agent working. See [Voice agent](https://docs.diska.ai/en/concepts/agent) to compare types and modes. :: ## First adjustments In the editor, the agent's name, version (V1, V2…) and status are at the top. Changes save automatically; the indicator shows **Guardado às …** (Saved at …). - **Mensagem de saudação** (Greeting message, Prompt Builder): click **Configurar** (Configure) to choose whether the **Agente fala primeiro** (agent speaks first, with a fixed or generated message) or the **Humano fala primeiro** (human speaks first). - **Prompt** or **flow**: write the agent's instructions or design the flow on the canvas. See [Prompt Builder](https://docs.diska.ai/en/concepts/prompt-builder) and [Flow Builder](https://docs.diska.ai/en/flow-builder). - **Definições** (Settings): language, voice, call configuration, knowledge and security (call recording and personal data redaction). - **Ações** (Actions, Prompt Builder) or action nodes (Flow Designer): attach bookings, transfers, SMS or custom actions you created under [Actions](https://docs.diska.ai/en/actions). The **Lista de verificação** (Checklist) button at the top of the editor shows what is still missing (for example, an empty prompt or no phone number) and takes you to the right place. ## Test and publish 1. Test the agent with **Testar → Chamada web** (Test → Web call). See [Run a test call](https://docs.diska.ai/en/getting-started/test-call). 2. Click **Publicar** (Publish), give a **Nome da versão** (version name, optional) and review the changes against the last published version. 3. Confirm with **Publicar**. The agent becomes **Ativo** (Active) and the new version starts answering real traffic. The **Publicar** button is only enabled when there are unpublished changes. A Prompt-mode agent with an empty prompt, or a flow with validation errors, is not published. More in [Publish an agent](https://docs.diska.ai/en/guides/publish-agent). ## Connect a channel After publishing, open **Publicação** (Publishing) at the top of the editor to connect the agent to a channel: - **Telefone** (Phone) — assign a DISKA number or your SIP number (owners and administrators only). See [Telephony](https://docs.diska.ai/en/telephony). - **Link público** (Public link) — enable a link anyone can open in the browser to talk to the agent. - **Widget** — copy the script that embeds the voice widget on your website. See [Embed the widget](https://docs.diska.ai/en/guides/embed-widget). - **API** — integrate the agent with your systems through the [DISKA API](https://docs.diska.ai/en/api/api-channel). To answer on WhatsApp, connect your account under **Definições → Integrações** (Settings → Integrations) and pick a published Prompt-mode agent. See [WhatsApp](https://docs.diska.ai/en/whatsapp). ## Before you publish - The greeting is clear and short. - The agent doesn't reveal sensitive data and follows your organization's policies. - Transfers, SMS and bookings only fire when they should. - The call ends cleanly when the customer says goodbye. ## Next [Run a test call](https://docs.diska.ai/en/getting-started/test-call). # Run a test call In the agent editor, the **Testar** (Test) button opens the test panel in one of these modes: | Mode | What it does | Needs a number | | ----------------------------------- | --------------------------------------------------------------------------------------------- | -------------- | | **Chamada web** (Web call) | Talk to the agent by voice in the browser, using your microphone. | No | | **Chamada telefónica** (Phone call) | The agent calls your mobile from its DISKA number (**Ligar-me**, Call me). | Yes | | **Chat** | Exchange text messages with the agent. | No | | **Simulação** (Simulation) | Runs the agent's test suites: a simulated caller talks by text and each case passes or fails. | No | The same menu has **Abrir Centro de Testes** (Open Test Center), with every suite and run in the organization. For the detail of each mode, see the [Test the agent](https://docs.diska.ai/en/guides/test-agent) guide. ![Web call panel with caller contact and the Start test call button](https://docs.diska.ai/images/docs/agents/web-call-panel.png) ## Draft or published version With the test panel open, the editor shows the **Modo de teste · não é tráfego live** (Test mode · not live traffic) banner and a switch between **Rascunho** (Draft) and **Publicado** (Published): - **Rascunho** tests the changes not yet published. Actions are simulated: no real SMS goes out, nothing is booked in the calendar and the call isn't transferred. - **Publicado** tests the version that answers customers. Actions are real. The switch only lets you choose **Publicado** once the agent has been published at least once. ## Web call 1. Click **Testar → Chamada web**. 2. Optional: fill in **Contacto do chamador** (caller contact, used at the end of the call for SMS and variables) and the **Variável: …** fields for the agent's pre-call variables. 3. Click **Iniciar chamada de teste** (Start test call) and allow microphone access. 4. Talk to the agent. The transcript appears in the panel, labelled **Agente** (Agent) and **Você** (You). 5. Click **Terminar** (End). The panel shows the **Resultados pós-chamada** (post-call results): extracted data, evaluations, post-call SMS and executed actions. The test web call isn't recorded, even with **Gravar chamadas** (Record calls) enabled. ## Phone call The agent calls your mobile from the DISKA number assigned to it, just like a real call. 1. Click **Testar → Chamada telefónica**. 2. Under **Versão do agente** (Agent version), choose **Rascunho — ações simuladas** (draft, simulated actions) or the published version (**ações reais**, real actions). 3. Check the number under **Chamada de** (Call from) — the agent's number. 4. Under **Ligar para** (Call), enter your Angolan mobile (Africell or Unitel), 9 digits, for example 923 000 000. 5. Click **Ligar-me** and answer. The panel shows the state (ringing, in call, ended) and a **Desligar** (Hang up) button. To use this mode: - the agent must have an active DISKA number and have been published at least once; - the organization must be enabled for outgoing phone calls; - you can only have one test call in progress at a time, and there is an hourly limit on test calls. The call uses real minutes on the DISKA line. How long your mobile rings follows the **Duração do toque** (Ring duration), and the duration limit follows the **Configuração de chamada** (Call configuration) of the version under test. If **Gravar chamadas** is enabled, the call is recorded (the first 27 minutes). See [Phone calls](https://docs.diska.ai/en/telephony/phone-calls). ## Chat Click **Testar → Chat**, type a message and send it. Use **Novo chat** (New chat) to start over. It is the quickest way to check answers and knowledge without audio. ## Simulation Choose **Testar → Simulação** to see the agent's test suites. Create one with **Suite**, generate cases with **Gerar com IA** (Generate with AI) and click **Executar** (Run): each case shows whether it passed and why. See [Test the agent](https://docs.diska.ai/en/guides/test-agent#simulation). ## What to check - The greeting is clear and arrives on time. - The agent handles interruptions well. - The data the agent should collect is collected correctly. - Transfers, SMS and bookings only fire when they should. - The call ends cleanly when the customer says goodbye. ::callout{type="info"} Real calls (phone, widget, public link, WhatsApp) always use the **published** version. After testing the draft, publish so the changes reach your customers. :: ## Next - [Publish an agent](https://docs.diska.ai/en/guides/publish-agent) - Build test suites in the [Test Center](https://docs.diska.ai/en/test-center). - Go deeper into flow logic in the [Flow Builder](https://docs.diska.ai/en/flow-builder). # Getting started This section takes you from signing up for Diska to your first test call. It follows the same order as the **Primeiros passos** (First steps) list that the backoffice shows on the **Visão geral** (Overview) page of a new organization: 1. **Create the first agent** — from a template or from scratch. 2. **Run a test call** — the web call runs in the browser, no number needed. 3. **Publish the agent** — publishing fixes the version that answers real calls. 4. **Assign a number** — only needed for phone calls. ::card-group :::card --- description: Create an account, sign in, review company details and invite the team. icon: i-lucide-settings title: Initial setup to: https://docs.diska.ai/en/getting-started/initial-setup --- ::: :::card --- description: Pick a template or start from scratch, in Prompt or Flow mode. icon: i-lucide-bot title: Create your first agent to: https://docs.diska.ai/en/getting-started/first-agent --- ::: :::card --- description: Test by web call, chat, phone call or simulation. icon: i-lucide-phone title: Run a test call to: https://docs.diska.ai/en/getting-started/test-call --- ::: :: # Voice agent An **agent** is the AI assistant that talks to your customers. It brings together instructions (a prompt or a flow), a greeting, a voice, call settings, knowledge and actions, and it is published in versions that the channels use. ## Components | Component | Where it's configured | What it defines | | --------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Instructions | Editor: **Prompt** or the flow canvas | Who the agent is, the goal, the tone and the limits; in Flow Designer, the conversation steps. | | Greeting | **Mensagem de saudação** (Prompt) or the **Saudação** node (Flow) | Whether the agent speaks first or waits for the customer. | | Global settings | **Definições** (Settings) | Language, voice, call configuration, knowledge and memory, security and compliance (recording and personal data redaction). | | Actions | **Ações** (Prompt) or flow nodes and steps (Flow) | Book, transfer, send SMS, call APIs, extract data and evaluate the call. See [Actions](https://docs.diska.ai/en/actions). | | Variables | **Variáveis** (Variables) | System variables, pre-call variables (received before the call starts) and action results. See [Variables](https://docs.diska.ai/en/flow-builder/variables). | | Knowledge | **Definições → Conhecimento e memória** (Knowledge and memory) | Assigned knowledge bases and free-text notes. See [Knowledge base](https://docs.diska.ai/en/knowledge-base). | | Channels | **Publicação** (Publishing) | Phone, public link, widget and API. | ## Agent types The type is chosen when you create the agent and shows at the top of the editor and in the agent list. | Type | In the backoffice | What for | | ---------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | **Inbound** | “Para chamadas recebidas.” (For incoming calls.) | Answer customers who call the agent's number, open the public link or use the widget. | | **Outbound** | “Para chamadas efetuadas.” (For outgoing calls.) | Calls the agent places, such as follow-ups and reminders. | | **Voice Widget** | “Widget de voz para o seu site.” (Voice widget for your website.) | An agent whose main channel is the widget on your website; **Publicação** opens straight on the **Widget** tab. | | **Chat** | “Para mensagens e live chat.” (For messaging and live chat.) | Text conversations. Created with **Novo agente → Chat Agent**. | ::callout{type="info"} Today, an **Outbound** agent can be tested with the test panel's **Chamada telefónica** (Phone call), where the agent calls your mobile. Outgoing calls require the organization to be enabled for outgoing phone calls, and they can't yet be started from the backoffice or the DISKA API. See [Phone calls](https://docs.diska.ai/en/telephony/phone-calls) . :: ## Editing modes | Mode | How it works | When to use it | | ------------------ | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | **Prompt Builder** | A single prompt, with a greeting, settings and actions attached per phase, drives the whole conversation. | Open conversations, FAQs, simple qualification. The quickest way to start. See [Prompt Builder](https://docs.diska.ai/en/concepts/prompt-builder). | | **Flow Designer** | A visual flow of nodes, conditions and subflows, with actions at specific steps. | Conversations with stages, branching, validated data collection or transfers at defined points. See [Flow](https://docs.diska.ai/en/concepts/flow). | The mode is chosen when you create the agent (or install a template) and doesn't change afterwards. Only Prompt-mode agents can be connected to WhatsApp, and the test panel's **Simulação** (Simulation) only exists in Flow Designer mode. ## Versions and publishing - What you edit lives in a **draft**. Changes save automatically and don't affect customers. - **Publicar** (Publish) freezes the draft into a new version (V1, V2…). In Flow Designer mode it publishes the main flow and the subflows it reaches. - Real calls and conversations always use the **published version**. Test panel tests can use the draft or the published version. - Under **Versões** (**Histórico de versões**, version history) you see each version's name, date and author, and you can **Ver alterações** (View changes), **Exportar para JSON** (Export to JSON), **Restaurar esta versão** (Restore this version — the draft becomes identical to that version; publish to put it live) or **Descartar rascunho** (Discard draft). See [Publish an agent](https://docs.diska.ai/en/guides/publish-agent). ## Statuses | Status | Meaning | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Rascunho** (Draft) | The agent hasn't been published yet (or was restored from the archive). You can edit and test it. | | **Ativo** (Active) | The agent has a published version, which answers real traffic. | | **Inativo** (Inactive) | The agent isn't available; it can't be connected to WhatsApp. This status isn't set from the editor. | | **Arquivado** (Archived) | The agent leaves the usual list and can't be edited. Find it with the **Arquivado** filter and bring it back to **Rascunho** with **Restaurar agente** (Restore agent). | The **Estado** (Status) field under **Definições → Geral** (Settings → General) is read-only: it changes when you publish or archive. Only owners and administrators archive and restore agents. ## Other operations In each agent's menu (agent list, or **⋮** in the editor): - **Registos de chamadas** (Call logs) — opens **Históricos** (History) filtered by that agent; - **Copiar ID** (Copy ID) — the agent's identifier, useful for the API and support; - **Duplicar** (Duplicate) — creates a copy of the agent; - **Exportar para JSON** (Export to JSON) — downloads the configuration, which you can import into another organization with **Importar de JSON**; - **Arquivar** (Archive) — takes the agent out of use (reversible). # Flow In a **Flow Designer** agent, a **flow** is a graph of nodes that describes the conversation step by step: what the agent says, what it asks, which path it follows depending on the answer and which actions it runs. ## Main flow and subflows Each agent has a **Fluxo principal** (Main flow) and can have subflows, each in its own tab above the canvas (**+** creates a new one). A subflow is a reusable block within the agent: its **Condições de entrada** (Entry conditions) define when it can be activated, and the **Disparar subfluxo** (Trigger subflow) node takes the conversation there. The main flow remains the agent's entry point. When you publish, Diska publishes the main flow and the subflows it reaches. ## Required structure The main flow always starts like this: ```text Fluxo principal → Antes da conversa → Saudação → next step ``` and each **Terminar chamada** (End call) connects to its own **Depois da conversa** (After the conversation) marker. A subflow starts with `Subfluxo → Condições de entrada`. These nodes are structural and can't be deleted. - **Antes da conversa** (Before the conversation) runs before the conversation starts. You can attach an **Acção personalizada** (Custom action, to load context) or a **Tratamento IVR** (IVR handling, to navigate voice menus on an outgoing call). - **Depois da conversa** (After the conversation) runs after the call ends. You can attach **SMS pós-chamada** (Post-call SMS), **Extrator de informação** (Information extractor) and **Avaliação personalizada** (Custom evaluation). ## Node types The node picker groups the types by category: | Category | Nodes | What for | | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | | Conversação (Conversation) | [Conversação](https://docs.diska.ai/en/nodes/conversation), [Mensagem](https://docs.diska.ai/en/nodes/message), [Terminar chamada](https://docs.diska.ai/en/nodes/end-call) | Drive the dialogue and collect data, say an exact message, end the call. | | Controlo de fluxo (Flow control) | [Disparar subfluxo](https://docs.diska.ai/en/nodes/trigger-subflow), [Dividir o caminho](https://docs.diska.ai/en/nodes/split-path), [Saltar para](https://docs.diska.ai/en/nodes/jump-to) | Move to a subflow, branch on conditions, jump to another node. | | Acções (Actions) | [Acção personalizada](https://docs.diska.ai/en/nodes/custom-action), [Enviar SMS durante a chamada](https://docs.diska.ai/en/nodes/send-sms-during-call) | Call an API and use the response, send an SMS while the call is in progress. | | Transferência humana (Human handoff) | [Transferência](https://docs.diska.ai/en/nodes/transfer) | Transfer the call to a person or team. | | Negócio (Business) | [Agendamento](https://docs.diska.ai/en/nodes/booking) | Book or reschedule a meeting in the calendar. | On the canvas, the **Dividir o caminho** (Split the path) node shows as **Condição** (Condition). The types marked as coming soon in the picker (Espera, Ciclo, Definir variável, Enviar WhatsApp durante a chamada, Enviar email) can't be inserted yet; see [Coming soon](https://docs.diska.ai/en/nodes/coming-soon). ### Transfer The **Transferência** (Transfer) node transfers phone calls: the customer's line moves to the destination number. It can also be a warm transfer, where the person who answers first hears, in the agent's voice, the reason for the call or a summary of it. A web call has no phone line to transfer, so the node takes the failure path. On phone lines the destination must be a number; a queue isn't accepted. See [Transfer to a human](https://docs.diska.ai/en/guides/transfer-to-human). ## Connection rules The canvas only accepts valid connections and explains why when it refuses one. The main ones: - **Fluxo principal** only connects to **Antes da conversa**. - **Antes da conversa** connects to the **Saudação** (Greeting) or to a pre-conversation step (for example, an action). - The **Saudação** doesn't collect an answer, so it can't connect directly to a **Condição**: put a **Conversação** node first. - A **Conversação** reaches the next one through an exit condition, never through a direct connection. - **Terminar chamada** only connects to **Depois da conversa**, which has no outgoing connection. The full table is in [Flow structure](https://docs.diska.ai/en/flow-builder/structure). Before publishing, the editor's checklist and the server-side validation point out errors in the flow; an invalid flow isn't published. See [Validation and publishing](https://docs.diska.ai/en/flow-builder/validation-publishing). # Runtime The **runtime** is the part of the platform that makes the agent talk: it opens the voice session, follows the prompt or the flow, runs the actions and, at the end, records the call in **Históricos** (History). ## Which version answers - Real calls and conversations always use the agent's **published version**. - Tests from the **Testar** (Test) panel use the draft or the published version, as you choose. On the draft, actions are simulated. See [Run a test call](https://docs.diska.ai/en/getting-started/test-call). ## Channels | Channel | How it reaches the agent | In History | | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | | Web call | Through the browser: a test in the editor, the [widget](https://docs.diska.ai/en/guides/embed-widget) on your website or the public link. | **Web Call** | | Phone | A customer calls the agent's number (a DISKA number or your own number over SIP), or the agent places the call, as in the test call to your mobile. | **Telefone** (Phone) | | WhatsApp | Messages to your WhatsApp Business account, answered by a published Prompt-mode agent. | **WhatsApp** (its own tab) | The [DISKA API](https://docs.diska.ai/en/api/api-channel) gives your systems access to agents, calls, analytics, numbers and knowledge; once DISKA switches the feature on, it also starts outbound calls. ## Call lifecycle Each call appears under **Históricos → Chamadas** (History → Calls) with one of these statuses: | Status | Meaning | | ------------------------------ | ---------------------------------------------------------------------------------------------------- | | **Criada** (Created) | The session was opened; the conversation hasn't started yet. | | **Em progresso** (In progress) | The conversation is under way. | | **Concluída** (Completed) | The call ended normally. | | **Falhou** (Failed) | The call ended because of a technical problem (microphone, network or connection). | | **Cancelada** (Cancelled) | The session was replaced by another one before it ended (for example, on a new connection attempt). | | **Abandonada** (Abandoned) | The session stopped responding (for example, the browser tab was closed) and the platform closed it. | ## During the call 1. **Opening** — the agent says the greeting, or waits for the customer to speak first, depending on the configuration. 2. **Conversation** — the agent listens, answers and follows the prompt or the flow. **Paciência** (Patience, under **Definições → Voz**) sets how much silence ends the customer's turn. 3. **Actions** — the agent uses the actions available at that point: book, transfer, send SMS, call APIs, consult knowledge. 4. **End** — the agent ends the call when the customer asks, when the task is done, after inactivity or on an error. On phone calls the agent's **Configuração de chamada** (Call configuration) also applies: - **Duração do toque** (Ring duration, 10–60 s) — how long the mobile rings on calls the agent places; - **Limitar duração da chamada** (Limit call duration, 1–240 min) — the phone call is hung up when it reaches the maximum, unless it has already been transferred to a person. See [Call settings](https://docs.diska.ai/en/telephony/call-settings). ## When the call ends After hang-up, Diska processes the call in this order: 1. **Information extractors** pull the requested data out of the conversation (for example, name, email, reason). 2. **Custom evaluations** score the call against your criteria. 3. **Post-call SMS** are sent, using the collected data. 4. **Custom actions** in the “Depois da conversa” (After the conversation) phase call your APIs. 5. The transcript and a **summary** are stored in History and, if the agent has a **Webhook** in the “Depois da conversa” phase, Diska sends it the call data. If **Gravar chamadas** (Record calls) is enabled, the recording is available in History (on a phone call, the first 27 minutes). On draft tests, SMS and the webhook aren't sent: the test panel shows the simulated result. See [Actions](https://docs.diska.ai/en/actions) and [Recordings](https://docs.diska.ai/en/history/recordings). ## Voice engines You choose the engine under **Definições → Voz → Motor de voz** (Settings → Voice → Voice engine); the section then shows that engine's fields. Changing the engine changes the voice: draft tests use it right away, calls once you publish. - **Grok Voice 3.0** is the engine new agents start on (voice **Celeste**, high reasoning), for prompt and Flow Designer agents and on every channel. The section shows **Voz Grok** (Grok voice), **Velocidade da fala** (speech speed), **Variedade da fala** (speech variety), **Raciocínio** (reasoning), **Termos-chave da transcrição** (transcription key terms — names and brands the engine should recognise) and **Pronúncias** (pronunciations, for example `Kz = kwanzas`). - **GPT-Live**, with native full-duplex conversation, remains available. You choose the voice under **Voz GPT-Live**: **Bossa** (female voice) or **Tempo** (male voice), both native Portuguese voices. The voice stays the same for the whole call; the agent's instructions keep the European Portuguese accent. An agent that never chose an engine uses GPT-Live. - Older agents may show another engine, depending on how they were configured. The **Idioma** (Language) is Português (Portugal) and the **Fuso horário** (Time zone) is África/Luanda, set by the platform. # Organization and permissions In Diska, each company works in an **organization**. The organization has its own agents, flows, knowledge, actions, numbers, history, integrations, API keys and members, isolated from other organizations: data from different organizations never mixes. ## Structure ```text Organization ├── Agents (with their flows and versions) ├── Knowledge ├── Actions ├── Numbers ├── History and Analytics ├── Test Center ├── Integrations (including WhatsApp) ├── API keys └── Members and invitations ``` ## One organization or several - When you create an account, Diska creates an organization for you and makes you its **Proprietário** (Owner). On your first visit, the **Bem-vindo à Diska** (Welcome to Diska) screen asks for the company name; you can change it later under **Definições → Empresa** (Settings → Company). - When you accept an invitation, you become a member of another organization, with the role given in the invitation. If you created the account only for that, the empty organization from signup is archived. - If you belong to several organizations, switch organization in the menu at the top of the sidebar. You always work in one active organization at a time: everything you see and create belongs to that organization. ## Roles | Role | Summary | | --------------------------------- | --------------------------------------------------------------------------------- | | **Proprietário** (Owner) | Full control, including assigning the Owner role. | | **Administrador** (Administrator) | Runs the company: settings, members, integrations, API keys and numbers. | | **Membro** (Member) | Builds: creates, edits, tests and publishes agents, knowledge, actions and tests. | | **Visualizador** (Viewer) | Views and tests, without changing anything. | In invitations, the **Administrador** role shows as **Admin**. Invitations only offer Membro and Admin; the Visualizador role is assigned afterwards, under **Definições → Membros** (Settings → Members). Only an Owner assigns the Owner role, and the organization always keeps at least one. ## Permissions | What you can do | Owner | Administrator | Member | Viewer | | ---------------------------------------------------------------------------- | :---: | :-----------: | :----: | :----: | | View agents, knowledge, actions, numbers, history, analytics and test suites | ✓ | ✓ | ✓ | ✓ | | Test agents (web call, chat, phone call, simulation) and run test suites | ✓ | ✓ | ✓ | ✓ | | Create, edit, duplicate, import, export and publish agents | ✓ | ✓ | ✓ | — | | Create and edit knowledge bases | ✓ | ✓ | ✓ | — | | See Shared memory (groups, contacts and memories) | ✓ | ✓ | ✓ | ✓ | | Create and edit memory groups, contacts and memories | ✓ | ✓ | ✓ | — | | Create and edit actions | ✓ | ✓ | ✓ | — | | Create and edit test suites | ✓ | ✓ | ✓ | — | | Take over, hand back to the AI and resolve WhatsApp conversations | ✓ | ✓ | ✓ | — | | Archive and restore agents | ✓ | ✓ | — | — | | Buy, import and assign phone numbers | ✓ | ✓ | — | — | | Delete knowledge bases | ✓ | ✓ | — | — | | Delete memory groups | ✓ | ✓ | — | — | | Delete call recordings | ✓ | ✓ | — | — | | Edit Company, Organization, Integrations and API keys | ✓ | ✓ | — | — | | Invite members, change roles and remove members | ✓ | ✓ | — | — | | Assign the Owner role | ✓ | — | — | — | The backoffice only shows the menus and buttons your role allows. For example, a Member doesn't see **Empresa**, **Organização**, **Integrações**, **Chaves API** or **Membros** under **Definições**. More in [Members](https://docs.diska.ai/en/settings/members). ## Session and access You sign in with email and password or with Google. Every request the backoffice makes carries the active organization, and the platform checks on every request that you are a member of that organization and that your role allows the operation. If your access to an organization is removed, the backoffice stops showing it. [API keys](https://docs.diska.ai/en/settings/api-keys) authenticate a system, not a person: each key belongs to one organization and only gives access to the [DISKA API](https://docs.diska.ai/en/api/authentication), never to the backoffice. # Prompt Builder A **Prompt Builder** agent is driven by a single **prompt**: the system instruction that tells the agent who it is, what it must achieve and what it must never do. You choose this mode when you create the agent (or install a template in **Prompt** mode). It is the quickest way to get an agent working. ## The editor screen - **Mensagem de saudação** (Greeting message) — click **Configurar**(Configure) to choose: - **Agente fala primeiro** (Agent speaks first): the agent opens the call with the **Mensagem** (message) you write; leave it empty for the agent to generate the greeting; - **Humano fala primeiro** (Human speaks first): the agent waits for the person to speak (**Tempo de espera**, wait time, 1 to 10 seconds) and answers with a **Mensagem gerada pelo LLM** (LLM-generated message) or a **Mensagem fixa** (fixed message). - **Prompt** — the text of the instructions. It saves automatically as you type. - At the top: **Ações** (Actions), **Variáveis** (Variables), **Versões** (Versions), **Definições** (Settings), **Publicação** (Publishing), **Testar** (Test) and **Publicar** (Publish). ## What the agent receives During the call, the agent receives the prompt completed by these sections, when filled in: | Source | Where it's configured | What for | | ---------------------------- | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | Greeting | **Mensagem de saudação** | How the call opens. | | Personality and context | **Definições → Personalidade e objeções** (Personality and objections) | Who the agent is, what it does, its tone of voice and permanent rules. | | Objections and special cases | **Definições → Personalidade e objeções** | How to answer objections and special situations (for example, “if they ask whether you are an AI…”). | | Knowledge notes | **Definições → Conhecimento e memória** (Knowledge and memory) | Short facts and answers to frequent questions, as free text. | | Knowledge bases | **Definições → Conhecimento e memória** | The assigned bases, searched during the call. Tick them and click **Guardar atribuições** (Save assignments). | | Attached actions | **Ações** | When and how to use each attached action. | Changes reach real calls when you publish a new version; until then, test them on the draft. See [Knowledge base](https://docs.diska.ai/en/knowledge-base). ## Actions per phase The **Ações** button opens the **Acções** (Actions) panel, split into three phases. In each phase, **Adicionar** (Add) lists the available types; picking one lets you select an action already created under [Actions](https://docs.diska.ai/en/actions) (the **Abrir Acções** shortcut takes you there if you don't have one yet). | Phase | When it runs | Types | | ------------------------------------------------ | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Antes da conversa** (Before the conversation) | Before the conversation starts. | Acção personalizada (custom action), Tratamento IVR (IVR handling) | | **Durante a conversa** (During the conversation) | When the agent decides to use it. | Agendamento em tempo real (real-time booking), Transferência de chamada (call transfer), Acção personalizada, SMS durante a chamada (during-call SMS) | | **Depois da conversa** (After the conversation) | After the call ends. | SMS pós-chamada (post-call SMS), Extrator de informação (information extractor), Avaliação personalizada (custom evaluation), Acção personalizada, Webhook | - **Tratamento IVR** navigates voice menus (DTMF keys) on outgoing phone calls. See [IVR](https://docs.diska.ai/en/actions/ivr). - **Transferência de chamada** transfers phone calls, including warm transfers. See [Call transfers](https://docs.diska.ai/en/actions/call-transfers). - **Webhook** sends the call data to the URL you enter, after the call. - **WhatsApp durante a chamada** (WhatsApp during the call) and **Conectores MCP** (MCP connectors) show as **Em breve** (Coming soon). Click an attached booking to see its **Variáveis de saída** (output variables) and choose how each **Variável de entrada** (input variable) is obtained: collected by the agent during the call, taken from a variable, or set to a fixed value. ## Variables The **Variáveis** panel lists: - **Variáveis de sistema** (System variables) — provided by the platform; they can't be edited; - **Variáveis pré-chamada** (Pre-call variables) — received before the call starts; add them with a name and a description. In tests, the **Testar** panel shows a **Variável: …** field for each one; - **Resultados de ações** (Action results) — filled in by the actions' responses. ## Writing a good prompt - Say who the agent is, what it must achieve in this call and what it must never do. - Write in Portuguese, the language the agent speaks. - Prefer short, imperative rules to long paragraphs. - Don't paste whole documents into the prompt: assign a [knowledge base](https://docs.diska.ai/en/knowledge-base) and use knowledge notes only for short facts. - Say when to use each action (for example, “transfer to a human if the customer asks to speak to a person”). ## Testing Use **Testar → Chamada web** (Test → Web call) for a voice call in the browser, or **Testar → Chat** for a quick text exchange, on the draft or the published version. See [Test the agent](https://docs.diska.ai/en/guides/test-agent). ::callout{type="tip"} If the conversation needs fixed stages, branching or validated data collection, create the agent in **Flow Designer** mode: the mode is chosen when you create the agent and doesn't change afterwards. See [Flow](https://docs.diska.ai/en/concepts/flow) . :: # Concepts Before going deeper into the Flow Builder, actions or the API, get familiar with the vocabulary used throughout the documentation. ::card-group :::card --- description: Types, editing modes, versions and statuses of an agent. icon: i-lucide-bot title: Voice agent to: https://docs.diska.ai/en/concepts/agent --- ::: :::card --- description: Drive the agent with a prompt, personality, knowledge notes and actions per phase. icon: i-lucide-file-text title: Prompt Builder to: https://docs.diska.ai/en/concepts/prompt-builder --- ::: :::card --- description: Flow structure, node types, subflows and connection rules. icon: i-lucide-git-branch title: Flow to: https://docs.diska.ai/en/concepts/flow --- ::: :::card --- description: Channels, the call lifecycle, what happens at the end and voice engines. icon: i-lucide-zap title: Runtime to: https://docs.diska.ai/en/concepts/runtime --- ::: :::card --- description: Organizations, roles and what each role can do. icon: i-lucide-building-2 title: Organization and permissions to: https://docs.diska.ai/en/concepts/organization --- ::: :: # Create your first agent step by step An agent combines a voice, instructions (a prompt or a flow), the actions it can run and the channels it answers on. This guide takes you from nothing to the first published version. ![Agent list with type, version, status and last edit](https://docs.diska.ai/images/docs/agents/agents-list.png) ## Step 1. Create the agent 1. In the side menu, open **Agentes** (Agents) and click **Novo agente** (New agent). 2. Pick one of the options: | Option | What for | | ----------------------------------------- | ------------------------------------------------------ | | **Voice Agent** | An agent for voice calls and conversations. | | **Chat Agent** | An agent for messaging and live chat. | | **Importar de JSON** (Import from JSON) | Load a configuration file exported from another agent. | | **Explorar templates** (Browse templates) | Start from a ready-made Diska template. | 3. For a **Voice Agent**, choose the type and click **Continuar**(Continue): - **Inbound** — answers incoming calls; - **Outbound** — places calls; - **Voice Widget** — a voice widget for your website. 4. Choose the editing mode and click **Criar agente**(Create agent): - **Prompt Builder** — a single prompt defines the agent's behaviour; - **Flow Designer** — you design the conversation as a flow of nodes and conditions. The agent editor opens with the **Definições** (Settings) panel open. ::callout{type="tip"} With **Explorar templates** you can filter by industry (Healthcare, Real estate, Education, Restaurants and more) and by Inbound/Outbound. The preview shows what the agent does and the persona, flow and tools included; choose **Prompt** or **Flow Designer** and click **Instalar template** (Install template). :: ## Step 2. Review the settings The **Definições** button in the agent toolbar opens the global settings, organised in sections: | Section | What it configures | | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Geral** (General) | Language: **Multilingue** (Multilingual) — the agent answers in the caller's language and starts in European Portuguese. The time zone (Africa/Luanda) is set by the platform. Who the agent is, its tone and objection handling are written in the **Prompt**. | | **Voz** (Voice) | The agent's engine and voice (new agents start on **Grok Voice 3.0**, with the **Celeste** voice; **GPT-Live** offers **Bossa**, female, and **Tempo**, male) and **Paciência** (Patience) — how much silence ends the caller's turn (Low, Medium or High). | | **Configuração de chamada** (Call settings) | Ring time for calls the agent places and the duration limit for phone calls. | | **Motivos de fim de chamada** (End-of-call reasons) | The reasons the agent can report when it ends a call (set by the system). | | **Conhecimento e memória** (Knowledge and memory) | The knowledge bases the agent consults, plus free-text notes. | | **Segurança e conformidade** (Security and compliance) | Call recording, the notice to the caller and retention — see [Record calls](https://docs.diska.ai/en/guides/record-calls) — and **Ocultar dados pessoais (PII)** (Redact personal data) — see [Redact personal data](https://docs.diska.ai/en/guides/redact-personal-data). | Changes are saved automatically: the indicator at the top right shows **Guardado às …** (Saved at …) when they finish. There is no Save button. ## Step 3. Write the behaviour **In the Prompt Builder:** 1. Under **Mensagem de saudação** (Greeting message), click **Configurar** and choose **Agente fala primeiro** (Agent speaks first, with a generated or fixed message) or **Humano fala primeiro** (Human speaks first — the agent waits for the person to speak). 2. Write the instructions in the **Prompt** editor: goal, tone, information to collect and limits. 3. Open **Ações** (Actions) in the agent toolbar to attach actions (bookings, transfers, SMS, extractors) — see the following guides. **In the Flow Designer:** The canvas opens with the required structure `Fluxo principal → Antes da conversa → Mensagem de saudação` (Main flow → Before the conversation → Greeting message) and a **+** button below it. Click **+** to add the first step. The [Use the Flow Builder](https://docs.diska.ai/en/guides/use-flow-builder) guide covers the rest. ## Step 4. Add knowledge (optional) If the agent must answer from your documents or your website: 1. Create a base under **Conhecimento** (Knowledge) in the side menu and add sources — see [Knowledge base](https://docs.diska.ai/en/knowledge-base). 2. In the agent, open **Definições → Conhecimento e memória**, select the base and click **Guardar atribuições** (Save assignments). ## Step 5. Test Click **Testar → Chamada web** (Test → Web call) and then **Iniciar chamada de teste** (Start test call). The browser asks for microphone access and you can talk to the agent's draft. See [Test an agent](https://docs.diska.ai/en/guides/test-agent) for the other modes, including a call to your own mobile. ## Step 6. Publish When the draft is ready, click **Publicar** (Publish), name the version (optional) and confirm. The published version is the one that answers on the phone, the public link and the widget. See [Publish and receive calls](https://docs.diska.ai/en/guides/publish-agent). ::callout{type="info"} Creating and editing agents requires the Owner, Administrator or Member role. A Viewer can open and test agents but not change them. :: # Use the Flow Builder The Flow Builder is the visual editor for agents created in **Flow Designer** mode. Every agent has a **Fluxo principal** (Main flow) and can have subflows. This guide covers the essentials; the [Flow Builder](https://docs.diska.ai/en/flow-builder) section has the full reference. ## The starting point A new agent opens with the required Main flow structure: ```text Fluxo principal → Antes da conversa → Mensagem de saudação → + ``` - **Fluxo principal** (Main flow) — where the call enters. - **Antes da conversa** (Before the conversation) — steps that run before the greeting (for example, an action that looks the caller up in your CRM). - **Mensagem de saudação** (Greeting message) — the first turn: who speaks first and what is said. - **+** — where you connect the first real step. These structural nodes cannot be deleted. ## Step 1. Add a step 1. Click **+** (**Adicionar próximo passo**, Add next step). 2. Search for or pick the node type. Nodes are grouped into **Conversação** (Conversation), **Controlo de fluxo** (Flow control), **Acções** (Actions), **Transferência humana** (Human handoff) and **Negócio** (Business). 3. A node that cannot follow the current step is shown as **Inválido** (Invalid), with the reason. ## Step 2. Configure the node Click a node to open its configuration panel next to the canvas. For example, in a **Conversação** node you write the step's **Instruções** (Instructions) and, under **Recolher variáveis** (Collect variables), the information the agent must obtain (name, phone, email…). ## Step 3. Branch the conversation Every **Conversação** node is automatically followed by a **Condição** (Condition) with a **Continuar** (Continue) path that moves the conversation forward. To create alternatives, add paths to the condition: - **Prompt LLM** — describe in plain language when to take the path (e.g. "the caller wants to speak to a person"); - **Regra determinística** (Deterministic rule) — compare a variable with a value (e.g. `plan` equals `premium`). Action nodes (**Acção personalizada**, **Enviar SMS durante a chamada**, **Transferência**, **Agendamento** — custom action, SMS during the call, transfer, booking) have two exits: **Sucesso da acção** (Action success) and **Falha da acção** (Action failure). Connect both. ## Step 4. End the call Every path must end in a **Terminar chamada** (End call) node, with an end reason and a farewell. Without at least one reachable **Terminar chamada**, the flow cannot be published. ## Step 5. Reuse logic with subflows 1. Click **+** to the right of the canvas tabs to create a subflow. 2. In the **Condições de entrada** (Entry conditions) node, define when the subflow can be activated. 3. In the Main flow, use a **Disparar subfluxo** (Trigger subflow) node to enter it. Each subflow tab offers **Renomear** (Rename), **Duplicar** (Duplicate) and **Apagar** (Delete). ## Useful shortcuts | Shortcut | Action | | --------------------------- | ------------------------------ | | `Ctrl/⌘ + K` | Search nodes | | `Ctrl/⌘ + C` / `Ctrl/⌘ + V` | Copy / paste the selected node | | `Ctrl/⌘ + D` | Duplicate the selected node | | `Ctrl/⌘ + Z` | Undo | | `Ctrl/⌘ + Shift + Z` | Redo | | `Ctrl/⌘ + 0` | Fit the flow to the screen | | `Backspace` | Delete the selected node | ## Validate and publish The Flow Builder saves automatically and validates the flow as you edit. The **Lista de verificação** (Checklist) button in the agent toolbar shows the number of issues; click an issue to jump to the node. Errors block publishing; warnings do not. When there are no errors, click **Publicar** (Publish). See [Validation and publishing](https://docs.diska.ai/en/flow-builder/validation-publishing) and [Test a flow](https://docs.diska.ai/en/flow-builder/testing). # Publish and receive calls While you edit, you are changing the agent's **draft**. Customers never talk to the draft: the phone, the public link, the widget and the API always serve the **published version**. Publishing is therefore the step that puts your changes into production. ## What publishing freezes Each publish creates a numbered version (V1, V2, …) containing: - the name, description, prompt and greeting message; - the agent settings (voice, call settings, recording and consent); - the attached actions and assigned knowledge bases; - the assigned phone number; - for Flow Designer agents, the Main flow and the subflows it reaches. Calls that start after you publish use the new version. ## Publish a version 1. In the agent editor, click **Publicar** (Publish). The button is disabled when there is nothing new to publish. 2. For a Flow Designer agent, the platform validates the flow first and opens the **Lista de verificação** (Checklist). Errors block publishing; fix them and try again. For a Prompt Builder agent, the prompt cannot be empty. 3. In the **Publicar** dialog, name the version (optional). Use **Mostrar alterações** (Show changes) to compare it with the last published version. 4. Click **Publicar**. Publishing requires the Owner, Administrator or Member role. ::callout{type="tip"} The **Versões** (Versions) panel shows the history. Each version's menu offers **Ver alterações** (View changes), **Exportar para JSON** (Export to JSON), **Descartar rascunho** (Discard draft) and **Restaurar esta versão** (Restore this version). Restoring only aligns the draft with that version — publish afterwards to put it into production. :: ## Publishing settings The **Publicação** (Publishing) button in the agent toolbar opens the **Definições de publicação** (Publishing settings), with one tab per channel: | Agent type | Tabs | | ----------------------- | ------------------------------------------------------------------------- | | Inbound, Outbound, Chat | **Telefone** (Phone), **Link público** (Public link), **Widget**, **API** | | Voice Widget | **Widget**, **WebSocket**, **API** | ### Phone Under **Número de telefone** (Phone number), click **Adicionar número de telefone** (Add phone number) and pick a number. The list shows your organization's active numbers, each with its status (for example **Configurado** — configured, **Sem agente** — no agent, or **Credenciais pendentes** — credentials pending). **Importar** (Import) opens the import of a SIP number from your own carrier. - Only **Owners** and **Administrators** can assign, change or remove numbers. - A number can be answered by only **one** Inbound agent. An Outbound agent uses the number as its caller ID, and several Outbound agents can share the same number. ::callout{type="warning"} **After assigning or changing the number, publish the agent.** The line only rings the agent once the assignment is in the published version, and it always answers with that version. :: Below the number are the agent's webhooks: **Inbound Webhook** (Inbound agents), which receives each call before the agent speaks and can give it facts about the caller, and **Data Webhook**, which receives each call's data when it ends. **Inicializar** (initialize) sends a test request. Like the number, they apply once the agent is published. See [Agent webhooks](https://docs.diska.ai/en/telephony/webhooks). To get numbers, see [Numbers](https://docs.diska.ai/en/telephony/numbers); for what happens during a call, see [Phone calls](https://docs.diska.ai/en/telephony/phone-calls). ### Public link The public link lets anyone talk to the published version of the agent in the browser, without a Diska account. 1. Publish the agent at least once — before that, **Ativar link público** (Enable public link) is disabled. 2. Click **Ativar link público**. 3. Copy the **Endereço para partilhar** (Address to share) or open it in a new window. The tab also shows the **Token público** (Public token) and the **Endpoint de sessão (API)** (Session endpoint), which you only need to integrate the agent into another player. - **Gerar novo link** (Generate new link) creates a new token: every link and widget code shared before stops working immediately. - **Desativar** (Disable) stops new calls through the link. The token is kept: when you re-enable, the same link works again. Managing the public link requires the Owner, Administrator or Member role. ### Widget The widget uses the same public channel. If it is not enabled yet, click **Ativar canal público** (Enable public channel). Then copy the code into your website and customise its look — see [Embed the voice widget](https://docs.diska.ai/en/guides/embed-widget). ### WebSocket Available on **Voice Widget** agents: under **Sessões em tempo real** (real-time sessions), it shows the public channel endpoint, the request the widget and the public link use to open the voice conversation. The session protocol is not a public contract; see [Realtime](https://docs.diska.ai/en/api/realtime). ### API Summarises what the [DISKA API](https://docs.diska.ai/en/api/api-channel) lets your backend do (agents, calls, analytics, numbers, knowledge and webhooks) and links to these docs with the **Começar com a API** (get started with the API) button. Text chat with the agent and outbound calls are also available through the API, once DISKA switches them on for the organization. ## Review calls Calls from every channel are stored under **Históricos** (Histories). From the agent, the **⋮ → Registos de chamadas** (Call logs) menu opens Histories already filtered by that agent. See [Calls](https://docs.diska.ai/en/history/calls). ::callout{type="info"} The **Número de telefone** warning in the Checklist does not block publishing: an agent without a number still works on the public link, the widget and the API. :: # Test an agent The **Testar** (Test) button in the agent editor opens the test panel with four modes — **Chamada web** (Web call), **Chamada telefónica** (Phone call), **Chat** and **Simulação** (Simulation) — and gives access to the **Centro de Testes** (Test Center). Every role in the organization, including Viewer, can test agents. ## Draft or published version While the test panel is open, a bar at the top of the editor reads **Modo de teste · não é tráfego live** (Test mode · not live traffic) and shows which version is under test: - **Rascunho** (Draft) — the changes you have not published yet; - **Publicado** (Published) — the version in production. Use the switch in the bar to change it. Until you publish the agent for the first time, you can only test the draft. ::callout{type="warning"} In the **Web call** and the **Phone call** , the draft runs actions in simulated mode, but the **published version runs them for real** : SMS messages are sent and bookings are created; on the phone call, transfers really dial the destination. **Chat** and **Simulation** never run real actions. :: ## Web call Talk to the agent in the browser, using your computer's microphone. 1. Click **Testar → Chamada web**. 2. Optional: fill in **Contacto do chamador** (Caller contact — used, for example, as the SMS recipient) and the **Variável: …** fields for the agent's pre-call variables. 3. Click **Iniciar chamada de teste** (Start test call) and allow the microphone. 4. Click **Terminar** (End) to hang up. The web test call is not connected to any phone line: if the agent tries to transfer, the transfer does not happen and the agent carries on with the conversation. This call is not recorded. ## Phone call The agent calls your mobile from its DISKA number. This is how you hear the agent exactly as a customer does. ### Requirements - Your organization must be enabled by Diska for outbound phone calls. - The agent must have been published at least once **with an active DISKA number assigned**. The call always comes from the published version's number, even when you test the draft. - Testing the **published version** (real actions) requires permission to execute actions: a **Visualizador** (viewer) can only test the draft, with simulated actions. - The destination must be an Angolan mobile (Africell or Unitel) with 9 digits — for example `923 000 000`. Only the +244 country code is available, and you cannot call the agent's own number. ### Make the call 1. Click **Testar → Chamada telefónica**. 2. Under **Versão do agente** (Agent version), choose **Rascunho — ações simuladas** (Draft — simulated actions) or the published version (for example, **V3 publicada — ações reais**, V3 published — real actions). 3. Check the number under **Chamada de** (Call from — the agent's number). 4. Under **Ligar para** (Call to), type your mobile number. 5. Fill in the pre-call variables, if the agent has any. 6. Click **Ligar-me** (Call me) and answer your phone. The status line follows the call: **A preparar a chamada…** (Preparing the call), **A tocar no …** (Ringing …), **Em chamada · m\:ss** (In call) and, at the end, **Chamada terminada** (Call ended). To hang up from the panel, click **Desligar** (Hang up). ::callout{type="info"} These are real DISKA line minutes. Your phone rings for the chosen version's **Duração do toque** (Ring time) and the call follows that version's duration limit — see [Call settings](https://docs.diska.ai/en/telephony/call-settings) . If **Gravar chamadas** (Record calls) is on, the call is recorded (the first 27 minutes) — see [Record calls](https://docs.diska.ai/en/guides/record-calls) . The call is stored under **Históricos** (Histories), like any other. :: ### Limits and messages | Message | What to do | | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | Indique um telemóvel angolano (Africell ou Unitel)… (Enter an Angolan mobile) | Fix the number: 9 digits, starting with 92–96. | | Esta organização ainda não está habilitada para chamadas telefónicas de saída. (Not enabled for outbound calls) | Ask Diska to enable outbound calls. | | Publique o agente uma vez para lhe atribuir o número que faz a chamada. (Publish the agent once) | Publish the agent. | | Atribua ao agente um número DISKA activo e publique-o para testar por telefone. (Assign an active DISKA number and publish) | Assign a DISKA number under **Publicação → Telefone** and publish. | | Indique o seu telemóvel, não o número do agente. (Your mobile, not the agent's number) | Use a different destination number. | | Já tem uma chamada de teste em curso. Termine-a antes de ligar de novo. (A test call is already in progress) | Each person can only have one test call at a time. | | Atingiu o limite de chamadas de teste desta hora. Tente mais tarde. (Hourly test call limit reached) | Each organization has a limit on test calls per hour. | | A organização atingiu o limite de chamadas em simultâneo. (Concurrent call limit reached) | Wait for another phone call to end. | | O número está ocupado, desligado ou rejeitou a chamada. / A chamada não foi atendida. (Busy, off or rejected / Not answered) | Check your phone and try again. | | A linha telefónica não está disponível neste momento. (Phone line unavailable) | Try again later; if it persists, contact support. | ## Chat Talk to the agent by text, without voice. For a Flow Designer agent, each message goes through the flow; for a Prompt Builder agent, the agent answers from its prompt. **Novo chat** (New chat) restarts the conversation. Chat never runs real actions. ## Simulation **Testar → Simulação** shows this agent's test suites — the same ones as in the [Test Center](https://docs.diska.ai/en/test-center), seen from the editor. A suite groups scenarios with success criteria: an AI-simulated caller talks to the agent by text and each case passes or fails. It works for both Prompt Builder and Flow Designer agents. The panel has two tabs: - **Suites de teste** (Test suites) — the agent's suites, with a search box and the **Suite** button to create one; - **Histórico** (History) — this agent's runs, with how many cases passed and the status. ### Create and run a suite 1. Click **Suite**. The suite is created for this agent, in its language, and opens empty. 2. Choose **Gerar com IA** (Generate with AI — tick the scenarios and the number of cases, then click **Gerar … casos de teste**) or **Criar caso personalizado** (Create custom case). 3. Review the cases: each one needs a **Prompt do cenário** (Scenario prompt) and at least one **Critério de sucesso** (Success criterion). 4. Click **Executar** (Run). **Testes iniciados.** (Tests started) appears and the run opens, with each case **Em curso** (Running) until it finishes. The run uses the version chosen in the test bar: **Rascunho** (Draft) or **Publicado** (Published). Click a finished case to see the criteria (**Visão geral**, Overview) and the conversation (**Transcrição**, Transcript). Everything you create here shows in the Test Center, and the other way round. **Abrir no Centro de Testes** (Open in the Test Center), at the bottom of the panel, opens it filtered to this agent. Each field and the evaluations are covered in [Test Center](https://docs.diska.ai/en/test-center). Every role can see and run suites; creating and editing suites and cases requires the Owner, Administrator or Member role. ::callout{type="tip"} To show the agent to someone outside your team, enable the [public link](https://docs.diska.ai/en/guides/publish-agent) — it works in the browser, without a Diska account. :: # Transfer to a human The agent can hand a phone call over to someone on your team — for example, when the caller asks to speak to a person or the request is outside the agent's scope. ## Where it works - **Phone calls** (received and placed by the agent, including the phone call from the test panel): the line passes to the destination when it answers. - **Web calls** (browser test, public link, widget): there is no phone line to transfer. The transfer does not happen and the agent carries on with the conversation. ### Allowed destinations | Number answering the call | Where it can transfer to | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | DISKA number | Only **Angolan mobiles** (Africell or Unitel) set as a fixed number in the action, the node or the phone book. A number said during the conversation is never used. Your organization must be allowed to place outbound calls. | | Number imported from your carrier (SIP trunk) | A number or a SIP URI on your trunk's domain; the call leaves through your trunk. See [Connect over SIP](https://docs.diska.ai/en/telephony/sip-trunk). | | WhatsApp number (voice call) | Only fixed **Angolan mobiles**, as on a DISKA number. The customer stays on the same WhatsApp call. See [Voice calls](https://docs.diska.ai/en/whatsapp/calls#transfer-to-a-person). | ## Step 1. Create the transfer action 1. In the side menu, open **Acções → Transferências de chamada** (Actions → Call transfers) and click **Criar novo** (Create new). 2. On the **Geral**(General) tab, fill in: - **Nome** (Name) — the action's identifier (lowercase letters, numbers and `_`, e.g. `transfer_sales`); - **Descrição da condição** (Condition description) — when the transfer should happen (e.g. "the caller asks to speak to a salesperson"); - **Transferir para** (Transfer to) — **Número** (Number), **SIP URI** or **Lista telefónica** (Phone book). For a number, use **Validar** (Validate) to check the format. 3. Click **Guardar** (Save). Creating and editing actions requires the Owner, Administrator or Member role. ## Step 2. Choose the mode On the **Definições de transferência** (Transfer settings) tab, choose the **Modo de transferência** (Transfer mode): | Mode | What happens | | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Transferência direta** (Direct transfer) | The person who answers is connected to the caller straight away, with no briefing. | | **Transferência assistida com mensagem** (Assisted transfer with message) | The person who answers first hears, in the agent's voice, the reason for the transfer ("Chamada transferida pela assistente virtual. Motivo: …" — call transferred by the virtual assistant, reason: …). Only then is the caller connected. | | **Transferência assistida com resumo contextual** (Assisted transfer with contextual summary) | The person who answers first hears a short summary of the call, in the agent's voice. Only then is the caller connected. | On the same tab, set what the **caller** hears: - **Mensagem «A tentar contactar o destinatário»** (Trying to reach the recipient) — said to the caller when the transfer starts (default: "Deixe-me transferi-lo para um humano. Por favor aguarde."). - **Mensagem «Destinatário falhou ou recusou»** (Recipient failed or declined) — said when the transfer fails. If the destination rings and does not take the call (no answer, busy or declined), the agent says «Infelizmente o número está indisponível neste momento.» (unfortunately the number is unavailable right now). Either way, the agent stays with the caller. The **Variáveis** (Variables) button inserts `{{caller_name}}`, `{{agent_name}}`, `{{destination}}` or `{{conversation_summary}}` into the messages. During the call, only variables that exist in the conversation at that moment are filled in; the others are dropped from the sentence, so write messages that still make sense without them. While the destination rings, the caller stays on the line with the agent (no hold music). ## Step 3. Set opening hours (optional) On the **Disponibilidade humana** (Human availability) tab, turn on **Activar horário de disponibilidade** (Enable availability schedule), choose the days and hours, the **Fuso horário** (Time zone) and the **Mensagem "Humano indisponível"** (Human unavailable message). Outside those hours, the transfer is not made and the agent says that message. When the schedule is off, transfers can happen at any time. ## Step 4. Connect the action to the agent **Prompt Builder agent:** 1. In the editor, open **Ações** (Actions). 2. Under **Durante a conversa** (During the conversation), click **Adicionar → Transferência de chamada** (Add → Call transfer). 3. Pick the transfer from the list. The agent transfers when the **Descrição da condição** applies. **Flow Designer agent:** Add a **Transferência** (Transfer) node (category **Transferência humana**) and choose the **Destino** (Destination): - **Telefone** (Phone), **SIP URI** or **Lista telefónica** (Phone book) — configured in the node itself; tick **Transferência assistida** (Assisted transfer) so the person who answers first hears a summary of what the flow collected (you can guide it under **Resumo para handoff**, Handoff summary); - **Acção de transferência** (Transfer action) — uses an action created in Step 1, with its mode, schedule, phone book and messages. The node has two exits: **Sucesso da acção** (the call was transferred) and **Falha da acção** (the destination did not answer or it is a web call — the agent carries on). Connect both. See [Transfer node](https://docs.diska.ai/en/nodes/transfer). Alternatively, in a **Conversação** (Conversation) step, open **Acções → Adicionar → Transferência de chamada**: the agent can then transfer at any point during that step, when the action's condition applies. ::callout{type="warning"} Transferring to a queue or team does not exist on phone lines: an older node set to **Fila ou equipa** (Queue or team) blocks publishing until you choose another destination. :: ## Step 5. Test - The **Simular** (Simulate) button (available once the action is saved) generates the events of a transfer without placing any call. The options on the **Simulação** (Simulation) tab only apply there. - For a real transfer, use **Testar → Chamada telefónica** with the published version: the agent calls you and, when you ask to speak to a person, the call is transferred. With the draft, the transfer is simulated. See [Test an agent](https://docs.diska.ai/en/guides/test-agent). ::callout{type="info"} The call duration limit ( **Definições → Configuração de chamada** ) never cuts off a call that has already been transferred to a person. :: # Book meetings with Cal.com With a **Agendamento em tempo real** (Real-time booking) action, the agent books the meeting in your Cal.com while talking to the caller and, optionally, sends a confirmation SMS. ## Prerequisites 1. A Cal.com account with at least one event type. 2. Cal.com connected under **Definições → Integrações** (Settings → Integrations) — see [Cal.com](https://docs.diska.ai/en/integrations/calcom). ## Step 1. Create the booking action 1. In the side menu, open **Acções → Agendamento em tempo real**, click **Criar novo** (Create new) and choose **Cal.com**. 2. Fill in: - **Nome da acção** (Action name) — lowercase letters, numbers and `_` (e.g. `book_demo`); - **Conta Cal.com** (Cal.com account) — confirms the connection is active (the settings icon opens Integrations); - **Evento** (Event) — the Cal.com event type the meeting is created in (the refresh button reloads the list). 3. Under **Sugestões de disponibilidade** (Availability suggestions), choose the **Fuso horário** (Time zone) used to convert the time the caller says: Africa/Luanda, Europe/Lisbon or UTC. 4. Optional: turn on **SMS de confirmação** (Confirmation SMS) and adjust the text. Use `{appointment_date}` and `{appointment_link}` to insert the details. The default text is: ```text Está tudo pronto! A sua marcação está agendada para {appointment_date}. Aceda por este link: {appointment_link} ``` 5. Click **Guardar** (Save). Cal.com sends a confirmation email to the address the agent collects in the `` variable. ::callout{type="info"} Automatic suggestion of free slots is marked **em breve** (coming soon). For now, the agent books the time the caller asks for and Cal.com checks availability. :: ## Step 2. Connect the action to the agent **Prompt Builder agent:** 1. In the editor, open **Ações** (Actions) and, under **Durante a conversa** (During the conversation), click **Adicionar → Agendamento em tempo real**. 2. Pick the action. 3. Click the attached action to see its **Variáveis de entrada** (Input variables) and set where each one comes from — for example, the email collected by the agent. **Flow Designer agent:** 1. Before the booking, collect the email and preferred time in a **Conversação** (Conversation) node (under **Recolher variáveis**, Collect variables). 2. Add an **Agendamento** (Booking) node and, under **Acção de agendamento** (Booking action), pick the action. 3. Fill in **Tipo de marcação** (Booking type — Demonstração, Reunião or Chamada de seguimento: demo, meeting or follow-up call), **Título** (Title), **Contacto / email** and **Horário** (Time — the collected variables), **Fuso horário** and the **Mensagem de confirmação** (Confirmation message) the agent says. 4. Connect the **Sucesso da acção** and **Falha da acção** exits. See [Booking node](https://docs.diska.ai/en/nodes/booking). ::callout{type="warning"} If the platform does not have the calendar available, a flow containing an **Agendamento** node cannot be published and the editor shows **Capacidades live ainda não disponíveis** (Live capabilities not yet available). :: ## Step 3. Test - With the **draft**, the booking is simulated: nothing is created in Cal.com. - With the **published version**, on a web or phone test call, the booking is real — check in Cal.com that the meeting appears under the chosen event type. Chat and simulation never create bookings. See [Test an agent](https://docs.diska.ai/en/guides/test-agent). # Send SMS during and after the call Diska has two kinds of SMS action: | Action | When it is sent | Example | | ----------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------ | | **SMS durante a chamada** (SMS during the call) | When the agent decides to send it, while the call is active. It can wait for the caller's reply. | A verification code, a payment link. | | **SMS pós-chamada** (Post-call SMS) | After the call ends, if the condition is met in the transcript. | A summary of what was agreed. | The SMS goes to the caller's number — on a phone call, the number of the person talking to the agent. ::callout{type="info"} The SMS status is shown under **Acções** (Actions), in the **Integrações** (Integrations) card (row **SMS (Ombala)** ). If SMS is not configured on the platform, no SMS is sent. :: ## SMS during the call ### Create the action 1. Open **Acções → SMS durante a chamada** and click **Criar novo** (Create new). 2. Fill in: - **Nome da acção** (Action name, e.g. `send_code`); - **Mensagem antes da acção** (Message before the action) — what the agent says before sending (e.g. "Vou enviar o código agora."); - **Corpo da mensagem** (Message body) — the SMS text. Use `` to insert variables, such as ``; detected variables are listed under **Variáveis de placeholder** (Placeholder variables). 3. Optional, under **Definições de resposta** (Reply settings): turn on **Aguardar resposta** (Wait for reply) so the agent waits for the caller to reply by SMS, set the **Tempo limite (segundos)** (Timeout in seconds — 45 seconds at most in practice) and the **Mensagem de fallback** said if no reply arrives. 4. Click **Guardar** (Save). The **Simular** (Simulate) button shows the resolved SMS for a test **Destinatário** (Recipient), with a **Resposta simulada** (Simulated reply) or a forced timeout — without sending anything. ### Connect it to the agent - **Prompt Builder:** **Ações → Durante a conversa → Adicionar → SMS durante a chamada**, then pick the action. - **Flow Designer:** add the **Enviar SMS durante a chamada** node, use **Anexar SMS durante a chamada** (Attach SMS during the call) and fill in the **Mapeamento de variáveis de entrada** (Input variable mapping) for each variable in the text. Connect the **Sucesso da acção** and **Falha da acção** exits. See [Send SMS during the call node](https://docs.diska.ai/en/nodes/send-sms-during-call). ## Post-call SMS ### Create the action 1. Open **Acções → SMS pós-chamada** and click **Criar novo**. 2. Fill in: - **Nome** (Name); - **Descrição da condição** (Condition description) — when to send it (e.g. "the caller accepted the offer"). The condition is checked against the call transcript; - **Conteúdo do SMS (variante A)** (SMS content, variant A), with `` variables; - optional, **Variante B (A/B opcional)** — an alternative text for A/B testing. 3. Click **Guardar**. **Simular** lets you enter a **Destinatário (E.164)** and a **Transcrição (para condição)** (Transcript, for the condition) to see whether the condition is met and what the text would be — without sending. ### Connect it to the agent - **Prompt Builder:** **Ações → Depois da conversa → Adicionar → SMS pós-chamada** (After the conversation → Add → Post-call SMS). - **Flow Designer:** click the **Depois da conversa** (After the conversation) node (after **Terminar chamada**) and use **Adicionar → SMS pós-chamada**. ## Test - With the **draft**, no SMS is sent: the result is marked as simulated. - With the **published version**, on a web or phone test call, the SMS is really sent. On the web call, the recipient is the **Contacto do chamador** (Caller contact) you fill in on the test panel. See [SMS during the call](https://docs.diska.ai/en/actions/during-call-sms) and [Post-call SMS](https://docs.diska.ai/en/actions/post-call-sms) for the full reference. ::callout{type="warning"} SMS sent with the published version are real and reach the caller. Test with the draft until the text is right. :: # Configure a phone book A **lista telefónica** (phone book) holds several numbers the agent can transfer a call to — for example, Sales and Support — each with its own condition. You use it as the destination of a [transfer to a human](https://docs.diska.ai/en/guides/transfer-to-human). ## Create a phone book 1. Open **Acções → Transferências de chamada** (Actions → Call transfers) and click **Listas telefónicas** (Phone books). 2. Click **Novo** (New) — or **Criar lista telefónica** (Create phone book) if you have none yet. 3. Give the phone book a **Nome** (Name). 4. For each destination, fill in: - **Número de telefone** (Phone number) — in international format, e.g. `+244 923 000 000`; - **Condição de transferência** (Transfer condition) — when to use this number, e.g. "When the caller asks for sales". 5. Use **Adicionar** (Add) for more destinations and click **Guardar** (Save). Both fields are required on every row. Creating and editing phone books requires the Owner, Administrator or Member role. Example: | Phone number | Transfer condition | | ---------------- | --------------------------------- | | +244 923 000 001 | sales, prices, buy | | +244 923 000 002 | support, fault, technical problem | ## How the destination is chosen When the agent decides to transfer during the conversation, it states the reason for the transfer. The platform compares that reason with the words in each number's **Condição de transferência**, in list order, and uses the first number whose condition matches. If none matches, the **first number in the list** is used. - Write conditions as short, distinct keywords (e.g. sales, support, billing) that the agent will use when explaining the reason. - Put the destination that should answer by default first. ::callout{type="warning"} A flow's **Transferência** (Transfer) node — with a **Lista telefónica** destination or a **Acção de transferência** (Transfer action) — does not state a reason, so it always uses the **first number** in the list. Choosing by condition applies when the transfer is attached as an action — in the Prompt Builder or in the **Acções** (Actions) of a **Conversação** (Conversation) step. :: ## Use the phone book - **In a transfer action:** under **Transferir para** (Transfer to), choose **Lista telefónica** and select the phone book. - **In a flow:** in the **Transferência** node, choose the **Lista telefónica** destination and select the phone book. If the agent answers on a **DISKA number**, every number in the phone book must be an Angolan mobile (Africell or Unitel) — see [Allowed destinations](https://docs.diska.ai/en/guides/transfer-to-human). ## Edit or delete In the **Listas telefónicas** window, use the pencil to edit and the bin to delete. A phone book used by a transfer cannot be deleted. # Embed the voice widget The voice widget lets visitors to **your website** talk to the agent in the browser, without a Diska account. The widget always talks to the agent's **published version**. ## Prerequisites 1. The agent has a published version — see [Publish and receive calls](https://docs.diska.ai/en/guides/publish-agent). 2. The public channel is enabled. Under **Publicação → Widget** (Publishing → Widget), click **Ativar canal público** (Enable public channel) — it is the same channel as the **Link público** (Public link). Enabling the public channel requires the Owner, Administrator or Member role. ## Get the code Under **Publicação → Widget**, the **Código incorporável** (Embed code) section has two variants. Use the copy button next to each. **Script (Recomendado — Recommended)** — paste before ``. The loader draws the button and handles position and open/close: ```html ``` **Alternativa sem JavaScript** (No-JavaScript alternative) — for sites that block third-party scripts: a fixed iframe in the bottom-right corner, without the loader: ```html ``` ::callout{type="warning"} Keep the `allow="microphone"` attribute on the iframe. Without it, the browser refuses the microphone inside the frame and the call never starts. The script variant sets it for you. :: ## Customise the look The settings live in the same tab and are saved automatically (**A guardar…** → **Guardado**, Saving… → Saved). They apply to the widget already installed — you do not need to paste the code again. | Section | Options | | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Visualizador** (Visualiser) | **Esfera** (Sphere) or **Imagem** (Image — enter an `https://` image URL), shown while the agent speaks. | | **Paleta de cores** (Colour palette) | Visualiser, card background, button text, button background and text (hex colours). | | **Personalização de texto** (Text customisation) | Call button, availability, starting call, during the call and end of call (up to 60 characters). | | **Widget flutuante** (Floating widget) | **Ativar widget flutuante** (Enable floating widget) shows a fixed button in a corner of the site; when off, the widget appears where you pasted the code. In floating mode you can also **Mostrar nome do agente quando recolhido** (Show agent name when collapsed), **Expandir ao carregar a página** (Expand on page load), choose the **Posição** (Position — bottom/top, right/left) and an **Atraso (ms)** (Delay) of up to 60,000. | The **Pré-visualização do widget** (Widget preview) next to it is live: you can start a call with the published version from it. ::callout{type="info"} For **Voice Widget** agents, the publishing settings open on their own after each publish and, once the public channel is enabled, show a wide view with the preview alongside. :: ## Update the agent The widget always uses the latest published version. To change what the agent says or does, edit it and **publish** again — the code on your site does not change. If you use **Gerar novo link** (Generate new link) on the **Link público** tab, the token changes and codes already pasted stop working: copy the code again. ## Troubleshooting - **Nothing appears on the page.** The widget hides itself rather than breaking your site. Open the browser console: `[diska-widget] indisponível` means the public channel is off or the agent has no published version; a network error means the browser could not reach Diska. - **The microphone prompt never appears.** Check the `allow` attribute (iframe variant) and that your site is served over HTTPS — browsers block the microphone on insecure pages. - **Is the call recorded?** Only if **Gravar chamadas** (Record calls) is on for the agent — see [Record calls](https://docs.diska.ai/en/guides/record-calls). # Record calls With **Gravar chamadas** (Record calls) on, Diska stores the audio of the agent's calls so you can listen to them under **Históricos** (Histories). Recording is off by default on every agent and can only be turned on after you configure the consent notice the agent says to the caller. ::callout{type="warning"} **Recording calls is a legal decision.** Recording without telling the caller is illegal in most jurisdictions. Your company is responsible for complying with the data protection rules of its market — check them before turning recording on. :: ## Turn recording on 1. In the agent editor, open **Definições → Segurança e conformidade** (Settings → Security and compliance). 2. Turn on **Gravar chamadas** (Record calls). **Avisar que a chamada é gravada** (Tell the caller the call is recorded) turns on too, with a suggested message: "Esta chamada é gravada para efeitos de qualidade e formação. Se preferir não ser gravado, diga-o e a gravação é interrompida." 3. Adapt the message: the agent reads it word for word at the start of the call and then carries on with the conversation. It must be between 20 and 600 characters. 4. Choose **Retenção das gravações** (Recording retention) — see below. 5. **Publish the agent**: recording settings are part of the version, and real calls use the published version. Agents that already used **explicit consent** keep it: the agent says the message and waits for a clear "sim" (yes) before recording; if the caller says "não" (no), the conversation continues without recording. ## Recording without notice With **Avisar que a chamada é gravada** off, the agent records without telling the caller anything. Any user who edits the agent can choose this; Diska logs who chose it and when. ## What is recorded | Call | Recorded? | | ---------------------------------------------- | -------------------------- | | Widget on your website | Yes | | Public link | Yes | | Phone calls (received and placed by the agent) | Yes — the first 27 minutes | | Phone call from the test panel (**Ligar-me**) | Yes — the first 27 minutes | | Web test call in the backoffice | No | | Chat and Simulation | No (there is no audio) | On a phone call, the caller's and the agent's voices are in the same recording. For each recording, Diska stores which consent message was in force, so changing the notice later does not change what applied to earlier calls. ## Retention Recordings are deleted automatically at the end of the retention period: - **Organization period** — the maximum for the whole organization. By default, 90 days. - **Retenção das gravações** (Recording retention — on the agent, once recording is on) — **Usar o período da organização** (Use the organization's period) or 7, 30, 90, 180 or 365 days. The agent can only **shorten** the period: a longer value is capped at the organization's period. The deletion date is fixed when the recording is stored; changing the period later does not affect existing recordings. ::callout{type="info"} The backoffice does not yet have a control to change the organization's period. If you need a period other than 90 days, contact Diska. :: ## Listen to a recording 1. Open **Históricos → Chamadas** (Histories → Calls) and click the call. 2. On the **Transcrição** (Transcript) tab, use the player: play/pause, seek on the bar, change the speed and **Descarregar gravação** (Download recording). Below the player you see the file size and the date it will be deleted automatically. When there is no audio to play, the call shows its state: **A gravar…** (Recording…), **A enviar…** (Uploading…), **Falha na gravação** (Recording failed), **Gravação expirada** (Recording expired) or **Gravação eliminada** (Recording deleted). See [Recordings](https://docs.diska.ai/en/history/recordings). Every role with access to Histories can listen to and download recordings. ## Delete a recording Owners and Administrators see the **Eliminar gravação** (Delete recording) icon in the player. Deletion is **immediate and permanent** — there is no confirmation and no way to recover the audio. The transcript and the rest of the call data are kept. Use it, for example, to answer a caller's data erasure request. ## Other options in the section - **Guardar transcrições** (Save transcripts) — the conversation text is always stored. - **Ocultar dados pessoais (PII)** (Redact personal data) — replaces names, contacts, addresses, ID documents and cards with tags such as `[NOME]` in the text the call leaves. The audio recording is not changed. See [Redact personal data](https://docs.diska.ai/en/guides/redact-personal-data). # Redact personal data With **Ocultar dados pessoais (PII)** (Redact personal data) on, Diska removes personal data from the text each call leaves: the transcript, the summary, the post-call analysis and the webhook. Each item is replaced by a tag: > Falas com o **[NOME]**. O meu número é **[TELEFONE]** e moro na **[MORADA]**. The call itself does not change: the agent hears and uses everything the caller says. Redaction happens when the call ends, before any analysis or delivery. ## Turn it on 1. In the agent editor, open **Definições → Segurança e conformidade** (Settings → Security and compliance). 2. Turn on **Ocultar dados pessoais (PII)**. 3. **Publish the agent.** The option is part of the version, and real calls use the published version. It applies to calls that end after you publish. Earlier calls are not changed. Test calls from the panel follow the draft, so you can try it before publishing. ## What is redacted | Data | Tag | Examples | | ---------------- | ------------------- | --------------------------------------------------------------------------- | | People's names | `[NOME]` | "Márcio Quimbundo" and, later in the call, just "Márcio" | | Phone numbers | `[TELEFONE]` | "958 114 794", "+244 923 …", "nove cinco oito, um um quatro…" (spelled out) | | E-mail addresses | `[EMAIL]` | "", "nome arroba gmail ponto com" (spoken) | | Addresses | `[MORADA]` | Street, neighbourhood with a house number, building, floor, postcode | | ID documents | `[DOCUMENTO]` | BI, NIF, passport, driving licence | | Cards | `[CARTÃO]` | Number, expiry date and CVV | | Bank accounts | `[IBAN]` | IBAN | | Dates of birth | `[DATA_NASCIMENTO]` | "nasci a 3 de Maio de 1990" | Data with a known shape (phone numbers, e-mails, cards, IBAN, BI) is found by rules, including when spelled out in words. Names, addresses and dates of birth are identified by a language model that can only point at excerpts present in the transcript: it never rewrites the text. These stay visible: - the company contacts written in the agent's instructions (when the agent reads out the sales number, that number is not the caller's); - the agent's name and the company's name; - amounts, dates and times. ## Where it applies | Where | Redacted? | | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | | Transcript in **Históricos** (Histories) | Yes | | Call summary | Yes — written from the already redacted call | | Evaluations and sentiment | Yes — computed on the already redacted call | | Extractor values stored with the call | Yes | | [Post-call webhook](https://docs.diska.ai/en/api/webhooks) | Yes | | Log of the tools used during the call | Yes | | [Shared memory](https://docs.diska.ai/en/knowledge-base/shared-memory) | Yes — built from the already redacted call | | DISKA API chats | Yes, when the conversation closes | | Caller's number (caller ID) | No — needed for the SMS to the caller, memory and billing | | Audio recording | No — if the audio must not hold personal data, turn **Gravar chamadas** (Record calls) off | | Data an action stores on purpose (a calendar booking, a record in your CRM) | No | | WhatsApp text conversations | No — the option applies to calls | ## Post-call actions [Information extractors](https://docs.diska.ai/en/actions/information-extractors) still read the full call to feed the actions that act on the caller's behalf. The [post-call SMS](https://docs.diska.ai/en/actions/post-call-sms) and [custom actions](https://docs.diska.ai/en/actions/custom-actions) receive the real values, for example the name for "Olá {nome}". What Diska stores, and what it sends in the webhook, carries the tags. If you need the caller's name or contact in your system, send them with a custom action: the post-call webhook arrives without them. ## Limitations - **Redaction is permanent.** The original text is not kept and cannot be recovered. - **No detector is perfect**, especially on transcribed speech. A misheard name can slip through, and a common word can be hidden by mistake. Treat redaction as one layer of protection, not the only one. - **The summary and memory wait for redaction.** They are normally ready seconds after the call. For an interrupted call (abandoned, for example), the platform redacts it a few minutes later and only then creates them. - Name and address detection uses the same model provider that already writes the call summary. # Guides This section contains step-by-step instructions for the most common tasks, from your first agent to a recorded phone call. ::card-group :::card --- description: From the New agent button to your first test call. icon: i-lucide-bot title: Create your first agent to: https://docs.diska.ai/en/guides/create-first-agent --- ::: :::card --- description: Design the conversation with nodes, conditions and subflows. icon: i-lucide-workflow title: Use the Flow Builder to: https://docs.diska.ai/en/guides/use-flow-builder --- ::: :::card --- description: Versions, phone number, public link, widget and API. icon: i-lucide-rocket title: Publish and receive calls to: https://docs.diska.ai/en/guides/publish-agent --- ::: :::card --- description: Web call, phone call, chat, simulation and the Test Center. icon: i-lucide-flask-conical title: Test an agent to: https://docs.diska.ai/en/guides/test-agent --- ::: :::card --- description: Direct or assisted transfer to a person. icon: i-lucide-phone-forwarded title: Transfer to a human to: https://docs.diska.ai/en/guides/transfer-to-human --- ::: :::card --- description: Real-time booking with Cal.com. icon: i-lucide-calendar-check title: Book meetings to: https://docs.diska.ai/en/guides/book-meetings --- ::: :::card --- description: SMS during and after the call. icon: i-lucide-message-square title: Send SMS to: https://docs.diska.ai/en/guides/send-sms --- ::: :::card --- description: Several transfer destinations, chosen by condition. icon: i-lucide-contact title: Configure a phone book to: https://docs.diska.ai/en/guides/configure-phone-book --- ::: :::card --- description: Put the published agent on your website. icon: i-lucide-app-window title: Embed the voice widget to: https://docs.diska.ai/en/guides/embed-widget --- ::: :::card --- description: Consent, what is recorded, retention and where to listen. icon: i-lucide-mic title: Record calls to: https://docs.diska.ai/en/guides/record-calls --- ::: :::card --- description: Names, contacts and ID documents out of your call text. icon: i-lucide-shield-check title: Redact personal data to: https://docs.diska.ai/en/guides/redact-personal-data --- ::: :: # Builder interface The Flow Builder fills the centre of the agent editor. Around the canvas you find the flow tabs, the canvas controls and, when you select a node, the configuration panel. ## Flow tabs At the top of the canvas there is one tab per flow: the **Fluxo principal** (Main flow) and each subflow. - The **+** on the right creates a new subflow (**Subfluxo 1**, **Subfluxo 2**, …). - Each subflow's menu offers **Renomear** (Rename), **Duplicar** (Duplicate) and **Apagar** (Delete). - People without edit permission (Viewer role) see the **Só leitura** (Read-only) label and cannot change the flow. ## Canvas The central area, holding the nodes and connections. - Drag the background to move the view and use the mouse wheel to zoom. - Click a node to select it and open the configuration panel. - Each node shows a badge with its number of validation errors or warnings. - To connect two nodes, drag from one node's output to the other. A connection that is not allowed is refused, with the reason — see [Flow structure](https://docs.diska.ai/en/flow-builder/structure). ### Canvas controls | Control | What it does | | ---------------------------------------------------- | ---------------------------------------------------------------------------- | | **Pesquisar** (Search, `Ctrl/⌘ + K`) | Finds nodes by name, type, variable, action or issue, and jumps to the node. | | **Variáveis** (Variables) | Opens the agent's variables panel. | | **Desfazer** / **Refazer** (Undo / Redo) | Reverts or reapplies the last change. | | **Ecrã inteiro** (Full screen) | Opens the canvas full screen. | | **Ajustar ao ecrã** (Fit to screen) | Frames the whole flow. | | **Reduzir zoom** / **Aumentar zoom** (Zoom out / in) | Adjusts the zoom; the current percentage is shown next to it. | | **Mostrar minimapa** (Show minimap) | Shows an overview of the flow. | ## Add nodes Click a **+** (**Adicionar próximo passo**, Add next step) — at the end of the flow or on a path's exit — to open the node catalogue: | Category | Nodes | | ---------------------------------------- | ---------------------------------------------------------------------------------------------- | | **Conversação** (Conversation) | Conversação (Conversation), Mensagem (Message), Terminar chamada (End call) | | **Controlo de fluxo** (Flow control) | Disparar subfluxo (Trigger subflow), Dividir o caminho (Split the path), Saltar para (Jump to) | | **Acções** (Actions) | Acção personalizada (Custom action), Enviar SMS durante a chamada (Send SMS during the call) | | **Transferência humana** (Human handoff) | Transferência (Transfer) | | **Negócio** (Business) | Agendamento (Booking) | - Type in **Pesquisar nós…** (Search nodes) to filter. - A node that cannot follow the current step is shown as **Inválido** (Invalid), with the reason. - If you have copied a node, the catalogue also shows **Colar** (Paste). - Nodes not yet available are not listed in the catalogue — see [Coming-soon nodes](https://docs.diska.ai/en/nodes/coming-soon). ## Configuration panel When you select a node, the panel opens next to the canvas with that node type's fields — instructions, variables to collect, messages, attached actions, destinations. Clicking a path of a condition opens that path's **Condição** (Condition) panel. Close the panel with its close button or `Esc`. Each node also has copy and delete buttons. Structural nodes (**Fluxo principal**, **Antes da conversa**, **Mensagem de saudação**, **Depois da conversa**) cannot be deleted. ## Agent toolbar At the top of the editor, above the canvas: | Element | What it does | | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | Save indicator | **A guardar…** (Saving…), **Guardado às …** (Saved at …) or **Erro ao guardar** (Error saving). The flow is saved automatically. | | **Lista de verificação** (Checklist) | The agent's and the flow's errors and warnings; click one to jump to the node. | | **Variáveis**, **Versões**, **Definições**, **Publicação** | The agent panels: variables, versions, settings, publishing. | | **Testar** (Test) | Web call, phone call, chat, simulation and Test Center. | | **Publicar** (Publish) | Validates the flow and publishes a new version. | | **⋮** | **Registos de chamadas** (Call logs), **Copiar ID** (Copy ID), **Duplicar** (Duplicate) and **Arquivar** (Archive). | ## Shortcuts | Shortcut | Action | | ------------------------------------ | ---------------------------------------- | | `Ctrl/⌘ + K` | Search nodes | | `Ctrl/⌘ + C` | Copy the selected node | | `Ctrl/⌘ + V` | Paste | | `Ctrl/⌘ + D` | Duplicate the selected node | | `Ctrl/⌘ + Z` | Undo | | `Ctrl/⌘ + Shift + Z` or `Ctrl/⌘ + Y` | Redo | | `Ctrl/⌘ + 0` | Fit to screen | | `Backspace` | Delete the selected node | | `Esc` | Close search, the catalogue or the panel | Copy, paste and undo shortcuts do nothing while you are typing in a text field. # Flow structure Every flow has a fixed entry structure. The Main flow and subflows start differently; from there, the connection rules say which nodes can follow each one. ## Main flow ```text Fluxo principal → Antes da conversa → Mensagem de saudação → next step ``` | Node | What it is for | | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Fluxo principal** (Main flow) | Where the call enters. | | **Antes da conversa** (Before the conversation) | Runs before the greeting. You can attach **Acções personalizadas** (custom actions) to it — **Tratamento IVR** (IVR handling) only exists for Prompt Builder agents — and connect steps that must happen before the agent greets the caller. | | **Mensagem de saudação** (Greeting message) | The first turn: **Agente fala primeiro** (Agent speaks first — fixed or generated message) or **Humano fala primeiro** (Human speaks first — the agent waits; you can set for how long). | These nodes are structural: they cannot be deleted, and the `Fluxo principal → Antes da conversa → Mensagem de saudação` connection cannot be undone — if it is, publishing is blocked. ## End of the call Every path ends in a **Terminar chamada** (End call) node, with a **Motivo de fim** (End reason — Concluído, Pedido pelo cliente, Não qualificado, Transferido or Erro: completed, requested by the caller, not qualified, transferred or error) and a farewell. After each **Terminar chamada**, a **Depois da conversa** (After the conversation) node appears automatically, where you attach actions that run after the call ends: **SMS pós-chamada** (post-call SMS), **Extrator de informação** (information extractor) and **Avaliação personalizada** (custom evaluation). ## Subflows A subflow starts like this: ```text Subfluxo → Condições de entrada → next step ``` - In **Condições de entrada** (Entry conditions), add one or more conditions with **Adicionar condição de entrada** (Add entry condition). Each condition has a type — **Manual**, **Intenção do cliente** (Customer intent), **Condição** (Condition), **Acção com sucesso** (Action succeeded) or **Acção falhou** (Action failed) — and a name. - To enter a subflow from another flow, use the **Disparar subfluxo** (Trigger subflow) node and pick the subflow. A subflow cannot trigger itself. - When you publish, the Main flow and the subflows it reaches are published. Use subflows for logic you repeat, such as verifying the caller's identity or collecting an address. ## Connection rules | Source node | Can be followed by | | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Fluxo principal** | Only **Antes da conversa**. | | **Antes da conversa** | Greeting message, Conversation, Message, Custom action, Send SMS during the call, Transfer, Booking. | | **Mensagem de saudação** | Conversation, Message, Jump to, Trigger subflow, Custom action, Send SMS during the call, Transfer, Booking, End call. *Not* Split the path: the greeting does not collect an answer. | | **Conversação** (Conversation) | Its exit **Condição**, Message, Jump to, Trigger subflow, the four actions, End call. *Not* another Conversation directly — it goes through the Condition. | | **Mensagem** (Message) | Conversation, Message, Split the path, Jump to, Trigger subflow, the four actions, End call. | | **Dividir o caminho** / **Condição** (each path) | Conversation, Message, Jump to, Trigger subflow, the four actions, End call. | | **Saltar para** (Jump to) | Conversation, Message, Split the path, Trigger subflow, the four actions, End call. | | **Disparar subfluxo** (Trigger subflow) | Conversation, Message, Split the path, Jump to, the four actions, End call. | | **Acção personalizada**, **Enviar SMS durante a chamada**, **Transferência**, **Agendamento** (each exit) | Greeting message, Conversation, Message, Split the path, Jump to, Trigger subflow, the four actions, End call. | | **Terminar chamada** (End call) | Only **Depois da conversa**. | | **Depois da conversa** | Nothing — it closes the flow. | "The four actions" are **Acção personalizada** (Custom action), **Enviar SMS durante a chamada** (Send SMS during the call), **Transferência** (Transfer) and **Agendamento** (Booking). Each has two exits — **Sucesso da acção** (Action success) and **Falha da acção** (Action failure) — and each exit follows the rules in the table. ## The + button The **+** marks where the flow continues. It is not a node: click it to choose the next step. Condition paths and action exits each have their own **+**. # Flow variables Variables keep information during the call so it can be used in instructions, messages, conditions and actions. The **Variáveis** (Variables) panel — in the agent toolbar or the canvas controls — lists them in four groups. ## System variables Available in every flow: | Name | Type | Description | | ------------------- | ----- | ------------------------------ | | `call_id` | text | Unique identifier of the call. | | `user_phone_number` | phone | The caller's number. | | `from_phone_number` | phone | Originating number. | | `to_phone_number` | phone | Destination number. | ## Pre-call variables Values the agent receives when the call starts — for example, the customer's name in a campaign. 1. Open the **Variáveis** panel. 2. Under **Variáveis pré-chamada** (Pre-call variables), type the name (`variable_name`; spaces become `_`), choose the type (**Texto**, **Número**, **Telefone**, **Email**, **Data** or **Boolean** — text, number, phone, email, date or boolean) and, optionally, a description. 3. Click **Adicionar** (Add). In the test panel, each pre-call variable has a **Variável: …** field to fill in before the web or phone call. ## Conversation variables Collected by the agent in a **Conversação** (Conversation) node, under **Recolher variáveis → Adicionar** (Collect variables → Add): | Field | Description | | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome** (Name) | Technical identifier: letters, numbers and `_`, not starting with a number (e.g. `customer_email`). | | **Tipo** (Type) | **String**, **Number**, **Integer**, **Boolean**, **List**, **Email** or **Phone number**. Number and Integer accept an optional **Mínimo** and **Máximo** (minimum and maximum). | | **Pergunta / instruções para recolher a variável** (Question / instructions) | How the agent should ask for the information. | | **Obrigatório** (Required) | Whether the step is only complete once this variable is collected. | An invalid name is a validation error and blocks publishing. ## Action results Action nodes store their result in a variable: | Node | Variable | | --------------------------------------- | ------------------------------------------------------------------------------ | | **Acção personalizada** (Custom action) | The one set in **Guardar resultado em** (Store result in — e.g. `crm_result`). | | **Agendamento** (Booking) | `booking_result_` | | **Transferência** (Transfer) | `transfer_result_` | | **Disparar subfluxo** (Trigger subflow) | `subflow_result_` | ## Using variables - **In text** (instructions, messages, greeting, farewell): use the **{ Variáveis** button to insert `{{variable_name}}`. - **In conditions:** in a **Regra determinística** (Deterministic rule), choose the variable, operator and value — see [Conditions and paths](https://docs.diska.ai/en/flow-builder/branches). - **In actions:** in an action's input mapping (for example, the SMS during the call). ::callout{type="warning"} If a text or condition uses a variable that is never collected or set, the Checklist shows a warning. Check the name — it is case-sensitive and accepts no accents or spaces. :: # Conditions and paths A condition splits the conversation into paths. Paths are evaluated in order and the conversation follows the first one that matches; if none matches, it follows the **Caso contrário** (Otherwise) path. ## Where conditions appear - **After every Conversation** — the Flow Builder automatically adds a **Condição** (Condition) with a single **Continuar** (Continue) path that acts as the otherwise path. Add paths to react to what the caller said (e.g. "wants to speak to a person"). - **In the Dividir o caminho node** (Split the path) — insert it after a Message, a Jump to, a Trigger subflow or an action's exit, to decide based on variables or context. See [Split the path](https://docs.diska.ai/en/nodes/split-path). ## Configure a path Click a path of the condition to open the **Condição** panel: 1. **Nome** (Name) — a short name shown on the canvas. 2. **Tipo de condição** (Condition type) — **Prompt LLM** or **Regra determinística** (Deterministic rule). 3. The condition itself (see below). 4. The destination — connect the path's **+** to a next step. In the **Dividir o caminho** node panel, **Adicionar caminho** (Add path) creates more paths and **Adicionar caso contrário** (Add otherwise) creates the default path (the button changes to **Alternativa activa**, Alternative active, once it exists). ### LLM prompt Under **Seguir este caminho se** (Follow this path if), describe in plain language when to take the path. The model decides from the conversation. You can insert variables with **{ Variáveis**. > The caller asked to speak to a person or said the matter is urgent. ### Deterministic rule Compares variables with values. Under **Seguir este caminho se [Qualquer | Todas] das seguintes regras corresponderem** (Follow this path if [any | all] of the following rules match), add one or more **Regras** (Rules), each with a **Variável** (Variable), **Operador** (Operator) and **Valor de comparação** (Comparison value): | Operator | Needs a value | | ------------------------------- | ------------- | | É igual a (equals) | Yes | | É diferente de (does not equal) | Yes | | Contém (contains) | Yes | | Maior que (greater than) | Yes | | Menor que (less than) | Yes | | Está vazio (is empty) | No | | Não está vazio (is not empty) | No | | É verdadeiro (is true) | No | | É falso (is false) | No | With **Qualquer** (any), one rule being true is enough; with **Todas** (all), every rule must be true. ::callout{type="tip"} Use deterministic rules for exact logic (a menu option, a value, a collected yes/no) and the LLM prompt for open-ended intents. :: ## Validation | Problem | Severity | | ---------------------------------------------------------------------- | -------- | | A condition without a **Caso contrário** path | Error | | More than one **Caso contrário** path | Error | | An LLM prompt path without a description | Error | | A rule without a variable or operator | Error | | A path with no connected destination | Warning | | A path that repeats another path's condition (it will never be chosen) | Warning | | A rule using a variable that is never collected or set | Warning | See [Validation and publishing](https://docs.diska.ai/en/flow-builder/validation-publishing). # Test a flow There are several ways to test a flow, from the fastest (text) to the most realistic (a call to your mobile). They all start from the **Testar** (Test) button in the agent editor. ## Draft or published version The **Modo de teste · não é tráfego live** (Test mode · not live traffic) bar shows which version is under test (**Rascunho** — draft — or **Publicado** — published) and has a switch to change it. Test the draft while you build; test the published version to confirm what callers hear. On the web call and the phone call, the published version runs actions for real (SMS, bookings and, on the phone, transfers). Chat and simulation never do. ## Chat **Testar → Chat.** Type as if you were the caller: each message goes through the flow and the agent's reply appears in the conversation, labelled with the step type when it is not a conversation step (for example, `end`). **Novo chat** (New chat) restarts from the beginning. It is the fastest way to check the order of steps and the conditions. ## Simulation **Testar → Simulação** shows the agent's test suites (the same ones as in the [Test Center](https://docs.diska.ai/en/test-center)). For a Flow Designer agent, each case goes through the real flow engine with a simulated caller, and the result shows the **Percurso do fluxo** (Flow path) — the nodes visited and whether the conversation reached the end — along with the criteria that passed. How to create and run suites: [Test an agent](https://docs.diska.ai/en/guides/test-agent#simulation). ## Web call **Testar → Chamada web → Iniciar chamada de teste** (Test → Web call → Start test call). Talk to the agent through your computer's microphone to check the voice, pacing and interruptions. There is no phone line: a **Transferência** (Transfer) node always takes the **Falha da acção** (Action failure) path. ## Phone call **Testar → Chamada telefónica → Ligar-me** (Test → Phone call → Call me). The agent calls you from its DISKA number, as it would a customer. It is the only way to test a real **Transferência**. Requirements and limits are in [Test an agent](https://docs.diska.ai/en/guides/test-agent). ## What to look for - The greeting comes quickly and sounds natural. - The agent collects the right variables before moving on. - Each condition leads to the expected path — test the **Caso contrário** (Otherwise) path too. - Actions run, and both paths (**Sucesso da acção** and **Falha da acção**) make sense. - Every path ends in a **Terminar chamada** (End call). ## After the test Web and phone calls are stored under **Históricos** (Histories), with the transcript, the actions run and the call outcome — see [Calls](https://docs.diska.ai/en/history/calls). Suite runs are kept under **Testar → Simulação**, on the **Histórico** (History) tab, and in the [Test Center](https://docs.diska.ai/en/test-center). # Validation and publishing The Flow Builder validates the flow while you edit and validates it again on the platform before publishing. **Errors** block publishing; **warnings** do not. ## Checklist The **Lista de verificação** (Checklist) button in the agent toolbar shows how many issues there are. Open it to see each issue with its node type, the flow it is in and a description; click an issue to jump to the node. Nodes with issues also show a badge on the canvas. - While the platform confirms the validation, a loading indicator appears. If the confirmation fails (**Não foi possível confirmar a validação no servidor.** — could not confirm validation on the server), use the retry button. - The **Número de telefone** (Phone number) warning (agent without a number) does not block publishing. - The **Canais live** (Live channels) note recalls what runs in production: WhatsApp and email not yet; SMS yes; transfer and IVR on phone calls. ## Errors that block publishing Messages are shown in Portuguese in the product; they are summarised here. | Where | Message (summary) | How to fix | | ------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------- | | Structure | The required Main Flow → Antes da conversa → Mensagem de saudação structure was disconnected. | Reconnect the three structural nodes. | | End | The flow needs at least one reachable End node. | End at least one path in a **Terminar chamada** (End call). | | Connections | Connection not allowed (with the reason) / The connection points to a node that does not exist. | Follow the [connection rules](https://docs.diska.ai/en/flow-builder/structure). | | Conversation | Conversation needs a clear instruction. | Write the step's **Instruções** (Instructions). | | Conversation | Variable "…" has an invalid name. | Use only letters, numbers and `_`. | | Message | Message needs fixed content or an instruction / needs a next step or End. | Write the message and connect the next step. | | End call | End needs an end reason / a farewell. | Choose the **Motivo de fim** (End reason) and write the farewell. | | Condition | Needs a "Caso contrário" (otherwise) path / can only have one fallback path. | Keep exactly one **Caso contrário**. | | Condition | A condição precisa de pelo menos um caminho. (The condition needs at least one path.) | Keep at least one path (a Conversation's exit already has **Continuar**). | | Condition | Path "…" needs an LLM prompt / a variable and operator. | Complete the path's condition. | | Jump to | Jump needs a target / cannot point to itself / the target no longer exists. | Choose a valid target. | | Trigger subflow | Choose the subflow / a subflow cannot trigger itself. | Choose another subflow. | | Subflow | Each active entry trigger needs a type and a name. | Complete the **Condições de entrada** (Entry conditions). | | Custom action | No action attached / webhook mode without a URL / input mapping with invalid JSON / timeout outside 1–120 seconds. | Attach the action and fix its configuration. | | SMS during the call | No SMS action attached. | Attach an **SMS durante a chamada**. | | Transfer | Transfer needs a destination / number / URI / phone book / action. | Complete the destination. | | Transfer | Transferring to a queue or team does not exist on phone lines. | Choose Phone, SIP URI, Phone book or Transfer action. | | Transfer | Call transfer is not available on this server (no phone line connected). | Only appears if the platform has no phone lines: remove the node to publish. | | Booking | Booking needs a title / Select a Real-time booking action. | Choose the booking action. | | Booking | Booking (calendar) is not connected to a provider yet. | Connect Cal.com under **Definições → Integrações** or remove the node. | | Any node | The node uses a channel that is not implemented yet. | Remove the node. | When the platform does not have the calendar or phone lines available, the editor also shows the **Capacidades live ainda não disponíveis** (Live capabilities not yet available) banner above the canvas. ## Warnings They do not block, but deserve a look: - a node disconnected from the flow, which will never run; - a loop from which no path reaches **Terminar chamada**; - a Conversation without expected information or variables to collect; - a path or a **Caso contrário** with no connected destination; - a path that repeats another path's condition; - a variable used in a text or rule that is never collected or set; - missing variables in an SMS text; - a Booking without a contact or time variable; - a subflow without active entry conditions. ## Publish 1. Click **Publicar** (Publish). The Checklist opens and the platform validates every flow. 2. If there are errors, fix them — publishing does not go ahead. 3. With no errors, the **Publicar** dialog opens: name the version (optional) and click **Publicar**. 4. The confirmation **Agente e fluxos publicados com sucesso!** (Agent and flows published successfully) means the new version is in production. The Main flow and every subflow it reaches are published, together with the agent settings. Calls that start from then on use the new version. If the platform still rejects the flow, the **Fluxo inválido** (Invalid flow) message appears with the first issue. Publishing requires the Owner, Administrator or Member role. See also [Publish and receive calls](https://docs.diska.ai/en/guides/publish-agent) and [Flow not publishing](https://docs.diska.ai/en/troubleshooting/flow-not-publishing). # Flow Builder The **Flow Builder** is the visual editor for agents created in **Flow Designer** mode. Each flow is a graph of connected nodes: the conversation starts in the **Fluxo principal** (Main flow) and moves from node to node — conversation steps, messages, conditions, actions, transfers and the end of the call. For a first look, follow the [Use the Flow Builder](https://docs.diska.ai/en/guides/use-flow-builder) guide. This section is the full reference; each node is described in [Nodes](https://docs.diska.ai/en/nodes). ::card-group :::card --- description: Tabs, canvas, node catalogue, configuration panel and shortcuts. icon: i-lucide-layout title: Builder interface to: https://docs.diska.ai/en/flow-builder/interface --- ::: :::card --- description: Required nodes, subflows and which nodes can follow each one. icon: i-lucide-git-branch title: Flow structure to: https://docs.diska.ai/en/flow-builder/structure --- ::: :::card --- description: System, pre-call and collected variables, and action results. icon: i-lucide-braces title: Flow variables to: https://docs.diska.ai/en/flow-builder/variables --- ::: :::card --- description: Split the conversation with an LLM prompt or deterministic rules. icon: i-lucide-git-fork title: Conditions and paths to: https://docs.diska.ai/en/flow-builder/branches --- ::: :::card --- description: Chat, simulation, web call and phone call. icon: i-lucide-play title: Test a flow to: https://docs.diska.ai/en/flow-builder/testing --- ::: :::card --- description: Checklist, errors, warnings and how to publish. icon: i-lucide-check-circle title: Validation and publishing to: https://docs.diska.ai/en/flow-builder/validation-publishing --- ::: :: # Conversation The **Conversação** (Conversation) node is the main step of a flow: the agent listens to the customer, replies following your instructions and, if you want, collects variables. It can also have attached actions, which the agent uses when needed during that step. ## Fields | Field | Description | | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome do passo** (Step name) | Name shown on the canvas (e.g. "Ask for the name"). In a large flow, it stops every card from saying "Conversação". | | **Instruções** (Instructions) | How the agent should behave in this step (e.g. "First ask for the age, then the gender."). The maximize button enlarges the text box. | | **{ Variáveis** (Variables) | Inserts a variable into the instructions. The tabs filter by source: **Todas** (All), **Sistema** (System), **Recolhidas** (Collected), **Acções** (Actions) and **Pré-chamada** (Pre-call). | ## Collecting variables Open **Recolher variáveis** (Collect variables — "Capturar dados do utilizador para usar mais tarde") and click **Adicionar** (Add): | Field | Description | | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | | **Nome** (Name) | Variable name: letters, digits and `_`, not starting with a digit (e.g. `customer_name`). | | **Tipo** (Type) | **String**, **Number**, **Integer**, **Boolean**, **List**, **Email** or **Phone number**. | | **Pergunta / instruções para recolher a variável** (Question / instructions to collect the variable) | The question the agent asks (e.g. "Are you over 18?"). | | **Mínimo (opcional)** / **Máximo (opcional)** (Minimum / Maximum, optional) | **Number** and **Integer** only. The minimum cannot be greater than the maximum. | | **Obrigatório** (Required) | When on, the agent must get this variable before moving on. | Click **Adicionar variável** (Add variable) — or **Guardar variável** (Save variable) when editing. Collected variables are available in the following steps, in conditions and in actions. See [Variables](https://docs.diska.ai/en/flow-builder/variables). ## Actions Under **Acções** (Actions), click **Adicionar** (Add) and choose: | Option | What it attaches | | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | **Marcação em tempo real** (Real-time booking) | A [Real-time booking](https://docs.diska.ai/en/actions/real-time-booking) action. Only one per step. | | **Transferência de chamada** (Call transfer) | A [call transfer](https://docs.diska.ai/en/actions/call-transfers). | | **Acção personalizada** (Custom action) | A [custom action](https://docs.diska.ai/en/actions/custom-actions) (API). | | **SMS durante a chamada** (SMS during the call) | An [SMS during the call](https://docs.diska.ai/en/actions/during-call-sms). | Attached actions can run at any moment of this step: the agent decides when to use them, as in a Prompt Builder agent. To run an action at a fixed point of the flow, use an action node instead ([Custom action](https://docs.diska.ai/en/nodes/custom-action), [Send SMS during the call](https://docs.diska.ai/en/nodes/send-sms-during-call), [Transfer](https://docs.diska.ai/en/nodes/transfer) or [Booking](https://docs.diska.ai/en/nodes/booking)). ## Leaving the step Every Conversation is followed by a condition node (on the canvas, **Condição**) that starts with a single path, **Continuar** (Continue). To route the conversation according to the customer's answer, add paths to that condition. See [Split path](https://docs.diska.ai/en/nodes/split-path). From a Conversation you can go to Split path, Message, Jump to, Trigger subflow, Custom action, Send SMS during the call, Transfer, Booking or End call. Two Conversations never connect directly: the path between them always goes through a condition. ## Example ```text Nome do passo: Reason for calling Instruções: Ask the customer why they are calling. Be brief and friendly. Recolher variáveis: - reason (String, required) → "What is the reason for your call?" - urgent (Boolean, optional) → "Is it urgent?" ``` ## Validation - Error if **Instruções** is empty — publishing is blocked. - Warning in the panel if a variable name is not valid ("Nome de variável inválido"). # Message The **Mensagem** (Message) node makes the agent say an exact text — a notice, a piece of information, a confirmation. It does not collect variables. ## Fields | Field | Description | | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | **Nome** (Name) | Name shown on the canvas. | | **Mensagem exacta** (Exact message) | The text the agent says, word for word. **{ Variáveis** inserts a variable into the text (e.g. the name collected earlier). | | **Esperar resposta do utilizador** (Wait for the user's reply) | On: the agent says the message and waits for the customer to speak. Off: it says the message and moves straight on to the next node. | ## Connections A Message can go to Conversation, Message, Split path, Jump to, Trigger subflow, Custom action, Send SMS during the call, Transfer, Booking or End call. ## Validation - Error if **Mensagem exacta** is empty. - Error if the node has no next step (at least End call). # Split path The **Dividir o caminho** (Split path) node routes the conversation according to what has happened so far. Each path has a condition and a destination; the **Caso contrário** (Otherwise) path catches everything that matches nothing else. On the canvas, the node shows as **Condição** (Condition). Every [Conversation](https://docs.diska.ai/en/nodes/conversation) node already has a condition after it, with the **Continuar** (Continue) path: that is usually where you add paths. For a full guide to conditions, see [Branches and conditions](https://docs.diska.ai/en/flow-builder/branches). ## Fields | Field | Description | | ------------------------------------- | ---------------------------------------------------------------- | | **Nome do nó** (Node name) | Name shown on the canvas (default "Condição"). | | Path name | A short name for each path (e.g. "Wants to book"). | | **Tipo de condição** (Condition type) | **Prompt LLM** or **Regra determinística** (Deterministic rule). | | **Ir para…** (Go to…) | The step the path leads to. | Conditions are evaluated in order; if none matches, the **Caso contrário** path is taken. ### Prompt LLM Under **Seguir este caminho se** (Follow this path if), describe in natural language when to take the path (e.g. "The customer wants to book a meeting."). **{ Variáveis** inserts a variable into the description. The AI decides based on the conversation. ### Deterministic rule Under **Seguir este caminho se**, choose **Qualquer regra corresponder** (Any rule matches) or **Todas as regras corresponderem** (All rules match), and add rules with **Adicionar** (Add). Each rule has: - **Variável** (Variable) — a flow variable; - **Operador** (Operator) — **É igual a** (equals), **É diferente de** (not equal), **Contém** (contains), **Maior que** (greater than), **Menor que** (less than), **Está vazio** (is empty), **Não está vazio** (is not empty), **É verdadeiro** (is true) or **É falso** (is false); - **Valor de comparação** (Comparison value) — when the operator needs a value. ### Paths - **Adicionar caminho** (Add path) adds a path with a condition. - **Adicionar caso contrário** (Add otherwise) adds the **Caso contrário** path; when it exists, the button shows **Alternativa activa** (Fallback active) and removes it again. ## Validation - Error if the node has no path. - Error if the **Caso contrário** path is missing — without it, an answer that matches no rule would leave the call with no next step. - Error if there is more than one **Caso contrário**. - Error if a **Prompt LLM** path has no description. - Error if a deterministic rule has no variable or operator. # Jump to The **Saltar para** (Jump to) node moves the conversation to another step of the same flow. Use it to go back (for example, to repeat a question) or to reuse a step without crossing connections on the canvas. ## Fields | Field | Description | | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome do nó** (Node name) | Name shown on the canvas. | | **Select** | The list of destination steps. The **Todas** (All), **Conversação**, **Mensagem** and **Disparar subfluxo** filters narrow the list. The chosen destination is highlighted next to the title. | If the list is empty, add more steps to the flow first. ## Possible destinations Conversation, Message, Split path, Trigger subflow, Custom action, Send SMS during the call, Transfer, Booking or End call — always in the same flow. ## Loops Jumping back to an earlier step creates a loop, and that is allowed ("anything else? → answer → ask again"). Validation only warns when no step in the loop can end the call: make sure there is a way out, for example a [Split path](https://docs.diska.ai/en/nodes/split-path) path that leads to [End call](https://docs.diska.ai/en/nodes/end-call). ## Validation - Error if there is no destination. - Error if the destination is the node itself. - Error if the destination no longer exists in the flow. - Warning if the jump creates a loop with no way out. # Trigger subflow The **Disparar subfluxo** (Trigger subflow) node hands the conversation to a subflow of the same agent. When the subflow reaches its **Terminar chamada** (End call), the conversation comes back and continues through the step connected after this node. Subflows are created as tabs in the Flow Designer. See [Flow structure](https://docs.diska.ai/en/flow-builder/structure). ## Fields | Field | Description | | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | | **Escolha que subfluxo disparar** (Choose which subflow to trigger) | The agent's subflows, with the number of nodes and actions in each. Click the subflow you want. | Once chosen, the panel confirms: "Volta a este nó depois de «subflow name» terminar." (Returns to this node after the subflow ends). If there are no subflows yet, create a subflow tab first. ::callout{type="info"} Always connect a step after the Trigger subflow node: that is where the conversation continues when the subflow ends. Variables collected in the subflow remain available in the main flow. :: ## Subflow entry conditions Inside the subflow, the starting node defines when it can be activated. Click **Adicionar condição de entrada** (Add entry condition) and fill in: - the activation checkbox (the condition only counts when ticked); - **Nome da condição** (Condition name); - the type — **Manual**, **Intenção do cliente** (Customer intent), **Condição** (Condition), **Acção com sucesso** (Action succeeded) or **Acção falhou** (Action failed); - the description — "Quando este subfluxo deve ser usado?" (When should this subflow be used?); - for the **Condição** type, the expression (e.g. `intent == suporte ou lead_score > 70`). ## Typical uses - Reuse an identity check at several points of the flow. - Isolate collecting an address or confirming details. - Keep booking or transfer logic in a single place. ## Validation - Error if no subflow is chosen. - Error if the chosen subflow is the flow itself. - In the subflow: warning if there are no active entry conditions; error if an active condition has no type or name. # Custom action The **Acção personalizada** (Custom action) node calls an external API at that point of the flow — for example, to look up an order after collecting its number — and stores the response in a variable. The node uses an action created under **Acções → Acções personalizadas**; the action's own fields (URL, method, authentication, messages) are described in [Custom actions](https://docs.diska.ai/en/actions/custom-actions). ## Attaching the action A new node says "Nenhuma acção anexada a este nó." (No action attached to this node). Click **Anexar acção** (Attach action), search for the action and pick it. The node card then shows the name, URL and method; the bin icon removes the action. ## Action settings Under **Definições da acção** (Action settings): | Field | Description | | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Mapeamento de input** (Input mapping) | A JSON object saying which flow variable fills each of the action's inputs: `{"input": "flow_variable"}`. When you attach the action, its `` inputs are already listed, with an empty value. | | **Guardar resultado em** (Store result in) | Name of the variable where the response is stored (e.g. `crm_result`), for use in later steps. | | **Timeout** | Seconds to wait for the response, from 1 to 120. | Example, with an action that has the `` input and a flow that collected the `order` variable: ```json { "order_number": "order" } ``` ## How the node calls the API The node sends the request to the action's URL, with the method and headers the action had when you attached it. The request body is a JSON object with the **Mapeamento de input** values and the action's identification (`action_id` and `label`). ::callout{type="warning"} The node keeps a copy of the action (URL, method, headers) from the moment you attach it. If you later change the action under **Acções** , attach it to the node again and publish the flow. :: For the agent to use the full action — with the configured request body, authentication and messages — and decide on its own when to call it, attach it under **Acções** on a [Conversation](https://docs.diska.ai/en/nodes/conversation) node. ## Outputs | Output | When | | ------------------------------------- | ------------------------------------------------------------------------------------------------ | | **Sucesso da acção** (Action success) | The API responded successfully. | | **Falha da acção** (Action failure) | The API responded with an error or the request was refused (for example, a private-network URL). | In the **Testar** (Test) panel, with the draft the request is simulated and the flow takes **Sucesso da acção**; with the published version, the API is called. ## Validation - Error if no action is attached ("Este nó não tem nenhuma acção anexada" — this node has no action attached). - Error if the URL is missing. - Error if the timeout is outside 1–120 seconds. # Send SMS during the call The **Enviar SMS durante a chamada** (Send SMS during the call) node sends an SMS at that point of the flow — for example, a payment link right after the customer asks for it. It is sent through Ombala. The node uses an action created under **Acções → SMS durante a chamada**; the action's own fields (body, wait for reply, fallback) are described in [SMS during the call](https://docs.diska.ai/en/actions/during-call-sms). ## Attaching the action A new node says there are no during-call SMS actions attached. Click **Anexar SMS durante a chamada** (Attach SMS during the call) and pick the action. The node card then shows the name and the SMS text; the bin icon removes the action. ## SMS settings Under **Definições do SMS durante a chamada** (During-call SMS settings): | Field | Description | | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Pré-visualização do template** (Template preview) | The SMS text, copied from the action. You can adjust it here: the change applies to this node only. | | **Mapeamento de variáveis de entrada** (Input variable mapping) | A JSON object saying which flow variable fills each `` in the text: `{"code": "generated_code"}`. When you attach the action, the `` placeholders are already listed, with an empty value. | | **Mensagem antes da acção** (Message before the action) | Text copied from the action; only shown when the action has one. | A **Variáveis em falta** (Missing variables) warning lists the mapping entries that still have no variable. A `` is also filled, without mapping, by a flow variable with the same name. ### Recipient By default, the SMS goes to the customer's number on the call. To send it to another number, add the `to` key to the mapping with the name of the variable that holds that number: ```json { "code": "generated_code", "to": "alternative_mobile" } ``` ::callout{type="warning"} The node keeps a copy of the action (text, wait for reply, timeout, fallback) from the moment you attach it. If you later change the action under **Acções** , attach it to the node again and publish the flow. :: ## Outputs | Output | When | | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | **Sucesso da acção** (Action success) | The SMS was sent. With **Aguardar resposta** (Wait for reply) on, also when the timeout ends with no reply. | | **Falha da acção** (Action failure) | There is no destination number (for example, on a web call with no contact), SMS sending is not configured, or the provider refused to send. | In the **Testar** (Test) panel, with the draft the SMS is simulated; with the published version, it is sent. ## Validation - Error if no SMS action is attached. - **Variáveis em falta** (missing variables) warning if a mapping entry has no variable. # Transfer The **Transferência** (Transfer) node, in the **Transferência humana** (Human transfer) category, hands the phone call over to a person at that point of the flow — for example, after collecting the customer's details. - **On a phone call**, the line moves to the destination when it answers and the agent leaves the call. If the destination does not answer, the flow takes **Falha da acção** (Action failure) and the agent stays with the customer. - **On a web call**, there is no phone line: the flow always takes **Falha da acção**. Allowed destinations depend on the call's number (DISKA number or your own SIP trunk) — see [Call transfers](https://docs.diska.ai/en/actions/call-transfers). ## Fields | Field | Description | | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome do nó** (Node name) | Name shown on the canvas (e.g. "Transfer to sales"). | | **Destino** (Destination) | **Telefone** (Phone), **SIP URI**, **Lista telefónica** (Phone book) or **Acção de transferência** (Transfer action). | | **Número de telefone** (Phone number) | With **Telefone**: the number, in international format (e.g. `+244 923 000 000`). | | **SIP URI** | With **SIP URI**: the address (e.g. `sip:agent@example.com`). | | **Lista telefónica** | With **Lista telefónica**: the phone book; the node calls the first number in it. | | **Acção de transferência** | With **Acção de transferência**: an action created under **Acções → Transferências de chamada**. | | **Transferência assistida** (Assisted transfer) | On by default. The person who answers first hears, in the agent's voice, a summary of what the flow collected; only then is the customer connected. | | **Resumo para handoff** (Handoff summary) | With an assisted transfer: how to write the summary the person who answers hears (e.g. "Summarize the request, the details collected and the next step."). | ### «Acção de transferência» destination With an action, the action's own settings apply: the transfer mode (direct or assisted), the availability schedule, the phone book and the messages. The node's **Transferência assistida** and **Resumo para handoff** options do not apply. The action's fields are described in [Call transfers](https://docs.diska.ai/en/actions/call-transfers). ### Queue or team Phone lines have no queues. An older node with the **Fila ou equipa (indisponível)** (Queue or team, unavailable) destination shows the notice "As linhas telefónicas não têm filas: escolha um telefone, SIP URI, lista ou acção para publicar." (Phone lines have no queues: choose a phone, SIP URI, phone book or action to publish) and blocks publishing until you choose another destination. It can still run in tests with the draft. ## Outputs | Output | When | | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Sucesso da acção** (Action success) | The call was transferred. | | **Falha da acção** (Action failure) | The destination did not answer, was busy or rejected the call; the call is a web call; it is outside the action's schedule; or the destination is not allowed on that line. The agent stays with the customer. | Always connect **Falha da acção** to a step that handles it — for example, a [Message](https://docs.diska.ai/en/nodes/message) offering a call back. ## Testing In the **Testar** (Test) panel, with the draft the transfer is simulated and the flow takes **Sucesso da acção**. For a real transfer, use **Testar → Chamada telefónica** (Test → Phone call) with the published version. See [Test an agent](https://docs.diska.ai/en/guides/test-agent). ## Validation - Error if the number, SIP URI, phone book or action is missing, depending on the destination. - Error if the destination is **Fila ou equipa**. - Error if the platform has no phone line available; in that case, remove the node to publish (it remains available in tests with the draft). # Booking The **Agendamento** (Booking) node, in the **Negócio** (Business) category, creates a booking in Cal.com at that point of the flow, with the email and time the flow has already collected. The node uses an action created under **Acções → Agendamento em tempo real**, which sets the Cal.com account, event type, duration and time zone — see [Real-time booking](https://docs.diska.ai/en/actions/real-time-booking). In production, the booking uses the organization's Cal.com connection. ## Fields | Field | Description | | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | **Nome do nó** (Node name) | Name shown on the canvas (e.g. "Book a demo"). | | **Acção de agendamento** (Booking action) | Pick the action from the list (**Seleccionar acção…**) or use **Anexar** (Attach). **Remover** (Remove) disconnects the action. | | **Título** (Title) | The booking title in Cal.com. When you pick the action, it is filled with the event type's title; you can change it. | | **Contacto / email** (Contact / email) | The variable holding the customer's email (e.g. `lead_email`). Accepts `email@domain.com` or `Name `. | | **Horário** (Time) | The variable holding the preferred date and time. | The event type, duration and time zone always come from the selected action. Collect the email and the time in a [Conversation](https://docs.diska.ai/en/nodes/conversation) node before the Booking node, with variables of type **Email** and **String**. ## Outputs | Output | When | | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | **Sucesso da acção** (Action success) | The booking was created in Cal.com. | | **Falha da acção** (Action failure) | The email or time is missing, the email is not valid, Cal.com is not connected or it refused the booking (for example, the time is unavailable). | In the **Testar** (Test) panel, with the draft the booking is simulated (nothing is created in Cal.com); with the published version, it is created. ::callout{type="info"} For the agent to book on its own, at any moment of a step, and send the confirmation SMS configured in the action, attach the action under **Acções** on a [Conversation](https://docs.diska.ai/en/nodes/conversation) node ( **Marcação em tempo real** ) instead of using this node. :: ## Validation - Error if there is neither a booking action nor a title. - Error if the calendar is available and no action is selected ("Seleccione uma acção de Agendamento em tempo real"). - Error if calendar booking is not available on the platform; in that case, remove the node to publish (it remains available in tests with the draft). - Warning if the contact or time variable is missing. # End call The **Terminar chamada** (End call) node says the farewell and ends the call. It is terminal: it has no next step other than the **Depois da conversa** (After the conversation) node. The main flow needs at least one reachable End call. ## Fields | Field | Description | | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome do nó** (Node name) | Name shown on the canvas. | | **Instruções** (Instructions) | The farewell. In **Fixa** (Fixed), write the exact text; in **IA** (AI), write an instruction for the agent to generate the farewell (e.g. "Generate a short, professional goodbye."). **{ Variáveis** inserts a variable into the text. | | **Motivo de fim** (End reason) | **Concluído** (Completed), **Pedido pelo cliente** (Requested by the customer), **Não qualificado** (Not qualified), **Transferido** (Transferred) or **Erro** (Error). | | **Pré-visualização** (Preview) | Shows the farewell as configured. | The panel reminds you: "Terminar chamada é terminal. Diga uma despedida curta antes de desligar." (End call is terminal. Say a short goodbye before hanging up.) ## Actions before hanging up Under **Acções** (Actions), click **Adicionar** (Add) and choose **Marcação em tempo real** (Real-time booking), **Transferência de chamada** (Call transfer), **Acção personalizada** (Custom action) or **SMS durante a chamada** (SMS during the call). Attached actions run automatically before the farewell and before the call ends — for example, to record the outcome in your CRM. See [Actions](https://docs.diska.ai/en/actions). ## After the conversation The **Depois da conversa** button ("Anexe hooks pós-chamada depois de Terminar chamada" — attach post-call hooks after End call) takes you to the node where you attach actions that run after the call ends: Post-call SMS, Information extractor and Custom evaluation. See [Post-call SMS](https://docs.diska.ai/en/actions/post-call-sms), [Information extractors](https://docs.diska.ai/en/actions/information-extractors) and [Custom evaluations](https://docs.diska.ai/en/actions/custom-evaluations). ## Validation - Error if the farewell is missing (text in **Fixa** or instruction in **IA**). - Error if the end reason is missing. - Error if the main flow has no reachable End call — blocks publishing. - Error if End call connects to any node other than After the conversation. # Nodes coming soon These nodes are not available yet and do not appear in the node picker: | Node | Category | What it will do | Status | | --------------------------------------------------------------------- | -------------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Espera** (Wait) | Controlo de fluxo (Flow control) | Pause the flow for a set interval. | Waiting for timing support in the platform. | | **Ciclo** (Loop) | Controlo de fluxo (Flow control) | Repeat a segment of the flow. | The loop model is still being designed. | | **Definir variável** (Set variable) | Acções (Actions) | Assign or update a flow variable. | Dedicated node planned. Meanwhile, collect values under **Recolher variáveis** (Collect variables) on a [Conversation](https://docs.diska.ai/en/nodes/conversation) node. | | **Enviar WhatsApp durante a chamada** (Send WhatsApp during the call) | Canais (Channels) | Send a WhatsApp message during an active call. | Depends on the WhatsApp provider. | | **Enviar email** (Send email) | Canais (Channels) | Send an email from the flow. | The email channel is not connected yet. | To repeat steps today, use [Jump to](https://docs.diska.ai/en/nodes/jump-to) to go back to an earlier step. ::callout{type="info"} When one of these nodes becomes available, it will appear in the node picker and this page will be updated. :: # Nodes Nodes are the steps of a flow. To add one, click a **+** on the canvas — on a connection between two steps, on a condition path or at the end of the flow. The node picker opens, with search (**Pesquisar nós...**) and the nodes grouped by category. Use **↑**/**↓** to move, **↵** to choose and **Esc** to close. A node that cannot follow the step where you clicked shows the **Inválido** (Invalid) label; hover over it to see why. If you copied a node, the first option is **Colar** (Paste). ## Nodes in the picker | Category | Node | Purpose | | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------- | | **Conversação** (Conversation) | [Conversation](https://docs.diska.ai/en/nodes/conversation) — **Conversação** | Collects information and guides the dialogue | | | [Message](https://docs.diska.ai/en/nodes/message) — **Mensagem** | Says an exact message (optionally waits for a reply) | | | [End call](https://docs.diska.ai/en/nodes/end-call) — **Terminar chamada** | Says goodbye and ends the call | | **Controlo de fluxo** (Flow control) | [Trigger subflow](https://docs.diska.ai/en/nodes/trigger-subflow) — **Disparar subfluxo** | Hands the conversation to a subflow and comes back when it ends | | | [Split path](https://docs.diska.ai/en/nodes/split-path) — **Dividir o caminho** | Splits the path based on conditions | | | [Jump to](https://docs.diska.ai/en/nodes/jump-to) — **Saltar para** | Jumps to another node in the flow | | **Acções** (Actions) | [Custom action](https://docs.diska.ai/en/nodes/custom-action) — **Acção personalizada** | Calls an external API and stores the response | | | [Send SMS during the call](https://docs.diska.ai/en/nodes/send-sms-during-call) — **Enviar SMS durante a chamada** | Sends an SMS during an active call | | **Transferência humana** (Human transfer) | [Transfer](https://docs.diska.ai/en/nodes/transfer) — **Transferência** | Transfers the phone call to a person | | **Negócio** (Business) | [Booking](https://docs.diska.ai/en/nodes/booking) — **Agendamento** | Books a meeting or demo | The **Custom action**, **Send SMS during the call**, **Transfer** and **Booking** nodes use actions created under [Actions](https://docs.diska.ai/en/actions) and have two outputs on the canvas: **Sucesso da acção** (Action success) and **Falha da acção** (Action failure). Connect both. ## Structure nodes Every flow has fixed nodes that do not come from the picker: **Antes da conversa** (Before the conversation), **Mensagem de saudação** (Greeting message) and, after **Terminar chamada**, **Depois da conversa** (After the conversation). See [Flow structure](https://docs.diska.ai/en/flow-builder/structure). ## Not available yet Wait, Loop, Set variable, Send WhatsApp during the call and Send email are not available yet and do not appear in the picker. See [Nodes coming soon](https://docs.diska.ai/en/nodes/coming-soon). # Call transfers A **call transfer** moves the active phone call from the agent to another number, to a SIP URI or to a number picked from a phone book. Open **Acções → Transferências de chamada** (Actions → Call transfers). For a complete walkthrough, see the [Transfer to a human](https://docs.diska.ai/en/guides/transfer-to-human) guide. ## Where it works - **Phone calls** — received or placed by the agent, including the phone call from the **Testar** (Test) panel. The line moves to the destination when it answers. - **Web calls** — there is no phone line to transfer: the agent is told and carries on with the conversation. While the destination rings (about 20 seconds), the customer stays on the line with the agent, without hold music. If nobody answers, the destination is busy or rejects the call, the transfer fails and the agent stays with the customer. ### Allowed destinations | The call came in or went out on | Where you can transfer | | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | A **DISKA number** | Only to **Angolan mobile numbers** (Unitel or Africell) fixed in the action, in the flow node or in a phone book. A number the customer says during the conversation is never used. Your organization must be authorized by Diska to place outbound calls on DISKA lines. | | An **imported number** (your carrier's SIP trunk) | To a number or a SIP URI on your trunk's domain (`sip:number@domain`); the call goes out through your trunk. | | A **WhatsApp number** (voice call) | Only to fixed **Angolan mobile numbers**, as on a DISKA number; the customer stays on the same WhatsApp call. See [Voice calls](https://docs.diska.ai/en/whatsapp/calls#transfer-to-a-person). | See [Numbers](https://docs.diska.ai/en/telephony/numbers), [Connect over SIP](https://docs.diska.ai/en/telephony/sip-trunk) and, for what happens on the line, [Phone and SIP transfers](https://docs.diska.ai/en/telephony/transfers). ## The transfers list The list shows **Nome** (Name), **Condição** (Condition), **Destino** (Destination), **Tipo** (transfer mode) and **Runtime** (phone line status). You can filter by destination (**Número**, **SIP URI**, **Lista telefónica**) and by type (**Direta**, **Assistida (mensagem)**, **Assistida (resumo)**). The **Listas telefónicas** (Phone books) button opens phone book management (see the **Phone books** section below). ## Creating a transfer Click **Criar novo** (Create new). The editor has four tabs. ### Geral (General) | Field | Description | | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome** | Action identifier in `snake_case` (e.g. `transfer_sales`). | | **Descrição da condição** (Condition description) | Required. When the transfer should happen (e.g. "the customer asks to speak to a salesperson"). The agent uses this text to decide when to transfer. | | **Transferir para** (Transfer to) | **Número** (Number), **SIP URI** or **Lista telefónica** (Phone book). | | **Número de telefone** (Phone number) | In international format (e.g. `+244 922 884 032`). **Validar** (Validate) checks the format and normalizes the number. | | **SIP URI** | In the form `sip:user@domain`. | | **Lista telefónica** | Pick a phone book; the number is chosen at transfer time (see below). | ### Definições de transferência (Transfer settings) **Modo de transferência** (Transfer mode): | Mode | What happens on a phone call | | ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Transferência direta** (Direct transfer) | The person who answers is connected to the customer right away, with no briefing. | | **Transferência assistida com mensagem** (Assisted, with message) | The person who answers first hears, in the agent's voice, the reason for the transfer ("Chamada transferida pela assistente virtual. Motivo: …"). Only then is the customer connected. | | **Transferência assistida com resumo contextual** (Assisted, with contextual summary) | The person who answers first hears, in the agent's voice, a short summary generated at transfer time from the reason the agent gave. Only then is the customer connected. | If the briefing is not ready in time, the call is connected anyway: a transfer is never lost because of the briefing. Messages for the **customer**: - **Mensagem «A tentar contactar o destinatário»** ("Trying to reach the recipient" message, under **Antes da transferência**) — what the agent tells the customer when the transfer starts. Default: "Deixe-me transferi-lo para um humano. Por favor aguarde." - **Mensagem «Destinatário falhou ou recusou»** ("Recipient failed or declined" message, under **Depois da transferência**) — what the agent says when the transfer cannot be completed. When the destination does not answer, is busy or rejects the call, the agent says the number is unavailable right now. ### Disponibilidade humana (Human availability) Turn on **Activar horário de disponibilidade** (Enable availability schedule) to limit transfers to set hours. When it is off, transfers can happen at any time. - Tick the days and set a start and end time for each (default: Monday to Friday, 09:00–17:00). - **Fuso horário** (Time zone) — the schedule's time zone. It starts as `Africa/Luanda`. - **Mensagem "Humano indisponível"** ("Human unavailable" message) — outside the schedule the transfer does not happen and the agent uses this message. ### Simulação (Simulation) Options used only by the **Simular** button: **Música de espera (id)**, **Mensagens de estágio**, **Max retries (simulação)**, **SIP X-headers**, **Screening (simular)** and **Deteção humana (simular)**. On real phone calls the customer stays with the agent while the destination rings (no hold music) and SIP headers are not sent. Click **Guardar** (Save). ## Simulating Once saved, the **Simular** (Simulate) button at the top of the editor generates the events of a transfer with the options from the **Simulação** tab, without placing any call. The result appears in a notification with the outcome and the destination. To test a real transfer, use **Testar → Chamada telefónica** (Test → Phone call) with the agent's published version; with the draft, the transfer is simulated. See [Test an agent](https://docs.diska.ai/en/guides/test-agent). ## Connecting it to the agent - **Prompt Builder** — under **Acções → Durante a conversa**, click **Adicionar → Transferência de chamada** and pick the action. The agent transfers when the **Descrição da condição** is met, and states the reason for the transfer. - **Flow Designer** — in a [Transfer](https://docs.diska.ai/en/nodes/transfer) node with the **Acção de transferência** (Transfer action) destination, or under **Acções** on a Conversation or End call node (**Transferência de chamada**). ## Phone books A phone book groups several numbers, each with a condition, to route the transfer to the right person. 1. In **Transferências de chamada**, click **Listas telefónicas** and then **Novo** (New). 2. Give the phone book a **Nome** (Name). 3. For each entry, enter the **Número de telefone** (Phone number) and the **Condição de transferência** (Transfer condition, e.g. "When the user asks for sales"). Use **Adicionar** (Add) for more entries (up to 50). 4. Click **Guardar**. How the number is chosen: - When the agent decides to transfer (Prompt Builder, or a transfer attached to a Conversation step), the platform uses the first entry whose condition has words that appear in the reason the agent gave; if none matches, it uses the first number in the phone book. - In a flow's **Transfer** node, the first number in the phone book is used. A phone book linked to transfers cannot be deleted. See the [Configure a phone book](https://docs.diska.ai/en/guides/configure-phone-book) guide. # IVR When the agent calls a company that answers with an automated menu ("press 1 for sales, 2 for support…"), the **IVR** action tells it where it wants to get to and which keys exist. During the call, the agent listens to the menu and presses the keys on the line. Open **Acções → IVR**. ## Where it works - **Outbound phone calls** — the agent presses the keys (DTMF) on the call's line. - **Web calls** — there is no phone line: the agent is told it cannot press keys and carries on with the conversation. The **Telefonia SIP** row in the **Integrações** box (and the status at the top of the page) must be **Ativo** (Active). See [Actions](https://docs.diska.ai/en/actions). ## Creating an IVR action Click **Criar novo** (Create new) and fill in: | Field | Description | | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome** (Name) | Required, free text up to 64 characters (e.g. "Reach sales"). | | **Instruções de IVR** (IVR instructions) | Required. Where the agent should try to get to in the menu (e.g. "Navigate to the sales department."). The agent receives this goal together with the menu. | | **Itens do menu** (Menu items) | Optional. Each item has a **digit** and a **label** (e.g. `1` → Sales). Use the branch icon to add a submenu to an item and the bin icon to remove it. | For digits, use `0`–`9`, `*` and `#`. If you do not know the menu, leave the items empty and describe the goal in the instructions. ::callout{type="tip"} To use this feature, the agent must wait for what it hears on the line before speaking. On an outbound agent that will meet an IVR, set the greeting to **Humano fala primeiro** (Human speaks first). :: Click **Guardar** (Save). The list shows **Nome**, **Objectivo** (the instructions) and **Agentes**. ## Simulating the plan Once saved, **Simular plano** (Simulate plan) walks the menu through the first item of each level and shows, under **Última simulação** (Last simulation), the key path (**Path**), whether the menu is valid and the steps (digit — label). No key is pressed on any call. The menu is invalid when there are repeated digits on the same level or items without a digit. ## Connecting it to the agent In the Prompt Builder, open **Acções → Antes da conversa** (Actions → Before the conversation), click **Adicionar → Tratamento IVR** (Add → IVR handling) and pick the action. From then on, on every call the agent can press the keys when it hears the menu. To test with a real call, use **Testar → Chamada telefónica** (Test → Phone call) with the published version; with the draft, key presses are simulated. See [Test an agent](https://docs.diska.ai/en/guides/test-agent). ::callout{type="info"} IVR handling only exists for Prompt Builder agents: in flow agents, the **Antes da conversa** node does not offer it. :: # SMS during the call An **SMS during the call** is sent while the conversation is going on, for example with a verification code, a link or the details of a confirmation. It is sent through Ombala. Open **Acções → SMS durante a chamada** (Actions → SMS during the call). For a walkthrough, see the [Send SMS](https://docs.diska.ai/en/guides/send-sms) guide. ## Before you start The **SMS (Ombala)** row in the **Integrações** box must be **Ativo** (Active). With **Por configurar** ("O envio por SMS ainda não está configurado na plataforma." — SMS sending is not configured on the platform yet), sending fails on real calls. Delivery depends on the carrier and the recipient. ## Creating an SMS Click **Criar novo** (Create new) and fill in: | Field | Description | | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | | **Nome da acção** (Action name) | Required, in `snake_case` (e.g. `send_code`). | | **Mensagem antes da acção** (Message before the action) | What the agent says before sending (e.g. "I'll send you the code now."). | | **Corpo da mensagem** (Message body) | Required. The SMS text. Use `` for values that change on each call (e.g. `Your code is .`). | | **Variáveis de placeholder** (Placeholder variables) | Read-only list of the `` placeholders found in the body. | Under **Definições de resposta** (Reply settings): | Field | Description | | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | **Aguardar resposta** (Wait for reply) | The agent pauses until the customer replies by SMS. | | **Tempo limite (segundos)** (Timeout, seconds) | From 1 to 600. The actual wait never exceeds **45 seconds**, so the conversation is not left hanging. | | **Mensagem de fallback** (Fallback message) | Text handed back to the agent when the timeout ends without a reply (e.g. "I haven't received your reply yet. Shall I resend it?"). | ::callout{type="warning"} The SMS provider only sends messages: SMS replies do not reach Diska yet. With **Aguardar resposta** on, the wait always ends at the timeout (at most 45 seconds) and the agent carries on with the fallback message. :: Click **Guardar** (Save). The list shows **Nome**, **Corpo da mensagem**, **Resposta** (**Aguarda resposta** — waits for reply — or **Sem espera** — no wait), **Agentes** and **Runtime** (SMS status). ## Simulating Once saved, the editor shows the **Simulação** (Simulation) section: - **Destinatário** (Recipient) — a number (e.g. `+244…`); - **Resposta simulada** (Simulated reply) — the reply the customer "would" give (default "Sim, confirmo."); - **Forçar timeout** (Force timeout) — simulates the timeout ending with no reply. Click **Simular** (Simulate) at the top of the editor. The result shows the status, the simulated reply or, on timeout, the fallback message. No SMS is sent. ## Connecting it to the agent - **Prompt Builder** — under **Acções → Durante a conversa**, **Adicionar → SMS durante a chamada**. The agent decides when to send, says the message before the action and fills the `` placeholders with data from the conversation. By default, the SMS goes to the customer's number on the call. - **Flow Designer** — with the [Send SMS during the call](https://docs.diska.ai/en/nodes/send-sms-during-call) node, or under **Acções** on a Conversation or End call node (**SMS durante a chamada**). ## Phone call or web call On a phone call, the customer's number is known and the SMS goes to it. On a web call, the SMS is only sent if the call has a destination number (for example the **Contacto do chamador** — caller contact — entered in the test, or a number mapped in the flow); with no number, sending fails. In the **Testar** panel, with the draft the SMS is simulated; with the published version it is sent. # Post-call SMS A **post-call SMS** is sent after the call ends, when the conversation meets a condition you set — for example, "the customer asked for the price list". It is sent through Ombala. Open **Acções → SMS pós-chamada** (Actions → Post-call SMS). ## Before you start The **SMS (Ombala)** row in the **Integrações** box must be **Ativo** (Active); otherwise the SMS is not sent. ## Creating a post-call SMS Click **Criar novo** (Create new) and fill in: | Field | Description | | --------------------------------------------------------- | ------------------------------------------------------------------------------------- | | **Nome** (Name) | Required, in `snake_case` (e.g. `send_prices`). | | **Descrição da condição** (Condition description) | Required. When the message should be sent (e.g. "the customer asked for the prices"). | | **Conteúdo do SMS (variante A)** (SMS content, variant A) | Required. The SMS text. Use `` for dynamic values. | | **Variante B (A/B opcional)** (Variant B, optional A/B) | Alternative text for an A/B test. | | **Variáveis de placeholder** (Placeholder variables) | Read-only list of the `` placeholders found in the content. | Click **Guardar** (Save). The list shows **Nome**, **Condição**, **Conteúdo do SMS**, **Agentes** and **Runtime** (SMS status). ## What happens after the call 1. The platform reads the transcript and the AI decides whether the **Descrição da condição** is met. With no transcript, the SMS is not sent. 2. If there is a variant B, one of the variants is picked; the same recipient always gets the same one. 3. `` placeholders are filled with the call variables of the same name, including the values of [information extractors](https://docs.diska.ai/en/actions/information-extractors) (by extractor name or by its typed variable). A `` with no value is left empty. 4. The SMS goes to the customer's number. If the call has none (for example a web call), a number found in the conversation or an extractor named `phone` is used; with no number, the SMS is not sent. The outcome of each SMS (sent, skipped or failed, and the variant used) appears under **Históricos** (History), in the call detail, **Análise → SMS pós-chamada** tab (Analysis → Post-call SMS). See [Calls](https://docs.diska.ai/en/history/calls). ## Simulating (dry-run) Once saved, the editor shows the **Dry-run** section: - **Destinatário (E.164)** (Recipient) — a test number; - **Transcrição (para condição)** (Transcript, for the condition) — an excerpt of conversation. Click **Simular** (Simulate). The notification says **Dry-run: enviaria** (would send) or **Dry-run: não envia** (would not send), with the reason. No SMS is sent. ::callout{type="info"} The dry-run does a simplified check: it looks for the condition's words in the transcript. On a real call, the AI evaluates the condition against the full transcript. :: ## Connecting it to the agent - **Prompt Builder** — under **Acções → Depois da conversa**, **Adicionar → SMS pós-chamada**. - **Flow Designer** — on the **Depois da conversa** (After the conversation) node, after End call, **Adicionar → SMS pós-chamada**. On real calls, the agent's published configuration applies. In a test with the draft, the condition is evaluated but the SMS is not sent. # Custom actions A **custom action** makes an HTTP request to an external API — your CRM, booking system or ERP — and hands the response back to the agent. Open **Acções → Acções personalizadas** (Actions → Custom actions). The list shows **Nome** (Name), **Método** (Method), **URL do endpoint** (Endpoint URL), **Autenticação** (Authentication), **Agentes** and **Estado** (Status: **Não inicializado** — not initialized, **Inicializado** — initialized, or **Falhou** — failed), with filters by method, authentication and status. ## Creating an action Click **Criar novo** (Create new). The editor has two columns: on the right you configure the action, on the left (**Resultados** — Results) you test it. **Ocultar resposta** / **Ver resposta** (Hide / Show response) hides or shows the results column. ### «Configurar» tab (Configure) | Field | Description | | ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome da acção** (Action name) | Required, in `snake_case` (e.g. `check_order`). | | **Descrição** (Description) | Tell the AI how and when to use this tool (e.g. "Use when the customer asks about an order's status."). In a Prompt Builder agent, this is the text the agent uses to decide to call the API. | | **Método do endpoint e URL** (Endpoint method and URL) | `GET`, `POST`, `PUT`, `PATCH` or `DELETE`, and the full URL. Use `` for variable parts (e.g. `https://api.example.ao/orders/`). | | **Autenticação** (Authentication) | **Sem autenticação** (None) or **Personalizada** (Custom). For custom, enter a **Bearer token** (sent as `Authorization: Bearer …`) or a **Cabeçalho** (Header) and its **Valor** (Value). These values are stored encrypted. | | **Tempo limite** (Timeout) | From 1 to 30 seconds (**Máx. 30 segundos**). With **Sem tempo limite** (No timeout), the platform waits up to 10 seconds. | | **Cabeçalhos** (Headers) | Key/value pairs; the key cannot be empty. | | **Corpo do pedido** (Request body) | JSON sent with `POST`, `PUT` and `PATCH` (disabled for `GET` and `DELETE`). It must be valid JSON and cannot be empty. Use `` for dynamic values. | | **Variáveis de entrada** (Input variables) | Detected automatically from the URL, headers and body. | The URL cannot point to local or private-network addresses: Diska rejects it for security. ### «Instruções de IA» tab (AI instructions) What the agent should say at each stage of the action: | Field | Description | | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | **Mensagem inicial** (Start message) | What to say when the action starts running. | | **Mensagem de atraso** (Delay message) | What to say if the action takes longer than expected. | | **Limiar de atraso** (Delay threshold) | How long to wait (0–30 s) before the delay message. | | **Max retries (HTTP)** | From 0 to 5. Shown in the simulation; on calls, the action makes a single request. | | **Mensagem de falha** (Failure message) | What to say if the action fails. | | **Deixar o agente falar naturalmente** (Let the agent speak naturally) | The agent says something that fits the context and falls back to your messages if it cannot. Turn it off to use only your messages. | Click **Guardar** (Save). ## Testing: Inicializar and Simular In the **Resultados** column, under **Configurar entradas** (Configure inputs), enter a **Valor de teste** (Test value) for each **Variável dinâmica** (Dynamic variable). Then: - **Inicializar** (Initialize) — saves the action and makes the real request to the API with the test values. **Estado** becomes **Inicializado** (2xx response) or **Falhou**, and the response appears under **Corpo da resposta** (Response body). - **Simular (sem HTTP live)** (Simulate, no live HTTP) — available once saved. Shows the request that would be sent and the agent's message sequence, without calling the API. ## Connecting it to the agent ### Prompt Builder Under **Acções**, a custom action can go into all three groups: | Group | What happens | | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Antes da conversa** (Before the conversation) | The API is called before the conversation starts; the response becomes available as call variables. The conversation only starts once the request finishes, so use fast APIs. | | **Durante a conversa** (During the conversation) | The agent calls the API when the **Descrição** says so and fills the `` placeholders with data from the conversation. The response fields become available as action results. | | **Depois da conversa** (After the conversation) | The API is called after the call ends. | Each attached action has an optional **Mapeamento de variáveis** (Variable mapping, source → target) to fill the inputs from call variables. ### Flow Designer - With the [Custom action](https://docs.diska.ai/en/nodes/custom-action) node, at a fixed point of the flow. - Under **Acções** on a Conversation node (the agent uses it when needed, during that step) or on an End call node (it runs before the farewell). - On the **Antes da conversa** node. In the **Testar** panel, with the draft the requests are simulated; with the published version, the API is called. # Information extractors An **information extractor** reads the transcript after the call and answers a question about it — for example, "Is the customer interested in the service?" or "What is the customer's email?". The value is stored with the call and sent in the post-call webhook. Open **Acções → Extratores de Informação** (Actions → Information extractors). The list shows **Nome** (Name), **Dados a extrair** (Data to extract), **Tipo** (Type) and **Agentes**, with a filter by type. ## Creating an extractor Click **Criar novo** (Create new) and choose: - **Novo extrator** (New extractor) — start from scratch; - **Explorar templates** (Browse templates) — opens **Templates de Extratores**, with ready-made templates (`user_name`, `user_email`, `user_company`, `user_address`, `dnd`, `call_outcome`, `reason_for_call`, `issue_description`, `user_interest_level`, `callback_requested`, `budget_range`, `lead_qualification`). Pick one and click **Usar este modelo** (Use this template); you can edit everything afterwards. Fill in: | Field | Description | | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome** (Name) | Required, in `snake_case`. It is the value's key in the post-call webhook (e.g. `user_email`). | | **Variável tipada (binding)** (Typed variable) | Optional. The name of a variable where the value is also stored (e.g. `customer_name`). | | **Tipo** (Type) | **Sim / Não** (Yes / No — true or false), **Escolha Única** (Single choice — one of several options) or **Pergunta Aberta** (Open question — free text). | | **Dados a extrair** (Data to extract) | Required. The question, in plain text (e.g. "Is the user interested in the service?"). Do not use JSON or the characters `{}`, `[]` or `<>`. | | **Opções** (Options) | **Escolha Única** only: at least two. The value is always one of these options, or empty. | | **Exemplos de saída** (Output examples) | **Pergunta Aberta** only, optional: they help the AI follow the format (e.g. `João Silva`). | Click **Guardar** (Save). ## Re-run: test without a new call Once saved, paste an excerpt of conversation into **Transcrição (re-run sem nova chamada)** (Transcript, re-run without a new call) and click **Re-run**. The notification shows the extracted value. No call is made. ## Connecting it to the agent - **Prompt Builder** — under **Acções → Depois da conversa**, **Adicionar → Extrator de informação**. - **Flow Designer** — on the **Depois da conversa** (After the conversation) node, **Adicionar → Extrator de informação**. Extractors run after each of the agent's calls. ## Where to see the results - Under **Históricos** (History), in the call detail, **Análise → Dados extraídos** tab (Analysis → Extracted data), with the **Histórico por extractor** (per-extractor history). When the information is not in the conversation, the value is empty and shown as `n.a.`. See [Calls](https://docs.diska.ai/en/history/calls). - In the post-call webhook, under `extracted_data`. See [Webhooks](https://docs.diska.ai/en/api/webhooks). - In [post-call SMS](https://docs.diska.ai/en/actions/post-call-sms): a `` matching the extractor's name (or its typed variable) is filled with the extracted value. With [Redact personal data](https://docs.diska.ai/en/guides/redact-personal-data) on, the post-call SMS and custom actions still receive the real value; the value stored in **Históricos** and sent in the webhook carries the tag (for example `[NOME]`). ::callout{type="tip"} If your calls are web calls and you want to send post-call SMS, create a **Pergunta Aberta** (Open question) extractor named `phone` that captures the customer's mobile number: when the call has no number, the post-call SMS uses that value. :: # Custom evaluations A **custom evaluation** scores the conversation after the call against a criterion you define — for example, "Was the agent professional and did it confirm the customer's details?". The result says whether the call **Passou** (Passed) or **Falhou** (Failed). Open **Acções → Avaliações Personalizadas** (Actions → Custom evaluations). The list shows **Nome** (Name), **O que avaliar** (What to evaluate), **Tipo de saída** (Output type, with the pass threshold) and **Agentes**, with a filter by output type. ::callout{type="info"} These evaluations run on real calls, after they end. To test an agent against scenarios before publishing it, use the [Test Center](https://docs.diska.ai/en/test-center/evaluations) evaluations. :: ## Creating an evaluation Click **Criar novo** (Create new) and fill in: | Field | Description | | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome da acção** (Action name) | Required, in `snake_case` (e.g. `booking_confirmed`). | | **O que avaliar** (What to evaluate) | Required. The criterion, in natural language (e.g. "Assess the agent's tone and professionalism during the call"). | | **Tipo de saída** (Output type) | **Numérico** (Numeric, a 1 to 10 scale), **Descritivo** (Descriptive: Excelente, Bom, Razoável, Fraco), **Escala Likert** (Likert scale, from Concordo totalmente to Discordo totalmente) or **Verdadeiro / Falso** (True / False). | | **Limite de aprovação** (Pass threshold) | The reference value for passing: a number from 1 to 10 for the numeric type, or one of the scale values for the other types (see below). | | **Rubricas (scorecard)** (Rubrics) | Optional. Use **Critério** (Criterion) to add criteria with a name (e.g. `empathy`), a weight and a description. | Click **Guardar** (Save). ### How «Passou» or «Falhou» is decided - **Numérico** — passes when the score is equal to or above the threshold. - **Verdadeiro / Falso** — passes when the result equals the value chosen as the threshold. - **Descritivo** and **Escala Likert** — passes when the result matches the value chosen as the threshold. To pass "from" a level upwards, prefer the **Numérico** type. On calls, rubrics appear as an indicative scorecard with a weighted score; the **Passou**/**Falhou** result comes from the evaluation compared with the pass threshold. ## Simulating Once saved, paste an excerpt of conversation into **Transcrição de teste (simular)** (Test transcript) and click **Simular** (Simulate). The notification shows **Simulação: passou** (passed), **Simulação: falhou** (failed) or **Simulação: sem resultado conclusivo** (no conclusive result). No call is made. If the evaluation has rubrics, the simulation gives every criterion the same test score and the result shown comes from that score. To see how the AI evaluates the transcript, simulate before adding rubrics. ## Connecting it to the agent - **Prompt Builder** — under **Acções → Depois da conversa**, **Adicionar → Avaliação personalizada**. - **Flow Designer** — on the **Depois da conversa** (After the conversation) node, **Adicionar → Avaliação personalizada**. ## Where to see the results - Under **Históricos** (History), in the call detail, **Análise → Avaliações / scorecards** tab: each evaluation with **Passou**, **Falhou** or `n.a.`, the rationale and the scorecard. The **CSV** button exports the evaluations. See [Calls](https://docs.diska.ai/en/history/calls). - In the post-call webhook, under `evaluations`. See [Webhooks](https://docs.diska.ai/en/api/webhooks). # Real-time booking A **real-time booking** action lets the agent create a booking in Cal.com during the call, on an event type from your account. Open **Acções → Agendamento em tempo real** (Actions → Real-time booking) — it is the first page of the Actions area. For a walkthrough, see the [Book meetings](https://docs.diska.ai/en/guides/book-meetings) guide. ## Before you start Connect your Cal.com account under **Definições → Integrações** (Settings → Integrations). Without the connection you cannot save a booking action. See [Cal.com](https://docs.diska.ai/en/integrations/calcom). ## Creating an action Click **Criar novo** (Create new) and choose **Cal.com** ("Criar marcações a partir de tipos de evento Cal.com e slots disponíveis." — create bookings from Cal.com event types and available slots). Fill in: | Field | Description | | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome da acção** (Action name) | Required, in `snake_case` (e.g. `book_demo`). | | **Conta Cal.com** (Cal.com account) | Connection status and the account email. The settings icon takes you to **Definições → Integrações**. | | **Evento** (Event) | Required. The Cal.com event type (title, ID, duration and location). The refresh button reloads the event types. | | **Fuso horário** (Time zone) | Under **Sugestões de disponibilidade** (Availability suggestions): **África/Luanda** (default), **Europa/Lisboa** or **UTC**. It is the time zone sent to Cal.com with the booking. | | **SMS de confirmação** (Confirmation SMS) | Switch and text of the SMS sent to the customer after the booking is created. | Cal.com sends the booking confirmation email to the guest's email (``), which you set when connecting the action to the agent. Click **Guardar** (Save). The list shows **Nome**, **Evento**, **Fuso** (Time zone), **SMS** (**Ativo** / **Desativado** — on / off) and **Cal.com** (**Configurado** / **Por configurar** — configured / not configured). ::callout{type="info"} Under **Sugestões de disponibilidade** , automatic suggestion of free slots is shown as **em breve** (coming soon). For now, the agent books the time the customer asks for and Cal.com checks availability. :: ### Confirmation SMS With the switch on, after creating the booking the agent sends an SMS to the customer's number on the call (requires the **SMS (Ombala)** row to be **Ativo**). In the text you can use: - `` — guest name; - `` — guest email; - `` — date and time of the booking; - `` — event title; - `` — booking identifier. The confirmation SMS is sent when the booking is made by a Prompt Builder agent or by a booking attached to a Conversation step of a flow. ## Connecting it to the agent ### Prompt Builder Under **Acções → Durante a conversa**, click **Adicionar → Agendamento em tempo real** and pick the action. Click the action's card to open **Variáveis de entrada** (Input variables) and choose where the guest's email (`{lead_email}`) comes from: | Source | Description | | -------------------------------------------------- | ------------------------------------------------------------------------------------------- | | **Recolhido pelo agente** (Collected by the agent) | Default. The agent asks for the email during the call, following the instruction you write. | | **Saída de acção** (Action output) | The email comes from a custom action's response. | | **Sistema** (System) | A system variable. | | **Variáveis pré-chamada** (Pre-call variables) | A variable received before the call starts. | | **Valor fixo** (Fixed value) | A fixed email. | The agent asks for the preferred date and time, and creates the booking once it has the email and the time. ### Flow Designer - With the [Booking](https://docs.diska.ai/en/nodes/booking) node, at a fixed point of the flow. - Under **Acções** on a Conversation node (**Marcação em tempo real** — real-time booking): the agent can book at any moment of that step. Each step accepts one booking. ## What happens on the call - The booking is created in Cal.com with the organization's connected account, on the action's event type and duration. - If the email is not valid or the date and time are missing, no booking is made and the agent is told. - If the time is not available, Cal.com refuses and the agent is told. In the **Testar** panel, with the draft the booking is simulated (nothing is created in Cal.com); with the published version, it is created. # Actions **Actions** give the agent abilities beyond the conversation itself: transfer the call, press keys in an IVR menu, send SMS, call your company's API, extract data from and score the call, and book meetings in Cal.com. You create each action once, in the **Acções** (Actions) area of the side menu, and then connect it to the agents that use it. The same action can serve several agents. ## Action types | Action | When it runs | What it is for | | --------------------------------------------------------------------------------- | ----------------------- | ----------------------------------------------------------------------- | | [Call transfers](https://docs.diska.ai/en/actions/call-transfers) | During the call | Hand a phone call over to a person (number, SIP URI or phone book). | | [IVR](https://docs.diska.ai/en/actions/ivr) | During the call | Navigate voice menus (DTMF keys) on outbound phone calls. | | [SMS during the call](https://docs.diska.ai/en/actions/during-call-sms) | During the call | Send a code, link or confirmation by SMS while the call is in progress. | | [Post-call SMS](https://docs.diska.ai/en/actions/post-call-sms) | After the call | Send a follow-up SMS when a condition is met. | | [Custom actions](https://docs.diska.ai/en/actions/custom-actions) | Before, during or after | Call an external HTTP API and use the response. | | [Information extractors](https://docs.diska.ai/en/actions/information-extractors) | After the call | Extract a piece of data from the conversation (yes/no, choice, text). | | [Custom evaluations](https://docs.diska.ai/en/actions/custom-evaluations) | After the call | Score the conversation against your own criterion. | | [Real-time booking](https://docs.diska.ai/en/actions/real-time-booking) | During the call | Create a booking on a Cal.com event type. | ## The Actions area Open **Acções** in the side menu. The bar on the left lists the eight types, with the number of actions of each; the area opens on **Agendamento em tempo real** (Real-time booking). Every list works the same way: - **Pesquisar...** (Search) filters by name; some types have extra filters (destination, type, method, status). - **Criar novo** (Create new) opens the editor. Clicking a row opens the action for editing. - Each row's **⋮** menu has **Copiar ID** (Copy ID), **Duplicar** (Duplicate) and **Eliminar** (Delete). - In the editor, **Usado em agentes** (Used in agents) shows which agents use the action. - If you close the editor with unsaved changes, Diska asks whether to **Descartar** (Discard) or **Continuar a editar** (Keep editing). Most actions have a **Nome** (Name) that is a `snake_case` identifier (lowercase letters, digits and `_`, up to 64 characters): the editor converts what you type, so "Transferir Vendas" becomes `transferir_vendas`. The IVR accepts a free-text name. Creating, editing and deleting actions requires the **Proprietário** (Owner), **Administrador** (Administrator) or **Membro** (Member) role. The **Visualizador** (Viewer) role can only look. See [Members](https://docs.diska.ai/en/settings/members). ### The «Integrações» box At the bottom of the side bar, the **Integrações** (Integrations) box shows whether the services that actions depend on are ready. The status refreshes on its own every 15 seconds. | Row | What it shows | | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **SMS (Ombala)** | Whether SMS sending is configured on the platform. Used by SMS during and after the call and by the booking confirmation SMS. | | **Telefonia SIP** (SIP telephony) | Whether the platform's phone line is ready. Used by transfers and the IVR, which only run on phone calls. | | **Webhook pós-chamada** (Post-call webhook) | Whether there is a destination for post-call events: an organization webhook subscribed to `call.completed`, or a **Webhook** under **Depois da conversa** (After the conversation) on a published agent. See [Webhooks](https://docs.diska.ai/en/api/webhooks). | | Status | Meaning | | ----------------------------------- | ---------------------------------------------------------- | | **Ativo** (Active) | Ready to use. | | **Por configurar** (Not configured) | Not configured yet. | | **Indisponível** (Unavailable) | The phone line is configured but not responding right now. | | **Não confirmado** (Not confirmed) | The check failed; use **Tentar novamente** (Try again). | | **A verificar…** (Checking…) | The check is running. | The transfer editor, the IVR page and the SMS editors show the same status at the top. ## Connecting an action to an agent Creating the action is not enough: you must connect it to the agent and publish the agent. ### Prompt Builder agent In the agent editor, open the **Acções** (Actions) panel. Actions are grouped into three moments; in each group click **Adicionar** (Add) and pick the action. | Group | What you can add | How it runs | | ------------------------------------------------ | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | **Antes da conversa** (Before the conversation) | Custom action, IVR handling (**Tratamento IVR**) | The custom action runs before the conversation starts. The IVR becomes available for the agent to press keys during the call. | | **Durante a conversa** (During the conversation) | Real-time booking, Call transfer, Custom action, SMS during the call | The agent decides when to use each action, based on the action's condition or description. | | **Depois da conversa** (After the conversation) | Post-call SMS, Information extractor, Custom evaluation, Custom action, Webhook | Runs after the call ends. | **WhatsApp durante a chamada** (WhatsApp during the call) and **Conectores MCP** (MCP connectors) show the **Em breve** (Coming soon) label and cannot be added yet. See [Prompt Builder](https://docs.diska.ai/en/concepts/prompt-builder). ### Flow Designer agent In a flow, actions come in three ways: - **As a node** — the [Custom action](https://docs.diska.ai/en/nodes/custom-action), [Send SMS during the call](https://docs.diska.ai/en/nodes/send-sms-during-call), [Transfer](https://docs.diska.ai/en/nodes/transfer) and [Booking](https://docs.diska.ai/en/nodes/booking) nodes run the action at that point of the flow and have two outputs: **Sucesso da acção** (Action success) and **Falha da acção** (Action failure). - **Attached to a step** — under **Acções** on a [Conversation](https://docs.diska.ai/en/nodes/conversation) node (the agent can use them at any moment of that step) or on an [End call](https://docs.diska.ai/en/nodes/end-call) node (they run before the farewell). You can attach Real-time booking, Call transfer, Custom action and SMS during the call. - **On the structure nodes** — **Antes da conversa** accepts Custom action (IVR handling only exists for Prompt Builder agents); **Depois da conversa** accepts Post-call SMS, Information extractor and Custom evaluation. See [Flow structure](https://docs.diska.ai/en/flow-builder/structure). ## Phone call or web call | Action | Phone call | Web call (browser, widget, public link) | | ----------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------- | | Call transfer | The line moves to the destination when it answers. | There is no line to transfer: the agent is told and carries on with the conversation. | | IVR | The agent presses the keys on the line. | There is no line: the agent is told and carries on with the conversation. | | SMS during the call | Sent to the customer's number. | Only sent if the call has a destination number. | | Post-call SMS | Sent to the customer's number. | Only sent if there is a customer number (for example, collected in the conversation). | | Custom action, extractors, evaluations, booking | Work the same way. | Work the same way. | See [Phone calls](https://docs.diska.ai/en/telephony/phone-calls). ## Testing without real effects Each editor has its own simulation (**Simular**, **Simular plano**, **Re-run** or **Inicializar**), described on each action's page. In the agent's **Testar** (Test) panel, the version under test decides what happens. The panel header shows **Rascunho** (Draft) or **Publicado** (Published); for the phone call you pick it under **Versão do agente** (Agent version). - **Draft** (**Rascunho — ações simuladas**, "draft — simulated actions"): SMS, bookings, transfers, IVR and API calls are simulated; nothing leaves the platform. After the call, extractors and evaluations still run, but the post-call SMS is not sent. - **Published** (e.g. **V3 publicada — ações reais**, "V3 published — real actions"): actions run for real. See [Test an agent](https://docs.diska.ai/en/guides/test-agent). ::callout{type="warning"} Actions have no versions. When you change an action under **Acções** (a transfer number, an API URL, a condition), the change applies immediately to every agent that uses it, including published ones. The exception is the **Custom action** and **Send SMS during the call** nodes, which keep a copy of the action from the moment you attach it: to apply changes to those nodes, attach the action again and publish the flow. :: # Sources Each knowledge base takes content in four ways. Open the base under **Conhecimento** and use the **Adicionar item** (Add item) button — or, in an empty base, the shortcuts in the middle of the page. | Option | Type in the table | Use it for | | ----------------------------------------------------- | ----------------- | ---------------------------------------------------------- | | **Carregar PDFs** (Upload PDFs) | PDF | Manuals, price lists, regulations you already have as PDF. | | **Criar documento em branco** (Create blank document) | Manual | Writing or pasting text directly (FAQs, standard answers). | | **Importar de URL** (Import from URL) | URL | One public page of your website. | | **Crawl de site** (Site crawl) | URL | Several pages of the same site at once. | Every source is indexed automatically when it is added or edited: the text is split into segments and prepared for the semantic search the agent runs during the conversation. ## PDF 1. Choose **Carregar PDFs**, or drag the files onto the **Arraste PDFs para aqui** (drop PDFs here) area of the base page. You can send several PDFs at once. 2. A progress bar follows each upload. 3. When it finishes, a message gives the result: - **Texto extraído e indexado para retrieval.** — text extracted and indexed, ready to use. - **Texto extraído; indexação pendente ou parcial.** — the text exists but indexing has not finished or failed; use **Reindexar** (Reindex). - **Ficheiro guardado. Extração limitada / indexing pending.** — the PDF has no text the platform can read. Limits and rules: - Only valid PDF files are accepted, up to 25 MB each. - Text is read from the first 100 pages of each PDF. - The PDF must contain **selectable text**. A scanned PDF (images of pages) is stored, but without text, and the agent cannot use it. Export a version with text or copy the content into a blank document. The original file is kept: use **Descarregar** (Download) in the row menu to get it back. ## Written document 1. Choose **Criar documento em branco**. 2. Fill in **Nome** (Name) and **Conteúdo** (Content, up to 200,000 characters). 3. Click **Guardar** (Save). These are the only documents you can change in the platform: use **Editar** (Edit) in the row menu. Editing reindexes the document. ::callout{type="tip"} Give documents descriptive names (for example "Prices — business plans"). The name is shown as the source of every excerpt the agent uses, which makes it easier to see where an answer came from. :: ## Web page (URL) 1. Choose **Importar de URL**. 2. Fill in **Nome** and **URL da página** (page URL) — a full `https://…` address. 3. Click **Adicionar URL** (Add URL). The platform reads the visible text of that single page (it does not follow links). Only public pages are accepted: local and private-network addresses are blocked. The content is imported once — if the page changes, delete the document and import it again. ## Site crawl 1. Choose **Crawl de site**. 2. Fill in **Nome**, **URL inicial** (start URL) and **Máximo de páginas** (maximum pages, 1 to 10). 3. Click **Iniciar crawl** (Start crawl). The platform starts at the start URL and follows links within the **same domain**, creating one URL document per page (named after the page title). The platform also applies its own per-crawl page limit, so it may import fewer pages than the maximum you set — the **Crawl concluído** (crawl finished) message says how many pages were imported. As with URL import, the content is not refreshed automatically. ## Document states The **Estado** (State) column shows whether a document is ready to be used, with a short explanation underneath when useful. | State | Meaning | What to do | | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | **Indexado** (Indexed) | Text segmented and indexed. The agent finds it when it searches during the conversation. | Nothing. | | **Pronto** (Ready) | Text available, but indexing has not been confirmed. | If the agent does not find it, use **Reindexar**. | | **Indexação pendente** (Indexing pending) | The text exists and is waiting to be indexed. | Wait or use **Reindexar**. | | **Sem texto / indexação pendente** (No text / indexing pending) | File stored without readable text (typical of a scanned PDF). | Upload a PDF with selectable text or create a blank document with the content. | | **Sem indexação** (Not indexed) | There was not enough text to index. | Same as above. | | **Extração falhou** (Extraction failed) | The PDF was stored, but reading its text failed. | Try another file. | | **Indexação falhou** (Indexing failed) | Indexing did not finish. | Use **Reindexar** or **Reindexar tudo** (Reindex all); if it persists, contact Diska. | PDFs that are still uploading only appear in the progress bar. If an upload fails, the error message appears under the bar and the document is not added. ## Reindex - **Reindexar** (row menu) indexes one document again and tells you how many segments were created. - **Reindexar tudo** (top of the base page) reindexes every document in turn and shows how many succeeded. You do not need to reindex after creating or editing a document — that already happens automatically. Use these options when a document shows **Indexação falhou** or stays in **Indexação pendente** for a long time. ## Delete **Eliminar** (Delete) in the row menu removes the document and, if there is one, the original file. The deletion applies immediately to every agent that uses the base. ## Through the API Bases and documents can also be created through the [DISKA API](https://docs.diska.ai/en/api/api-channel) (scopes `knowledge:read` and `knowledge:write`): list and create bases, create written documents, import URLs and upload PDFs. This is useful to keep a base in sync with your CMS or CRM. See [Endpoints](https://docs.diska.ai/en/api/endpoints). # Citations When the agent searches the knowledge base during a conversation, every excerpt it receives is labelled with its source — **base / document**. The agent is instructed to answer only from those excerpts and to mention the source when it states facts. You can audit those searches after the call. ## See the searches in a call 1. Open **Históricos → Chamadas** (History → Calls) and click the call. 2. Open the **Acções** (Actions) tab. 3. Look for the `search_knowledge` entries — one for each search the agent ran. 4. Expand **Pedido / resposta** (request / response) to see: | Field | What it shows | | ------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `query` (request) | The question the agent searched for. | | `found` | `true` if relevant content was found; `false` if nothing was found. | | `results[].source` | Where the excerpt came from, as `Base name / Document name`. | | `results[].content` | The exact text the agent received. | | `message` | The guidance given to the agent — for example, to tell the customer it does not have the information when `found` is `false`. | Compare `content` with what the agent said in the **Transcrição** (Transcript) tab: if the answer matches no excerpt, the agent did not rely on the knowledge base. The same searches appear for test calls made in the agent's test panel, because those are also stored in **Históricos**. See [Calls](https://docs.diska.ai/en/history/calls). ## Diagnosis in the Test Center In the results of a [Test Center](https://docs.diska.ai/en/test-center) run, each case shows a **Diagnóstico da base de conhecimento** (knowledge base diagnosis) block with the mode used and how many documents and excerpts were included (`mode=… · docs=… · chunks=…`): | Mode | Meaning | | ------------------- | --------------------------------------------------------------------------------------- | | `retrieval` | The search found relevant excerpts. | | `full_doc_fallback` | No relevant excerpts; the full text of the documents was used, up to the context limit. | | `instructions_only` | Only the bases' instructions were used, with no document content. | | `empty` | No knowledge available (for example, no base assigned). | | `n/a` | The case did not use the knowledge base. | ## Good practices - Give bases and documents descriptive names — they are what shows up as the source. - Split long content into themed documents: excerpts become more precise and the initial context limit covers more topics. - Write the **Quando deve o agente consultar esta base?** instruction with concrete situations. - When the agent answers badly, first check whether the search returned `found: false` (missing content) or the wrong excerpt (ambiguous or outdated content). - Make sure documents are **Indexado** — see [document states](https://docs.diska.ai/en/knowledge-base/sources#document-states). # Shared memory **Memória partilhada** (Shared memory) makes your agents remember your contacts. After each call, Diska keeps a summary and what the caller said about themselves. On the next call from the same contact, with the same agent or another agent of the group, the agent starts with that context: it greets the caller by name, picks up what was left pending and does not ask again what it already knows. You find it in the **Memória partilhada** menu. If the menu is not there, the feature is not active in your organisation yet: ask Diska. ## What it is for - **Customer support** — callers don't have to explain their problem again when they call back. - **Sales and follow-up** — the agent remembers the product the caller asked about and picks up the conversation. - **Appointments** — preferred times and earlier requests are at hand for the next agent. - **Teams with several agents** — the inbound agent and the outbound agent share what each one learned. ## How it works | Element | What it is | | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Grupo de memória** (Memory group) | A shared memory space, with a name, a description and a **retention** period. | | **Contactos** (Contacts) | The people the group recognises, by phone number: the contacts your team adds and, with automatic memory on (see below), anyone who calls for the first time. | | **Agentes associados** (Attached agents) | The agents that use the group. They all read and feed the same memory; agents outside the group never see it. | | **Memórias** (Memories) | Facts, interests, preferences and pending items the caller mentioned, plus notes from your team. Each one keeps its date and the call it came from. | | **Interacções** (Interactions) | A short summary of each call, with its outcome and the agent that handled it. | 1. **Before answering**, the agent looks the caller's number up in the group's contacts. If it is there, the agent receives the memories and the summaries of the latest calls. 2. **During the call**, it uses that context to avoid repeating questions and to follow up on what was left pending. 3. **After the call**, Diska summarises the conversation and keeps what will be useful next time. The memory is available a few seconds after the call ends. Memory is only used on **phone calls** whose number comes from the network: calls to your numbers, calls the agent places (including [Campaigns](https://docs.diska.ai/en/telephony/campaigns)) and test calls to a mobile. A browser test, the public link and WhatsApp have no reliable number and do not use memory. ## 1. Create a group 1. In **Memória partilhada**, click **Novo grupo** (New group). 2. Enter the **Nome do grupo** (Group name), a **Descrição** (Description, optional) and the **Retenção das memórias** (Memory retention): 30 days, 90 days, 6 months, 1 year or 2 years. 3. If you want the group to register first-time callers by itself, tick **Memória automática de novos contactos** (Automatic memory for new contacts). 4. Click **Criar** (Create). ::callout{type="tip"} Use names that say what the group is for, such as "Workshop customers" or "Luanda leads". Separate groups are separate memories: a contact in one group is unknown to the agents of another. :: Each group's **⋮** menu has **Editar** (Edit), **Copiar ID** (Copy ID) and **Eliminar** (Delete). Deleting a group erases its contact list and all its memories. Attached agents stop using memory until you pick another group. ## 2. Add contacts 1. Open the group and, under **Contactos**, click **Adicionar contacto** (Add contact). 2. Choose the country code and type the **Número de telefone** (Phone number). Fill in **Nome** (First name), **Apelido** (Last name) and, optionally, **Email**. 3. Click **Guardar** (Save). The number is stored in international format (for example, +244 923 000 000). If the number already exists in another group, it is the same contact. The same number cannot be in one group twice. Each contact's **⋮** menu has: - **Memórias e histórico** (Memories and history): what the group remembers about the contact and the summary of each call, with a link to the call in **Históricos**. - **Ver chamadas** (See calls): opens Históricos filtered by the number. - **Editar**, **Copiar ID** and **Remover do grupo** (Remove from group). Removing erases that contact's memories in this group. With automatic memory on, you don't need to add contacts one by one: see the next section. ## Automatic memory for new contacts With **Memória automática de novos contactos** ticked in the group's settings (it is off by default): 1. A number the group does not know calls an attached agent. 2. After the call, Diska summarises the conversation. If there is something worth remembering, it registers the number as a contact of the group and keeps the **name** the caller gave, their **interests** (for example, "asked about strawberry yogurt"), requests, preferences, the outcome and pending items, dated with the call. 3. On the next call, the agent greets the caller by name and picks up the topic, without asking again what it already knows. Rules: - Only **inbound** calls with a caller ID. Calls the agent places, test calls, withheld numbers and the public link never register anyone. - A wrong number, a silent call or one with only greetings creates no contact. - If the agent asks for explicit recording consent and the caller refuses (or never answers), the call is not kept in memory, for new or existing contacts. - If the number already belongs to a contact of your organisation, that contact is reused and keeps its name. A name your team typed is never replaced by what the caller says; a name that came from a call is corrected if the caller corrects it on a later call. - Each group registers at most 200 new numbers a day. - In the contact list, the **Origem** (Origin) column shows **Automático** (Automatic) or **Manual**. **Turning it off** deletes nothing: contacts already registered keep their memories and are still recognised; only new numbers stop being added. If it is turned off during a call, that call no longer registers the number; if it is turned on during a call, registration starts with the next call. Automatically registered contacts follow the group's retention: once nothing is kept about them, they leave the group. ## 3. Attach an agent 1. Open the agent and go to **Definições → Conhecimento e memória** (Settings → Knowledge and memory). 2. Under **Memória partilhada**, click **Associar grupo** (Attach group), pick the group and click **Associar** (Attach). 3. Publish the agent. Real calls use the published version. Each agent uses one group at a time. To switch, click the pencil; to stop using memory, click ✕. The group's **Agentes associados** tab lists the agents using it, in their draft or published version. Memory works with Prompt Builder and Flow Designer agents, on any voice engine. In a flow, the memory goes with the call through every node. ## 4. How the agent uses memory You don't need to change the prompt. When it recognises the contact, Diska hands the memories to the agent **before** the agent's own instructions, with rules of their own: - **Opening:** the agent greets the caller by name and sums up the last conversation or what was left pending in one sentence — for example, "Hi João! Last time you asked about strawberry yogurt. How can I help today?". This takes precedence over your script's opening, which usually asks who is calling. - **During the call:** it does not ask again what is already in memory and still valid; it confirms what is old (addresses, opening hours, decisions) before using it; it follows the caller's correction when they correct something. - **An interest is not a purchase:** the agent never says the caller bought or ordered something they only asked about. - **Identity:** a phone number does not prove who is speaking. Before revealing or changing personal data, bookings, amounts or accounts, the agent confirms who it is talking to. If you want, add your own business rules about memory to the prompt. For example: ```text If the caller already gave the car model on an earlier call, do not ask again: confirm it. If a quote request is pending, ask straight away whether the caller received it. ``` ## Share memory across agents Every agent attached to the same group shares what it learns about each contact, as long as the number is the same. For example: 1. The caller rings the inbound agent and says they are looking for strawberry yogurt. 2. A few days later, the outbound agent calls them in a campaign. 3. The outbound agent already knows the caller's name and what they were looking for. Memory is shared across phone calls. WhatsApp conversations and browser calls neither use nor feed the shared memory. ## Correct and delete memories In **Memórias e histórico** you can: - correct a memory (pencil) or delete it (bin); - add a **Nota** (Note), **Facto** (Fact), **Interesse** (Interest), **Preferência** (Preference) or **Pendente** (Pending item) written by your team; - **Apagar todas as memórias** (Delete all memories) of the contact in this group, keeping them in the group. Memories describe the contact. They are not instructions for the agent: text such as "ignore the rules" is refused. Agent instructions belong in the prompt. ## Memory processing The group page shows **Processamento das memórias** (Memory processing): how long memory takes to become available after a call (median and p95), how many calls were processed and how many new contacts joined in the last 24 hours, and whether any call is waiting or failed. Failures are retried automatically; you don't need to do anything. ## Troubleshooting | Problem | Likely causes | What to do | | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | | The agent did not remember the caller | The agent is not attached to the group or was not published after attaching it; the number is not in the group and automatic memory is off; the call came from the browser, the public link or a withheld number. | Attach the group and publish the agent; add the contact or turn on automatic memory; test by phone. | | A contact has no interactions | The call happened before the agent was attached; it was a wrong number or a call without conversation; the caller refused the consent the agent asked for. | Make a new call after attaching and publishing the agent. | | The agent used the wrong name | The name came from a call and the transcription misheard it. | Fix the contact's name in **Editar**: a name your team types always wins. | | Another agent does not know the contact | That agent uses another group, or none. | Attach the same group to both agents and publish them. | | A new number was not registered | Automatic memory is off; it was a call the agent placed or a test call; the call had nothing worth remembering; the group reached its 200 new numbers that day. | Check the option in the group's settings and the call's status in **Memórias e histórico**. | ## FAQ **Which agents can use memory?** Published voice agents, from the Prompt Builder or the Flow Designer, on phone calls. **How is the contact recognised?** By the phone number the network delivers, in international format. **Can several agents share one group?** Yes. Each agent uses one group at a time, and one group can serve several agents. **Does it work on WhatsApp or the website chat?** Not yet. Shared memory is for phone calls only. **Is the full transcript kept in memory?** No. Memory keeps only a short summary and short items. The call's transcript stays in **Históricos**, like any other call. **How long are memories kept?** The group's retention period, between 30 days and 2 years. After that they are deleted automatically. ## Security and privacy - Each organisation only sees its own groups, contacts and memories. - The phone number identifies the contact but does not prove who is speaking. The agent is instructed to confirm identity before revealing or changing personal data, bookings, amounts or accounts. - The transcript is not kept. Only a short summary and short items are stored. Card numbers, IBANs, document numbers, passwords and codes are removed before saving. - On an agent with [Redact personal data](https://docs.diska.ai/en/guides/redact-personal-data) on, memory is built from the already redacted call: the summary keeps no names, contacts or addresses said on the call. The contact is still identified by the phone number. - Old memories are presented to the agent as old, and it confirms them before using them. - If memory does not answer in time, the call is answered normally, without memory. - Memories are deleted automatically once they pass the group's retention period. # Knowledge base The **knowledge base** holds the content your agents look up during conversations: FAQs, price lists, policies, manuals or pages from your website. You find it under the **Conhecimento** (Knowledge) menu. ## How it is organised | Element | What it is | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Base | A themed set of documents (for example "Customer support" or "2026 pricing"). An organisation can have several bases. | | Base instruction | The **Quando deve o agente consultar esta base?** (When should the agent consult this base?) field — describes when the agent should turn to this base. | | Document | Each source added to a base: a PDF, a document written in the platform or a web page. See [Sources](https://docs.diska.ai/en/knowledge-base/sources). | | Assignment | The link between a base and an agent. An agent can use several bases; the same base can serve several agents. | ## Create a base 1. In the **Conhecimento** menu, click **Nova base** (New base). 2. Fill in: - **Nome** (Name) — for example "Customer support guides". - **Quando deve o agente consultar esta base?** — describe the trigger, not a generic instruction. Example: "The customer asks about prices, plans or payment terms". - **Descrição (opcional)** (Description, optional). 3. Click **Criar** (Create). The platform opens the base so you can start [adding content](https://docs.diska.ai/en/knowledge-base/sources). In the list of bases, each card shows the number of documents, how many agents use it (or **Não atribuída** — not assigned) and when it was last changed. Hover over a card to **Editar** (Edit) or **Eliminar** (Delete) the base. Deleting a base also removes its documents and its assignments to agents. ## Assign bases to an agent 1. Open the agent and click **Definições** (Settings) in the builder's top bar. 2. In the **Definições globais** (Global settings) panel, open the **Conhecimento e memória** (Knowledge and memory) section. 3. Under **Bases de conhecimento atribuídas** (Assigned knowledge bases), tick the bases the agent should use. 4. Click **Guardar atribuições** (Save assignments). The same section has a **Notas de conhecimento (texto livre)** (free-text knowledge notes) field, handy for short facts that do not justify a document. ::callout{type="info"} Tests in **Rascunho — ações simuladas** (draft, simulated actions) in the agent's test panel use newly assigned bases straight away. Real calls, tests of the published version and WhatsApp only use bases that were already assigned when the version was published: after assigning a new base, [publish the agent](https://docs.diska.ai/en/guides/publish-agent) for it to reach customers. Removing a base, on the other hand, takes effect immediately, and so do changes to the content of an assigned base (new documents, edits, deletions). :: ## How the agent uses knowledge 1. **At the start of the conversation**, the agent receives each assigned base's instruction and the text of its documents, up to a context limit. Long documents are cut and, once the limit is reached, the remaining ones are left out of this initial summary. 2. **During the conversation**, whenever it needs a fact, the agent runs a semantic search over the assigned bases and receives the most relevant excerpts, each labelled with its source base and document. It is instructed to answer only from those excerpts. 3. **If the search finds nothing**, the agent tells the customer it does not have that information instead of making something up. This applies to calls (web, widget, public link and phone) and to [WhatsApp](https://docs.diska.ai/en/whatsapp) conversations. For the in-conversation search, a document must be in the **Indexado** (Indexed) state — see [document states](https://docs.diska.ai/en/knowledge-base/sources#document-states). To find out where an answer came from, see [Citations](https://docs.diska.ai/en/knowledge-base/citations). ## Permissions | Action | Owner / Administrator | Member | Viewer | | ------------------------------ | :-------------------: | :----: | :----: | | View bases and documents | ✓ | ✓ | ✓ | | Create bases and add documents | ✓ | ✓ | — | | Edit and reindex | ✓ | ✓ | — | | Delete bases and documents | ✓ | — | — | | Assign bases to an agent | ✓ | ✓ | — | ## Next - [Add sources](https://docs.diska.ai/en/knowledge-base/sources) — PDF, written document, URL and site crawl. - [Citations](https://docs.diska.ai/en/knowledge-base/citations) — confirm which document produced each answer. - [Knowledge base not answering](https://docs.diska.ai/en/troubleshooting/kb-not-answering) — diagnosis when the agent does not use its knowledge. # Evaluations At the end of each simulated conversation, the Test Center evaluates the case's **Critérios de sucesso** (Success criteria) and decides whether the case passed. ## How each criterion is evaluated An automatic evaluator (an AI model) reads the scenario, the full transcript and the knowledge base diagnostics, and decides, criterion by criterion, whether the conversation meets it. It is instructed to be strict and to rely on what is in the transcript. For each criterion, the result shows: - **Passou** (Passed) or **Falhou** (Failed); - a short explanation of why. If the evaluator cannot assess a criterion, it counts as failed, with the explanation **Critério não avaliado pelo juiz.** (Criterion not evaluated by the judge) or **Avaliação automática indisponível: …** (Automatic evaluation unavailable). ## When a case passes Under **A chamada tem sucesso quando** (The call succeeds when), each case sets the mode: | Mode | The case passes if… | | ------------------------------------- | ------------------------------ | | **Todos os critérios** (All criteria) | every criterion passes. | | **Qualquer critério** (Any criterion) | at least one criterion passes. | The score appears next to **Critérios de sucesso** in the result, as passed criteria / total (e.g. 3/4). A case with the **Erro** (Error) status had a technical failure and was not evaluated. ## Knowledge base check With **Validar se a base de conhecimento entra no runtime** (Check that the knowledge base reaches the runtime) on, the case gets an extra criterion, **Knowledge Base injectiu conteúdo no runtime** (Knowledge base injected content at runtime). It passes when the agent's knowledge base supplied documents, excerpts or instructions during the conversation. This criterion counts towards the score and the case mode like any other. The result also shows the **Diagnóstico da base de conhecimento** (Knowledge base diagnostics) — the search mode and how many documents and excerpts were used. ## Writing good criteria - Write criteria you can observe in the transcript: "The agent asked for the caller's name", "The agent confirmed the booking date and time". - One idea per criterion: it makes it easier to see what failed. - Avoid subjective criteria ("good service") — the evaluator has no way to check them. - Include what the agent must **not** do: "The agent did not reveal other customers' data". - Use **Qualquer critério** when there are several equally correct answers. ::callout{type="info"} These evaluations only run in the Test Center. To evaluate real calls automatically after they end, use [Custom evaluations](https://docs.diska.ai/en/actions/custom-evaluations) . :: # Test Center The **Centro de Testes** (Test Center) validates the agent with simulated conversations: an AI-simulated caller follows the scenario you write, talks to the agent by text and, at the end, each success criterion is evaluated automatically. Use it before publishing and whenever you change the agent. Open it from the side menu under **Centro de Testes**. It has two pages: **Suites de teste** (Test suites) and **Histórico de execuções** (Run history). ::callout{type="info"} An agent's suites also show in the agent editor, under **Testar → Simulação** : you can create them, generate cases and run them without leaving the agent. They are the same suites — see [Test an agent](https://docs.diska.ai/en/guides/test-agent#simulation) . :: ## Concepts | Concept | Description | | ------------------------------- | --------------------------------------------------------------------------------------- | | **Suite de teste** (Test suite) | A set of cases linked to one agent. | | **Caso de teste** (Test case) | A scenario: what the simulated caller does and the criteria the conversation must meet. | | **Execução** (Run) | One run of all the cases in a suite, with each case's result. | ## Create a suite 1. Under **Suites de teste**, click **Suite de teste**. 2. Fill in: - **Nome** (Name); - **Agente** (Agent) — the suite stays linked to this agent permanently; - **Idioma** (Language) — Português (PT), Português (BR) or Inglês (English); - **Correr por defeito contra o rascunho (não o publicado)** (Run against the draft by default, not the published version) — untick it to test the published version. 3. Click **Criar** (Create). The suite opens empty. ## Create cases In an empty suite, choose **Criar caso personalizado** (Create custom case) or **Gerar com IA** (Generate with AI). In a suite that already has cases, use **Adicionar** (Add). Each case has: | Field | Description | | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | **Nome** (Name) | Identifies the case. | | **Prompt do cenário** (Scenario prompt) | Instructions for the simulated caller: who they are, what they want, how they behave. | | **Critérios de sucesso** (Success criteria) | What the conversation must achieve, one per line (**+ Critério** for more; up to 20). | | **A chamada tem sucesso quando** (The call succeeds when) | **Todos os critérios** (All criteria) or **Qualquer critério** (Any criterion) pass. | | **Validar se a base de conhecimento entra no runtime** (Check that the knowledge base reaches the runtime) | Adds a criterion confirming the agent's knowledge base supplied content. | Click **Guardar alterações** (Save changes). The name, the scenario prompt and at least one criterion are required — incomplete cases prevent the run. ### Generate with AI Available while the suite has no cases: 1. Click **Gerar com IA**. 2. Choose the **Cenários comuns** (Common scenarios): answer accuracy, flow compliance, stressed or angry caller, task completion, knowledge base and citations, tools and actions (honesty), conversational naturalness, repetitive phrases and fillers. 3. Choose the **Número de casos** (Number of cases, 1 to 25). 4. Click **Gerar … casos de teste** (Generate … test cases — the button shows the chosen number). Cases are created for your agent, with suggested criteria. You can close the window while they are generated. Review and edit them before running. ## Run Click **Executar** (Run — on the suite card or inside the suite) and confirm **Executar testes** (Run tests). **Testes iniciados.** (Tests started) appears and the **Histórico de execuções** opens with the run selected. Under **Testar → Simulação** in the agent editor, **Executar** starts at once, without a confirmation, against the version chosen in the test bar (**Rascunho** or **Publicado**). Cases run one at a time. In each case, the simulated caller and the agent exchange up to 12 text turns, then the criteria are evaluated — see [Evaluations](https://docs.diska.ai/en/test-center/evaluations). ::callout{type="warning"} This is a text simulation: it uses no voice and never runs real actions (SMS, bookings, transfers). For a Flow Designer agent, the conversation goes through the real flow engine; for a Prompt Builder agent, the agent answers from its prompt. To hear the voice and test real actions, use the [test phone call](https://docs.diska.ai/en/guides/test-agent) . :: ## Review results The **Histórico de execuções** lists runs with **Data** (Date), **Agente** (Agent), **Suite de teste**, **Resultados** (Results — e.g. "3 de 4 casos passaram", 3 of 4 cases passed) and **Estado** (Status). You can filter by agent and by suite. | Run status | Meaning | | ------------------------- | -------------------------------------------------- | | **Em fila** (Queued) | Waiting. | | **Em curso** (Running) | Cases are running. | | **Concluído** (Completed) | Every case passed. | | **Falhou** (Failed) | At least one case did not pass, or the run failed. | Click a run to see each case, with the status **Passou** (Passed), **Falhou** (Failed) or **Erro** (Error — a technical failure), and two tabs: - **Visão geral** (Overview) — the **Critérios de sucesso** with the score (e.g. 3/4), the result and explanation for each criterion; the **Diagnóstico da base de conhecimento** (Knowledge base diagnostics); the **Percurso do fluxo** (Flow path — for Flow Designer agents: nodes visited and whether it reached the end); and the **Prompt do cenário**. - **Transcrição** (Transcript) — the full conversation between the simulated caller and the agent. Each run also shows **Pronto para publicar** (Ready to publish) or **Publicação com pendências** (Publishing has pending items), with the list of pending items (for example, no usable knowledge base). The editor's **Lista de verificação** (Checklist) remains the reference for publishing. ## Manage suites and cases - Suite menu: **Histórico de execuções** (Run history), **Copiar ID** (Copy ID), **Duplicar** (Duplicate) and **Eliminar suite de teste** (Delete test suite). - Each case's menu: **Editar** (Edit), **Copiar ID** and **Eliminar** (Delete). ## Permissions | Action | Roles | | -------------------------------- | ------------------------------- | | View suites and results | Everyone | | Run suites | Everyone, including Viewer | | Create and edit suites and cases | Owner, Administrator and Member | ## Next When the tests pass, publish the agent and connect it to channels — see [Publish and receive calls](https://docs.diska.ai/en/guides/publish-agent). If tests fail for no obvious reason, see [Tests failing](https://docs.diska.ai/en/troubleshooting/tests-failing). # Overview **Visão geral** (Overview) is the page that opens after you sign in to the backoffice (menu **Visão geral**). It shows one of two things, depending on whether there have been calls in the last seven days. ## First steps As long as there have been no calls in the last seven days, the page shows the **Primeiros passos** (First steps) card with what is left to do, in this order: | Step | Done when | Button | | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | **Criar o primeiro agente** (Create the first agent) | At least one agent exists. | **Ir aos agentes** (Go to agents) | | **Fazer uma chamada de teste** (Make a test call) | Calls were recorded in the last seven days. The web call runs in the browser, no number needed. | **Testar agente** (Test agent) — opens the agent's test panel | | **Publicar o agente** (Publish the agent) | At least one agent is published. | **Abrir o agente** (Open the agent) — the publish button is in the builder's top bar | | **Atribuir um número** (Assign a number) | At least one agent has a phone number. Only needed for phone calls. | **Ver números** (See numbers) | - The **X de Y concluídos** (X of Y done) counter shows progress, and the next step to do is highlighted. - Steps your role cannot carry out are hidden (for example, assigning numbers is only for Owners and Administrators). Steps already done stay visible. - If no step applies to your role, the page asks you to talk to an administrator of the organisation. For the first test, follow [Make a test call](https://docs.diska.ai/en/getting-started/test-call). ## Weekly summary As soon as there are calls, the page shows the **last seven days**: - **Estatísticas de chamadas** (Call statistics) — **Total de chamadas** (total calls), **Total de minutos** (total minutes) and **Duração média** (average duration), each with the change from the previous seven days. When the previous period has no data, the change shows as "—". - **Chamadas por dia** (Calls per day) — daily volume for the period. - **Estado das chamadas** (Call status) — the split by final status (Concluída, Falhou, Cancelada, Abandonada, Em progresso). The **Ver análises completas** (See full analytics) button opens [Analytics](https://docs.diska.ai/en/history/analytics), where you can change the period, filter by agent and export. ::callout{type="info"} The Overview counts the same calls as [Históricos → Chamadas](https://docs.diska.ai/en/history/calls) , including test calls. WhatsApp conversations are not part of these metrics. :: # Calls **Históricos → Chamadas** (History → Calls) records every call made by your organisation's agents, newest first, 25 per page. ## The list | Column | What it shows | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | **Data** (Date) | Start date and time. | | **Agente** (Agent) | The agent that answered or placed the call. | | **Duração** (Duration) | Minutes and seconds (or hours, minutes and seconds). | | **Contacto** (Contact) | On an incoming phone call, the caller's number; on a call the agent placed, the number dialled. Underneath, the contact's name when known. | | **Call ID** | The call's identifier, shortened. Click to copy it in full. | | **Tipo** (Type) | **Web Call** (a call in the browser: test panel, widget or public link) or **Telefone** (Phone). | | **Estado** (Status) | The call's status (see below). | Click a row to open the details. ### Statuses | Status | Meaning | | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | **Concluída** (Completed) | The call ended normally. | | **Em progresso** (In progress) | The call is still going on. | | **Falhou** (Failed) | The call ended because of an error. | | **Abandonada** (Abandoned) | The caller's browser stopped responding mid-call (for example, the tab was closed). It does not indicate a fault. | | **Cancelada** (Cancelled) | The connection was replaced by another one before the conversation started (for example, the call was restarted). Usually has no transcript. | ### Search and filter - **Pesquisar por Call ID ou contacto** (search by Call ID or contact) — searches the Call ID, the contact's number or name and the session identifier. - **Todos os estados** (All statuses) — filters by one status. - **Qualquer data** (Any date) — **Hoje** (Today), **Últimos 7 dias** (Last 7 days), **Últimos 30 dias** (Last 30 days) or **Personalizado** (Custom: two dates, inclusive). If the start date is after the end date, the page warns: "A data inicial é posterior à data final." - **Actualizar** (Refresh) — reloads the list. To see only one agent's calls, use **Registos de chamadas** (Call logs) in the agent's **⋮** menu (or **Ver registos de chamadas** in the agent list). The list opens filtered by that agent; to see all calls again, open **Históricos** from the side menu. ## Call details The **Detalhes da chamada** (Call details) panel shows the type at the top (**Web Call**, **Telefone**, **WhatsApp** or **Chat**) and the shortened Call ID. The **Copiar link** (Copy link) button copies a direct link to this call, which you can share with colleagues in the organisation. The panel has four tabs. ### Detalhes (Details) | Field | Description | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Data** | Start date and time. | | **Estado** | The call's final status. | | **Contacto** | Contact number and name, when available. | | **Tipo** | The channel (**Web Call**, **Telefone**…) and, below it, the origin: **Widget ou link público** (a real customer in the browser), **Teste no backoffice** (the panel's web test), **Demonstração no site** (site demo) or **Chamada de teste do painel** (the call the agent places to your mobile from the test panel). | | **Agente** | The call's agent. | | **Duração** | Total duration. | | **Motivo de fim** (End reason) | How the call ended (see below). | | **Call ID** | The full identifier, with a copy button. Quote it when contacting Diska support. | | **Sessão** (Session) | The technical session identifier, when there is one. | Most common end reasons: | Reason | Meaning | | ---------------------------------------------------------------- | -------------------------------------------------------------- | | **Cliente desligou** | The customer hung up. | | **Cliente pediu para terminar** | The customer asked the agent to end the call. | | **Agente terminou** / **Concluída pela agente** | The agent ended the conversation. | | **Tarefa concluída** / **Fluxo concluído** | The conversation's goal or the flow reached its end. | | **Terminada por silêncio** / **Terminada por inatividade** | Nobody spoke for too long. | | **Página fechada** / **Página em segundo plano** | On a web call, the page was closed or moved to the background. | | **Ligação perdida** / **Reconexão falhou** / **Erro de ligação** | A network problem during the call. | | **Microfone desligou-se** | The caller's microphone stopped sending audio. | | **Sessão expirada** | The session exceeded its allowed time. | ### Transcrição (Transcript) - At the top, the recording player, when the call was recorded — see [Recordings](https://docs.diska.ai/en/history/recordings). - Then the conversation in order: **Chamada iniciada** (call started) and each turn with its time, labelled with the agent's name, **Cliente** (customer), **Sistema** (system) or **Ferramenta** (tool). If there is no text, you see "Sem transcrição gravada para esta chamada." (no transcript recorded for this call). On an agent with [Redact personal data](https://docs.diska.ai/en/guides/redact-personal-data) on, personal data shows as tags — `[NOME]`, `[TELEFONE]`, `[MORADA]`… — in the transcript, the summary and the analysis. ### Análise (Analysis) The output of the processing done when the call ends: - **Dados extraídos** (Extracted data) — the values collected by [information extractors](https://docs.diska.ai/en/actions/information-extractors), with **Histórico por extractor** (per-extractor history). With no extractors configured you see "Sem extractores ou ainda sem pipeline pós-chamada." - **Avaliações / scorecards** (Evaluations / scorecards) — each [custom evaluation](https://docs.diska.ai/en/actions/custom-evaluations) with **Passou** (passed), **Falhou** (failed) or **n.a.**, the **Score ponderado** (weighted score), the criteria and the rationale. The **CSV** button exports this agent's recent evaluations. - **SMS pós-chamada** (Post-call SMS) — each [post-call SMS](https://docs.diska.ai/en/actions/post-call-sms) sent, with its delivery status, preview and **Variante A/B** (A/B variant), when applicable. - **Resumo** (Summary) — the call summary, when there is one. ### Acções (Actions) The **Acções** tab (with the number of actions in its title) lists every action or tool the agent ran: the technical name (for example `search_knowledge` for a knowledge base search), the time, the latency in ms and the status. Expand **Pedido / resposta** (request / response) to see the data sent and received — useful to confirm a booking, an SMS or a transfer, or to see the knowledge base [citations](https://docs.diska.ai/en/knowledge-base/citations). With no actions, you see "Nenhuma acção/tool foi executada nesta chamada." (no action or tool ran during this call). ## Export to CSV The **Exportar tudo (CSV)** (Export all) button becomes **Exportar filtrado (CSV)** (Export filtered) when a search, status or date filter is active. The `chamadas-YYYY-MM-DD.csv` file contains every call in the current filter (not just the visible page), up to 5,000 rows, with these columns: `id`, `started_at`, `agent`, `duration_seconds`, `contact`, `channel`, `status`, `end_reason` `channel`, `status` and `end_reason` are exported as codes (for example `phone`, `completed`, `user_hangup`). If the filter has more than 5,000 calls, the final message says how many were exported — use a shorter date range to get the rest. ::callout{type="info"} Calls and transcripts cannot be deleted in the backoffice. If you need to erase a call's audio (for example, at the customer's request), an Owner or Administrator can [delete the recording](https://docs.diska.ai/en/history/recordings#delete) . :: To bring the history into your CRM, use the [DISKA API](https://docs.diska.ai/en/api/api-channel) or [webhooks](https://docs.diska.ai/en/api/webhooks). # Recordings When an agent records calls, the audio is available in each call's details under **Históricos → Chamadas**, at the top of the **Transcrição** (Transcript) tab. ## Which calls are recorded Only calls of agents with **Gravar chamadas** (Record calls) switched on are recorded. That option can only be turned on after you choose the type of consent and write the message the agent says to the customer. See how to set it up in [Record calls](https://docs.diska.ai/en/guides/record-calls). With recording on, these calls are recorded: - calls from the widget on your website and from the public link; - phone calls, incoming or outgoing, including the test phone call from the agent's test panel. On a phone call, the **first 27 minutes** are recorded. The web test call in the agent's test panel is not recorded. Calls made before recording was switched on are not recorded either. ## Listen and download Open the call and the **Transcrição** tab. When audio is available, the player lets you: - play and pause, and click the bar to jump to another point; - change the playback speed (the button showing the current speed); - **Descarregar gravação** (Download recording, download icon) — saves the audio file. Below the player: **Gravação da chamada** (call recording), the file size and the date it will be deleted automatically ("Eliminada automaticamente a …"). ::callout{type="info"} The playback and download address is temporary: it expires five minutes after you open the **Transcrição** tab. If playback or download fails after the panel has been open for a while, close the call and open it again. :: ## Recording states | What you see | Meaning | | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | The audio player | **Gravação disponível** (recording available) — you can listen and download. | | **Falha na gravação** (Recording failed) | "O áudio desta chamada não chegou a ser guardado." — the audio of this call was never stored. A technical reason may also be shown. | | **Gravação expirada** (Recording expired) | "O áudio foi eliminado automaticamente pelo período de retenção." — deleted automatically by the retention period. | | **Gravação eliminada** (Recording deleted) | "O áudio foi eliminado permanentemente." — someone in the organisation deleted it. | | Nothing | The call was not recorded (the agent was not recording at the time, or it is a web test call). | | "Não foi possível carregar a gravação desta chamada." | The recording information could not be loaded right now. Try again later. | In every case, the transcript and the rest of the call record are kept. ## Retention Each recording has a deadline after which the audio is deleted automatically and the call shows **Gravação expirada**. - **Organisation period** — the maximum for the whole organisation. By default it is 90 days; to change it, contact Diska. - **Retenção desta gravação** (Retention for this recording) — in the agent's recording settings you can choose a shorter period: **7 dias**, **30 dias**, **90 dias**, **180 dias** or **365 dias**, or **Usar o período da organização** (use the organisation's period). An agent can only shorten the organisation's period, never extend it; a longer value is capped at the organisation's. The deadline is set when the recording is stored. Changing retention later only affects later recordings. ## Delete Owners and Administrators see the **Eliminar gravação** (Delete recording) icon in the player. When clicked: - the audio is erased **immediately**, without a confirmation prompt, and cannot be recovered; - the call then shows **Gravação eliminada**; - the transcript, actions and extracted data are kept. Use it, for example, to honour a customer's request to erase the recording of their call. Other roles can listen and download, but not delete. # Analytics The **Análises** (Analytics) page (menu **Análises**) aggregates the calls in [Históricos → Chamadas](https://docs.diska.ai/en/history/calls) over a period. It is available to every role that can see the History. ## Filters | Filter | Options | | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Agent type | **Todos os tipos** (all types), **Recebidas** (inbound) or **Efectuadas** (outbound). Filters by the agent's type (inbound or outbound agents), not by the direction of each call. | | Agent | **Todos os agentes** (all agents) or one specific agent. | | Period | **Diário** (daily: last 24 hours), **Semanal** (weekly: last 7 days) or **Mensal** (monthly: last 30 days). | Each metric is compared with the previous period of the same length (for example, the 7 days before the last 7). The change is shown as a percentage; when the previous period has no data, it shows "—". With no calls in the period, the page shows "Ainda sem dados para analisar" (no data to analyse yet). ## Cards | Card | What it shows | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Acções executadas** (Executed actions) | How many times each action ran during calls (**Utilização** — usage) and its daily trend. Pick the action from the list — for example **Agendamento** (booking), **Transferência de chamada** (call transfer), **SMS durante a chamada** (during-call SMS), **SMS pós-chamada** (post-call SMS), **Acção personalizada** (custom action), **Extractor de informação** (information extractor) or **Avaliação personalizada** (custom evaluation). | | **Sentimento** (Sentiment) | **Interacções positivas** (positive interactions): the share of calls with a positive tone among the classified calls ("N de M chamadas analisadas" — N of M calls analysed), with the Positivo / Neutro / Negativo split. Tone is classified at the end of each call. | | **Desempenho dos agentes** (Agent performance) | Agents ranked by **Minutos** (minutes), **Chamadas** (calls) or **Conclusão técnica** (technical completion: share of calls with status Concluída), with the change from the previous period. | | **Estatísticas de chamadas** (Call statistics) | **Total de chamadas**, **Total de minutos**, **Duração média** and the **Chamadas por dia** (calls per day) chart. | | **Chamadas falhadas** (Failed calls) | The most recent calls with status Falhou (up to 20). Click a row to open the call in History. | | **Estado das chamadas** (Call status) | Split by final status: Concluída, Falhou, Cancelada, Abandonada, Em progresso. | | **Motivo de fim de chamada** (End reason) | Split by end reason (Cliente desligou, Agente terminou, Terminada por silêncio…). | ## Export CSV **Exportar CSV** downloads `analises--YYYY-MM-DD.csv` with the same filters and period you are viewing, in sections: - **Resumo** (summary) — period, calls, minutes and average duration, with the change; - **Chamadas por dia** — calls and minutes per day; - **Estado das chamadas**; - **Motivo de fim**; - **Desempenho por agente** — calls and minutes per agent. ## What is counted - Every call recorded in History, including test calls made in the agent's test panel — bear this in mind when reading the numbers for a period with many tests. - WhatsApp conversations are not included in Analytics. - Duration comes from each call's start and end. The same numbers are available through the API — see the [DISKA API](https://docs.diska.ai/en/api/api-channel). # History and analytics Everything your agents do is recorded. The backoffice organises those records in three places in the side menu: | Menu | What you find | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Visão geral** (Overview) | The home page: a summary of the last seven days or, in a new organisation, the first steps. | | **Históricos** (History) | **Chamadas** (Calls) — each call with transcript, actions, extracted data, evaluations and recording. **WhatsApp** — the WhatsApp channel conversations. | | **Análises** (Analytics) | Metrics by period, agent and agent type, with CSV export. | ## Which calls appear **Históricos → Chamadas** lists every call made by the organisation's agents: - web calls made in the agent's test panel; - calls from the widget on your website and from the public link; - phone calls received and placed through the organisation's numbers, including the test phone call from the agent's test panel. WhatsApp conversations have their own list under **Históricos → WhatsApp** and are not counted in **Análises** — see [WhatsApp conversations](https://docs.diska.ai/en/whatsapp/conversations). ## Permissions | Action | Owner / Administrator | Member | Viewer | | ---------------------------------------------- | :-------------------: | :----: | :----: | | View Overview, calls, recordings and analytics | ✓ | ✓ | ✓ | | Export CSV | ✓ | ✓ | ✓ | | Delete a recording | ✓ | — | — | Calls and transcripts cannot be deleted from the backoffice. Only the audio of recordings can be deleted — see [Recordings](https://docs.diska.ai/en/history/recordings). ## In this section ::card-group :::card --- description: The weekly summary and the first-steps checklist. icon: i-lucide-layout-dashboard title: Overview to: https://docs.diska.ai/en/history/dashboard --- ::: :::card --- description: Filter, open a call's details and export CSV. icon: i-lucide-phone-call title: Calls to: https://docs.diska.ai/en/history/calls --- ::: :::card --- description: Listen to, download and delete call audio. icon: i-lucide-audio-lines title: Recordings to: https://docs.diska.ai/en/history/recordings --- ::: :::card --- description: Volume, duration, sentiment, actions and per-agent performance. icon: i-lucide-chart-line title: Analytics to: https://docs.diska.ai/en/history/analytics --- ::: :: # Connect the number You connect the number in **Definições → Integrações** (Settings → Integrations), in the **WhatsApp** section. Only Owners and Administrators see this page. You do not need to copy tokens or IDs: you authorise Diska in a Meta window and the platform validates the rest. ## Connect the first number 1. In **Definições → Integrações**, **WhatsApp** section, click **Ligar WhatsApp** (Connect WhatsApp). 2. Under **Agente para novas conversas** (agent for new conversations), choose the agent that will answer. Only Prompt Builder agents with a published version are listed; if there are none, you see **Publique um agente primeiro** (publish an agent first). 3. Click **Preparar ligação** (Prepare connection) and then **Continuar na Meta** (Continue at Meta). 4. In the Meta window, sign in and choose the business, the WhatsApp Business account and the number to connect. If the window does not open, allow pop-ups for the Diska backoffice and try again. 5. When the window closes, Diska validates the authorisation (**A validar ligação…** — validating connection). At the end you see **WhatsApp ligado** (WhatsApp connected) — "Número validado e agente associado." (number validated and agent linked). Complete the Meta authorisation without interruptions: if it takes too long, the preparation expires and you have to start again. To connect more numbers, use **Ligar outro número** (Connect another number). Each number can belong to only one Diska organisation. ## The connection card Each connected number has a card. At the top, always visible: | Field | Description | | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | **Número** (Number) and **nome apresentado** (display name) | The number customers see and the name verified at Meta. | | **Estado** (State) | The connection state, on the right (see below). | | **Agente das mensagens** (Messages agent) | The agent answering new conversations. | | **Webhook** | **Ligado** (connected), **Falhou** (failed) or **Por validar** (to be validated) — whether Meta is sending this number's messages to Diska. | | **Ligado desde** / **Desligado em** | When it was connected or disconnected. | When something needs fixing, it shows right below: the state alert, with **Repetir subscrição do webhook** (Retry webhook subscription) when the webhook failed and the connection allows it, and the **Por resolver antes de atender clientes** (to resolve before serving customers) list — for example "Associar um agente publicado em Prompt Mode" (link a published Prompt Mode agent) or "Confirmar o registo e a verificação do número" (confirm number registration and verification). The number's buttons follow, such as **Alterar agente** (Change agent) and **Desligar** (Disconnect). The rest of the card is split into sections that open with a click: - **Chamadas de voz** (Voice calls) — turn calls on and choose the agent that answers them. The title shows **Activas** (on) or **Desligadas** (off). See [Voice calls](https://docs.diska.ai/en/whatsapp/calls). - **Templates de mensagem** (Message templates) — the templates approved at Meta. See [Templates](https://docs.diska.ai/en/whatsapp/templates). - **Diagnóstico técnico**(Technical diagnosis) — the title shows operational health. Inside are the credential status, last message received, last reply sent, last delivery event, the send queue and the WABA and Phone Number ID identifiers, with the buttons: - **Validar com a Meta** (Validate with Meta) — checks with Meta and refreshes the state. It does not send messages or change the number or the credential. - **Actualizar estado** (Refresh state) — reloads the card. - **Ver histórico** (See history) — opens **Históricos → WhatsApp**. ## Connection states | State | Meaning | What to do | | ------------------------------------------------ | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | **Activo** (Active) | Incoming messages go to the agent and replies go out through this number. | Nothing. | | **Configuração incompleta** (Setup incomplete) | Steps are missing before serving customers. | See the **Por resolver antes de atender clientes** list. | | **Requer atenção** (Needs attention) | The connection works, but there are open alerts (for example, failed sends). | Check the alerts on the card and the affected conversations. | | **Webhook com falha** (Webhook failed) | Meta is not sending this number's messages to Diska. | Click **Repetir subscrição do webhook**. | | **Número indisponível** (Number unavailable) | The number is not registered or verified at Meta. | Complete verification in WhatsApp Manager and use **Reconectar**. | | **Autorização expirada** (Authorisation expired) | The Meta credential expired or is invalid. | Use **Reconectar** (Reconnect). | | **Autorização removida** (Authorisation removed) | The authorisation was removed at Meta. | Use **Reconectar**. History is preserved. | | **Desligação pendente** (Disconnection pending) | Service is already off in Diska, but Meta has not confirmed yet. | Use **Concluir desligação** (Complete disconnection) or **Reconectar**. | | **Só chamadas** (Calls only) | Messages are off on this number, but voice calls are on. | Nothing, if intended. To answer messages again, use **Reconectar** (Reconnect). | | **Desligado** (Disconnected) | No service and no sending through this number. | Reconnect whenever you want; history is preserved. | ## Send a test message **Mensagem de teste** (Test message) sends a message through the connected number without creating a conversation or changing the agent's service. 1. Enter the **Número de destino** (destination number) in international format (for example `+244 923 456 789`). 2. Choose: - **Texto de teste** (test text) — sends "Mensagem de teste da Diska: este número WhatsApp está ligado e pronto a responder." It is only delivered if that number wrote to the connected WhatsApp in the last 24 hours. Send a "Hello" from that phone first. - **Template aprovado** (approved template) — an approved utility template with no variables. 3. Confirm that the number belongs to your team or agreed to receive the message, and click **Enviar teste** (Send test). The result goes through **A enviar** (sending), **Aceite pela Meta, a aguardar entrega** (accepted by Meta, awaiting delivery), **Enviada pela Meta** (sent by Meta), **Entregue** (delivered) and **Lida** (read); or **Falhou** (failed) / **Envio por confirmar** (send unconfirmed). If Meta does not confirm the send, check the phone before trying again. There is a limit on tests per hour. ## Change the agent **Alterar agente** (Change agent) picks another published Prompt Builder agent. The new agent answers **new** conversations; conversations already under way keep their current agent and context. ## Reconnect, switch numbers and disconnect - **Reconectar** renews the authorisation and restores the webhook. At Meta, select **the same number**. The connection, conversations and history are preserved. - **Switch numbers**: connect the new number with **Ligar outro número** and then disconnect the old one. The old number's history is preserved. - **Desligar** (Disconnect) turns off automatic service and sending through that number. Pending sends are blocked and not resumed automatically; a message that is being sent must finish first. History is preserved and you can reconnect later. ## Common errors | Message | What to do | | ------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | | "Ligação cancelada. Pode voltar a tentar quando quiser." | The Meta window was closed before the end. Try again. | | "A autorização não terminou a tempo. Volte a ligar o WhatsApp." / "Esta autorização expirou. Inicie novamente a ligação." | Start again with **Preparar ligação** and complete the Meta authorisation straight away. | | "Não foi possível abrir a Meta. Verifique a ligação e os bloqueadores do navegador." | Allow pop-ups and disable blockers for the backoffice. | | "Escolha uma conta Cloud API com um número. Coexistência e migrações ainda não são suportadas neste fluxo." | Use a Cloud API number that is not in use in the WhatsApp Business app. | | "Este número ou conta WhatsApp já está associado a outra organização. Contacte a Diska." | Each number can only be in one organisation. | | "Este número já está ligado. Use Reconectar na conexão existente." | Use **Reconectar** on the number's card. | | "Conclua a verificação do número no WhatsApp Manager e volte a ligar." | Verify the number at Meta and try again. | | "Autorize a gestão da conta WhatsApp e o envio de mensagens na Meta." | In the Meta window, accept all the permissions requested. | | "Escolha um agente em Prompt Mode com uma versão publicada." | Publish a Prompt Builder agent and choose it. | For other errors, the message says whether history was preserved; try again or contact Diska. # Templates Outside the 24-hour window — or to contact a customer who never wrote — WhatsApp only lets you send **templates**: messages approved in advance by Meta. In Diska, templates are sent by your team, inside a conversation, and only to customers with recorded consent for the template's category. ## Create templates Templates are created and submitted for approval in Meta's **WhatsApp Manager**, on the connected WhatsApp Business account. Diska does not create or edit templates: it imports them from Meta. To be sendable through Diska, templates must follow these rules: | Rule | Detail | | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | Category | **Notificações de serviço** (Utility) or **Marketing**. **Autenticação** (Authentication) templates cannot be sent. | | Format | Text only: text header (optional), body (required) and footer (optional, no variables). Buttons and image, video or document headers are not supported yet. | | Variables | Either all named (`{{name}}`) or all numbered in order (`{{1}}`, `{{2}}`, …). Only in the header and body. | | Meta sample | Meta's sample template can be viewed but not sent. Use your own approved template. | ## Sync Each connected number has, under **Definições → Integrações → WhatsApp**, the **Templates de mensagem** (Message templates) section. Open it to see the templates. 1. After creating or changing templates at Meta, click **Sincronizar com Meta** (Sync with Meta) — Owner or Administrator. 2. Expand a template to see its preview, category, sync date and variables. Possible states: **Aprovado** (approved), **Em análise** (in review), **Rejeitado** (rejected), **Em pausa** (paused), **Desactivado** (disabled), **Removido** (removed). Only **Aprovado** templates in a supported format are offered for sending. The others show "Consulta disponível. Este formato ainda não pode ser enviado pela Diska." (view only; this format cannot be sent by Diska yet). The state and content are checked again with Meta before every send. ## Consent A message from the customer opens the reply window, but does **not** authorise future contact. Before sending a template, record the customer's consent for the template's category in the conversation's **Consentimento para iniciar contacto** (consent to start contact) panel — see [Conversations](https://docs.diska.ai/en/whatsapp/conversations#consent). Without recorded consent, sending is refused: "É necessário registar consentimento para esta categoria antes de enviar." ## Send a template 1. Open the conversation under **Históricos → WhatsApp** (or create it with **Iniciar contacto**) and **take over** — only the operator in charge of the conversation can send. 2. At the bottom of the conversation: - with the 24-hour window closed, the template form appears directly; - with the window open, choose **Template** (instead of **Mensagem**). 3. Under **Template aprovado** (approved template), choose the template. Content and language are sent exactly as approved by Meta. 4. Fill in each **Variável** (variable) — up to 500 characters, no line breaks. 5. Check the **Pré-visualização** (preview) and click **Enviar template** (Send template). If the send confirmation does not arrive, the button becomes **Confirmar envio pendente** (confirm pending send): retrying reuses the same identifier, so the message is not sent twice. If there are no approved templates, you see "Sem templates de texto aprovados. Sincronize em Definições → Integrações → WhatsApp." ## Common errors | Message | What to do | | ------------------------------------------------------------------------------------- | ------------------------------------------------------------- | | "É necessário consentimento registado para a categoria deste template." | Record the customer's consent for that category. | | "O template não está aprovado ou precisa de nova sincronização com a Meta." | Check the state at Meta and sync. | | "O template foi alterado. Actualize a lista e confirme novamente a pré-visualização." | The template changed at Meta: sync and review before sending. | | "Preencha todas as variáveis, com até 500 caracteres e sem quebras de linha." | Fix the variable values. | | "Este formato de template ainda não pode ser enviado pela Diska." | Create a text-only version. | | "O envio de templates não está disponível neste momento." | Template sending is temporarily unavailable. Try later. | | "Não foi possível sincronizar com a Meta. O catálogo anterior foi preservado." | Try syncing later. | # Conversations WhatsApp conversations live under **Históricos → WhatsApp** (the **Conversas WhatsApp** page). Here you follow what the AI is answering, take over conversations and reply to the customer in the same thread. ## The list Each row shows the customer's number, the time of the last message, the agent and who is handling it, the last message, and tags for the handling state, operational state, delivery and **por ler** (unread) messages. The list refreshes itself every 15 seconds; use **Actualizar** (Refresh) to force it. Filters: | Filter | Options | | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Agente** (Agent) | All agents or one agent. | | **Conexão / número** (Connection / number) | All numbers or one connected number. | | **Conversa** (Conversation) | **Abertas** (open) or **Encerradas** (closed). | | **Atendimento** (Handling) | **Em atendimento pela IA** (handled by the AI), **Aguardando humano** (waiting for a human), **Com operador** (with an operator), **Resolvida** (resolved). | | **Estado operacional** (Operational state) | **Falhas** (failures), **Entregas incertas** (uncertain deliveries), **Pendentes** (pending), **Bloqueadas** (blocked). | | **Desde** / **Até** (From / To) | Date range. | WhatsApp conversations do not appear in **Históricos → Chamadas** and are not counted in Analytics. ## Handling states | State | Who replies | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Em atendimento pela IA** | The agent replies automatically. | | **Aguardando humano** | The AI is paused and the conversation waits for an operator. This happens when the agent asks for a human (the reason shows as **Motivo:**) or when the customer writes again in a resolved conversation. | | **Com operador** | A team member took over the conversation; the AI is paused. | | **Resolvida** | Service finished; the history is preserved. | ## Take over and hand back At the top of the conversation, the handling block shows who is in charge and the available buttons: - **Assumir atendimento** (Take over) — moves the conversation to you (**Com operador**) and pauses the AI. - **Reatribuir a mim** (Reassign to me) — Owners and Administrators can take a conversation held by another operator. - **Devolver à IA** (Hand back to the AI) — the agent replies again. - **Resolver conversa** (Resolve conversation) — closes the service. - **Reabrir e assumir** (Reopen and take over) — reopens a resolved conversation and assigns it to you. Only the operator in charge (or an Owner or Administrator) can hand back or resolve a conversation that is **Com operador**. Viewers see the history but cannot reply. ## Reply To reply, the conversation must be **Com operador** and assigned to you. ### The 24-hour window The tag at the top of the conversation tells you what you can send: - **Janela de atendimento ativa** (service window active) — the customer wrote in the last 24 hours. You can send free-form messages until the time shown ("Pode responder até …"). - **Template necessário** (template required) — more than 24 hours have passed since the customer's last message, or they never wrote. You can only send an [approved template](https://docs.diska.ai/en/whatsapp/templates), with consent. ### Send a message 1. Type in **Resposta ao cliente** (reply to the customer) — up to 4,096 characters; 1,024 with an attachment. 2. Optionally use **Anexar ficheiro** (attach file). 3. Click **Enviar** (Send). | Attachment | Formats | Maximum size | | ---------- | ----------------------- | ------------------- | | Image | JPG, PNG | 5 MB | | Document | PDF | 10 MB | | Text | TXT | 1 MB | | Audio | MP3, M4A, OGG, AAC, AMR | 16 MB and 5 minutes | Audio is sent without a caption; send the text as a separate message. PDFs with active content are rejected — export a plain copy. If the send confirmation does not arrive, the button becomes **Confirmar envio** (confirm send): retrying reuses the same identifier, so the customer does not receive the message twice. ## Messages and attachments Each message shows the sender (**Cliente**, **Agente IA**, **Operador · name** or **Sistema**), the time and the status: **Recebida** (received), **A enviar** (sending), **Enviada** (sent), **Entregue** (delivered), **Lida** (read), **Falhou** (failed), **Entrega incerta** (uncertain delivery), **Bloqueada** (blocked) or **Tipo não suportado** (unsupported type). **Dados da mensagem** (message data) shows the Meta ID and the receive and send times. - Customer attachments open with **Abrir anexo** (open attachment): an image, an audio player or a document to download. - If the AI cannot interpret an attachment, you see "Anexo disponível para o operador. A IA não conseguiu interpretar o conteúdo." (attachment available to the operator; the AI could not interpret it) — take over and reply. - Attachments are kept for a limited period. After that you see "O prazo de conservação deste anexo terminou." (this attachment's retention period has ended), but the message record is kept. - Message types Diska does not process yet (for example video or location) show as "Este tipo de mensagem ainda não é suportado." (this message type is not supported yet). ## Consent The **Consentimento para iniciar contacto** (consent to start contact) panel shows, per category (**Notificações de serviço** — utility, **Marketing**, **Autenticação** — authentication), whether the customer authorised contact started by your company. A message from the customer opens the reply window but does not count as authorisation. To record an authorisation: 1. Click **Registar autorização** (Record authorisation). 2. Choose the **Categoria autorizada** (authorised category) and the **Origem** (source): **Confirmação escrita** (written confirmation), **Formulário web** (web form), **Contrato** (contract), **Autorização verbal registada** (recorded verbal authorisation) or **Teste controlado autorizado** (authorised controlled test). 3. Enter the **Data e hora do consentimento ou revogação** (date and time), the **Finalidade** (purpose) and the **Evidência** (evidence: where the authorisation was recorded — no credentials or sensitive data). 4. Confirm the statement and click **Guardar registo** (Save record). **Registar revogação** (Record revocation) blocks new templates in every category. **Ver registos** (See records) shows the history of authorisations and revocations. If the customer writes an explicit request to stop receiving messages — for example "STOP", "Sair", "Parar mensagens" or "Não quero receber mais mensagens" — Diska records the revocation automatically, with the source **Pedido do cliente no WhatsApp** (customer request on WhatsApp). ## Start contact To write to a customer who has no conversation yet: 1. Under **Históricos → WhatsApp**, click **Iniciar contacto** (Start contact). 2. Choose the **Número da empresa** (company number) and enter the **WhatsApp do cliente** (customer's WhatsApp) with the country code (for example `+244…`). 3. Click **Abrir conversa** (Open conversation). Opening the contact sends nothing. The conversation opens already assigned to you: record consent and send an [approved template](https://docs.diska.ai/en/whatsapp/templates#send-a-template). If a conversation with that number already exists, Diska opens the same history. ## Activity and diagnosis - **Atividade do atendimento** (handling activity) — who took over, handed back, resolved or reopened the conversation, and when. - **Diagnóstico operacional** (operational diagnosis, Owner and Administrator) — send attempts, failures and delivery events. Uncertain sends are not resent automatically; after investigating a failure, use **Registar análise** (record analysis) to document it. ## Common errors | Message | What to do | | --------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | "Assuma esta conversa antes de responder." | Click **Assumir atendimento**. | | "Esta conversa está atribuída a outro operador." | Ask that operator or an Owner or Administrator to reassign it. | | "A janela de resposta terminou. Use um template aprovado com consentimento ou aguarde uma mensagem do cliente." | Send a template. | | "O atendimento mudou entretanto. Actualize a conversa e tente novamente." | Someone else changed the conversation: click **Actualizar**. | | "Foram enviadas várias mensagens seguidas. Aguarde um minuto." | Wait and send again. | | "O formato ou tamanho do ficheiro não é suportado." | See the attachment table above. | | "A conexão WhatsApp está desactivada." | The number was disconnected — see [Connect the number](https://docs.diska.ai/en/whatsapp/connect). | # Voice calls With **WhatsApp voice calls**, a customer taps the call icon in their chat with your business and a Diska agent answers. It works like a [phone call](https://docs.diska.ai/en/telephony/phone-calls): the agent uses its published version, with the same voice, rules, [knowledge base](https://docs.diska.ai/en/knowledge-base) and actions. When needed, it hands the call to a person on your team. ::callout{type="info"} This page covers **voice calls** . For text messages, see [WhatsApp](https://docs.diska.ai/en/whatsapp) . :: ## How it works 1. The customer opens the chat with your business on WhatsApp and taps the call icon. 2. Meta routes the call to Diska and the agent answers. 3. The conversation runs as on a phone call. When the condition of a transfer action is met, the agent [hands the call to a person](https://docs.diska.ai/#transfer-to-a-person). 4. The call is recorded in **Históricos → Chamadas** (History → Calls), with the channel **WhatsApp**. For the customer, it is a normal WhatsApp call over their internet connection. Calls are **inbound only**: the agent does not call customers on WhatsApp. ## Requirements - The WhatsApp Business number connected to Diska, on Meta's **Cloud API**. See [Connect the number](https://docs.diska.ai/en/whatsapp/connect). - The messaging limit Meta requires for calling: at least **2,000 unique recipients per day** on that number. Meta sets this limit based on the volume and quality of your conversations. - An active **Inbound** agent with a published version to answer the calls. - To transfer to a person: an organization allowed to place outbound calls, and one of the organization's DISKA numbers to identify the transfers. - The **Proprietário** (Owner) or **Administrador** (Administrator) role in the Diska organization to turn calls on. ## Turn calls on Calls are turned on under **Definições → Integrações** (Settings → Integrations), in the **WhatsApp** section: on the number's card, open **Chamadas de voz** (Voice calls). 1. Under **Agente que atende as chamadas** (agent that answers calls), choose the agent. Only active Inbound agents with a published version are listed. 2. Optional: under **Número DISKA para transferências** (DISKA number for transfers), choose the number people see when they receive a transferred call. To not transfer, leave **Sem transferências** (no transfers). 3. Click **Guardar alterações** (Save changes). 4. Click **Activar chamadas** (Turn calls on) and confirm. Diska sets up the number's calls with Meta, which can take a few seconds. The section title then shows **Activas** (on), and the text gives the number. From then on, customers see the call icon in their chat with your business. To stop receiving calls, click **Desactivar chamadas** (Turn calls off) and confirm. Customers can no longer call that number on WhatsApp; messages are unaffected. While calls are on, you can change the agent but not remove it. ::callout{type="info"} If the **Chamadas de voz** section does not appear on the number's card, WhatsApp calls are not available to your organization yet. Contact Diska. :: ### If turning calls on fails | Message | What to do | | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | «A Meta não activou as chamadas neste número. Confirme os requisitos: …» (Meta did not turn calling on for this number) | The number does not meet Meta's requirements yet. Try again once Meta raises the number's messaging limit. | | «As chamadas deste número já estão ligadas a outro serviço na Meta. …» (calls already go to another service) | Diska never replaces another calling setup. Turn it off in WhatsApp Manager first, then try again. | | «Reconecte o número WhatsApp antes de activar as chamadas.» (reconnect the number first) | The number's connection must be renewed. See [Connect the number](https://docs.diska.ai/en/whatsapp/connect). | | «Escolha primeiro o agente que atende as chamadas.» (choose the agent first) | Choose and save the agent before turning calls on. | | «A Meta não aceitou a configuração de áudio das chamadas. …» (Meta did not accept the audio settings) | Contact Diska. Calls stay off, so no customer hears a failed call. | ## Which agent answers The calls agent is separate from the **Agente para novas conversas** (agent for new conversations), which answers messages. A number can have one agent for messages and another for calls, or the same agent for both. Changing one never changes the other. It must be an active **Inbound** agent with a published version. A change to the agent reaches WhatsApp calls only after you [publish it](https://docs.diska.ai/en/guides/publish-agent). | Available on a WhatsApp call | Not available | | ---------------------------- | --------------------------------------------------------- | | Knowledge base search | IVR handling and keypad digits (DTMF) | | Custom actions | Transfers to SIP URIs, landlines or international numbers | | Real-time booking | Calls placed by the agent (Outbound agents and Campaigns) | | Transfers to Angolan mobiles | | ## Transfer to a person Meta does not allow a WhatsApp call to be transferred to another number. So the customer **stays on the same call**: Diska calls the person and joins them to the conversation. 1. The agent decides to transfer, when the action's condition is met, and tells the customer. 2. The customer hears the ringing tone while the person's mobile rings, for up to 30 seconds. 3. When the person answers, they talk to the customer on the same WhatsApp call and the agent leaves. 4. If the person does not answer, is busy or declines, the customer is back with the agent, which says «Infelizmente o número está indisponível neste momento.» (Unfortunately the number is unavailable right now.) and carries on. The transfer uses your existing [transfer actions](https://docs.diska.ai/en/actions/call-transfers) and [transfer node](https://docs.diska.ai/en/nodes/transfer), with the rules of a DISKA number: - **Destination:** Angolan mobiles only (Africell or Unitel), with the number fixed in the action, the node or a **Lista telefónica** (Phone book). A number said during the conversation is never used. - **Authorization:** the organization must be allowed to place outbound calls. The call to the mobile goes out over the DISKA network. - **Caller ID:** the person sees the **Número DISKA para transferências** chosen under **Chamadas de voz**, not the customer's WhatsApp number. Without that number, transfers are not available on that WhatsApp number. - **Assisted modes:** the assisted transfer with a message and the assisted transfer with a contextual summary connect the call **directly**. The person does not hear the briefing first. - **Hours:** the action's availability hours apply as on the phone. Outside them, the agent says the unavailability message. - **Duration:** once transferred, the call can last up to 1 hour. ## Concurrent call limit WhatsApp calls count towards the organization's [concurrent call limit](https://docs.diska.ai/en/telephony/concurrency), together with phone calls. When the limit is reached, new calls are not answered. ## Limitations - Inbound calls only: the agent does not call customers on WhatsApp. - No keypad digits (DTMF): IVR handling and keypad menus don't work. - Transfers go to Angolan mobiles only, and assisted modes connect directly. - Each WhatsApp number has a single agent for calls. - Audio quality depends on the customer's internet connection. ## FAQ **Can I use the WhatsApp number my business already uses, or does it have to be a Diska number?** You can use your own number, as long as it is connected to Diska on the Cloud API and has the limit of 2,000 unique recipients per day. If the number is on the WhatsApp or WhatsApp Business app on a phone today, it has to move to the Cloud API, and it can no longer be used in the app. Coexistence (the app and the Cloud API on the same number) does not work, because Meta does not allow calls through the API in that mode. You only need a DISKA number to transfer calls to a person. **Can the same agent answer the phone and WhatsApp?** Yes. A published Inbound agent can answer phone numbers and WhatsApp numbers at the same time. **Can I have one agent for messages and another for calls?** Yes, on the same WhatsApp number. **Can I change the agent's voice, language or instructions?** Yes, as with any agent. WhatsApp calls use the published version. **Does the person who receives the transfer see the customer's number?** No. They see the DISKA number set for transfers on that WhatsApp number. **Do I see the caller's number?** Usually, yes. When Meta identifies the customer only by their WhatsApp ID, the call appears without a number. **Does the customer pay for the call?** It is not a phone call: WhatsApp uses the customer's internet connection. **Where do I see the calls?** In **Históricos → Chamadas** (History → Calls), with the channel **WhatsApp**. ## Further reading - [Phone and SIP transfers](https://docs.diska.ai/en/telephony/transfers) - [Call transfers](https://docs.diska.ai/en/actions/call-transfers) - [WhatsApp Calling API (Meta)](https://developers.facebook.com/docs/whatsapp/cloud-api/calling){rel=""nofollow""} # WhatsApp The **WhatsApp** channel connects a number from your WhatsApp Business account (Meta) to Diska. From then on: - **the agent answers automatically**, in text, the messages customers send to that number; - your team follows everything under **Históricos → WhatsApp** and can **take over the conversation** at any time; - to start or resume contact outside the 24-hour window, your team sends Meta-**approved templates**, with recorded consent; - customers can also **call** the number and talk to an agent by voice: see [Voice calls](https://docs.diska.ai/en/whatsapp/calls). ## Which agent answers Each connected number has an **agent for new conversations**. It must be an agent built with the **Prompt Builder** and have a published version — Flow Designer agents cannot be linked to WhatsApp. WhatsApp uses the agent's **published version**, with the same personality, rules, [knowledge base](https://docs.diska.ai/en/knowledge-base) and actions: | Available in messages | Not applicable to messages | | ----------------------------------------------------------------------------------------------------------- | -------------------------- | | Knowledge base search | Call transfers | | Custom actions | IVR handling | | SMS and real-time booking | | | Asking for a human (the AI pauses and the conversation becomes **Aguardando humano** — waiting for a human) | | The agent adapts to written messaging: short messages, one question at a time, no references to calls or microphones. When the customer sends an image, a document or a voice message, the agent tries to interpret it; if it cannot, the attachment is left for your team. ## Requirements - A WhatsApp Business account at Meta with a number on the **Cloud API**, registered and verified in WhatsApp Manager. Numbers in coexistence with the WhatsApp Business app, and migrations, are not yet supported when connecting. - A published Prompt Builder agent. - The **Proprietário** (Owner) or **Administrador** (Administrator) role in the Diska organisation to connect and manage the number. ::callout{type="warning"} Self-service connection of new numbers may not be open to your organisation yet. In that case, **Definições → Integrações** (Settings → Integrations) shows **Novas ligações em preparação** (new connections in preparation) with the reason — for example "Onboarding de empresas externas a aguardar validação Meta." (onboarding of external companies awaiting Meta validation) — and the **Ligar WhatsApp** button is disabled. Contact Diska to connect your number. :: ## Permissions | Action | Owner / Administrator | Member | Viewer | | ----------------------------------------------------------------------------------------- | :-------------------: | :----: | :----: | | Connect, reconnect and disconnect numbers; change the agent; test message; sync templates | ✓ | — | — | | View conversations | ✓ | ✓ | ✓ | | Take over conversations, reply, send templates, record consent, start contact | ✓ | ✓ | — | | Reassign to yourself a conversation held by another operator; operational diagnosis | ✓ | — | — | ## FAQ **Can customers call the agent on WhatsApp (voice call)?** Yes, once you turn calls on in the number's **Chamadas de voz** (Voice calls) section, under **Definições → Integrações**. The agent answers by voice and can transfer to a mobile on your team. See [Voice calls](https://docs.diska.ai/en/whatsapp/calls). **Does the agent remember on WhatsApp what the customer said on a call?** Not yet. [Shared memory](https://docs.diska.ai/en/knowledge-base/shared-memory) is for phone calls only; each WhatsApp conversation keeps its own history in **Históricos → WhatsApp**. **Can I use the same agent on the phone and on WhatsApp?** Yes, if it is a Prompt Builder agent: its published version answers on both channels, with the same rules and the same knowledge base. ## In this section ::card-group :::card --- description: Authorise Diska at Meta, connection states and test message. icon: i-simple-icons-whatsapp title: Connect the number to: https://docs.diska.ai/en/whatsapp/connect --- ::: :::card --- description: Sync approved templates and send them with consent. icon: i-lucide-file-text title: Templates to: https://docs.diska.ai/en/whatsapp/templates --- ::: :::card --- description: Follow the AI, take over and reply to the customer. icon: i-lucide-messages-square title: Conversations to: https://docs.diska.ai/en/whatsapp/conversations --- ::: :::card --- description: The customer calls on WhatsApp and the agent answers, with transfers to your team. icon: i-lucide-phone-call title: Voice calls to: https://docs.diska.ai/en/whatsapp/calls --- ::: :: # Getting started with the API The [DISKA API](https://docs.diska.ai/en/api/api-channel) is a REST API for your server. It reads agents, calls and transcripts, creates and publishes agents, feeds knowledge bases and tells your system when a call ends. It works from any environment that can make HTTPS requests. ::callout{type="info"} For AI assistants and coding tools, the whole documentation is available as plain text in [`llms.txt`](https://docs.diska.ai/llms.txt){rel=""nofollow""} (index) and [`llms-full.txt`](https://docs.diska.ai/llms-full.txt){rel=""nofollow""} (full content). :: ## Base URL | Environment | Base URL | | ----------- | ------------------------- | | Production | `https://api.diska.ai/v1` | There is a single base URL for every organization, always over HTTPS. The `/api/v1` prefix is the backoffice's internal API and does not accept API keys. ## What you can do | Group | What it does | Endpoints | | -------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | Identity | Confirms the organization and the key. | `GET /v1/me` | | Agents | Lists, reads, creates, edits and publishes agents. | `GET /v1/agents`, `GET /v1/agents/{agent_id}`, `POST /v1/agents`, `PATCH /v1/agents/{agent_id}`, `POST /v1/agents/{agent_id}/publish` | | Calls | Call history with filters, each call's detail (transcript, executed actions and post-call result) and its recording. | `GET /v1/calls`, `GET /v1/calls/{call_id}`, `GET /v1/calls/{call_id}/recording` | | Outbound calls | The agent calls a person when your system asks. | `/v1/outbound-calls` | | Campaigns | Outbound calls in bulk, with windows and limits. | `/v1/campaigns` | | Chat | Text chat with an agent, with the reply in the same request. | `/v1/chats` | | Analytics | Volume, outcomes, sentiment and performance per agent. | `GET /v1/analytics/overview` | | Phone numbers | The organization's phone numbers. | `GET /v1/phone-numbers` | | Knowledge | Creates knowledge bases and adds text, web pages and PDFs. | `GET /v1/knowledge-bases`, `POST /v1/knowledge-bases` and the document endpoints | | Webhooks | Registers the endpoints that receive each completed call's data. | `/v1/webhook-endpoints` | Each endpoint's parameters, bodies, responses and errors are in [Endpoints](https://docs.diska.ai/en/api/endpoints). What the API does not do yet is in [What the DISKA API does not do yet](https://docs.diska.ai/en/api/api-channel#what-the-diska-api-does-not-do-yet). ## Make your first request ### 1. Create an API key 1. In the backoffice, open **Definições → Chaves API** (Settings → API keys; Owners and Administrators only). 2. Click **Criar nova chave API** (Create new API key) and name it, for example "API test". 3. Under **Âmbitos** (Scopes), choose **Agentes — leitura** (agents, read) and **Chamadas e transcrições** (calls and transcripts) to follow this guide. With no scope, the key has full access. 4. Click **Gerar** (Generate) and copy the key (`dsk_…`). It is shown only this once. Keep the key in an environment variable on your server: ```bash export DISKA_API_KEY="dsk_…" ``` More in [Authentication](https://docs.diska.ai/en/api/authentication). ### 2. Check the key `GET /v1/me` needs no scope and returns the organization and the key: ```bash curl https://api.diska.ai/v1/me \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```json { "organization": { "id": "…", "name": "My Company", "slug": "my-company" }, "key": { "id": "…", "name": "API test", "key_preview": "dsk_a1b2…F5A4", "scopes": ["agents:read", "calls:read"], "expires_at": null, "created_at": "…", "last_used_at": "…" } } ``` A `401` means the key is missing, wrong, revoked or expired. See [authentication errors](https://docs.diska.ai/en/api/authentication#authentication-errors). ### 3. List your agents `GET /v1/agents` only reads data and has no required parameters: ::code-group ```bash [cURL] curl https://api.diska.ai/v1/agents \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/agents", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() for agent in response.json()["items"]: print(agent["id"], agent["name"], agent["status"]) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/agents', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) const { items } = await response.json() for (const agent of items) console.log(agent.id, agent.name, agent.status) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status !== 200) { throw new RuntimeException("HTTP $status: $body"); } foreach (json_decode($body, true)['items'] as $agent) { echo $agent['id'], ' ', $agent['name'], ' ', $agent['status'], PHP_EOL; } ``` :: `200` response: ```json { "items": [ { "id": "3f1c2a7e-…", "name": "Reception", "slug": "reception", "description": null, "status": "active", "agent_type": "inbound", "editing_mode": "prompt", "version": 3, "phone_number": null, "public_channel_enabled": false, "created_at": "2026-10-22T19:14:00Z", "updated_at": "2026-10-25T18:40:00Z" } ] } ``` Archived agents only appear with `?status=archived`. The fields are described in [The agent object](https://docs.diska.ai/en/api/endpoints#the-agent-object). ### 4. Read an agent's calls With an agent's `id`, ask for its latest calls: ```bash curl "https://api.diska.ai/v1/calls?agent_id=3f1c2a7e-…&limit=10" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` Each call has its channel, status, duration, summary and caller. The detail, with the transcript, is at `GET /v1/calls/{call_id}`. To export large histories, use [cursor pagination](https://docs.diska.ai/en/api/api-channel#pagination). ::callout{type="tip"} An agent's ID is also shown in the backoffice: on the agent page, next to its name, and under **Publicação → API** (Publishing → API), with a copy button. :: ## Next steps ::card-group :::card --- description: Your system receives each completed call's data, without polling. icon: i-lucide-webhook title: Receive webhooks to: https://docs.diska.ai/en/api/webhooks --- ::: :::card --- description: Create knowledge bases and add text, web pages and PDFs. icon: i-lucide-book-open title: Feed knowledge to: https://docs.diska.ai/en/api/endpoints#knowledge --- ::: :::card --- description: 120 requests per minute per key, cursor pagination and the error format. icon: i-lucide-gauge title: Pagination, limits and errors to: https://docs.diska.ai/en/api/api-channel#rate-limits --- ::: :::card --- description: Import it into Postman or generate a client for your language. icon: i-lucide-file-json title: OpenAPI specification to: https://docs.diska.ai/en/api/api-channel#openapi-specification --- ::: :::card --- description: One page per endpoint, with schemas, examples in four languages and Try it. icon: i-lucide-book-marked title: API reference to: https://docs.diska.ai/en/api/reference --- ::: :::card --- description: Sync with your CRM, export the history and feed knowledge from your website. icon: i-lucide-map title: Guides to: https://docs.diska.ai/en/api/guides --- ::: :: ## FAQ **Can I start calls or campaigns through the API?** Yes: [outbound calls](https://docs.diska.ai/en/api/reference/outbound-calls) and [campaigns](https://docs.diska.ai/en/api/reference/campaigns), with published outbound agents, within contact hours. Because they have a cost, Diska switches them on for the organization when asked. **Can I talk to an agent through the API?** By text, yes: the [chat](https://docs.diska.ai/en/api/reference/chats) returns the agent's reply in the same request (switched on by Diska when asked). By voice, use the widget, the public link, a phone number or WhatsApp. See [Realtime](https://docs.diska.ai/en/api/realtime). **Is there a test environment?** There is no sandbox: the API always works on the key's organization data. To test, use a test agent and a key with read scopes only. **Is there an official SDK?** Not yet. Generate a client from the [OpenAPI specification](https://docs.diska.ai/en/api/api-channel#openapi-specification) or call HTTP directly, as in the examples above. To explore the API without writing code, use the [Postman collection](https://docs.diska.ai/en/api/api-channel#postman) or **Try it** in the [API reference](https://docs.diska.ai/en/api/reference). **How do I know if the API has problems?** Check [status.diska.ai](https://status.diska.ai){rel=""nofollow""}: it shows the status of the API, the backoffice and telephony, with ongoing incidents. You can subscribe to updates on the page itself. **Will the API change?** Within `/v1` there are only compatible changes. See [Versioning and changelog](https://docs.diska.ai/en/api/changelog). **How many requests can I make?** 120 per minute, per key. Above that, the API answers `429` with `Retry-After`. See [Rate limits](https://docs.diska.ai/en/api/api-channel#rate-limits). **Can I use the key in a browser or a mobile app?** No. The key gives access to the organization's data: use it only on your server. # DISKA API The DISKA API is the platform's public REST interface, built for server-to-server integrations: sync calls and transcripts into your CRM, create and publish agents, feed knowledge bases, and receive [webhooks](https://docs.diska.ai/en/api/webhooks) when a call ends instead of polling. ## Base URL ```text https://api.diska.ai/v1 ``` The DISKA API lives under `/v1`. The `/api/v1` prefix belongs to the backoffice's internal API and does not accept API keys. ## What you can do | Resource | Operations | Scope | | -------------- | ------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | Identity | See the organization and key behind the token | — (any valid key) | | Agents | List and read agents | `agents:read` | | Agents | Create an agent (blank or from a template), edit its prompt, greeting, language and knowledge bases, and publish it | `agents:write` | | Calls | List calls and read the detail (transcript, executed actions, post-call result) | `calls:read` | | Recordings | Download a call's recording | `recordings:read` | | Outbound calls | The agent calls a person when your system asks | `calls:write` | | Campaigns | Create campaigns, add recipients, start, pause, resume, cancel and read results | `campaigns:read`, `campaigns:write` | | Chat | Chat by text with an agent: send the message and get the reply in the same request | `chats:write` | | Analytics | Summary of volume, outcomes, sentiment and per-agent performance | `analytics:read` | | Numbers | The organization's phone number inventory | `phone-numbers:read` | | Knowledge | List knowledge bases | `knowledge:read` | | Knowledge | Create bases and add documents (text, web page, PDF) | `knowledge:write` | | Webhooks | Register, update, test and remove webhook endpoints | `webhooks:manage` | The full reference (parameters, bodies, responses and errors for every endpoint) is in [Endpoints](https://docs.diska.ai/en/api/endpoints). ### What the DISKA API does not do yet - **Talk by voice** through the API: to have people talk to an agent, use the widget, the public link, a phone number or WhatsApp. See [Realtime](https://docs.diska.ai/en/api/realtime). - Chat by text with Flow Builder agents: the API chat uses prompt-mode agents. - List agent templates, edit an agent's voice, engine, actions or flows, or manage API keys — do that in the backoffice. - List, change or delete knowledge documents. ## Authentication Create a key under **Definições → Chaves API** (Settings → API keys; owners and admins only) and send it with every request: ```http Authorization: Bearer dsk_… ``` The `X-API-Key: dsk_…` header is also accepted. The full key is shown only once, when it is created. Details in [Authentication](https://docs.diska.ai/en/api/authentication). ::callout{type="warning"} Use the key only on your server, stored in an environment variable or a secrets vault. Never put it in code that runs in a browser, in a mobile app or in a repository. :: ### Scopes When you create a key you can choose its **Âmbitos** (scopes). **With no scope selected, the key has full access** to every endpoint. With scopes, only those endpoints respond; the others return `403` with `A chave não tem o âmbito ''.` ("the key does not have the scope"). | Scope | Name in the backoffice | Grants access to | | -------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------- | | `agents:read` | Agentes — leitura | `GET /v1/agents`, `GET /v1/agents/{agent_id}` | | `agents:write` | Agentes — criar, editar e publicar | `POST /v1/agents`, `PATCH /v1/agents/{agent_id}`, `POST /v1/agents/{agent_id}/publish` | | `calls:read` | Chamadas e transcrições | `GET /v1/calls`, `GET /v1/calls/{call_id}`, `GET /v1/outbound-calls/{outbound_call_id}` | | `calls:write` | Chamadas — ligar a clientes | `POST /v1/outbound-calls`, `POST /v1/outbound-calls/{outbound_call_id}/hangup` | | `recordings:read` | Gravações — descarregar | `GET /v1/calls/{call_id}/recording` | | `campaigns:read` | Campanhas — leitura | `GET /v1/campaigns`, `GET /v1/campaigns/{campaign_id}`, `GET /v1/campaigns/{campaign_id}/recipients` | | `campaigns:write` | Campanhas — gestão | Create campaigns, add recipients, start, pause, resume and cancel | | `chats:write` | Chat com agentes | Every `/v1/chats` endpoint | | `analytics:read` | Análises | `GET /v1/analytics/overview` | | `phone-numbers:read` | Números | `GET /v1/phone-numbers` | | `knowledge:read` | Conhecimento — leitura | `GET /v1/knowledge-bases` | | `knowledge:write` | Conhecimento — escrita | `POST /v1/knowledge-bases` and the three document endpoints | | `webhooks:manage` | Webhooks — gestão | Every `/v1/webhook-endpoints` endpoint | `GET /v1/me` needs no scope. A key's scopes cannot be changed after it is created: to change access, create a new key and revoke the old one. Outbound calls, campaigns and chat must also be switched on for the organization: they have a cost, so Diska turns them on when asked. Until then they answer `403`, even to a key with full access. ## First request ```bash curl https://api.diska.ai/v1/me \ -H "Authorization: Bearer dsk_…" ``` ```json { "organization": { "id": "…", "name": "My Company", "slug": "my-company" }, "key": { "id": "…", "name": "CRM integration", "key_preview": "dsk_a1b2…F5A4", "scopes": [], "expires_at": null, "created_at": "…", "last_used_at": "…" } } ``` `scopes: []` means full access. ## Conventions - Requests and responses are JSON (UTF-8), except PDF uploads, which are `multipart/form-data`. - Dates are ISO 8601. - Everything belongs to the key's organization: an identifier from another organization returns `404`, as if it did not exist. - Every response carries an `X-Request-Id` header. You can send your own `X-Request-Id` (8 to 64 characters: letters, digits, `.`, `_`, `:` or `-`); if you don't, Diska generates one. Quote it when you contact support. ## Pagination Only `GET /v1/calls` is paginated; the other lists return every item at once. The call list has two modes: **Offset** (default) — `limit` (1–200, default 50) and `offset`. The response includes `total` with the exact count. Calls are ordered from newest to oldest. **Cursor** — recommended for exporting large histories, because every page costs the same at any depth: 1. First request: `GET /v1/calls?cursor=start&limit=200`. 2. The response includes `next_cursor`; request the next page with `cursor=`, keeping the same filters. 3. When `next_cursor` is `null`, you have reached the end. In cursor mode, `total` and `offset` are `null` and the `search` parameter is not accepted (`400`). A malformed cursor returns `400` with `Cursor inválido.` ("invalid cursor"). ## Rate limits By default, each key can make **120 requests per minute**. The counter belongs to each key — several keys of the same organization do not share the limit — and the 60-second window starts with the first request. Above the limit, the API returns `429` with the headers `Retry-After` (seconds until you can retry), `X-RateLimit-Limit` and `X-RateLimit-Remaining: 0`: ```json { "detail": { "error": "rate_limited", "retry_after_seconds": 42, "limit": 120, "window_seconds": 60 } } ``` Wait for the time given in `Retry-After` before retrying. Successful responses do not carry rate-limit headers. ## Errors | Code | When | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | Request refused: invalid cursor, `search` combined with `cursor`, invalid webhook URL or event, endpoint limit reached, invalid knowledge document (PDF too large, page without text…). | | `401` | Key missing, invalid, revoked or expired. | | `403` | Organization suspended, or the key lacks the required scope. | | `404` | The resource does not exist or belongs to another organization. | | `409` | Conflict — for example, publishing an archived agent. | | `422` | Validation failed: parameters or body in an invalid format, or an agent that cannot be published (empty prompt, invalid flow). | | `429` | Rate limit exceeded — honour `Retry-After`. | | `500` | Unexpected Diska error. | | `502` / `503` | Temporary platform failure — retry with increasing back-off and check the [service status](https://docs.diska.ai/#service-status). | Most errors have the shape `{ "detail": "message" }`, with the message in Portuguese. Format validation errors (`422`) carry `detail` as a list (field, message), and `429` carries the object shown above. A `500` looks like this: ```json { "error": { "code": "internal_server_error", "message": "Internal server error." }, "request_id": "…" } ``` ## OpenAPI specification `GET https://api.diska.ai/v1/openapi.json` returns the OpenAPI specification of the DISKA API only. It needs no authentication and can be cached for 5 minutes. You can use it to generate a client in your language; the [API reference](https://docs.diska.ai/en/api/reference) is generated from it. The specification version (`info.version`) follows the [versioning policy](https://docs.diska.ai/en/api/changelog). ### Postman There is a ready-made Postman collection, with every endpoint, example bodies and authentication already set up: - [Collection in Portuguese](https://docs.diska.ai/api/diska-canal-api.pt.postman_collection.json){rel=""nofollow""} - [Collection in English](https://docs.diska.ai/api/diska-canal-api.en.postman_collection.json){rel=""nofollow""} 1. In Postman, click **Import** and choose the downloaded file. 2. In the collection, open **Variables** and set `apiKey` to your key (`dsk_…`). `baseUrl` already points to `https://api.diska.ai`. 3. Also fill in the IDs you will use (`agent_id`, `call_id`, `knowledge_base_id`, `endpoint_id`). `POST`, `PATCH` and `DELETE` requests change the organization's real data. ## Service status [status.diska.ai](https://status.diska.ai){rel=""nofollow""} shows the status of the API, the backoffice and telephony (SIP/PBX), with incidents and maintenance. You can subscribe to updates on the page itself or follow the [RSS](https://status.diska.ai/feed.rss){rel=""nofollow""} feed. If you get `502`, `503` or unusual response times, check it before opening a support request. If it shows no incident, contact support with the request's `X-Request-Id`. # Authentication The [DISKA API](https://docs.diska.ai/en/api/api-channel) is authenticated with **organization API keys**. A key acts on behalf of the organization, not of a person: it keeps working if the person who created it leaves the organization, until it is revoked or expires. ## Create a key Only the organization's **owners** and **admins** can see and manage API keys. 1. In the backoffice, open **Definições → Chaves API** (Settings → API keys). 2. Click **Criar nova chave API** (create new API key). 3. Fill in the **Nome** (name — required, up to 120 characters) and, optionally, the **Descrição** (description — up to 500). 4. Under **Âmbitos** (scopes), choose what the key can do. With nothing selected, the key has full access. See [scopes](https://docs.diska.ai/en/api/api-channel#scopes). 5. Under **Expira em** (expires on), pick a date if you want the key to stop working on its own. The key is valid until the end of that day. 6. Click **Gerar** (generate). The **A sua chave API** (your API key) window shows the full key (`dsk_…`) **only once**. Copy it and store it somewhere safe: once you close the window there is no way to see it again — Diska keeps only a hash of the key, not the key itself. If you lose it, create a new one. In the list, each key shows its name, a masked preview (`dsk_a1b2…F5A4`), its scopes (**Acesso total** — full access — when it has none), creation date, expiry and **Último uso** (last used). Last use is updated at most every 5 minutes, so a key used just now may show a slightly earlier time. ## Send the key Send the key with every request, in one of these headers: ```http Authorization: Bearer dsk_… ``` ```http X-API-Key: dsk_… ``` If you send both, `Authorization` wins. To check that the key works and which organization it belongs to, call `GET /v1/me`: ```bash curl https://api.diska.ai/v1/me \ -H "Authorization: Bearer dsk_…" ``` ## Expiry and revocation - **Expiry**: after the chosen date, the key returns `401` with `Chave de API expirada.` ("API key expired"). A key with no expiry date is valid until it is revoked. - **Revocation**: in the list, click the bin icon and confirm with **Revogar chave** (revoke key). The key stops working immediately and disappears from the list. To rotate a key without interrupting your integration: create the new one, update your system, and only then revoke the old one. ## Good practices - Use one key per integration, with the minimum scopes that integration needs. - Store keys in environment variables or a secrets vault, on the server only. - Never use a key in code that runs in a browser or a mobile app. - If a key is exposed, revoke it and create another. ## Where a key does not work An API key only opens the DISKA API endpoints (`https://api.diska.ai/v1`). It gives no access to the backoffice or to the internal API the backoffice uses (`/api/v1`), and it cannot start voice sessions. The backoffice (`app.diska.ai`) authenticates people with the signed-in user's session and uses its own internal API. Those session tokens are short-lived and belong to the product: do not use them in integrations. ## Authentication errors | Code | `detail` | Cause | | ----- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | `401` | `Chave de API em falta. Envie 'Authorization: Bearer dsk_…'.` | The request carried no key. | | `401` | `Chave de API inválida ou revogada.` | The key does not exist, was revoked, or does not start with `dsk_` (for example, a backoffice session token). | | `401` | `Chave de API expirada.` | The key's expiry date has passed. | | `403` | `Organização suspensa.` | The key's organization is suspended. | | `403` | `A chave não tem o âmbito '…'.` | The key has scopes and none of them covers this endpoint. | # Webhooks A webhook is a `POST` request Diska makes to a URL of yours when a call ends, carrying the transcript and the result of post-call processing. Your system receives the data without having to keep asking for it. There are two ways to receive this data: | | Organization webhooks | The agent's **Webhook** action | | ------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- | | Where it is set up | Through the [DISKA API](https://docs.diska.ai/en/api/api-channel), scope `webhooks:manage` | In the agent (prompt mode): **Ações** (actions) → **Depois da conversa** (after the conversation) | | Covers | Every completed call in the organization | That agent's calls | | Signature | Yes — HMAC-SHA256 with the endpoint's secret | No | | Retries | Up to 3 attempts | A single attempt | | Testing | `POST /v1/webhook-endpoints/{id}/test` | Make a call | For new integrations, use **organization webhooks**: they are signed, report their delivery status and are managed through the API. Each agent can also have its own signed webhooks, including one that receives the call **before** the agent answers: see [Agent webhooks](https://docs.diska.ai/en/telephony/webhooks). ## Organization webhooks ### Register an endpoint ```bash curl -X POST https://api.diska.ai/v1/webhook-endpoints \ -H "Authorization: Bearer dsk_…" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-system.com/hooks/diska", "description": "CRM — production", "events": ["call.completed"] }' ``` `201` response: ```json { "endpoint": { "id": "…", "url": "https://your-system.com/hooks/diska", "description": "CRM — production", "events": ["call.completed"], "active": true, "disabled_reason": null, "failure_count": 0, "last_delivery_at": null, "last_delivery_status": null, "secret_preview": "dskw_AbC…wXyZ", "created_at": "…" }, "secret": "dskw_…" } ``` The `secret` (starts with `dskw_`) is used to verify the signature and **is only shown in this response**. Store it with your receiver's configuration. If you lose it, delete the endpoint and register it again. URL and event rules: - The URL must be a full `https://` address with a domain (12 to 2000 characters). Private or internal addresses are refused. - `events` is optional; it defaults to `["call.completed"]`. It must contain at least one event. - Each organization can have up to **10** endpoints. ### Events | Event | When it is sent | | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `call.completed` | A call ends with status `completed` and post-call processing (extractions, evaluations, post-call SMS and actions) finishes. Calls that failed, were cancelled or were abandoned do **not** produce this event. | | `booking.created` | Accepted as a subscription, but **the platform does not send this event yet**. Do not rely on it. | | `ping` | Only sent when you call the test endpoint. Cannot be subscribed to. | `call.completed` is also sent for answered [outbound calls](https://docs.diska.ai/en/api/reference/outbound-calls) and [campaign](https://docs.diska.ai/en/api/reference/campaigns) calls, and for [chat](https://docs.diska.ai/en/api/reference/chats) conversations when they end (channel `web_chat`). ### `call.completed` payload The body is JSON (UTF-8). Example: ```json { "event": "call.completed", "call_id": "8d0c6a3e-…", "session_id": "…", "organization_id": "…", "agent_id": "…", "ended_at": "2026-10-23T14:05:12.345678+00:00", "caller_contact": "+244923000000", "extracted_data": { "nome": "Ana Silva" }, "evaluations": [], "sentiment": "positive", "post_call_sms": [], "custom_actions": [], "executed_actions": [], "transcript": [ { "role": "assistant", "content": "Bom dia, fala com a assistente da …" }, { "role": "user", "content": "Bom dia, queria marcar uma consulta." } ] } ``` | Field | Description | | ----------------------------- | ---------------------------------------------------------------------------------------------------------- | | `call_id` | The call's identifier. Use it with `GET /v1/calls/{call_id}` to get the full detail. | | `session_id` | The voice session's identifier (shown as `external_ref` in DISKA API calls). | | `agent_id`, `organization_id` | The agent that handled the call, and the organization. | | `ended_at` | End date and time (ISO 8601). | | `caller_contact` | The caller's contact, when known. | | `extracted_data` | Values from the agent's [information extractors](https://docs.diska.ai/en/actions/information-extractors). | | `evaluations` | Results of the [custom evaluations](https://docs.diska.ai/en/actions/custom-evaluations). | | `sentiment` | `positive`, `neutral`, `negative`, or `null` when it could not be classified. | | `post_call_sms` | Result of the [post-call SMS](https://docs.diska.ai/en/actions/post-call-sms). | | `custom_actions` | Result of the [custom actions](https://docs.diska.ai/en/actions/custom-actions) that run after the call. | | `executed_actions` | Actions executed during and after the call. | | `transcript` | The conversation transcript, turn by turn. | On an agent with [Redact personal data](https://docs.diska.ai/en/guides/redact-personal-data) on, `transcript`, `extracted_data`, `evaluations`, `post_call_sms`, `custom_actions` and `executed_actions` arrive with tags such as `[NOME]` and `[TELEFONE]` instead of the personal data. `caller_contact` keeps the call's number. The payload may gain new fields; your receiver should ignore the ones it does not know. If a call has no stored post-call result, the event carries only `event`, `call_id`, `session_id`, `organization_id`, `agent_id`, `ended_at`, `caller_contact` and an empty `transcript`. ### Headers ```text Content-Type: application/json User-Agent: Diska-Webhooks/1.0 X-Diska-Event: call.completed X-Diska-Delivery: X-Diska-Timestamp: X-Diska-Signature: sha256= ``` `X-Diska-Delivery` stays the same across retries of the same delivery: use it to avoid processing the same event twice. ### Verify the signature The signature is the hex HMAC-SHA256 of the text `{X-Diska-Timestamp}.{body}` using the endpoint's secret. Compute it over the **raw body**, exactly as received — not over JSON you parsed and serialized again. ::code-group ```python [Python] import hashlib import hmac import time def is_valid(secret: str, timestamp: str, body: bytes, signature: str) -> bool: if abs(time.time() - int(timestamp)) > 300: # reject requests older than 5 minutes return False expected = hmac.new( secret.encode(), f"{timestamp}.".encode() + body, hashlib.sha256 ).hexdigest() return hmac.compare_digest(f"sha256={expected}", signature) ``` ```js [Node.js] import crypto from 'node:crypto' export function isValid(secret, timestamp, rawBody, signature) { if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false const expected = 'sha256=' + crypto .createHmac('sha256', secret) .update(`${timestamp}.`) .update(rawBody) // Buffer with the raw body .digest('hex') const a = Buffer.from(expected) const b = Buffer.from(signature || '') return a.length === b.length && crypto.timingSafeEqual(a, b) } ``` ```php [PHP] 300) { return false; } $expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret); return hash_equals($expected, $signature); } // In the receiver: the raw body comes from php://input. $rawBody = file_get_contents('php://input'); $valid = diska_signature_is_valid( getenv('DISKA_WEBHOOK_SECRET'), $_SERVER['HTTP_X_DISKA_TIMESTAMP'] ?? '', $rawBody, $_SERVER['HTTP_X_DISKA_SIGNATURE'] ?? '' ); if (!$valid) { http_response_code(401); exit; } ``` :: The 5-minute window is a recommendation, to stop an old request from being replayed by a third party. ### Responding and retries - Respond with a `2xx` code within 10 seconds. Ideally, put the event on a queue and process it later. - Any other response counts as a failure. Redirects (`3xx`) are not followed and also count as failures. - A failed delivery is retried up to 3 attempts in total, a few seconds apart. `4xx` responses (except `408` and `429`) are not retried. For some calls Diska makes a single attempt. - After that there is no re-sending. Delivery is best-effort: for reconciliation, `GET /v1/calls` is the source of truth. ### Automatic deactivation After **20 consecutive failed deliveries**, the endpoint is deactivated: `active` becomes `false` and `disabled_reason` explains why. A successful delivery resets the counter to zero. Once your receiver is fixed, reactivate the endpoint: ```bash curl -X PATCH https://api.diska.ai/v1/webhook-endpoints/ \ -H "Authorization: Bearer dsk_…" \ -H "Content-Type: application/json" \ -d '{ "active": true }' ``` Reactivating resets `failure_count` to zero and clears `disabled_reason`. To pause deliveries, send `{ "active": false }`. ### Test your receiver ```bash curl -X POST https://api.diska.ai/v1/webhook-endpoints//test \ -H "Authorization: Bearer dsk_…" ``` Diska sends a signed `ping` event to your URL, with the same headers and retry rules: ```json { "event": "ping", "organization_id": "…", "endpoint_id": "…" } ``` The response tells you how it went: `status` (`delivered`, `failed` or `blocked`), `attempts`, `http_status` and, on failure, `error`. The test works even when the endpoint is deactivated, and a failed test does not count towards automatic deactivation. ### Monitor deliveries `GET /v1/webhook-endpoints` shows, for each endpoint, `last_delivery_at`, `last_delivery_status` (for example `delivered (200)` or `failed (HTTP 500)`) and `failure_count`. The full reference of the management endpoints is in [Endpoints](https://docs.diska.ai/en/api/endpoints#webhooks). ## The agent's Webhook action In a prompt-mode agent you can send the data of each of that agent's calls to a URL, without using the DISKA API: 1. Open the agent and click **Ações** (actions). 2. Under **Depois da conversa** (after the conversation), click **Adicionar** (add) and choose **Webhook** ("Enviar os dados da chamada para um URL." — send the call data to a URL). 3. Enter the URL. It must use HTTPS and have a valid domain. 4. Publish the agent: published calls use the actions of the published version. When post-call processing of each of that agent's calls finishes, Diska makes a JSON `POST` to that URL with the same content as the `call.completed` event, except `call_id` (use `session_id`, which matches `external_ref` in DISKA API calls). Differences from organization webhooks: - The request is **not signed** and carries no `X-Diska-…` headers. Use a hard-to-guess URL and treat the content as unverified. - **A single attempt** is made, with a 20-second limit; there are no retries and no automatic deactivation. - It does not depend on the call's final status: it can also be sent for calls that failed or were cancelled (not for abandoned ones). - If the agent has several Webhook actions, only the first one with a valid URL is used. ## The agent's webhooks: Inbound and Data In the **Telefone** (phone) tab of each agent's **Definições de publicação** (publish settings) you can set two webhooks for that agent, signed with the agent's secret: - **Inbound Webhook**: receives each inbound call before the agent speaks. Its answer can give the agent facts about the caller (name, plan, balance…). - **Data Webhook**: receives the data of each of the agent's completed calls — the same content as `call.completed`, plus the `call` and `metadata` fields. See [Agent webhooks](https://docs.diska.ai/en/telephony/webhooks). # Endpoints ::callout{type="tip"} Every endpoint also has its own page in the [API reference](https://docs.diska.ai/en/api/reference) , with the full schema, examples in cURL, Python, JavaScript and PHP, and **Try it** . :: Every endpoint below belongs to the [DISKA API](https://docs.diska.ai/en/api/api-channel), at `https://api.diska.ai/v1`, and requires an [API key](https://docs.diska.ai/en/api/authentication) in the `Authorization: Bearer dsk_…` header (or `X-API-Key`). Errors shared by all of them — `401`, `403`, format `422`, `429`, `5xx` — are described under [Errors](https://docs.diska.ai/en/api/api-channel#errors); this page lists only the errors specific to each endpoint. ## Summary | Method | Path | Scope | | ------ | ------------------------------------------------------- | -------------------- | | GET | `/v1/me` | — | | GET | `/v1/agents` | `agents:read` | | GET | `/v1/agents/{agent_id}` | `agents:read` | | POST | `/v1/agents` | `agents:write` | | POST | `/v1/agents/{agent_id}/publish` | `agents:write` | | GET | `/v1/calls` | `calls:read` | | GET | `/v1/calls/{call_id}` | `calls:read` | | GET | `/v1/analytics/overview` | `analytics:read` | | GET | `/v1/phone-numbers` | `phone-numbers:read` | | GET | `/v1/knowledge-bases` | `knowledge:read` | | POST | `/v1/knowledge-bases` | `knowledge:write` | | POST | `/v1/knowledge-bases/{knowledge_base_id}/documents` | `knowledge:write` | | POST | `/v1/knowledge-bases/{knowledge_base_id}/documents/url` | `knowledge:write` | | POST | `/v1/knowledge-bases/{knowledge_base_id}/documents/pdf` | `knowledge:write` | | GET | `/v1/webhook-endpoints` | `webhooks:manage` | | POST | `/v1/webhook-endpoints` | `webhooks:manage` | | PATCH | `/v1/webhook-endpoints/{endpoint_id}` | `webhooks:manage` | | DELETE | `/v1/webhook-endpoints/{endpoint_id}` | `webhooks:manage` | | POST | `/v1/webhook-endpoints/{endpoint_id}/test` | `webhooks:manage` | | GET | `/v1/openapi.json` | No authentication | ## Identity ### `GET /v1/me` Returns the organization and key behind the token. Needs no scope — use it to check that the key works. `200` response: `organization` (`id`, `name`, `slug`) and `key` (`id`, `name`, `key_preview`, `scopes`, `expires_at`, `created_at`, `last_used_at`). `scopes: []` means full access. Example in [DISKA API](https://docs.diska.ai/en/api/api-channel#first-request). ## Agents ### The agent object | Field | Description | | ----------------------------- | --------------------------------------------------------------------------- | | `id` | The agent's identifier. | | `name`, `slug`, `description` | Name, readable identifier and description (may be `null`). | | `status` | `draft`, `active`, `inactive` or `archived`. A published agent is `active`. | | `agent_type` | `inbound`, `outbound`, `voice_widget` or `chat`. | | `editing_mode` | `prompt` or `flow` (Flow Builder). Cannot change after creation. | | `version` | The agent's version number. | | `phone_number` | The number assigned to the agent, or `null`. | | `public_channel_enabled` | `true` when the agent's public link is active. | | `created_at`, `updated_at` | Creation and last-change dates. | The agent's internal configuration (prompt, flows, voice, actions) is not exposed. ### `GET /v1/agents` Lists the organization's agents, most recently changed first. | Parameter | Description | | ------------ | ----------------------------------------------------------------------------------------------- | | `agent_type` | `inbound`, `outbound`, `voice_widget` or `chat`. | | `status` | `draft`, `active`, `inactive` or `archived`. Without this filter, archived agents are left out. | | `search` | Text contained in the name (up to 200 characters). | `200` response: `{ "items": [ , … ] }`. ### `GET /v1/agents/{agent_id}` Returns one agent. `404` with `Agente não encontrado.` ("agent not found") if it does not exist in the organization. ### `POST /v1/agents` Creates an agent. The agent starts as a draft (`status: draft`); publish it to make it available on the channels. | Field | Required | Description | | -------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `name` | No | Up to 120 characters. Default: `Novo agente`, or the template's name. | | `agent_type` | No | `inbound`, `outbound`, `voice_widget` or `chat`. Default: `inbound`, or the template's type. | | `editing_mode` | No | `prompt` or `flow`. Default: `prompt` for a blank agent, `flow` from a template. | | `template_id` | No | Identifier of a Diska agent template (up to 64 characters). Without it, a blank agent is created. The DISKA API does not list templates. | ```bash curl -X POST https://api.diska.ai/v1/agents \ -H "Authorization: Bearer dsk_…" \ -H "Content-Type: application/json" \ -d '{ "name": "Reception", "agent_type": "inbound", "editing_mode": "prompt" }' ``` `201` response: the created agent. Errors: `404` with `Modelo não encontrado.` ("template not found") when the `template_id` does not exist; `422` if the template cannot be installed. ### `POST /v1/agents/{agent_id}/publish` Publishes the agent's draft as a new version and makes the agent `active`. For flow agents it also publishes the main flow and the subflows it uses. If nothing changed since the last publish, no new version is created. Optional body: | Field | Description | | ------- | -------------------------------------------------------- | | `label` | Version name, up to 120 characters. Default: `Versão N`. | ```bash curl -X POST https://api.diska.ai/v1/agents//publish \ -H "Authorization: Bearer dsk_…" \ -H "Content-Type: application/json" \ -d '{ "label": "December opening hours" }' ``` `200` response: the updated agent. Errors: | Code | When | | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `404` | `Agente não encontrado.` | | `409` | `O agente está arquivado. Restaure-o antes de publicar.` (the agent is archived; restore it before publishing) | | `422` | The agent cannot be published — for example `O agente precisa de instruções (prompt) antes de ser publicado.` (the agent needs a prompt) or a flow validation error. | ## Calls ### `GET /v1/calls` Lists the organization's calls, newest first. See [pagination](https://docs.diska.ai/en/api/api-channel#pagination). | Parameter | Description | | ---------- | ---------------------------------------------------------------------------------------------------------------------------- | | `agent_id` | Only calls handled by this agent. | | `status` | `created`, `active`, `completed`, `failed`, `cancelled` or `abandoned`. | | `channel` | `browser_demo` (web call), `phone`, `whatsapp` or `web_chat`. | | `search` | Text in the identifier, `external_ref`, or the caller's name or contact (up to 200 characters). Not available with `cursor`. | | `limit` | 1–200, default 50. | | `offset` | Offset mode: how many calls to skip (default 0). | | `cursor` | Cursor mode: `start` for the first page, then the `next_cursor` you received. | `200` response: ```json { "items": [ { "id": "…", "agent_name": "Reception", "channel": "phone", "status": "completed", "…": "…" } ], "limit": 50, "total": 1234, "offset": 0, "next_cursor": null } ``` In offset mode, `total` and `offset` are filled in and `next_cursor` is `null`. In cursor mode, `total` and `offset` are `null` and `next_cursor` points to the next page (or is `null` at the end). Each call in the list has: | Field | Description | | -------------------------------------------- | ----------------------------------------------------------------------- | | `id` | The call's identifier (the `call_id` in webhooks). | | `external_ref` | The voice session's identifier (the `session_id` in webhooks). | | `agent_id`, `agent_name` | The agent that handled the call. | | `channel` | `browser_demo`, `phone`, `whatsapp` or `web_chat`. | | `direction` | `inbound`, `outbound`, or `null` for web calls. | | `status` | `created`, `active`, `completed`, `failed`, `cancelled` or `abandoned`. | | `caller_name`, `caller_contact` | The caller's name and contact, when known. | | `started_at`, `ended_at`, `duration_seconds` | Start, end and duration in seconds. | | `end_reason` | Why the call ended. | | `summary` | Call summary, when generated. | | `is_simulation` | `true` when `channel` is `browser_demo`. | | `labels` | The call's labels. | | `has_post_call` | `true` when a post-call result exists. | | `executed_actions_count` | Number of executed actions. | ### `GET /v1/calls/{call_id}` Returns one call with every list field plus: | Field | Description | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `organization_id` | The call's organization. | | `messages` | Transcript: a list of `{ id, sequence, role, content, created_at }`, in order. | | `tool_calls` | Executed actions: `{ id, tool_name, status, input, output, error_message, latency_ms, called_at, completed_at }`. | | `post_call` | Post-call result (the content of the `call.completed` [webhook](https://docs.diska.ai/en/api/webhooks), without `call_id`), or `null`. | | `has_recording` | `true` when a recording is available. | | `recording_state` | `disabled`, `available`, `failed`, `expired` or `deleted`. | | `metadata` | The call's technical metadata. Its content is not stable — do not rely on it. | The recording audio is not returned by the DISKA API. `404` with `Chamada não encontrada.` ("call not found") if the call does not exist in the organization. ## Analytics ### `GET /v1/analytics/overview` The same summary as the backoffice's **Análises** (analytics) page, for a window that ends at the time of the request, compared with the previous window of the same size. | Parameter | Description | | ------------ | ------------------------------------------------------------------------------------- | | `period` | `daily` (last 24 hours), `weekly` (last 7 days, default) or `monthly` (last 30 days). | | `agent_id` | Only this agent. | | `agent_type` | `all` (default), `inbound` or `outbound`. | `200` response: | Field | Description | | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `period`, `start`, `end` | The analysed window. | | `totals` | `calls`, `minutes` and `avg_duration_seconds`, each with `value`, `previous` and `change_pct` (`null` when the previous window has no data). | | `daily` | Per day (UTC): `date`, `calls`, `minutes`, `completed`, `failed`, `cancelled`. | | `by_status`, `by_end_reason` | Breakdown: `key`, `label`, `count`, `pct`. | | `sentiment` | Share of positive calls (`positive_pct`), `classified`, `total`, `breakdown` and daily trend. | | `agents` | Per-agent performance: calls, minutes, completions and changes. | | `actions` | Usage of each executed action, with a daily trend. | | `failed_calls` | Recent failed calls: `id`, `started_at`, `contact`, `agent_name`, `end_reason`. | ## Numbers ### `GET /v1/phone-numbers` The organization's phone number inventory. | Parameter | Description | | ------------- | ---------------------------------------------------------------------- | | `search` | Text in the number, the name or the SIP domain (up to 200 characters). | | `number_type` | `purchased` (DISKA numbers) or `imported` (your own numbers over SIP). | `200` response: `{ "items": [ … ], "total": N }`. Each number includes `id`, `e164`, `friendly_name`, `number_type`, `status` (`active` or `inactive`), `country_code`, `capabilities` (`calls`, `sms`), `agent_id` and `agents` (agents using the number: `id`, `name`, `status`). Numbers imported over SIP also carry the trunk fields (`sip_domain`, `sip_username`, `sip_transport`, `sip_status`…); the SIP password is never returned, only `sip_password_configured`. ## Knowledge ### The knowledge base object `id`, `organization_id`, `name`, `instruction` (when the agent should use this base), `description`, `document_count`, `assigned_agent_count`, `created_at`, `updated_at`. ### The document object `id`, `organization_id`, `knowledge_base_id`, `name`, `source_type` (`manual`, `pdf` or `url`), `status`, `extraction_status`, `indexing_status` (`indexed` once indexing has finished), `content_text`, `original_url`, `mime_type`, `size_bytes`, `error_message`, `has_file`, `created_at`, `updated_at`, among others. ### `GET /v1/knowledge-bases` Lists the knowledge bases. Optional `search` parameter: text contained in the name or the instruction. `200` response: `{ "items": [ , … ] }`. ### `POST /v1/knowledge-bases` | Field | Required | Description | | ------------- | -------- | ------------------------------------------------------------------ | | `name` | Yes | 1 to 200 characters. | | `instruction` | Yes | When and how the agent should use this base. 1 to 4000 characters. | | `description` | No | Up to 2000 characters. | `201` response: the created base. For an agent to use the base, assign it in the backoffice. ### `POST /v1/knowledge-bases/{knowledge_base_id}/documents` Adds a text document. Indexing starts right away. | Field | Required | Description | | --------- | -------- | ----------------------------------- | | `name` | Yes | 1 to 200 characters. | | `content` | Yes | The text, up to 200,000 characters. | ```bash curl -X POST https://api.diska.ai/v1/knowledge-bases//documents \ -H "Authorization: Bearer dsk_…" \ -H "Content-Type: application/json" \ -d '{ "name": "Opening hours", "content": "We are open Monday to Friday, 8am to 5pm." }' ``` ### `POST /v1/knowledge-bases/{knowledge_base_id}/documents/url` Imports the text of a public web page. | Field | Required | Description | | ------ | -------- | -------------------------------------------------------------- | | `name` | Yes | 1 to 200 characters. | | `url` | Yes | A full `http://` or `https://` address, up to 2000 characters. | The page must respond within 15 seconds, be at most 2 MB and be HTML, text or JSON. Private or internal addresses are refused, and at most 3 redirects are followed. ### `POST /v1/knowledge-bases/{knowledge_base_id}/documents/pdf` Uploads a PDF as `multipart/form-data`, in the `file` field (up to 25 MB). ```bash curl -X POST https://api.diska.ai/v1/knowledge-bases//documents/pdf \ -H "Authorization: Bearer dsk_…" \ -F "file=@price-list.pdf;type=application/pdf" ``` ### Document responses and errors The three document endpoints respond `201` with the created document. Specific errors: | Code | When | | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | Content refused — for example `Ficheiro vazio.` (empty file), `PDF demasiado grande (máx. 25 MB).` (PDF too large), `Apenas ficheiros PDF são aceites.` (only PDFs accepted), `O ficheiro não parece ser um PDF válido.` (not a valid PDF), `Tempo esgotado ao obter a página.` (timed out fetching the page), `A página não devolveu texto legível.` (no readable text) or a URL blocked for security. | | `404` | `Base de conhecimento não encontrada.` ("knowledge base not found") | ## Webhooks How deliveries, events and signatures work: see [Webhooks](https://docs.diska.ai/en/api/webhooks). ### The endpoint object | Field | Description | | ------------------------------------------ | ---------------------------------------------------------- | | `id` | The endpoint's identifier. | | `url`, `description` | Destination and description. | | `events` | Subscribed events. | | `active` | `false` when it was deactivated (by you or automatically). | | `disabled_reason` | Why it was automatically deactivated, or `null`. | | `failure_count` | Consecutive failed deliveries. | | `last_delivery_at`, `last_delivery_status` | Last delivery and its result. | | `secret_preview` | Start and end of the secret, to identify it. | | `created_at` | Creation date. | ### `GET /v1/webhook-endpoints` Lists the organization's endpoints (active and inactive), newest first. `200` response: a list of endpoints. ### `POST /v1/webhook-endpoints` | Field | Required | Description | | ------------- | -------- | ----------------------------------------------------------------------------------- | | `url` | Yes | Full `https://` URL, 12 to 2000 characters. | | `description` | No | Up to 500 characters. | | `events` | No | List of events (`call.completed`, `booking.created`). Default `["call.completed"]`. | `201` response: `{ "endpoint": , "secret": "dskw_…" }`. The `secret` appears only in this response. `400` errors: `URL inválido: use um endpoint https:// completo.` (invalid URL), `URL bloqueado por segurança: …` (URL blocked for security), `Subscreva pelo menos um evento.` (subscribe to at least one event), `Eventos desconhecidos: …` (unknown events), `Limite de 10 endpoints por organização atingido.` (10-endpoint limit reached). ### `PATCH /v1/webhook-endpoints/{endpoint_id}` Changes only the fields you send: | Field | Description | | ------------- | -------------------------------------------------------------------------------------- | | `url` | New `https://` URL. | | `description` | New description; `""` clears it. | | `events` | New list of events (at least one). | | `active` | `true` reactivates the endpoint and resets `failure_count`; `false` pauses deliveries. | `200` response: the updated endpoint. Errors: `404` with `Endpoint não encontrado.` ("endpoint not found"); `400` with the same messages as creation. The secret does not change. ### `DELETE /v1/webhook-endpoints/{endpoint_id}` Deletes the endpoint. `200` response: the deleted endpoint. `404` with `Endpoint não encontrado.` ### `POST /v1/webhook-endpoints/{endpoint_id}/test` Sends a signed `ping` event to the endpoint's URL, even if it is deactivated. `200` response: ```json { "status": "delivered", "attempts": 1, "http_status": 200 } ``` `status` can be `delivered`, `failed` (with `error`) or `blocked` (the URL now points to an address that is not allowed). `404` with `Endpoint não encontrado.` ## The backoffice's internal API The backoffice uses other endpoints, at `https://api.diska.ai/api/v1`, authenticated with the signed-in person's session. They are not part of the DISKA API: they do not accept API keys, are not documented and can change without notice. If you need something only the backoffice does, [talk to us](mailto\:hello@diska.ai). # Realtime Real-time voice conversations happen on Diska's channels. The [DISKA API](https://docs.diska.ai/en/api/api-channel) does not open or control voice sessions, and API keys cannot be used for that: use it to read call results, and receive them by [webhook](https://docs.diska.ai/en/api/webhooks) when each call ends. ## Voice channels | Channel | What for | Where to set it up | | --------------- | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- | | Phone | Answer calls on a DISKA number or on a number of your own connected over SIP. | [Telephony](https://docs.diska.ai/en/telephony) | | Public link | A page with a microphone where anyone can talk to the agent's published version in the browser, without a Diska account. | [Publish an agent](https://docs.diska.ai/en/guides/publish-agent) | | Widget | The call button on your website (script or iframe). | [Embed the widget](https://docs.diska.ai/en/guides/embed-widget) | | Backoffice test | Test calls in the browser or to your mobile phone, from the agent. | [Test an agent](https://docs.diska.ai/en/guides/test-agent) | Each agent's number, public link and widget are set up from the agent's **Publicação** (publishing) button, in the **Definições de publicação** (publish settings) window. ## The public link's session endpoint When an agent's **Link público** (public link) is active, the **Link público** tab of **Definições de publicação** shows, besides the **Endereço para partilhar** (address to share) and the **Token público** (public token), the **Endpoint de sessão (API)** (session endpoint): ```text https://api.diska.ai/api/v1/public/agents//voice-session ``` A `POST` to this address creates an anonymous voice session on the agent's published version. It is what Diska's web player — the public link page and the widget — uses to start each call; the player takes care of the rest (audio, transcription and voice). - It only works while the public link is active and the agent has a published version; otherwise it returns `404`. It always runs the published version, never the draft. - **Gerar novo link** (generate new link) replaces the token: the old address stops working immediately. **Desativar** (disable) blocks new calls and keeps the token so you can re-enable it. - There are session limits per IP address and per link. Above them, the response is `429` with `Demasiadas chamadas de momento. Tente novamente dentro de alguns minutos.` ("too many calls right now, try again in a few minutes"). ::callout{type="warning"} What happens after that `POST` — the audio connection and the requests the player makes during the call — is not a public contract: it depends on the voice engine and can change without notice. To put the agent on your website or app, use the [widget](https://docs.diska.ai/en/guides/embed-widget) or the public link address. :: For **Voice Widget** agents, the **WebSocket** tab of **Definições de publicação** shows the same endpoint, as **Canal público** (public channel). Under the **Sessões em tempo real** (real-time sessions) heading, it explains that this is the request that opens the voice conversation. There is no public WebSocket channel for following the session state, transcripts or agent events during a call. ## Following calls There is no public event stream during a call. To get call data: - **`call.completed` webhook** — when the call ends, Diska sends the transcript and post-call result to your system. See [Webhooks](https://docs.diska.ai/en/api/webhooks). - **`GET /v1/calls/{call_id}`** — the call's detail, whenever you need it. See [Endpoints](https://docs.diska.ai/en/api/endpoints#calls). - **Históricos** (history) in the backoffice — see [Calls](https://docs.diska.ai/en/history/calls). ## Platform voice endpoints The endpoints under `https://api.diska.ai/api/v1/realtime/…` serve Diska's own applications (the test panel, the widget and the public link). They are authenticated with the backoffice session or with credentials specific to each call, do not accept API keys and are not part of the public API. Do not build integrations on them. # Get the key and organization ```http GET https://api.diska.ai/v1/me ``` **Scope:** none — any valid key It needs no scope: use it to check that the key works. `scopes: []` means full access. ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/me" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/me", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/me', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: [] body-type: none locale: en method: GET path: /v1/me --- :: ## Response `200` | Field | Type | Description | | ------------------- | -------------- | ----------------------------------------------------------- | | `organization` | object | The key's organization. | | `organization.id` | string | Organization ID. | | `organization.name` | string | Organization name. | | `organization.slug` | string | Readable organization identifier. | | `key` | object | The key used in the request. | | `key.id` | string | Key ID. | | `key.name` | string | Name given to the key. | | `key.key_preview` | string | Start and end of the key, to identify it (`dsk_a1b2…F5A4`). | | `key.scopes` | array | The key's scopes. Empty list = full access. | | `key.expires_at` | string \| null | Expiry date, or `null` if it does not expire. | | `key.created_at` | string \| null | Creation date (ISO 8601). | | `key.last_used_at` | string \| null | Last use (updated at most every 5 minutes). | ```json { "organization": { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "A Minha Empresa", "slug": "recepcao" }, "key": { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Integração CRM", "key_preview": "dsk_a1b2…F5A4", "scopes": [ "agents:read", "calls:read" ], "expires_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "last_used_at": "2026-10-25T18:40:00Z" } } ``` ## Errors This endpoint has no errors of its own. Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Identity | Method | Endpoint | Description | Scope | | ------ | ------------------------------------------------------------------------ | ---------------------------- | ----- | | `GET` | [`/v1/me`](https://docs.diska.ai/en/api/reference/identity/get-identity) | Get the key and organization | — | # List agents ```http GET https://api.diska.ai/v1/agents ``` **Scope:** `agents:read` Without the `status` filter, archived agents are left out. The list is not paginated. ## Parameters ### Query string | Name | Type | Required | Description | | ------------ | -------------- | -------- | -------------------------------------------------------------------------------------------------------------------- | | `agent_type` | string \| null | No | Only agents of this type. One of: `inbound`, `outbound`, `voice_widget`, `chat`. | | `status` | string \| null | No | Only agents in this state. Use `archived` to see archived agents. One of: `draft`, `active`, `inactive`, `archived`. | | `search` | string \| null | No | Text contained in the name. Up to 200 characters. | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/agents" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/agents", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/agents', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: agent_type in: query options: - inbound - outbound - voice_widget - chat - name: status in: query options: - draft - active - inactive - archived - name: search in: query body-type: none locale: en method: GET path: /v1/agents --- :: ## Response `200` | Field | Type | Description | | -------------------------------- | -------------- | ---------------------------------------------------------------------------------------- | | `items` | array | The agents. | | `items[].id` | string | Agent ID. | | `items[].name` | string | Agent name. | | `items[].slug` | string | Readable agent identifier. | | `items[].description` | string \| null | Description, or `null`. | | `items[].status` | string | `draft`, `active`, `inactive` or `archived`. A published agent is `active`. | | `items[].agent_type` | string | `inbound`, `outbound`, `voice_widget` or `chat`. | | `items[].editing_mode` | string | `prompt` or `flow` (Flow Builder). It does not change after creation. Default: `prompt`. | | `items[].version` | integer | Agent version number. Default: `1`. | | `items[].phone_number` | string \| null | Number assigned to the agent, or `null`. | | `items[].public_channel_enabled` | boolean | `true` when the agent's public link is on. Default: `false`. | | `items[].created_at` | string | Creation date (ISO 8601). | | `items[].updated_at` | string | Last change date (ISO 8601). | ```json { "items": [ { "id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "name": "Recepção", "slug": "recepcao", "description": "Atende as chamadas da recepção.", "status": "active", "agent_type": "inbound", "editing_mode": "prompt", "version": 3, "phone_number": "+244900000000", "public_channel_enabled": false, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z" } ] } ``` ## Errors This endpoint has no errors of its own. Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Get an agent ```http GET https://api.diska.ai/v1/agents/{agent_id} ``` **Scope:** `agents:read` It is the draft — what the next publish freezes. `has_unpublished_changes` says whether it differs from the published version. ## Parameters ### Path | Name | Type | Required | Description | | ---------- | ------ | -------- | --------------- | | `agent_id` | string | Yes | The agent's ID. | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/agents/" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/agents/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/agents/', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: agent_id in: path required: true body-type: none locale: en method: GET path: /v1/agents/{agent_id} --- :: ## Response `200` | Field | Type | Description | | ---------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------- | | `id` | string | Agent ID. | | `name` | string | Agent name. | | `slug` | string | Readable agent identifier. | | `description` | string \| null | Description, or `null`. | | `status` | string | `draft`, `active`, `inactive` or `archived`. A published agent is `active`. | | `agent_type` | string | `inbound`, `outbound`, `voice_widget` or `chat`. | | `editing_mode` | string | `prompt` or `flow` (Flow Builder). It does not change after creation. Default: `prompt`. | | `version` | integer | Agent version number. Default: `1`. | | `phone_number` | string \| null | Number assigned to the agent, or `null`. | | `public_channel_enabled` | boolean | `true` when the agent's public link is on. Default: `false`. | | `created_at` | string | Creation date (ISO 8601). | | `updated_at` | string | Last change date (ISO 8601). | | `configuration` | object | The editable configuration (the draft). | | `configuration.prompt` | string \| null | The agent's instructions (prompt-mode agents only; `null` for Flow Builder agents). | | `configuration.greeting` | object | How the conversation opens. | | `configuration.greeting.mode` | string | `agent_first` (the agent speaks first) or `human_first` (it waits for the person). Default: `agent_first`. | | `configuration.greeting.message` | string \| null | The greeting, or `null`. | | `configuration.language` | string \| null | Conversation language, for example `pt-PT`. | | `configuration.personality` | string \| null | Personality and tone. | | `configuration.objections` | string \| null | How to handle objections. | | `configuration.knowledge_notes` | string \| null | Knowledge notes written on the agent. | | `configuration.knowledge_base_ids` | array | Assigned knowledge bases. | | `has_unpublished_changes` | boolean | `true` when the draft differs from the published version. Default: `false`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "slug": "recepcao", "description": "CRM — produção", "status": "draft", "agent_type": "inbound", "editing_mode": "prompt", "version": 3, "phone_number": "+244900000000", "public_channel_enabled": false, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z", "configuration": { "prompt": "…", "greeting": { "mode": "agent_first", "message": "…" }, "language": "…", "personality": "…", "objections": "…", "knowledge_notes": "…", "knowledge_base_ids": [ "…" ] }, "has_unpublished_changes": false } ``` ## Errors | Code | When | | ----- | ------------------------------------------------------------------------- | | `404` | `Agente não encontrado.` — the agent does not exist in this organization. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Update an agent ```http PATCH https://api.diska.ai/v1/agents/{agent_id} ``` **Scope:** `agents:write` Calls keep using the published version until you [publish](https://docs.diska.ai/en/api/reference/agents/publish-agent). Voice, engine and actions are edited in the backoffice. Flow Builder agents take their text from their flows, so `prompt` is refused. If two changes arrive at once, the last one wins. ## Parameters ### Path | Name | Type | Required | Description | | ---------- | ------ | -------- | --------------- | | `agent_id` | string | Yes | The agent's ID. | ## Request body `application/json` | Field | Type | Required | Description | | -------------------- | -------------- | -------- | ------------------------------------------------------------------- | | `name` | string \| null | No | New name. Up to 120 characters. | | `description` | string \| null | No | New description; `null` clears it. Up to 2000 characters. | | `prompt` | string \| null | No | New instructions (prompt-mode agents only). Up to 60000 characters. | | `greeting` | object \| null | No | Changes the greeting; only the fields sent change. | | `greeting.mode` | string \| null | No | `agent_first` or `human_first`. | | `greeting.message` | string \| null | No | The greeting; `null` clears it. Up to 500 characters. | | `language` | string \| null | No | Language, in the `pt-PT` format. | | `personality` | string \| null | No | Personality and tone; `null` clears it. Up to 10000 characters. | | `objections` | string \| null | No | How to handle objections; `null` clears it. Up to 10000 characters. | | `knowledge_notes` | string \| null | No | Knowledge notes; `null` clears them. Up to 10000 characters. | | `knowledge_base_ids` | array \| null | No | Replaces the assigned bases with the list sent. | ```json { "prompt": "És a recepcionista da Clínica Sol. Marca consultas de segunda a sexta.", "greeting": { "mode": "agent_first", "message": "Clínica Sol, bom dia!" }, "language": "pt-PT" } ``` ## Examples ::code-group ```bash [cURL] curl -X PATCH "https://api.diska.ai/v1/agents/" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"prompt":"És a recepcionista da Clínica Sol. Marca consultas de segunda a sexta.","greeting":{"mode":"agent_first","message":"Clínica Sol, bom dia!"},"language":"pt-PT"}' ``` ```python [Python] import os import requests response = requests.patch( "https://api.diska.ai/v1/agents/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "prompt": "És a recepcionista da Clínica Sol. Marca consultas de segunda a sexta.", "greeting": { "mode": "agent_first", "message": "Clínica Sol, bom dia!", }, "language": "pt-PT", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/agents/', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "prompt": "És a recepcionista da Clínica Sol. Marca consultas de segunda a sexta.", "greeting": { "mode": "agent_first", "message": "Clínica Sol, bom dia!" }, "language": "pt-PT" }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'PATCH', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'prompt' => 'És a recepcionista da Clínica Sol. Marca consultas de segunda a sexta.', 'greeting' => [ 'mode' => 'agent_first', 'message' => 'Clínica Sol, bom dia!', ], 'language' => 'pt-PT', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: agent_id in: path required: true body: > { "prompt": "És a recepcionista da Clínica Sol. Marca consultas de segunda a sexta.", "greeting": { "mode": "agent_first", "message": "Clínica Sol, bom dia!" }, "language": "pt-PT" } body-type: json locale: en method: PATCH path: /v1/agents/{agent_id} --- :: ## Response `200` | Field | Type | Description | | ---------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------- | | `id` | string | Agent ID. | | `name` | string | Agent name. | | `slug` | string | Readable agent identifier. | | `description` | string \| null | Description, or `null`. | | `status` | string | `draft`, `active`, `inactive` or `archived`. A published agent is `active`. | | `agent_type` | string | `inbound`, `outbound`, `voice_widget` or `chat`. | | `editing_mode` | string | `prompt` or `flow` (Flow Builder). It does not change after creation. Default: `prompt`. | | `version` | integer | Agent version number. Default: `1`. | | `phone_number` | string \| null | Number assigned to the agent, or `null`. | | `public_channel_enabled` | boolean | `true` when the agent's public link is on. Default: `false`. | | `created_at` | string | Creation date (ISO 8601). | | `updated_at` | string | Last change date (ISO 8601). | | `configuration` | object | The editable configuration (the draft). | | `configuration.prompt` | string \| null | The agent's instructions (prompt-mode agents only; `null` for Flow Builder agents). | | `configuration.greeting` | object | How the conversation opens. | | `configuration.greeting.mode` | string | `agent_first` (the agent speaks first) or `human_first` (it waits for the person). Default: `agent_first`. | | `configuration.greeting.message` | string \| null | The greeting, or `null`. | | `configuration.language` | string \| null | Conversation language, for example `pt-PT`. | | `configuration.personality` | string \| null | Personality and tone. | | `configuration.objections` | string \| null | How to handle objections. | | `configuration.knowledge_notes` | string \| null | Knowledge notes written on the agent. | | `configuration.knowledge_base_ids` | array | Assigned knowledge bases. | | `has_unpublished_changes` | boolean | `true` when the draft differs from the published version. Default: `false`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "slug": "recepcao", "description": "CRM — produção", "status": "draft", "agent_type": "inbound", "editing_mode": "prompt", "version": 3, "phone_number": "+244900000000", "public_channel_enabled": false, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z", "configuration": { "prompt": "…", "greeting": { "mode": "agent_first", "message": "…" }, "language": "…", "personality": "…", "objections": "…", "knowledge_notes": "…", "knowledge_base_ids": [ "…" ] }, "has_unpublished_changes": false } ``` ## Errors | Code | When | | ----- | ------------------------------------------------------------------------------------------------- | | `404` | `Agente não encontrado.` — the agent does not exist in this organization. | | `404` | `Base de conhecimento não encontrada.` — one of the `knowledge_base_ids` does not exist. | | `409` | The agent is archived, or `prompt` was sent for a Flow Builder agent. | | `422` | An unknown field, a value out of bounds, or `null` in `name`, `prompt`, `greeting` or `language`. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Create an agent ```http POST https://api.diska.ai/v1/agents ``` **Scope:** `agents:write` The agent starts as a draft (`status: draft`): [publish it](https://docs.diska.ai/en/api/reference/agents/publish-agent) to make it available on your channels. The DISKA API does not list templates. ## Request body `application/json` | Field | Type | Required | Description | | -------------- | -------------- | -------- | -------------------------------------------------------------------------------------------------------------- | | `name` | string \| null | No | Agent name. Default: `Novo agente`, or the template's name. Up to 120 characters. | | `agent_type` | string \| null | No | Agent type. Default: `inbound`, or the template's type. One of: `inbound`, `outbound`, `voice_widget`, `chat`. | | `editing_mode` | string \| null | No | Default: `prompt` for a blank agent, `flow` from a template. | | `template_id` | string \| null | No | Diska agent template. Without it, the agent is created blank. Up to 64 characters. | ```json { "name": "Recepção", "agent_type": "inbound", "editing_mode": "prompt" } ``` ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/agents" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name":"Recepção","agent_type":"inbound","editing_mode":"prompt"}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/agents", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "name": "Recepção", "agent_type": "inbound", "editing_mode": "prompt", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/agents', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "name": "Recepção", "agent_type": "inbound", "editing_mode": "prompt" }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'name' => 'Recepção', 'agent_type' => 'inbound', 'editing_mode' => 'prompt', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: [] body: | { "name": "Recepção", "agent_type": "inbound", "editing_mode": "prompt" } body-type: json locale: en method: POST path: /v1/agents --- :: ## Response `201` | Field | Type | Description | | ------------------------ | -------------- | ---------------------------------------------------------------------------------------- | | `id` | string | Agent ID. | | `name` | string | Agent name. | | `slug` | string | Readable agent identifier. | | `description` | string \| null | Description, or `null`. | | `status` | string | `draft`, `active`, `inactive` or `archived`. A published agent is `active`. | | `agent_type` | string | `inbound`, `outbound`, `voice_widget` or `chat`. | | `editing_mode` | string | `prompt` or `flow` (Flow Builder). It does not change after creation. Default: `prompt`. | | `version` | integer | Agent version number. Default: `1`. | | `phone_number` | string \| null | Number assigned to the agent, or `null`. | | `public_channel_enabled` | boolean | `true` when the agent's public link is on. Default: `false`. | | `created_at` | string | Creation date (ISO 8601). | | `updated_at` | string | Last change date (ISO 8601). | ```json { "id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "name": "Recepção", "slug": "recepcao", "description": "Atende as chamadas da recepção.", "status": "active", "agent_type": "inbound", "editing_mode": "prompt", "version": 3, "phone_number": "+244900000000", "public_channel_enabled": false, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z" } ``` ## Errors | Code | When | | ----- | ------------------------------------------------------------ | | `404` | `Modelo não encontrado.` — the `template_id` does not exist. | | `422` | The template could not be installed. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Publish an agent ```http POST https://api.diska.ai/v1/agents/{agent_id}/publish ``` **Scope:** `agents:write` For flow agents it also publishes the main flow and the subflows it uses. If nothing changed since the last publish, no new version is created. The body is optional. ## Parameters ### Path | Name | Type | Required | Description | | ---------- | ------ | -------- | --------------- | | `agent_id` | string | Yes | The agent's ID. | ## Request body `application/json` — The body is optional. | Field | Type | Required | Description | | ------- | -------------- | -------- | -------------------------------------------------------- | | `label` | string \| null | No | Version name. Default: `Versão N`. Up to 120 characters. | ```json { "label": "Horário de Dezembro" } ``` ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/agents//publish" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"label":"Horário de Dezembro"}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/agents//publish", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "label": "Horário de Dezembro", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/agents//publish', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "label": "Horário de Dezembro" }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /publish'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'label' => 'Horário de Dezembro', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: agent_id in: path required: true body: | { "label": "Horário de Dezembro" } body-type: json locale: en method: POST path: /v1/agents/{agent_id}/publish --- :: ## Response `200` | Field | Type | Description | | ------------------------ | -------------- | ---------------------------------------------------------------------------------------- | | `id` | string | Agent ID. | | `name` | string | Agent name. | | `slug` | string | Readable agent identifier. | | `description` | string \| null | Description, or `null`. | | `status` | string | `draft`, `active`, `inactive` or `archived`. A published agent is `active`. | | `agent_type` | string | `inbound`, `outbound`, `voice_widget` or `chat`. | | `editing_mode` | string | `prompt` or `flow` (Flow Builder). It does not change after creation. Default: `prompt`. | | `version` | integer | Agent version number. Default: `1`. | | `phone_number` | string \| null | Number assigned to the agent, or `null`. | | `public_channel_enabled` | boolean | `true` when the agent's public link is on. Default: `false`. | | `created_at` | string | Creation date (ISO 8601). | | `updated_at` | string | Last change date (ISO 8601). | ```json { "id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "name": "Recepção", "slug": "recepcao", "description": "Atende as chamadas da recepção.", "status": "active", "agent_type": "inbound", "editing_mode": "prompt", "version": 3, "phone_number": "+244900000000", "public_channel_enabled": false, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z" } ``` ## Errors | Code | When | | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `404` | `Agente não encontrado.` — the agent does not exist in this organization. | | `409` | `O agente está arquivado. Restaure-o antes de publicar.` (archived: restore it first). | | `422` | The agent cannot be published — for example `O agente precisa de instruções (prompt) antes de ser publicado.` (needs a prompt) or a flow validation error. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Agents The agent's internal configuration (prompt, flows, voice and actions) is not exposed: edit it in the backoffice. | Method | Endpoint | Description | Scope | | ------- | ---------------------------------------------------------------------------------------------- | ---------------- | -------------- | | `GET` | [`/v1/agents`](https://docs.diska.ai/en/api/reference/agents/list-agents) | List agents | `agents:read` | | `GET` | [`/v1/agents/{agent_id}`](https://docs.diska.ai/en/api/reference/agents/get-agent) | Get an agent | `agents:read` | | `PATCH` | [`/v1/agents/{agent_id}`](https://docs.diska.ai/en/api/reference/agents/update-agent) | Update an agent | `agents:write` | | `POST` | [`/v1/agents`](https://docs.diska.ai/en/api/reference/agents/create-agent) | Create an agent | `agents:write` | | `POST` | [`/v1/agents/{agent_id}/publish`](https://docs.diska.ai/en/api/reference/agents/publish-agent) | Publish an agent | `agents:write` | # List calls ```http GET https://api.diska.ai/v1/calls ``` **Scope:** `calls:read` It has two [pagination](https://docs.diska.ai/en/api/api-channel#pagination) modes: **offset** (the default, with `total`) and **cursor** (`cursor=start`, then the `next_cursor` you receive), better for exporting large histories. ## Parameters ### Query string | Name | Type | Required | Description | | ---------- | -------------- | -------- | --------------------------------------------------------------------------------------------------------------- | | `search` | string \| null | No | Text in the ID, `external_ref`, caller name or caller contact. Not allowed with `cursor`. Up to 200 characters. | | `agent_id` | string \| null | No | Only calls of this agent. | | `status` | string \| null | No | Only calls in this state. One of: `created`, `active`, `completed`, `failed`, `cancelled`, `abandoned`. | | `channel` | string \| null | No | Only calls on this channel: `browser_demo` (web call), `phone`, `whatsapp` or `web_chat`. | | `limit` | integer | No | How many calls per page. Between 1 and 200. Default: `50`. | | `offset` | integer | No | Offset mode: how many calls to skip. Minimum 0. Default: `0`. | | `cursor` | string \| null | No | Cursor mode: `start` on the first page, then the `next_cursor` you received. Up to 200 characters. | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/calls?limit=10" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/calls?limit=10", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/calls?limit=10', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: search in: query - name: agent_id in: query - name: status in: query options: - created - active - completed - failed - cancelled - abandoned - name: channel in: query options: - browser_demo - phone - whatsapp - web_chat - name: limit in: query value: "10" - name: offset in: query - name: cursor in: query body-type: none locale: en method: GET path: /v1/calls --- :: ## Response `200` | Field | Type | Description | | -------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------- | | `items` | array | The calls on this page. | | `items[].id` | string | Call ID (the webhooks' `call_id`). | | `items[].external_ref` | string \| null | Voice session ID (the webhooks' `session_id`). | | `items[].agent_id` | string \| null | Agent that answered. | | `items[].agent_name` | string \| null | Name of the agent that answered. | | `items[].channel` | string | `browser_demo` (web call), `phone`, `whatsapp` or `web_chat`. Default: `browser_demo`. | | `items[].direction` | string \| null | `inbound`, `outbound`, or `null` for web calls. | | `items[].status` | string | Call state. One of: `created`, `active`, `completed`, `failed`, `cancelled`, `abandoned`. Default: `created`. | | `items[].caller_name` | string \| null | Caller name, when known. | | `items[].caller_contact` | string \| null | Caller contact, when known. | | `items[].started_at` | string \| null | Call start. | | `items[].ended_at` | string \| null | Call end. | | `items[].duration_seconds` | integer \| null | Duration in seconds. | | `items[].end_reason` | string \| null | Why the call ended. | | `items[].summary` | string \| null | Call summary, when generated. | | `items[].is_simulation` | boolean | `true` for web test calls (`browser_demo`). Default: `true`. | | `items[].labels` | array | Call labels. | | `items[].has_post_call` | boolean | `true` when there is a post-call result. Default: `false`. | | `items[].executed_actions_count` | integer | Number of executed actions. Default: `0`. | | `limit` | integer | Requested page size. | | `total` | integer \| null | Total calls matching the filters (offset mode); `null` in cursor mode. | | `offset` | integer \| null | This page's offset (offset mode); `null` in cursor mode. | | `next_cursor` | string \| null | Next page cursor (cursor mode), or `null` at the end. | ```json { "items": [ { "id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "external_ref": "sess_7f3a9c1e", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "channel": "phone", "direction": "inbound", "status": "completed", "caller_name": "Ana Silva", "caller_contact": "+244900000000", "started_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "duration_seconds": 95, "end_reason": "caller_hangup", "summary": "O cliente pediu o horário de abertura e marcou uma visita para sexta-feira.", "is_simulation": false, "labels": [ "urgente" ], "has_post_call": false, "executed_actions_count": 2 } ], "limit": 50, "total": 1, "offset": 0, "next_cursor": "…" } ``` ## Errors | Code | When | | ----- | -------------------------------------------------------------------- | | `400` | `Cursor inválido.` (invalid cursor), or `search` used with `cursor`. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Get a call ```http GET https://api.diska.ai/v1/calls/{call_id} ``` **Scope:** `calls:read` The recording audio is not returned: listen to it in [History](https://docs.diska.ai/en/history/recordings). ## Parameters ### Path | Name | Type | Required | Description | | --------- | ------ | -------- | ---------------------------------------- | | `call_id` | string | Yes | The call's ID (the webhooks' `call_id`). | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/calls/" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/calls/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/calls/', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: call_id in: path required: true body-type: none locale: en method: GET path: /v1/calls/{call_id} --- :: ## Response `200` | Field | Type | Description | | ---------------------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Call ID (the webhooks' `call_id`). | | `external_ref` | string \| null | Voice session ID (the webhooks' `session_id`). | | `agent_id` | string \| null | Agent that answered. | | `agent_name` | string \| null | Name of the agent that answered. | | `channel` | string | `browser_demo` (web call), `phone`, `whatsapp` or `web_chat`. Default: `browser_demo`. | | `direction` | string \| null | `inbound`, `outbound`, or `null` for web calls. | | `status` | string | Call state. One of: `created`, `active`, `completed`, `failed`, `cancelled`, `abandoned`. Default: `created`. | | `caller_name` | string \| null | Caller name, when known. | | `caller_contact` | string \| null | Caller contact, when known. | | `started_at` | string \| null | Call start. | | `ended_at` | string \| null | Call end. | | `duration_seconds` | integer \| null | Duration in seconds. | | `end_reason` | string \| null | Why the call ended. | | `summary` | string \| null | Call summary, when generated. | | `is_simulation` | boolean | `true` for web test calls (`browser_demo`). Default: `true`. | | `labels` | array | Call labels. | | `has_post_call` | boolean | `true` when there is a post-call result. Default: `false`. | | `executed_actions_count` | integer | Number of executed actions. Default: `0`. | | `organization_id` | string | The call's organization. | | `metadata` | object | Technical metadata. Its content is not stable: do not rely on it. | | `messages` | array | Transcript, in order. | | `messages[].id` | string | Turn ID. | | `messages[].sequence` | integer | Order of the turn in the conversation. Default: `0`. | | `messages[].role` | string | `user` (the caller) or `assistant` (the agent). Default: `user`. | | `messages[].content` | string | What was said. | | `messages[].created_at` | string \| null | When the turn was recorded. | | `tool_calls` | array | Actions executed during the call. | | `tool_calls[].id` | string | Execution ID. | | `tool_calls[].tool_name` | string | Executed action. | | `tool_calls[].status` | string | Execution state. Default: `pending`. | | `tool_calls[].input` | object | Data sent to the action. | | `tool_calls[].output` | object \| array \| null | Action result, or `null`. | | `tool_calls[].error_message` | string \| null | Error, when it failed. | | `tool_calls[].latency_ms` | integer \| null | Execution time in milliseconds. | | `tool_calls[].called_at` | string \| null | Execution start. | | `tool_calls[].completed_at` | string \| null | Execution end. | | `post_call` | object \| null | Post-call result (the `call.completed` webhook content, without `call_id`), or `null`. | | `has_recording` | boolean | `true` when a recording is available. Default: `false`. | | `recording_state` | string | Recording state. One of: `disabled`, `recording`, `uploading`, `available`, `failed`, `expired`, `deleted`. Default: `disabled`. | ```json { "id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "external_ref": "sess_7f3a9c1e", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "channel": "phone", "direction": "inbound", "status": "completed", "caller_name": "Ana Silva", "caller_contact": "+244900000000", "started_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "duration_seconds": 95, "end_reason": "caller_hangup", "summary": "O cliente pediu o horário de abertura e marcou uma visita para sexta-feira.", "is_simulation": false, "labels": [ "urgente" ], "has_post_call": true, "executed_actions_count": 2, "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "metadata": {}, "messages": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "sequence": 1, "role": "user", "content": "Bom dia, queria marcar uma consulta.", "created_at": "2026-10-25T18:40:00Z" } ], "tool_calls": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "tool_name": "transfer_call", "status": "completed", "input": {}, "output": {}, "error_message": null, "latency_ms": 820, "called_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z" } ], "post_call": {}, "has_recording": true, "recording_state": "available" } ``` ## Errors | Code | When | | ----- | ------------------------------------------- | | `404` | `Chamada não encontrada.` (call not found). | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Download the recording ```http GET https://api.diska.ai/v1/calls/{call_id}/recording ``` **Scope:** `recordings:read` By default it answers `302` to a signed link that lasts 5 minutes (`curl -L -o recording.webm …` follows it and saves the audio). With `?format=json` it returns the link as JSON. Ask for a new link whenever you need the audio instead of storing it. Every access is recorded in the audit log. ## Parameters ### Path | Name | Type | Required | Description | | --------- | ------ | -------- | -------------- | | `call_id` | string | Yes | The call's ID. | ### Query string | Name | Type | Required | Description | | -------- | ------ | -------- | -------------------------------------------------------- | | `format` | string | No | `redirect` (the default) or `json`. Default: `redirect`. | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/calls//recording?format=json" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/calls//recording?format=json", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/calls//recording?format=json', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /recording?format=json'); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: call_id in: path required: true - name: format in: query options: - redirect - json value: json body-type: none locale: en method: GET path: /v1/calls/{call_id}/recording --- :: ## Response `200` | Field | Type | Description | | ------------------ | --------------- | --------------------------------------- | | `call_id` | string | The call. | | `url` | string | Signed link to download the audio. | | `expires_in` | integer | Seconds until the link expires. | | `content_type` | string \| null | Audio format, for example `audio/webm`. | | `size_bytes` | integer \| null | Size in bytes. | | `duration_seconds` | integer \| null | Duration in seconds, when known. | ```json { "call_id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "url": "https://o-seu-sistema.com/hooks/diska", "expires_in": 0, "content_type": "…", "size_bytes": 48213, "duration_seconds": 95 } ``` ## Errors | Code | When | | ----- | ------------------------------------------------------------------------------------------------------------------- | | `404` | `Esta chamada não tem gravação.` (no recording), or the recording is no longer available (for example, it expired). | | `502` | The link could not be generated. Try again. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Calls To be told when a call ends, use [webhooks](https://docs.diska.ai/en/api/webhooks). | Method | Endpoint | Description | Scope | | ------ | -------------------------------------------------------------------------------------------------- | ---------------------- | ----------------- | | `GET` | [`/v1/calls`](https://docs.diska.ai/en/api/reference/calls/list-calls) | List calls | `calls:read` | | `GET` | [`/v1/calls/{call_id}`](https://docs.diska.ai/en/api/reference/calls/get-call) | Get a call | `calls:read` | | `GET` | [`/v1/calls/{call_id}/recording`](https://docs.diska.ai/en/api/reference/calls/get-call-recording) | Download the recording | `recordings:read` | # Make an outbound call ```http POST https://api.diska.ai/v1/outbound-calls ``` **Scope:** `calls:write` The response carries the request's `id`, in state `queued`. Follow it with [Get an outbound call](https://docs.diska.ai/en/api/reference/outbound-calls/get-outbound-call): once the agent's session starts, the `call_id` appears — the same as in `GET /v1/calls` and in webhooks. The agent receives the call context from the platform: it is an outbound call, the reason (`purpose`) and the contact's name. Send `Idempotency-Key` to retry the request without calling twice. ## Request body `application/json` | Field | Type | Required | Description | | -------------- | -------------- | -------- | ---------------------------------------------------------------------------------------------------------------------- | | `agent_id` | string | Yes | The agent that calls (outbound, published, prompt mode). Up to 64 characters. | | `to` | string | Yes | Angolan mobile: `+244 9XX XXX XXX`, `9XX XXX XXX` or `00244…`. 9 to 20 characters. | | `contact_name` | string \| null | No | The person's name, so the agent can address them. Up to 120 characters. | | `purpose` | string \| null | No | Why the company is calling, as the agent may say it. Never read as an instruction. Up to 120 characters. | | `variables` | object | No | Call variables (`{{name}}` in flows and actions). Up to 20; reserved keys or values carrying instructions are refused. | ```json { "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "+244923000000", "contact_name": "Ana Silva", "purpose": "Lembrete da consulta de sexta-feira", "variables": { "consulta": "sexta, 10h" } } ``` ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/outbound-calls" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"agent_id":"3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40","to":"+244923000000","contact_name":"Ana Silva","purpose":"Lembrete da consulta de sexta-feira","variables":{"consulta":"sexta, 10h"}}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/outbound-calls", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "+244923000000", "contact_name": "Ana Silva", "purpose": "Lembrete da consulta de sexta-feira", "variables": { "consulta": "sexta, 10h", }, }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/outbound-calls', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "+244923000000", "contact_name": "Ana Silva", "purpose": "Lembrete da consulta de sexta-feira", "variables": { "consulta": "sexta, 10h" } }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'agent_id' => '3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40', 'to' => '+244923000000', 'contact_name' => 'Ana Silva', 'purpose' => 'Lembrete da consulta de sexta-feira', 'variables' => [ 'consulta' => 'sexta, 10h', ], ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: [] body: | { "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "+244923000000", "contact_name": "Ana Silva", "purpose": "Lembrete da consulta de sexta-feira", "variables": { "consulta": "sexta, 10h" } } body-type: json locale: en method: POST path: /v1/outbound-calls --- :: ## Response `201` | Field | Type | Description | | ----------------- | -------------- | --------------------------------------------------------------------------------------- | | `id` | string | The call request's ID. | | `status` | string | `queued`, `ringing`, `in_progress`, `ended`, `failed` or `cancelled`. | | `failure_code` | string \| null | Why it failed, for example `destination_no_answer`. | | `failure_message` | string \| null | The same reason, in words. | | `agent_id` | string | The calling agent. | | `to` | string | Number called. | | `from_number` | string | DISKA number the person sees. | | `contact_name` | string \| null | Contact name. | | `purpose` | string \| null | Why the company is calling. | | `call_id` | string \| null | The call in `GET /v1/calls/{call_id}` and in webhooks, once the agent's session starts. | | `created_at` | string | When the request was made. | | `answered_at` | string \| null | When the person answered. | | `ended_at` | string \| null | When it ended. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "status": "queued", "failure_code": "…", "failure_message": "…", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "…", "from_number": "…", "contact_name": "…", "purpose": "…", "call_id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "created_at": "2026-10-25T18:40:00Z", "answered_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z" } ``` ## Errors | Code | When | | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `403` | API calls are not switched on for the organization, or the organization is not enabled for outbound calls. | | `404` | `Agente não encontrado.` (agent not found). | | `409` | The agent is not outbound, not published or not in prompt mode; it has no active DISKA number; outside contact hours; or the number is on the do-not-call list. | | `422` | The destination is not an Angolan mobile, is the agent's own number, or some variables were refused. | | `429` | The organization's concurrent call limit, or this hour's API call limit. | | `503` | The phone line is not available right now. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Get an outbound call ```http GET https://api.diska.ai/v1/outbound-calls/{outbound_call_id} ``` **Scope:** `calls:read` It stays available for 24 hours; after that, use the `call_id`. ## Parameters ### Path | Name | Type | Required | Description | | ------------------ | ------ | -------- | -------------------------------------------- | | `outbound_call_id` | string | Yes | The `id` returned when you created the call. | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/outbound-calls/" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/outbound-calls/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/outbound-calls/', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: outbound_call_id in: path required: true body-type: none locale: en method: GET path: /v1/outbound-calls/{outbound_call_id} --- :: ## Response `200` | Field | Type | Description | | ----------------- | -------------- | --------------------------------------------------------------------------------------- | | `id` | string | The call request's ID. | | `status` | string | `queued`, `ringing`, `in_progress`, `ended`, `failed` or `cancelled`. | | `failure_code` | string \| null | Why it failed, for example `destination_no_answer`. | | `failure_message` | string \| null | The same reason, in words. | | `agent_id` | string | The calling agent. | | `to` | string | Number called. | | `from_number` | string | DISKA number the person sees. | | `contact_name` | string \| null | Contact name. | | `purpose` | string \| null | Why the company is calling. | | `call_id` | string \| null | The call in `GET /v1/calls/{call_id}` and in webhooks, once the agent's session starts. | | `created_at` | string | When the request was made. | | `answered_at` | string \| null | When the person answered. | | `ended_at` | string \| null | When it ended. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "status": "queued", "failure_code": "…", "failure_message": "…", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "…", "from_number": "…", "contact_name": "…", "purpose": "…", "call_id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "created_at": "2026-10-25T18:40:00Z", "answered_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z" } ``` ## Errors | Code | When | | ----- | ------------------------------------------------------------------------------------------------------------ | | `404` | `Chamada de saída não encontrada.` — it does not exist, belongs to another organization, or 24 hours passed. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Hang up an outbound call ```http POST https://api.diska.ai/v1/outbound-calls/{outbound_call_id}/hangup ``` **Scope:** `calls:write` On a call that already ended it does nothing. ## Parameters ### Path | Name | Type | Required | Description | | ------------------ | ------ | -------- | -------------------------------------------- | | `outbound_call_id` | string | Yes | The `id` returned when you created the call. | ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/outbound-calls//hangup" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/outbound-calls//hangup", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/outbound-calls//hangup', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /hangup'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: outbound_call_id in: path required: true body-type: none locale: en method: POST path: /v1/outbound-calls/{outbound_call_id}/hangup --- :: ## Response `200` | Field | Type | Description | | ----------------- | -------------- | --------------------------------------------------------------------------------------- | | `id` | string | The call request's ID. | | `status` | string | `queued`, `ringing`, `in_progress`, `ended`, `failed` or `cancelled`. | | `failure_code` | string \| null | Why it failed, for example `destination_no_answer`. | | `failure_message` | string \| null | The same reason, in words. | | `agent_id` | string | The calling agent. | | `to` | string | Number called. | | `from_number` | string | DISKA number the person sees. | | `contact_name` | string \| null | Contact name. | | `purpose` | string \| null | Why the company is calling. | | `call_id` | string \| null | The call in `GET /v1/calls/{call_id}` and in webhooks, once the agent's session starts. | | `created_at` | string | When the request was made. | | `answered_at` | string \| null | When the person answered. | | `ended_at` | string \| null | When it ended. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "status": "queued", "failure_code": "…", "failure_message": "…", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "to": "…", "from_number": "…", "contact_name": "…", "purpose": "…", "call_id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "created_at": "2026-10-25T18:40:00Z", "answered_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z" } ``` ## Errors | Code | When | | ----- | ----------------------------------------------- | | `404` | `Chamada de saída não encontrada.` (not found). | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Outbound calls Only published outbound agents, Angolan mobiles, within contact hours (08:00–20:00) and outside the do-not-call list. Available once Diska switches API calls on for the organization. | Method | Endpoint | Description | Scope | | ------ | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------ | ------------- | | `POST` | [`/v1/outbound-calls`](https://docs.diska.ai/en/api/reference/outbound-calls/create-outbound-call) | Make an outbound call | `calls:write` | | `GET` | [`/v1/outbound-calls/{outbound_call_id}`](https://docs.diska.ai/en/api/reference/outbound-calls/get-outbound-call) | Get an outbound call | `calls:read` | | `POST` | [`/v1/outbound-calls/{outbound_call_id}/hangup`](https://docs.diska.ai/en/api/reference/outbound-calls/hang-up-outbound-call) | Hang up an outbound call | `calls:write` | # List campaigns ```http GET https://api.diska.ai/v1/campaigns ``` **Scope:** `campaigns:read` ## Parameters ### Query string | Name | Type | Required | Description | | -------- | -------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------- | | `status` | string \| null | No | Only campaigns in this state. One of: `draft`, `scheduled`, `running`, `paused`, `completed`, `cancelled`. Up to 20 characters. | | `limit` | integer | No | How many per page. Between 1 and 100. Default: `50`. | | `offset` | integer | No | How many to skip. Minimum 0. Default: `0`. | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/campaigns" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/campaigns", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/campaigns', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: status in: query options: - draft - scheduled - running - paused - completed - cancelled - name: limit in: query - name: offset in: query body-type: none locale: en method: GET path: /v1/campaigns --- :: ## Response `200` | Field | Type | Description | | -------------------------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `items` | array | The campaigns. | | `items[].id` | string | Campaign ID. | | `items[].name` | string | Name. | | `items[].status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` or `cancelled`. | | `items[].agent_id` | string \| null | Agent. | | `items[].agent_name` | string \| null | Agent name. | | `items[].phone_number_id` | string \| null | Line used. | | `items[].phone_number` | string \| null | Line number. | | `items[].schedule` | object | Schedule. | | `items[].schedule.start_at` | string \| null | Start (ISO 8601 with time zone), or `null` to begin when started. | | `items[].schedule.timezone` | string | Time zone of the windows. Default: `Africa/Luanda`. | | `items[].schedule.windows` | array | Windows per weekday. With no windows, it dials within contact hours. | | `items[].schedule.max_duration_days` | integer | Days the campaign may last; at the end, what is left is cancelled. Between 1 and 90. Default: `7`. | | `items[].limits` | object | Limits. | | `items[].limits.max_concurrency` | integer | Simultaneous calls of the campaign. Between 1 and 50. Default: `2`. | | `items[].limits.reserved_capacity` | integer | Organization concurrent calls kept free for other calls. Between 0 and 50. Default: `1`. | | `items[].limits.max_attempts` | integer | Attempts per recipient; only unanswered or busy calls are retried. Between 1 and 3. Default: `1`. | | `items[].limits.retry_delay_minutes` | integer | Minutes between attempts. Between 15 and 1440. Default: `60`. | | `items[].limits.budget_minutes` | integer \| null | Maximum minutes; the campaign pauses before exceeding them. Between 1 and 100000. | | `items[].pause_reason` | string \| null | Why it is paused: `manual`, `budget_exhausted`, `quota_exhausted` or `emergency_stop`. | | `items[].waiting_reason` | string \| null | Why it is not dialling right now, for example `outside_window` or `no_capacity`. One of: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `items[].next_window_at` | string \| null | When the next window opens. | | `items[].deadline_at` | string \| null | End of the maximum duration. | | `items[].created_at` | string \| null | Creation date (ISO 8601). | | `items[].started_at` | string \| null | When it was started. | | `items[].completed_at` | string \| null | When it finished. | | `items[].cancelled_at` | string \| null | When it was cancelled. | | `items[].stats` | object | Indicators. | | `items[].stats.total` | integer | Recipients. Default: `0`. | | `items[].stats.pending` | integer | Left to call. Default: `0`. | | `items[].stats.in_flight` | integer | Dialling or in a call. Default: `0`. | | `items[].stats.completed` | integer | Call placed (answered, not answered or busy). Default: `0`. | | `items[].stats.failed` | integer | Could not be called. Default: `0`. | | `items[].stats.cancelled` | integer | Cancelled. Default: `0`. | | `items[].stats.excluded` | integer | On the do-not-call list. Default: `0`. | | `items[].stats.calls_started` | integer | Attempts sent (each retry counts). Default: `0`. | | `items[].stats.answered` | integer | Answered. Default: `0`. | | `items[].stats.no_answer` | integer | Not answered. Default: `0`. | | `items[].stats.unavailable` | integer | Busy or unavailable. Default: `0`. | | `items[].stats.answer_rate` | number \| null | Answered ÷ (answered + not answered + unavailable). | | `items[].stats.total_duration_seconds` | integer | Total duration of answered calls. Default: `0`. | | `items[].stats.progress` | number | Recipients in a final state ÷ total. Default: `0`. | | `items[].stats.cost_kz` | number \| null | Cost in kwanzas, only when a rate is configured. | | `items[].stats.with_post_call` | integer | Calls with a post-call result. Default: `0`. | | `total` | integer | Total campaigns. | | `limit` | integer | Page size. | | `offset` | integer | This page's offset. | ```json { "items": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ {} ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ], "total": 1, "limit": 50, "offset": 0 } ``` ## Errors This endpoint has no errors of its own. Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Create a campaign ```http POST https://api.diska.ai/v1/campaigns ``` **Scope:** `campaigns:write` The agent must be outbound and published, and `phone_number_id` an active DISKA line of the organization (see [List phone numbers](https://docs.diska.ai/en/api/reference/phone-numbers/list-phone-numbers)). Windows must sit within contact hours (08:00–20:00). Then [add recipients](https://docs.diska.ai/en/api/reference/campaigns/add-campaign-recipients) and [start it](https://docs.diska.ai/en/api/reference/campaigns/start-campaign). Send `Idempotency-Key` to retry the request without creating two. ## Request body `application/json` | Field | Type | Required | Description | | ---------------------------- | --------------- | -------- | ---------------------------------------------------------------------------------------------------------- | | `name` | string | Yes | Campaign name. Up to 120 characters. | | `agent_id` | string | Yes | Published outbound agent that places the calls. | | `phone_number_id` | string | Yes | DISKA line to call from (from `GET /v1/phone-numbers`). | | `schedule` | object | No | When the campaign may dial. | | `schedule.start_at` | string \| null | No | Start (ISO 8601 with time zone), or `null` to begin when started. | | `schedule.timezone` | string | No | Time zone of the windows. Default: `Africa/Luanda`. | | `schedule.windows` | array | No | Windows per weekday. With no windows, it dials within contact hours. | | `schedule.windows[].day` | string | Yes | Weekday, in English. One of: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Yes | Start, `HH:MM`. | | `schedule.windows[].end` | string | Yes | End, `HH:MM`. | | `schedule.max_duration_days` | integer | No | Days the campaign may last; at the end, what is left is cancelled. Between 1 and 90. Default: `7`. | | `limits` | object | No | Concurrency, attempts and budget. | | `limits.max_concurrency` | integer | No | Simultaneous calls of the campaign. Between 1 and 50. Default: `2`. | | `limits.reserved_capacity` | integer | No | Organization concurrent calls kept free for other calls. Between 0 and 50. Default: `1`. | | `limits.max_attempts` | integer | No | Attempts per recipient; only unanswered or busy calls are retried. Between 1 and 3. Default: `1`. | | `limits.retry_delay_minutes` | integer | No | Minutes between attempts. Between 15 and 1440. Default: `60`. | | `limits.budget_minutes` | integer \| null | No | Maximum minutes; the campaign pauses before exceeding them. Between 1 and 100000. | ```json { "name": "Lembretes de Novembro", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "schedule": { "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "09:00", "end": "12:00" }, { "day": "monday", "start": "14:00", "end": "18:00" } ] }, "limits": { "max_concurrency": 2, "max_attempts": 2, "retry_delay_minutes": 60 } } ``` ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/campaigns" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name":"Lembretes de Novembro","agent_id":"3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40","phone_number_id":"5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93","schedule":{"timezone":"Africa/Luanda","windows":[{"day":"monday","start":"09:00","end":"12:00"},{"day":"monday","start":"14:00","end":"18:00"}]},"limits":{"max_concurrency":2,"max_attempts":2,"retry_delay_minutes":60}}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/campaigns", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "name": "Lembretes de Novembro", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "schedule": { "timezone": "Africa/Luanda", "windows": [{ "day": "monday", "start": "09:00", "end": "12:00", }, { "day": "monday", "start": "14:00", "end": "18:00", }], }, "limits": { "max_concurrency": 2, "max_attempts": 2, "retry_delay_minutes": 60, }, }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/campaigns', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "name": "Lembretes de Novembro", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "schedule": { "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "09:00", "end": "12:00" }, { "day": "monday", "start": "14:00", "end": "18:00" } ] }, "limits": { "max_concurrency": 2, "max_attempts": 2, "retry_delay_minutes": 60 } }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'name' => 'Lembretes de Novembro', 'agent_id' => '3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40', 'phone_number_id' => '5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93', 'schedule' => [ 'timezone' => 'Africa/Luanda', 'windows' => [[ 'day' => 'monday', 'start' => '09:00', 'end' => '12:00', ], [ 'day' => 'monday', 'start' => '14:00', 'end' => '18:00', ]], ], 'limits' => [ 'max_concurrency' => 2, 'max_attempts' => 2, 'retry_delay_minutes' => 60, ], ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: [] body: | { "name": "Lembretes de Novembro", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "schedule": { "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "09:00", "end": "12:00" }, { "day": "monday", "start": "14:00", "end": "18:00" } ] }, "limits": { "max_concurrency": 2, "max_attempts": 2, "retry_delay_minutes": 60 } } body-type: json locale: en method: POST path: /v1/campaigns --- :: ## Response `201` | Field | Type | Description | | ------------------------------ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Campaign ID. | | `name` | string | Name. | | `status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` or `cancelled`. | | `agent_id` | string \| null | Agent. | | `agent_name` | string \| null | Agent name. | | `phone_number_id` | string \| null | Line used. | | `phone_number` | string \| null | Line number. | | `schedule` | object | Schedule. | | `schedule.start_at` | string \| null | Start (ISO 8601 with time zone), or `null` to begin when started. | | `schedule.timezone` | string | Time zone of the windows. Default: `Africa/Luanda`. | | `schedule.windows` | array | Windows per weekday. With no windows, it dials within contact hours. | | `schedule.windows[].day` | string | Weekday, in English. One of: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Start, `HH:MM`. | | `schedule.windows[].end` | string | End, `HH:MM`. | | `schedule.max_duration_days` | integer | Days the campaign may last; at the end, what is left is cancelled. Between 1 and 90. Default: `7`. | | `limits` | object | Limits. | | `limits.max_concurrency` | integer | Simultaneous calls of the campaign. Between 1 and 50. Default: `2`. | | `limits.reserved_capacity` | integer | Organization concurrent calls kept free for other calls. Between 0 and 50. Default: `1`. | | `limits.max_attempts` | integer | Attempts per recipient; only unanswered or busy calls are retried. Between 1 and 3. Default: `1`. | | `limits.retry_delay_minutes` | integer | Minutes between attempts. Between 15 and 1440. Default: `60`. | | `limits.budget_minutes` | integer \| null | Maximum minutes; the campaign pauses before exceeding them. Between 1 and 100000. | | `pause_reason` | string \| null | Why it is paused: `manual`, `budget_exhausted`, `quota_exhausted` or `emergency_stop`. | | `waiting_reason` | string \| null | Why it is not dialling right now, for example `outside_window` or `no_capacity`. One of: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `next_window_at` | string \| null | When the next window opens. | | `deadline_at` | string \| null | End of the maximum duration. | | `created_at` | string \| null | Creation date (ISO 8601). | | `started_at` | string \| null | When it was started. | | `completed_at` | string \| null | When it finished. | | `cancelled_at` | string \| null | When it was cancelled. | | `stats` | object | Indicators. | | `stats.total` | integer | Recipients. Default: `0`. | | `stats.pending` | integer | Left to call. Default: `0`. | | `stats.in_flight` | integer | Dialling or in a call. Default: `0`. | | `stats.completed` | integer | Call placed (answered, not answered or busy). Default: `0`. | | `stats.failed` | integer | Could not be called. Default: `0`. | | `stats.cancelled` | integer | Cancelled. Default: `0`. | | `stats.excluded` | integer | On the do-not-call list. Default: `0`. | | `stats.calls_started` | integer | Attempts sent (each retry counts). Default: `0`. | | `stats.answered` | integer | Answered. Default: `0`. | | `stats.no_answer` | integer | Not answered. Default: `0`. | | `stats.unavailable` | integer | Busy or unavailable. Default: `0`. | | `stats.answer_rate` | number \| null | Answered ÷ (answered + not answered + unavailable). | | `stats.total_duration_seconds` | integer | Total duration of answered calls. Default: `0`. | | `stats.progress` | number | Recipients in a final state ÷ total. Default: `0`. | | `stats.cost_kz` | number \| null | Cost in kwanzas, only when a rate is configured. | | `stats.with_post_call` | integer | Calls with a post-call result. Default: `0`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z" } ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ``` ## Errors | Code | When | | ----- | -------------------------------------------------------------------------------------- | | `403` | Campaigns or API calls are not switched on for the organization. | | `404` | The agent or the number does not exist in the organization. | | `409` | The agent is not outbound or not published, or the number is not an active DISKA line. | | `422` | Windows outside contact hours, an unknown time zone or limits out of range. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Get a campaign ```http GET https://api.diska.ai/v1/campaigns/{campaign_id} ``` **Scope:** `campaigns:read` ## Parameters ### Path | Name | Type | Required | Description | | ------------- | ------ | -------- | ------------------ | | `campaign_id` | string | Yes | The campaign's ID. | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/campaigns/" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/campaigns/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/campaigns/', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: campaign_id in: path required: true body-type: none locale: en method: GET path: /v1/campaigns/{campaign_id} --- :: ## Response `200` | Field | Type | Description | | ------------------------------ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Campaign ID. | | `name` | string | Name. | | `status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` or `cancelled`. | | `agent_id` | string \| null | Agent. | | `agent_name` | string \| null | Agent name. | | `phone_number_id` | string \| null | Line used. | | `phone_number` | string \| null | Line number. | | `schedule` | object | Schedule. | | `schedule.start_at` | string \| null | Start (ISO 8601 with time zone), or `null` to begin when started. | | `schedule.timezone` | string | Time zone of the windows. Default: `Africa/Luanda`. | | `schedule.windows` | array | Windows per weekday. With no windows, it dials within contact hours. | | `schedule.windows[].day` | string | Weekday, in English. One of: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Start, `HH:MM`. | | `schedule.windows[].end` | string | End, `HH:MM`. | | `schedule.max_duration_days` | integer | Days the campaign may last; at the end, what is left is cancelled. Between 1 and 90. Default: `7`. | | `limits` | object | Limits. | | `limits.max_concurrency` | integer | Simultaneous calls of the campaign. Between 1 and 50. Default: `2`. | | `limits.reserved_capacity` | integer | Organization concurrent calls kept free for other calls. Between 0 and 50. Default: `1`. | | `limits.max_attempts` | integer | Attempts per recipient; only unanswered or busy calls are retried. Between 1 and 3. Default: `1`. | | `limits.retry_delay_minutes` | integer | Minutes between attempts. Between 15 and 1440. Default: `60`. | | `limits.budget_minutes` | integer \| null | Maximum minutes; the campaign pauses before exceeding them. Between 1 and 100000. | | `pause_reason` | string \| null | Why it is paused: `manual`, `budget_exhausted`, `quota_exhausted` or `emergency_stop`. | | `waiting_reason` | string \| null | Why it is not dialling right now, for example `outside_window` or `no_capacity`. One of: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `next_window_at` | string \| null | When the next window opens. | | `deadline_at` | string \| null | End of the maximum duration. | | `created_at` | string \| null | Creation date (ISO 8601). | | `started_at` | string \| null | When it was started. | | `completed_at` | string \| null | When it finished. | | `cancelled_at` | string \| null | When it was cancelled. | | `stats` | object | Indicators. | | `stats.total` | integer | Recipients. Default: `0`. | | `stats.pending` | integer | Left to call. Default: `0`. | | `stats.in_flight` | integer | Dialling or in a call. Default: `0`. | | `stats.completed` | integer | Call placed (answered, not answered or busy). Default: `0`. | | `stats.failed` | integer | Could not be called. Default: `0`. | | `stats.cancelled` | integer | Cancelled. Default: `0`. | | `stats.excluded` | integer | On the do-not-call list. Default: `0`. | | `stats.calls_started` | integer | Attempts sent (each retry counts). Default: `0`. | | `stats.answered` | integer | Answered. Default: `0`. | | `stats.no_answer` | integer | Not answered. Default: `0`. | | `stats.unavailable` | integer | Busy or unavailable. Default: `0`. | | `stats.answer_rate` | number \| null | Answered ÷ (answered + not answered + unavailable). | | `stats.total_duration_seconds` | integer | Total duration of answered calls. Default: `0`. | | `stats.progress` | number | Recipients in a final state ÷ total. Default: `0`. | | `stats.cost_kz` | number \| null | Cost in kwanzas, only when a rate is configured. | | `stats.with_post_call` | integer | Calls with a post-call result. Default: `0`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z" } ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ``` ## Errors | Code | When | | ----- | ------------------- | | `404` | Campaign not found. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Add recipients ```http POST https://api.diska.ai/v1/campaigns/{campaign_id}/recipients ``` **Scope:** `campaigns:write` Repeated numbers and repeated `external_id` values are skipped, so you can retry the request. Numbers on the do-not-call list become `excluded`. The response counts what was added, duplicated, excluded and invalid (with each one's reason). ## Parameters ### Path | Name | Type | Required | Description | | ------------- | ------ | -------- | ------------------ | | `campaign_id` | string | Yes | The campaign's ID. | ## Request body `application/json` | Field | Type | Required | Description | | -------------------------- | -------------- | -------- | ---------------------------------------------------------------- | | `recipients` | array | Yes | The recipients (1 to 1000). | | `recipients[].phone` | string | Yes | Angolan mobile. 3 to 40 characters. | | `recipients[].name` | string \| null | No | Name, so the agent can address the person. Up to 120 characters. | | `recipients[].email` | string \| null | No | Email. Up to 254 characters. | | `recipients[].variables` | object | No | Call variables. | | `recipients[].external_id` | string \| null | No | Your own ID; a repeat is skipped. Up to 120 characters. | ```json { "recipients": [ { "phone": "+244923000000", "name": "Ana Silva", "external_id": "crm-1042", "variables": { "consulta": "sexta, 10h" } }, { "phone": "+244924000000", "name": "João Neto", "external_id": "crm-1043" } ] } ``` ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/campaigns//recipients" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"recipients":[{"phone":"+244923000000","name":"Ana Silva","external_id":"crm-1042","variables":{"consulta":"sexta, 10h"}},{"phone":"+244924000000","name":"João Neto","external_id":"crm-1043"}]}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/campaigns//recipients", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "recipients": [{ "phone": "+244923000000", "name": "Ana Silva", "external_id": "crm-1042", "variables": { "consulta": "sexta, 10h", }, }, { "phone": "+244924000000", "name": "João Neto", "external_id": "crm-1043", }], }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/campaigns//recipients', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "recipients": [ { "phone": "+244923000000", "name": "Ana Silva", "external_id": "crm-1042", "variables": { "consulta": "sexta, 10h" } }, { "phone": "+244924000000", "name": "João Neto", "external_id": "crm-1043" } ] }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /recipients'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'recipients' => [[ 'phone' => '+244923000000', 'name' => 'Ana Silva', 'external_id' => 'crm-1042', 'variables' => [ 'consulta' => 'sexta, 10h', ], ], [ 'phone' => '+244924000000', 'name' => 'João Neto', 'external_id' => 'crm-1043', ]], ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: campaign_id in: path required: true body: | { "recipients": [ { "phone": "+244923000000", "name": "Ana Silva", "external_id": "crm-1042", "variables": { "consulta": "sexta, 10h" } }, { "phone": "+244924000000", "name": "João Neto", "external_id": "crm-1043" } ] } body-type: json locale: en method: POST path: /v1/campaigns/{campaign_id}/recipients --- :: ## Response `200` | Field | Type | Description | | ------------------- | ------- | ----------------------------------------------------- | | `added` | integer | Added. | | `duplicates` | integer | Skipped as duplicates. | | `excluded` | integer | On the do-not-call list. | | `invalid` | array | Refused, with the reason. | | `invalid[].row` | integer | Position in the request (from 1). | | `invalid[].phone` | string | Number sent. | | `invalid[].reason` | string | Reason. | | `warnings` | array | Added with warnings (for example, variables dropped). | | `warnings[].row` | integer | Position in the request (from 1). | | `warnings[].phone` | string | Number sent. | | `warnings[].reason` | string | Reason. | | `total` | integer | Campaign recipients after the request. | ```json { "added": 0, "duplicates": 0, "excluded": 0, "invalid": [ { "row": 0, "phone": "…", "reason": "…" } ], "warnings": [ { "row": 0, "phone": "…", "reason": "…" } ], "total": 1 } ``` ## Errors | Code | When | | ----- | -------------------------------------------- | | `404` | Campaign not found. | | `409` | The campaign already ended or was cancelled. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # List recipients ```http GET https://api.diska.ai/v1/campaigns/{campaign_id}/recipients ``` **Scope:** `campaigns:read` ## Parameters ### Path | Name | Type | Required | Description | | ------------- | ------ | -------- | ------------------ | | `campaign_id` | string | Yes | The campaign's ID. | ### Query string | Name | Type | Required | Description | | -------- | -------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | `status` | string \| null | No | Only recipients in this state. One of: `pending`, `reserved`, `calling`, `in_call`, `completed`, `failed`, `cancelled`, `excluded`. Up to 20 characters. | | `limit` | integer | No | How many per page. Between 1 and 200. Default: `50`. | | `offset` | integer | No | How many to skip. Minimum 0. Default: `0`. | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/campaigns//recipients" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/campaigns//recipients", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/campaigns//recipients', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /recipients'); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: campaign_id in: path required: true - name: status in: query options: - pending - reserved - calling - in_call - completed - failed - cancelled - excluded - name: limit in: query - name: offset in: query body-type: none locale: en method: GET path: /v1/campaigns/{campaign_id}/recipients --- :: ## Response `200` | Field | Type | Description | | -------------------------- | --------------- | ---------------------------------------------------------------------------------------------- | | `items` | array | The recipients. | | `items[].id` | string | Recipient ID. | | `items[].phone_e164` | string | Number. | | `items[].name` | string \| null | Name. | | `items[].email` | string \| null | Email. | | `items[].variables` | object | Variables. | | `items[].external_id` | string \| null | Your own ID. | | `items[].status` | string | `pending`, `reserved`, `calling`, `in_call`, `completed`, `failed`, `cancelled` or `excluded`. | | `items[].outcome` | string \| null | `answered`, `no_answer` or `unavailable`, when the call reached the network. | | `items[].attempts` | integer | Attempts made. Default: `0`. | | `items[].failure_code` | string \| null | Failure code. | | `items[].failure_reason` | string \| null | Failure reason. | | `items[].call_session_id` | string \| null | The call in `GET /v1/calls/{call_id}`. | | `items[].session_id` | string \| null | The voice session (the webhooks' `session_id`). | | `items[].duration_seconds` | integer \| null | Call duration. | | `items[].next_attempt_at` | string \| null | Next attempt. | | `items[].last_attempt_at` | string \| null | Last attempt. | | `items[].answered_at` | string \| null | When answered. | | `items[].ended_at` | string \| null | When it ended. | | `items[].created_at` | string \| null | Creation date (ISO 8601). | | `items[].has_recording` | boolean | `true` when the call has a recording. Default: `false`. | | `total` | integer | Total with this filter. | | `limit` | integer | Page size. | | `offset` | integer | This page's offset. | ```json { "items": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_e164": "…", "name": "Exemplo", "email": "…", "variables": {}, "external_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "status": "pending", "outcome": "answered", "attempts": 0, "failure_code": "…", "failure_reason": "…", "call_session_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "session_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "duration_seconds": 95, "next_attempt_at": "2026-10-25T18:40:00Z", "last_attempt_at": "2026-10-25T18:40:00Z", "answered_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "created_at": "2026-10-25T18:40:00Z", "has_recording": false } ], "total": 1, "limit": 50, "offset": 0 } ``` ## Errors | Code | When | | ----- | ------------------- | | `404` | Campaign not found. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Start a campaign ```http POST https://api.diska.ai/v1/campaigns/{campaign_id}/start ``` **Scope:** `campaigns:write` It needs at least one recipient still to call. ## Parameters ### Path | Name | Type | Required | Description | | ------------- | ------ | -------- | ------------------ | | `campaign_id` | string | Yes | The campaign's ID. | ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/campaigns//start" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/campaigns//start", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/campaigns//start', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /start'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: campaign_id in: path required: true body-type: none locale: en method: POST path: /v1/campaigns/{campaign_id}/start --- :: ## Response `200` | Field | Type | Description | | ------------------------------ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Campaign ID. | | `name` | string | Name. | | `status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` or `cancelled`. | | `agent_id` | string \| null | Agent. | | `agent_name` | string \| null | Agent name. | | `phone_number_id` | string \| null | Line used. | | `phone_number` | string \| null | Line number. | | `schedule` | object | Schedule. | | `schedule.start_at` | string \| null | Start (ISO 8601 with time zone), or `null` to begin when started. | | `schedule.timezone` | string | Time zone of the windows. Default: `Africa/Luanda`. | | `schedule.windows` | array | Windows per weekday. With no windows, it dials within contact hours. | | `schedule.windows[].day` | string | Weekday, in English. One of: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Start, `HH:MM`. | | `schedule.windows[].end` | string | End, `HH:MM`. | | `schedule.max_duration_days` | integer | Days the campaign may last; at the end, what is left is cancelled. Between 1 and 90. Default: `7`. | | `limits` | object | Limits. | | `limits.max_concurrency` | integer | Simultaneous calls of the campaign. Between 1 and 50. Default: `2`. | | `limits.reserved_capacity` | integer | Organization concurrent calls kept free for other calls. Between 0 and 50. Default: `1`. | | `limits.max_attempts` | integer | Attempts per recipient; only unanswered or busy calls are retried. Between 1 and 3. Default: `1`. | | `limits.retry_delay_minutes` | integer | Minutes between attempts. Between 15 and 1440. Default: `60`. | | `limits.budget_minutes` | integer \| null | Maximum minutes; the campaign pauses before exceeding them. Between 1 and 100000. | | `pause_reason` | string \| null | Why it is paused: `manual`, `budget_exhausted`, `quota_exhausted` or `emergency_stop`. | | `waiting_reason` | string \| null | Why it is not dialling right now, for example `outside_window` or `no_capacity`. One of: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `next_window_at` | string \| null | When the next window opens. | | `deadline_at` | string \| null | End of the maximum duration. | | `created_at` | string \| null | Creation date (ISO 8601). | | `started_at` | string \| null | When it was started. | | `completed_at` | string \| null | When it finished. | | `cancelled_at` | string \| null | When it was cancelled. | | `stats` | object | Indicators. | | `stats.total` | integer | Recipients. Default: `0`. | | `stats.pending` | integer | Left to call. Default: `0`. | | `stats.in_flight` | integer | Dialling or in a call. Default: `0`. | | `stats.completed` | integer | Call placed (answered, not answered or busy). Default: `0`. | | `stats.failed` | integer | Could not be called. Default: `0`. | | `stats.cancelled` | integer | Cancelled. Default: `0`. | | `stats.excluded` | integer | On the do-not-call list. Default: `0`. | | `stats.calls_started` | integer | Attempts sent (each retry counts). Default: `0`. | | `stats.answered` | integer | Answered. Default: `0`. | | `stats.no_answer` | integer | Not answered. Default: `0`. | | `stats.unavailable` | integer | Busy or unavailable. Default: `0`. | | `stats.answer_rate` | number \| null | Answered ÷ (answered + not answered + unavailable). | | `stats.total_duration_seconds` | integer | Total duration of answered calls. Default: `0`. | | `stats.progress` | number | Recipients in a final state ÷ total. Default: `0`. | | `stats.cost_kz` | number \| null | Cost in kwanzas, only when a rate is configured. | | `stats.with_post_call` | integer | Calls with a post-call result. Default: `0`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z" } ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ``` ## Errors | Code | When | | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `409` | The campaign is not a draft, has no recipients left to call, the organization cannot place outbound calls, or it already has 5 active campaigns. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Pause a campaign ```http POST https://api.diska.ai/v1/campaigns/{campaign_id}/pause ``` **Scope:** `campaigns:write` ## Parameters ### Path | Name | Type | Required | Description | | ------------- | ------ | -------- | ------------------ | | `campaign_id` | string | Yes | The campaign's ID. | ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/campaigns//pause" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/campaigns//pause", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/campaigns//pause', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /pause'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: campaign_id in: path required: true body-type: none locale: en method: POST path: /v1/campaigns/{campaign_id}/pause --- :: ## Response `200` | Field | Type | Description | | ------------------------------ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Campaign ID. | | `name` | string | Name. | | `status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` or `cancelled`. | | `agent_id` | string \| null | Agent. | | `agent_name` | string \| null | Agent name. | | `phone_number_id` | string \| null | Line used. | | `phone_number` | string \| null | Line number. | | `schedule` | object | Schedule. | | `schedule.start_at` | string \| null | Start (ISO 8601 with time zone), or `null` to begin when started. | | `schedule.timezone` | string | Time zone of the windows. Default: `Africa/Luanda`. | | `schedule.windows` | array | Windows per weekday. With no windows, it dials within contact hours. | | `schedule.windows[].day` | string | Weekday, in English. One of: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Start, `HH:MM`. | | `schedule.windows[].end` | string | End, `HH:MM`. | | `schedule.max_duration_days` | integer | Days the campaign may last; at the end, what is left is cancelled. Between 1 and 90. Default: `7`. | | `limits` | object | Limits. | | `limits.max_concurrency` | integer | Simultaneous calls of the campaign. Between 1 and 50. Default: `2`. | | `limits.reserved_capacity` | integer | Organization concurrent calls kept free for other calls. Between 0 and 50. Default: `1`. | | `limits.max_attempts` | integer | Attempts per recipient; only unanswered or busy calls are retried. Between 1 and 3. Default: `1`. | | `limits.retry_delay_minutes` | integer | Minutes between attempts. Between 15 and 1440. Default: `60`. | | `limits.budget_minutes` | integer \| null | Maximum minutes; the campaign pauses before exceeding them. Between 1 and 100000. | | `pause_reason` | string \| null | Why it is paused: `manual`, `budget_exhausted`, `quota_exhausted` or `emergency_stop`. | | `waiting_reason` | string \| null | Why it is not dialling right now, for example `outside_window` or `no_capacity`. One of: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `next_window_at` | string \| null | When the next window opens. | | `deadline_at` | string \| null | End of the maximum duration. | | `created_at` | string \| null | Creation date (ISO 8601). | | `started_at` | string \| null | When it was started. | | `completed_at` | string \| null | When it finished. | | `cancelled_at` | string \| null | When it was cancelled. | | `stats` | object | Indicators. | | `stats.total` | integer | Recipients. Default: `0`. | | `stats.pending` | integer | Left to call. Default: `0`. | | `stats.in_flight` | integer | Dialling or in a call. Default: `0`. | | `stats.completed` | integer | Call placed (answered, not answered or busy). Default: `0`. | | `stats.failed` | integer | Could not be called. Default: `0`. | | `stats.cancelled` | integer | Cancelled. Default: `0`. | | `stats.excluded` | integer | On the do-not-call list. Default: `0`. | | `stats.calls_started` | integer | Attempts sent (each retry counts). Default: `0`. | | `stats.answered` | integer | Answered. Default: `0`. | | `stats.no_answer` | integer | Not answered. Default: `0`. | | `stats.unavailable` | integer | Busy or unavailable. Default: `0`. | | `stats.answer_rate` | number \| null | Answered ÷ (answered + not answered + unavailable). | | `stats.total_duration_seconds` | integer | Total duration of answered calls. Default: `0`. | | `stats.progress` | number | Recipients in a final state ÷ total. Default: `0`. | | `stats.cost_kz` | number \| null | Cost in kwanzas, only when a rate is configured. | | `stats.with_post_call` | integer | Calls with a post-call result. Default: `0`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z" } ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ``` ## Errors | Code | When | | ----- | ----------------------------------------- | | `409` | The campaign is not scheduled or running. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Resume a campaign ```http POST https://api.diska.ai/v1/campaigns/{campaign_id}/resume ``` **Scope:** `campaigns:write` ## Parameters ### Path | Name | Type | Required | Description | | ------------- | ------ | -------- | ------------------ | | `campaign_id` | string | Yes | The campaign's ID. | ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/campaigns//resume" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/campaigns//resume", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/campaigns//resume', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /resume'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: campaign_id in: path required: true body-type: none locale: en method: POST path: /v1/campaigns/{campaign_id}/resume --- :: ## Response `200` | Field | Type | Description | | ------------------------------ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Campaign ID. | | `name` | string | Name. | | `status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` or `cancelled`. | | `agent_id` | string \| null | Agent. | | `agent_name` | string \| null | Agent name. | | `phone_number_id` | string \| null | Line used. | | `phone_number` | string \| null | Line number. | | `schedule` | object | Schedule. | | `schedule.start_at` | string \| null | Start (ISO 8601 with time zone), or `null` to begin when started. | | `schedule.timezone` | string | Time zone of the windows. Default: `Africa/Luanda`. | | `schedule.windows` | array | Windows per weekday. With no windows, it dials within contact hours. | | `schedule.windows[].day` | string | Weekday, in English. One of: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Start, `HH:MM`. | | `schedule.windows[].end` | string | End, `HH:MM`. | | `schedule.max_duration_days` | integer | Days the campaign may last; at the end, what is left is cancelled. Between 1 and 90. Default: `7`. | | `limits` | object | Limits. | | `limits.max_concurrency` | integer | Simultaneous calls of the campaign. Between 1 and 50. Default: `2`. | | `limits.reserved_capacity` | integer | Organization concurrent calls kept free for other calls. Between 0 and 50. Default: `1`. | | `limits.max_attempts` | integer | Attempts per recipient; only unanswered or busy calls are retried. Between 1 and 3. Default: `1`. | | `limits.retry_delay_minutes` | integer | Minutes between attempts. Between 15 and 1440. Default: `60`. | | `limits.budget_minutes` | integer \| null | Maximum minutes; the campaign pauses before exceeding them. Between 1 and 100000. | | `pause_reason` | string \| null | Why it is paused: `manual`, `budget_exhausted`, `quota_exhausted` or `emergency_stop`. | | `waiting_reason` | string \| null | Why it is not dialling right now, for example `outside_window` or `no_capacity`. One of: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `next_window_at` | string \| null | When the next window opens. | | `deadline_at` | string \| null | End of the maximum duration. | | `created_at` | string \| null | Creation date (ISO 8601). | | `started_at` | string \| null | When it was started. | | `completed_at` | string \| null | When it finished. | | `cancelled_at` | string \| null | When it was cancelled. | | `stats` | object | Indicators. | | `stats.total` | integer | Recipients. Default: `0`. | | `stats.pending` | integer | Left to call. Default: `0`. | | `stats.in_flight` | integer | Dialling or in a call. Default: `0`. | | `stats.completed` | integer | Call placed (answered, not answered or busy). Default: `0`. | | `stats.failed` | integer | Could not be called. Default: `0`. | | `stats.cancelled` | integer | Cancelled. Default: `0`. | | `stats.excluded` | integer | On the do-not-call list. Default: `0`. | | `stats.calls_started` | integer | Attempts sent (each retry counts). Default: `0`. | | `stats.answered` | integer | Answered. Default: `0`. | | `stats.no_answer` | integer | Not answered. Default: `0`. | | `stats.unavailable` | integer | Busy or unavailable. Default: `0`. | | `stats.answer_rate` | number \| null | Answered ÷ (answered + not answered + unavailable). | | `stats.total_duration_seconds` | integer | Total duration of answered calls. Default: `0`. | | `stats.progress` | number | Recipients in a final state ÷ total. Default: `0`. | | `stats.cost_kz` | number \| null | Cost in kwanzas, only when a rate is configured. | | `stats.with_post_call` | integer | Calls with a post-call result. Default: `0`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z" } ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ``` ## Errors | Code | When | | ----- | --------------------------- | | `409` | The campaign is not paused. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Cancel a campaign ```http POST https://api.diska.ai/v1/campaigns/{campaign_id}/cancel ``` **Scope:** `campaigns:write` It cannot be undone. ## Parameters ### Path | Name | Type | Required | Description | | ------------- | ------ | -------- | ------------------ | | `campaign_id` | string | Yes | The campaign's ID. | ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/campaigns//cancel" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/campaigns//cancel", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/campaigns//cancel', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /cancel'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: campaign_id in: path required: true body-type: none locale: en method: POST path: /v1/campaigns/{campaign_id}/cancel --- :: ## Response `200` | Field | Type | Description | | ------------------------------ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Campaign ID. | | `name` | string | Name. | | `status` | string | `draft`, `scheduled`, `running`, `paused`, `completed` or `cancelled`. | | `agent_id` | string \| null | Agent. | | `agent_name` | string \| null | Agent name. | | `phone_number_id` | string \| null | Line used. | | `phone_number` | string \| null | Line number. | | `schedule` | object | Schedule. | | `schedule.start_at` | string \| null | Start (ISO 8601 with time zone), or `null` to begin when started. | | `schedule.timezone` | string | Time zone of the windows. Default: `Africa/Luanda`. | | `schedule.windows` | array | Windows per weekday. With no windows, it dials within contact hours. | | `schedule.windows[].day` | string | Weekday, in English. One of: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday`. | | `schedule.windows[].start` | string | Start, `HH:MM`. | | `schedule.windows[].end` | string | End, `HH:MM`. | | `schedule.max_duration_days` | integer | Days the campaign may last; at the end, what is left is cancelled. Between 1 and 90. Default: `7`. | | `limits` | object | Limits. | | `limits.max_concurrency` | integer | Simultaneous calls of the campaign. Between 1 and 50. Default: `2`. | | `limits.reserved_capacity` | integer | Organization concurrent calls kept free for other calls. Between 0 and 50. Default: `1`. | | `limits.max_attempts` | integer | Attempts per recipient; only unanswered or busy calls are retried. Between 1 and 3. Default: `1`. | | `limits.retry_delay_minutes` | integer | Minutes between attempts. Between 15 and 1440. Default: `60`. | | `limits.budget_minutes` | integer \| null | Maximum minutes; the campaign pauses before exceeding them. Between 1 and 100000. | | `pause_reason` | string \| null | Why it is paused: `manual`, `budget_exhausted`, `quota_exhausted` or `emergency_stop`. | | `waiting_reason` | string \| null | Why it is not dialling right now, for example `outside_window` or `no_capacity`. One of: `outside_window`, `not_started`, `no_capacity`, `capacity_not_configured`, `line_unavailable`, `outbound_disabled`, `agent_unavailable`, `number_unavailable`, `halted`. | | `next_window_at` | string \| null | When the next window opens. | | `deadline_at` | string \| null | End of the maximum duration. | | `created_at` | string \| null | Creation date (ISO 8601). | | `started_at` | string \| null | When it was started. | | `completed_at` | string \| null | When it finished. | | `cancelled_at` | string \| null | When it was cancelled. | | `stats` | object | Indicators. | | `stats.total` | integer | Recipients. Default: `0`. | | `stats.pending` | integer | Left to call. Default: `0`. | | `stats.in_flight` | integer | Dialling or in a call. Default: `0`. | | `stats.completed` | integer | Call placed (answered, not answered or busy). Default: `0`. | | `stats.failed` | integer | Could not be called. Default: `0`. | | `stats.cancelled` | integer | Cancelled. Default: `0`. | | `stats.excluded` | integer | On the do-not-call list. Default: `0`. | | `stats.calls_started` | integer | Attempts sent (each retry counts). Default: `0`. | | `stats.answered` | integer | Answered. Default: `0`. | | `stats.no_answer` | integer | Not answered. Default: `0`. | | `stats.unavailable` | integer | Busy or unavailable. Default: `0`. | | `stats.answer_rate` | number \| null | Answered ÷ (answered + not answered + unavailable). | | `stats.total_duration_seconds` | integer | Total duration of answered calls. Default: `0`. | | `stats.progress` | number | Recipients in a final state ÷ total. Default: `0`. | | `stats.cost_kz` | number \| null | Cost in kwanzas, only when a rate is configured. | | `stats.with_post_call` | integer | Calls with a post-call result. Default: `0`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Exemplo", "status": "draft", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agent_name": "Recepção", "phone_number_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "phone_number": "+244900000000", "schedule": { "start_at": "2026-10-25T18:40:00Z", "timezone": "Africa/Luanda", "windows": [ { "day": "monday", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z" } ], "max_duration_days": 7 }, "limits": { "max_concurrency": 2, "reserved_capacity": 1, "max_attempts": 1, "retry_delay_minutes": 60, "budget_minutes": 0 }, "pause_reason": "manual", "waiting_reason": "outside_window", "next_window_at": "2026-10-25T18:40:00Z", "deadline_at": "2026-10-25T18:40:00Z", "created_at": "2026-10-25T18:40:00Z", "started_at": "2026-10-25T18:40:00Z", "completed_at": "2026-10-25T18:40:01Z", "cancelled_at": "2026-10-25T18:40:00Z", "stats": { "total": 1, "pending": 0, "in_flight": 0, "completed": 38, "failed": 3, "cancelled": 1, "excluded": 0, "calls_started": 0, "answered": 0, "no_answer": 0, "unavailable": 0, "answer_rate": 0, "total_duration_seconds": 0, "progress": 0, "cost_kz": 0, "with_post_call": 0 } } ``` ## Errors | Code | When | | ----- | -------------------------------------------- | | `409` | The campaign already ended or was cancelled. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Campaigns Diska dials within the windows and limits you set, and each call shows up in [Calls](https://docs.diska.ai/en/api/reference/calls) and in webhooks. It works like the backoffice [Campaigns](https://docs.diska.ai/en/telephony/campaigns). | Method | Endpoint | Description | Scope | | ------ | --------------------------------------------------------------------------------------------------------------------- | ----------------- | ----------------- | | `GET` | [`/v1/campaigns`](https://docs.diska.ai/en/api/reference/campaigns/list-campaigns) | List campaigns | `campaigns:read` | | `POST` | [`/v1/campaigns`](https://docs.diska.ai/en/api/reference/campaigns/create-campaign) | Create a campaign | `campaigns:write` | | `GET` | [`/v1/campaigns/{campaign_id}`](https://docs.diska.ai/en/api/reference/campaigns/get-campaign) | Get a campaign | `campaigns:read` | | `POST` | [`/v1/campaigns/{campaign_id}/recipients`](https://docs.diska.ai/en/api/reference/campaigns/add-campaign-recipients) | Add recipients | `campaigns:write` | | `GET` | [`/v1/campaigns/{campaign_id}/recipients`](https://docs.diska.ai/en/api/reference/campaigns/list-campaign-recipients) | List recipients | `campaigns:read` | | `POST` | [`/v1/campaigns/{campaign_id}/start`](https://docs.diska.ai/en/api/reference/campaigns/start-campaign) | Start a campaign | `campaigns:write` | | `POST` | [`/v1/campaigns/{campaign_id}/pause`](https://docs.diska.ai/en/api/reference/campaigns/pause-campaign) | Pause a campaign | `campaigns:write` | | `POST` | [`/v1/campaigns/{campaign_id}/resume`](https://docs.diska.ai/en/api/reference/campaigns/resume-campaign) | Resume a campaign | `campaigns:write` | | `POST` | [`/v1/campaigns/{campaign_id}/cancel`](https://docs.diska.ai/en/api/reference/campaigns/cancel-campaign) | Cancel a campaign | `campaigns:write` | # Create a chat ```http POST https://api.diska.ai/v1/chats ``` **Scope:** `chats:write` If the agent speaks first and has a greeting, the response already carries that message. The chat also shows in `GET /v1/calls`, with channel `web_chat`. `metadata` is yours: it is stored and returned, but the agent never sees it. Send `Idempotency-Key` to retry the request without opening two chats. ## Request body `application/json` | Field | Type | Required | Description | | ----------- | -------------- | -------- | -------------------------------------------------------------------- | | `agent_id` | string | Yes | Published prompt-mode agent. Up to 64 characters. | | `variables` | object | No | Chat variables (up to 20), as on calls. | | `metadata` | object | No | Up to 20 text → text pairs (500 characters per value), for you only. | | `contact` | string \| null | No | Who is chatting: phone, email or your own ID. Up to 120 characters. | ```json { "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "contact": "+244923000000", "variables": { "nome": "Ana" }, "metadata": { "crm_ticket": "T-1042" } } ``` ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/chats" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"agent_id":"3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40","contact":"+244923000000","variables":{"nome":"Ana"},"metadata":{"crm_ticket":"T-1042"}}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/chats", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "contact": "+244923000000", "variables": { "nome": "Ana", }, "metadata": { "crm_ticket": "T-1042", }, }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/chats', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "contact": "+244923000000", "variables": { "nome": "Ana" }, "metadata": { "crm_ticket": "T-1042" } }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'agent_id' => '3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40', 'contact' => '+244923000000', 'variables' => [ 'nome' => 'Ana', ], 'metadata' => [ 'crm_ticket' => 'T-1042', ], ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: [] body: | { "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "contact": "+244923000000", "variables": { "nome": "Ana" }, "metadata": { "crm_ticket": "T-1042" } } body-type: json locale: en method: POST path: /v1/chats --- :: ## Response `201` | Field | Type | Description | | ----------------------- | -------------- | ------------------------------------------------ | | `id` | string | Chat ID (the same as `GET /v1/calls/{call_id}`). | | `agent_id` | string | The agent. | | `status` | string | `active` or `ended`. | | `contact` | string \| null | Who is chatting, as you stated it. | | `metadata` | object | Your metadata, returned as sent. | | `created_at` | string | Creation date (ISO 8601). | | `ended_at` | string \| null | When it ended. | | `end_reason` | string \| null | `ended_by_api`, `agent_ended` or `inactivity`. | | `messages` | array | The messages, in order. | | `messages[].id` | string | Message ID. | | `messages[].role` | string | `user` (the person) or `assistant` (the agent). | | `messages[].content` | string | The text. | | `messages[].created_at` | string \| null | When it was written. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "status": "active", "contact": "+244900000000", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "end_reason": "caller_hangup", "messages": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "role": "user", "content": "Bom dia, queria marcar uma consulta.", "created_at": "2026-10-25T18:40:00Z" } ] } ``` ## Errors | Code | When | | ----- | ----------------------------------------------------------------- | | `403` | API chat is not switched on for the organization. | | `404` | `Agente não encontrado.` (agent not found). | | `409` | The agent is not published, is inactive or uses the Flow Builder. | | `422` | Variables refused or metadata over the limits. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Send a message ```http POST https://api.diska.ai/v1/chats/{chat_id}/messages ``` **Scope:** `chats:write` One message at a time per chat. If the agent concludes the chat, `chat.status` becomes `ended`. The agent's actions (for example, booking a meeting) run for real and ask for confirmation as on calls. ## Parameters ### Path | Name | Type | Required | Description | | --------- | ------ | -------- | -------------- | | `chat_id` | string | Yes | The chat's ID. | ## Request body `application/json` | Field | Type | Required | Description | | --------- | ------ | -------- | -------------------------------------------- | | `message` | string | Yes | The person's message. Up to 4000 characters. | ```json { "message": "Queria marcar uma consulta para sexta-feira." } ``` ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/chats//messages" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"message":"Queria marcar uma consulta para sexta-feira."}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/chats//messages", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "message": "Queria marcar uma consulta para sexta-feira.", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/chats//messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "message": "Queria marcar uma consulta para sexta-feira." }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /messages'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'message' => 'Queria marcar uma consulta para sexta-feira.', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: chat_id in: path required: true body: | { "message": "Queria marcar uma consulta para sexta-feira." } body-type: json locale: en method: POST path: /v1/chats/{chat_id}/messages --- :: ## Response `200` | Field | Type | Description | | ----------------------- | -------------- | ------------------------------------------------ | | `chat` | object | The chat, with its updated state. | | `chat.id` | string | Chat ID (the same as `GET /v1/calls/{call_id}`). | | `chat.agent_id` | string | The agent. | | `chat.status` | string | `active` or `ended`. | | `chat.contact` | string \| null | Who is chatting, as you stated it. | | `chat.metadata` | object | Your metadata, returned as sent. | | `chat.created_at` | string | Creation date (ISO 8601). | | `chat.ended_at` | string \| null | When it ended. | | `chat.end_reason` | string \| null | `ended_by_api`, `agent_ended` or `inactivity`. | | `reply` | string \| null | The agent's reply, or `null`. | | `messages` | array | The new messages: the person's and the agent's. | | `messages[].id` | string | Message ID. | | `messages[].role` | string | `user` (the person) or `assistant` (the agent). | | `messages[].content` | string | The text. | | `messages[].created_at` | string \| null | When it was written. | ```json { "chat": { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "status": "active", "contact": "+244900000000", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "end_reason": "caller_hangup" }, "reply": "…", "messages": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "role": "user", "content": "Bom dia, queria marcar uma consulta.", "created_at": "2026-10-25T18:40:00Z" } ] } ``` ## Errors | Code | When | | ----- | ------------------------------------------------------------------------------ | | `403` | API chat is not switched on for the organization. | | `404` | `Chat não encontrado.` (chat not found). | | `409` | The chat ended, or the previous message is still being answered. | | `502` | The agent could not answer in time. The message was not stored: send it again. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Get a chat ```http GET https://api.diska.ai/v1/chats/{chat_id} ``` **Scope:** `chats:write` ## Parameters ### Path | Name | Type | Required | Description | | --------- | ------ | -------- | -------------- | | `chat_id` | string | Yes | The chat's ID. | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/chats/" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/chats/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/chats/', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: chat_id in: path required: true body-type: none locale: en method: GET path: /v1/chats/{chat_id} --- :: ## Response `200` | Field | Type | Description | | ----------------------- | -------------- | ------------------------------------------------ | | `id` | string | Chat ID (the same as `GET /v1/calls/{call_id}`). | | `agent_id` | string | The agent. | | `status` | string | `active` or `ended`. | | `contact` | string \| null | Who is chatting, as you stated it. | | `metadata` | object | Your metadata, returned as sent. | | `created_at` | string | Creation date (ISO 8601). | | `ended_at` | string \| null | When it ended. | | `end_reason` | string \| null | `ended_by_api`, `agent_ended` or `inactivity`. | | `messages` | array | The messages, in order. | | `messages[].id` | string | Message ID. | | `messages[].role` | string | `user` (the person) or `assistant` (the agent). | | `messages[].content` | string | The text. | | `messages[].created_at` | string \| null | When it was written. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "status": "active", "contact": "+244900000000", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "end_reason": "caller_hangup", "messages": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "role": "user", "content": "Bom dia, queria marcar uma consulta.", "created_at": "2026-10-25T18:40:00Z" } ] } ``` ## Errors | Code | When | | ----- | ------------------------------------------------- | | `403` | API chat is not switched on for the organization. | | `404` | `Chat não encontrado.` (chat not found). | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # List chats ```http GET https://api.diska.ai/v1/chats ``` **Scope:** `chats:write` ## Parameters ### Query string | Name | Type | Required | Description | | ---------- | -------------- | -------- | ---------------------------------------------------- | | `agent_id` | string \| null | No | Only chats with this agent. Up to 64 characters. | | `status` | string \| null | No | `active` or `ended`. | | `limit` | integer | No | How many per page. Between 1 and 100. Default: `50`. | | `offset` | integer | No | How many to skip. Minimum 0. Default: `0`. | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/chats" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/chats", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/chats', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: agent_id in: query - name: status in: query options: - active - ended - name: limit in: query - name: offset in: query body-type: none locale: en method: GET path: /v1/chats --- :: ## Response `200` | Field | Type | Description | | -------------------- | -------------- | ------------------------------------------------ | | `items` | array | The chats. | | `items[].id` | string | Chat ID (the same as `GET /v1/calls/{call_id}`). | | `items[].agent_id` | string | The agent. | | `items[].status` | string | `active` or `ended`. | | `items[].contact` | string \| null | Who is chatting, as you stated it. | | `items[].metadata` | object | Your metadata, returned as sent. | | `items[].created_at` | string | Creation date (ISO 8601). | | `items[].ended_at` | string \| null | When it ended. | | `items[].end_reason` | string \| null | `ended_by_api`, `agent_ended` or `inactivity`. | | `total` | integer | Total with these filters. | | `limit` | integer | Page size. | | `offset` | integer | This page's offset. | ```json { "items": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "status": "active", "contact": "+244900000000", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "end_reason": "caller_hangup" } ], "total": 1, "limit": 50, "offset": 0 } ``` ## Errors | Code | When | | ----- | ------------------------------------------------- | | `403` | API chat is not switched on for the organization. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # End a chat ```http POST https://api.diska.ai/v1/chats/{chat_id}/end ``` **Scope:** `chats:write` The same processing as a completed call then runs — extractions, evaluations and summary — and the `call.completed` webhook is sent. A chat with no messages for 30 minutes ends by itself, the same way. Ending a chat that already ended does nothing. ## Parameters ### Path | Name | Type | Required | Description | | --------- | ------ | -------- | -------------- | | `chat_id` | string | Yes | The chat's ID. | ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/chats//end" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/chats//end", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/chats//end', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /end'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: chat_id in: path required: true body-type: none locale: en method: POST path: /v1/chats/{chat_id}/end --- :: ## Response `200` | Field | Type | Description | | ----------------------- | -------------- | ------------------------------------------------ | | `id` | string | Chat ID (the same as `GET /v1/calls/{call_id}`). | | `agent_id` | string | The agent. | | `status` | string | `active` or `ended`. | | `contact` | string \| null | Who is chatting, as you stated it. | | `metadata` | object | Your metadata, returned as sent. | | `created_at` | string | Creation date (ISO 8601). | | `ended_at` | string \| null | When it ended. | | `end_reason` | string \| null | `ended_by_api`, `agent_ended` or `inactivity`. | | `messages` | array | The messages, in order. | | `messages[].id` | string | Message ID. | | `messages[].role` | string | `user` (the person) or `assistant` (the agent). | | `messages[].content` | string | The text. | | `messages[].created_at` | string \| null | When it was written. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "status": "active", "contact": "+244900000000", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "ended_at": "2026-10-25T18:41:35Z", "end_reason": "caller_hangup", "messages": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "role": "user", "content": "Bom dia, queria marcar uma consulta.", "created_at": "2026-10-25T18:40:00Z" } ] } ``` ## Errors | Code | When | | ----- | ------------------------------------------------- | | `403` | API chat is not switched on for the organization. | | `404` | `Chat não encontrado.` (chat not found). | | `409` | The previous message is still being answered. | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Chat The agent uses the same instructions, knowledge and actions as on calls. Available once Diska switches API chat on for the organization. | Method | Endpoint | Description | Scope | | ------ | ------------------------------------------------------------------------------------------------ | -------------- | ------------- | | `POST` | [`/v1/chats`](https://docs.diska.ai/en/api/reference/chats/create-chat) | Create a chat | `chats:write` | | `POST` | [`/v1/chats/{chat_id}/messages`](https://docs.diska.ai/en/api/reference/chats/send-chat-message) | Send a message | `chats:write` | | `GET` | [`/v1/chats/{chat_id}`](https://docs.diska.ai/en/api/reference/chats/get-chat) | Get a chat | `chats:write` | | `GET` | [`/v1/chats`](https://docs.diska.ai/en/api/reference/chats/list-chats) | List chats | `chats:write` | | `POST` | [`/v1/chats/{chat_id}/end`](https://docs.diska.ai/en/api/reference/chats/end-chat) | End a chat | `chats:write` | # Analytics overview ```http GET https://api.diska.ai/v1/analytics/overview ``` **Scope:** `analytics:read` Daily dates are in UTC. ## Parameters ### Query string | Name | Type | Required | Description | | ------------ | -------------- | -------- | ----------------------------------------------------------------------------------------------- | | `period` | string | No | `daily` (last 24 hours), `weekly` (last 7 days) or `monthly` (last 30 days). Default: `weekly`. | | `agent_id` | string \| null | No | Only this agent. | | `agent_type` | string | No | `all`, `inbound` or `outbound`. Default: `all`. | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/analytics/overview?period=weekly" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/analytics/overview?period=weekly", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/analytics/overview?period=weekly', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: period in: query options: - daily - weekly - monthly value: weekly - name: agent_id in: query - name: agent_type in: query options: - all - inbound - outbound body-type: none locale: en method: GET path: /v1/analytics/overview --- :: ## Response `200` | Field | Type | Description | | ---------------------------------------- | -------------- | ---------------------------------------------------------------------------------------- | | `period` | string | Analyzed window. One of: `daily`, `weekly`, `monthly`. Default: `weekly`. | | `start` | string | Window start. | | `end` | string | Window end (when the request was made). | | `totals` | object | Window totals, compared with the previous one. | | `totals.calls` | object | Number of calls. | | `totals.calls.value` | number | Value in the current window. Default: `0`. | | `totals.calls.previous` | number | Value in the previous window. Default: `0`. | | `totals.calls.change_pct` | number \| null | Change in percent, or `null` when the previous window has no data. | | `totals.minutes` | object | Call minutes. | | `totals.minutes.value` | number | Value in the current window. Default: `0`. | | `totals.minutes.previous` | number | Value in the previous window. Default: `0`. | | `totals.minutes.change_pct` | number \| null | Change in percent, or `null` when the previous window has no data. | | `totals.avg_duration_seconds` | object | Average duration in seconds. | | `totals.avg_duration_seconds.value` | number | Value in the current window. Default: `0`. | | `totals.avg_duration_seconds.previous` | number | Value in the previous window. Default: `0`. | | `totals.avg_duration_seconds.change_pct` | number \| null | Change in percent, or `null` when the previous window has no data. | | `daily` | array | Day-by-day evolution. | | `daily[].date` | string | Day, in UTC (YYYY-MM-DD). | | `daily[].calls` | integer | Calls that day. Default: `0`. | | `daily[].minutes` | number | Minutes that day. Default: `0`. | | `daily[].completed` | integer | Completed calls. Default: `0`. | | `daily[].failed` | integer | Failed calls. Default: `0`. | | `daily[].cancelled` | integer | Cancelled calls. Default: `0`. | | `by_status` | array | Distribution by call state. | | `by_status[].key` | string | Value (code). | | `by_status[].label` | string | Readable name. | | `by_status[].count` | integer | Number of calls. Default: `0`. | | `by_status[].pct` | number | Percent of the total. Default: `0`. | | `by_end_reason` | array | Distribution by end reason. | | `by_end_reason[].key` | string | Value (code). | | `by_end_reason[].label` | string | Readable name. | | `by_end_reason[].count` | integer | Number of calls. Default: `0`. | | `by_end_reason[].pct` | number | Percent of the total. Default: `0`. | | `sentiment` | object | Call sentiment. | | `sentiment.positive_pct` | object | Percent of positive calls. | | `sentiment.positive_pct.value` | number | Value in the current window. Default: `0`. | | `sentiment.positive_pct.previous` | number | Value in the previous window. Default: `0`. | | `sentiment.positive_pct.change_pct` | number \| null | Change in percent, or `null` when the previous window has no data. | | `sentiment.classified` | integer | Calls with a classified sentiment. Default: `0`. | | `sentiment.total` | integer | Total calls. Default: `0`. | | `sentiment.breakdown` | array | Distribution by sentiment. | | `sentiment.breakdown[].key` | string | Value (code). | | `sentiment.breakdown[].label` | string | Readable name. | | `sentiment.breakdown[].count` | integer | Number of calls. Default: `0`. | | `sentiment.breakdown[].pct` | number | Percent of the total. Default: `0`. | | `sentiment.daily` | array | Daily evolution. | | `sentiment.daily[].date` | string | Day, in UTC (YYYY-MM-DD). | | `sentiment.daily[].positive` | integer | Positive calls. Default: `0`. | | `sentiment.daily[].neutral` | integer | Neutral calls. Default: `0`. | | `sentiment.daily[].negative` | integer | Negative calls. Default: `0`. | | `agents` | array | Performance per agent. | | `agents[].agent_id` | string \| null | Agent. | | `agents[].name` | string | Agent name. Default: `—`. | | `agents[].calls` | integer | Calls. Default: `0`. | | `agents[].minutes` | number | Minutes. Default: `0`. | | `agents[].completed` | integer | Completed calls. Default: `0`. | | `agents[].completion_pct` | number | Percent of completed calls (technical completion, not a business outcome). Default: `0`. | | `agents[].completion_change_pct` | number \| null | Change in completion against the previous window. | | `agents[].goal_achieved_pct` | number \| null | Percent of calls that reached the goal, or `null` when unknown. | | `agents[].calls_change_pct` | number \| null | Change in calls. | | `agents[].minutes_change_pct` | number \| null | Change in minutes. | | `agents[].goal_change_pct` | number \| null | Change in goal achieved. | | `actions` | array | Usage of each executed action. | | `actions[].tool_name` | string | Action (code). | | `actions[].label` | string | Action name. | | `actions[].usage` | object | Executions in the window, with the change. | | `actions[].usage.value` | number | Value in the current window. Default: `0`. | | `actions[].usage.previous` | number | Value in the previous window. Default: `0`. | | `actions[].usage.change_pct` | number \| null | Change in percent, or `null` when the previous window has no data. | | `actions[].daily` | array | Executions per day. | | `actions[].daily[].date` | string | Day, in UTC (YYYY-MM-DD). | | `actions[].daily[].count` | integer | Executions that day. Default: `0`. | | `failed_calls` | array | Recent failed calls. | | `failed_calls[].id` | string | Call ID. | | `failed_calls[].started_at` | string \| null | Call start. | | `failed_calls[].contact` | string \| null | Caller contact. | | `failed_calls[].agent_name` | string \| null | Agent. | | `failed_calls[].end_reason` | string \| null | Why it failed. | ```json { "period": "weekly", "start": "2026-10-25T18:40:00Z", "end": "2026-11-01T18:40:00Z", "totals": { "calls": { "value": 42, "previous": 38, "change_pct": 10.5 }, "minutes": { "value": 42, "previous": 38, "change_pct": 10.5 }, "avg_duration_seconds": { "value": 42, "previous": 38, "change_pct": 10.5 } }, "daily": [ { "date": "2026-10-25", "calls": 42, "minutes": 63.5, "completed": 38, "failed": 3, "cancelled": 1 } ], "by_status": [ { "key": "completed", "label": "Concluída", "count": 38, "pct": 90.5 } ], "by_end_reason": [ { "key": "completed", "label": "Concluída", "count": 38, "pct": 90.5 } ], "sentiment": { "positive_pct": { "value": 42, "previous": 38, "change_pct": 10.5 }, "classified": 40, "total": 1, "breakdown": [ { "key": "completed", "label": "Concluída", "count": 38, "pct": 90.5 } ], "daily": [ { "date": "2026-10-25", "positive": 30, "neutral": 8, "negative": 2 } ] }, "agents": [ { "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "name": "Recepção", "calls": 42, "minutes": 63.5, "completed": 38, "completion_pct": 90.5, "completion_change_pct": 0, "goal_achieved_pct": 0, "calls_change_pct": 0, "minutes_change_pct": 0, "goal_change_pct": 0 } ], "actions": [ { "tool_name": "transfer_call", "label": "Concluída", "usage": { "value": 42, "previous": 38, "change_pct": 10.5 }, "daily": [ { "date": "2026-10-25", "count": 38 } ] } ], "failed_calls": [ { "id": "8d0c6a3e-2f14-4b7a-9c55-1e3f0a6d2b81", "started_at": "2026-10-25T18:40:00Z", "contact": "+244900000000", "agent_name": "Recepção", "end_reason": "caller_hangup" } ] } ``` ## Errors This endpoint has no errors of its own. Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Analytics | Method | Endpoint | Description | Scope | | ------ | ----------------------------------------------------------------------------------------- | ------------------ | ---------------- | | `GET` | [`/v1/analytics/overview`](https://docs.diska.ai/en/api/reference/analytics/get-overview) | Analytics overview | `analytics:read` | # List phone numbers ```http GET https://api.diska.ai/v1/phone-numbers ``` **Scope:** `phone-numbers:read` Numbers imported over SIP also carry the trunk fields; the SIP password is never returned, only `sip_password_configured`. ## Parameters ### Query string | Name | Type | Required | Description | | ------------- | -------------- | -------- | ---------------------------------------------------------------------- | | `search` | string \| null | No | Text in the number, the name or the SIP domain. Up to 200 characters. | | `number_type` | string \| null | No | `purchased` (DISKA numbers) or `imported` (your own numbers over SIP). | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/phone-numbers" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/phone-numbers", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/phone-numbers', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: search in: query - name: number_type in: query options: - purchased - imported body-type: none locale: en method: GET path: /v1/phone-numbers --- :: ## Response `200` | Field | Type | Description | | --------------------------------- | -------------- | ------------------------------------------------------------------------------------------ | | `items` | array | The numbers. | | `items[].id` | string | ID. | | `items[].organization_id` | string | Organization it belongs to. | | `items[].e164` | string | The number in E.164 format. | | `items[].friendly_name` | string \| null | Name given to the number. | | `items[].number_type` | string | `purchased` (DISKA number) or `imported` (your own number over SIP). Default: `purchased`. | | `items[].status` | string | `active` or `inactive`. Default: `active`. | | `items[].country_code` | string | Number's country (ISO 3166). Default: `AO`. | | `items[].capabilities` | object | What the number supports. | | `items[].capabilities.calls` | boolean | Makes and receives calls. Default: `true`. | | `items[].capabilities.sms` | boolean | Sends SMS. Default: `true`. | | `items[].monthly_price_kz` | number \| null | Monthly price in kwanzas, when applicable. | | `items[].provider` | string \| null | Number's carrier. | | `items[].provider_sid` | string \| null | The number's ID at the carrier. | | `items[].agent_id` | string \| null | The number's main agent. | | `items[].agents` | array | Agents that use the number. | | `items[].agents[].id` | string | Agent. | | `items[].agents[].name` | string | Agent name. | | `items[].agents[].status` | string \| null | Agent state. | | `items[].sip_domain` | string \| null | SIP trunk: server domain. | | `items[].sip_username` | string \| null | SIP trunk: username. | | `items[].sip_password_configured` | boolean | `true` when the SIP password is set (it is never returned). Default: `false`. | | `items[].sip_outbound_proxy` | string \| null | SIP trunk: outbound proxy. | | `items[].sip_auth_username` | string \| null | SIP trunk: authentication username, if different. | | `items[].sip_outbound_register` | boolean | `true` when Diska registers with the SIP server. Default: `false`. | | `items[].origination_uri` | string \| null | SIP address the carrier sends incoming calls to. | | `items[].sip_status` | string \| null | SIP trunk state. One of: `pending_credentials`, `pending_provisioning`, `ready`, `error`. | | `items[].sip_status_detail` | string \| null | Trunk state detail. | | `items[].sip_transport` | string | SIP transport. One of: `udp`, `tcp`. Default: `udp`. | | `items[].sip_allowed_ips` | array | IP addresses allowed to send calls. | | `items[].created_at` | string \| null | Creation date (ISO 8601). | | `items[].updated_at` | string \| null | Last change date (ISO 8601). | | `total` | integer | How many numbers. | ```json { "items": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "e164": "+244900000000", "friendly_name": "Linha principal", "number_type": "purchased", "status": "active", "country_code": "AO", "capabilities": { "calls": true, "sms": true }, "monthly_price_kz": 0, "provider": "africell", "provider_sid": null, "agent_id": "3f1c2a7e-5b9d-4c1e-8f3a-2d6b7e9c1a40", "agents": [ { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Recepção", "status": "active" } ], "sip_domain": null, "sip_username": null, "sip_password_configured": false, "sip_outbound_proxy": null, "sip_auth_username": null, "sip_outbound_register": false, "origination_uri": null, "sip_status": null, "sip_status_detail": null, "sip_transport": "udp", "sip_allowed_ips": [], "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z" } ], "total": 1 } ``` ## Errors This endpoint has no errors of its own. Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Phone numbers | Method | Endpoint | Description | Scope | | ------ | ---------------------------------------------------------------------------------------------- | ------------------ | -------------------- | | `GET` | [`/v1/phone-numbers`](https://docs.diska.ai/en/api/reference/phone-numbers/list-phone-numbers) | List phone numbers | `phone-numbers:read` | # List knowledge bases ```http GET https://api.diska.ai/v1/knowledge-bases ``` **Scope:** `knowledge:read` ## Parameters ### Query string | Name | Type | Required | Description | | -------- | -------------- | -------- | -------------------------------------------------------------------- | | `search` | string \| null | No | Text contained in the name or the instruction. Up to 200 characters. | ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/knowledge-bases" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/knowledge-bases", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/knowledge-bases', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: search in: query body-type: none locale: en method: GET path: /v1/knowledge-bases --- :: ## Response `200` | Field | Type | Description | | ------------------------------ | -------------- | -------------------------------------------- | | `items` | array | The knowledge bases. | | `items[].id` | string | ID. | | `items[].organization_id` | string | Organization it belongs to. | | `items[].name` | string | Base name. | | `items[].instruction` | string | When and how the agent should use this base. | | `items[].description` | string \| null | Description, or `null`. | | `items[].document_count` | integer | Number of documents. Default: `0`. | | `items[].assigned_agent_count` | integer | Agents that use this base. Default: `0`. | | `items[].created_at` | string \| null | Creation date (ISO 8601). | | `items[].updated_at` | string \| null | Last change date (ISO 8601). | ```json { "items": [ { "id": "b2e4c6d8-1a3f-4e5b-9c7d-0f2a4b6c8e10", "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Produtos e preços", "instruction": "Use esta base para responder a perguntas sobre produtos, preços e horários.", "description": "Tabela de preços e horários de 2026.", "document_count": 3, "assigned_agent_count": 1, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z" } ] } ``` ## Errors This endpoint has no errors of its own. Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Create a knowledge base ```http POST https://api.diska.ai/v1/knowledge-bases ``` **Scope:** `knowledge:write` Add documents with the three endpoints that follow and assign the base to an agent in the backoffice. ## Request body `application/json` | Field | Type | Required | Description | | ------------- | -------------- | -------- | ------------------------------------------------------------------- | | `name` | string | Yes | Base name. Up to 200 characters. | | `instruction` | string | Yes | When and how the agent should use this base. Up to 4000 characters. | | `description` | string \| null | No | Description. Up to 2000 characters. | ```json { "name": "Produtos e preços", "instruction": "Use esta base para responder a perguntas sobre produtos, preços e horários.", "description": "Tabela de preços e horários de 2026." } ``` ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/knowledge-bases" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name":"Produtos e preços","instruction":"Use esta base para responder a perguntas sobre produtos, preços e horários.","description":"Tabela de preços e horários de 2026."}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/knowledge-bases", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "name": "Produtos e preços", "instruction": "Use esta base para responder a perguntas sobre produtos, preços e horários.", "description": "Tabela de preços e horários de 2026.", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/knowledge-bases', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "name": "Produtos e preços", "instruction": "Use esta base para responder a perguntas sobre produtos, preços e horários.", "description": "Tabela de preços e horários de 2026." }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'name' => 'Produtos e preços', 'instruction' => 'Use esta base para responder a perguntas sobre produtos, preços e horários.', 'description' => 'Tabela de preços e horários de 2026.', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: [] body: > { "name": "Produtos e preços", "instruction": "Use esta base para responder a perguntas sobre produtos, preços e horários.", "description": "Tabela de preços e horários de 2026." } body-type: json locale: en method: POST path: /v1/knowledge-bases --- :: ## Response `201` | Field | Type | Description | | ---------------------- | -------------- | -------------------------------------------- | | `id` | string | ID. | | `organization_id` | string | Organization it belongs to. | | `name` | string | Base name. | | `instruction` | string | When and how the agent should use this base. | | `description` | string \| null | Description, or `null`. | | `document_count` | integer | Number of documents. Default: `0`. | | `assigned_agent_count` | integer | Agents that use this base. Default: `0`. | | `created_at` | string \| null | Creation date (ISO 8601). | | `updated_at` | string \| null | Last change date (ISO 8601). | ```json { "id": "b2e4c6d8-1a3f-4e5b-9c7d-0f2a4b6c8e10", "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "name": "Produtos e preços", "instruction": "Use esta base para responder a perguntas sobre produtos, preços e horários.", "description": "Tabela de preços e horários de 2026.", "document_count": 3, "assigned_agent_count": 1, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z" } ``` ## Errors This endpoint has no errors of its own. Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Add a text document ```http POST https://api.diska.ai/v1/knowledge-bases/{knowledge_base_id}/documents ``` **Scope:** `knowledge:write` Indexing starts right away; the document is ready when `indexing_status` is `indexed`. ## Parameters ### Path | Name | Type | Required | Description | | ------------------- | ------ | -------- | ------------------------ | | `knowledge_base_id` | string | Yes | The knowledge base's ID. | ## Request body `application/json` | Field | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------ | | `name` | string | Yes | Document name. Up to 200 characters. | | `content` | string | Yes | The text. Up to 200000 characters. | ```json { "name": "Horários", "content": "Abrimos de segunda a sexta, das 8h às 17h." } ``` ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/knowledge-bases//documents" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name":"Horários","content":"Abrimos de segunda a sexta, das 8h às 17h."}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/knowledge-bases//documents", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "name": "Horários", "content": "Abrimos de segunda a sexta, das 8h às 17h.", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/knowledge-bases//documents', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "name": "Horários", "content": "Abrimos de segunda a sexta, das 8h às 17h." }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /documents'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'name' => 'Horários', 'content' => 'Abrimos de segunda a sexta, das 8h às 17h.', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: knowledge_base_id in: path required: true body: | { "name": "Horários", "content": "Abrimos de segunda a sexta, das 8h às 17h." } body-type: json locale: en method: POST path: /v1/knowledge-bases/{knowledge_base_id}/documents --- :: ## Response `201` | Field | Type | Description | | ------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | ID. | | `organization_id` | string | Organization it belongs to. | | `knowledge_base_id` | string | Base the document belongs to. | | `name` | string | Document name. | | `source_type` | string | `manual` (text), `pdf` or `url`. | | `status` | string | Overall document state. One of: `pending`, `uploading`, `processing`, `ready`, `failed`, `indexing_pending`. Default: `pending`. | | `extraction_status` | string | Text extraction state. One of: `pending`, `extracted`, `skipped`, `failed`. Default: `pending`. | | `indexing_status` | string | Indexing state: `indexed` when the agent can use it. One of: `pending`, `indexing_pending`, `indexed`, `skipped`, `failed`. Default: `indexing_pending`. | | `content_text` | string \| null | The extracted text. | | `original_url` | string \| null | Imported address (`url` documents). | | `storage_path` | string \| null | Internal file location. | | `mime_type` | string \| null | File type. | | `size_bytes` | integer \| null | Size in bytes. | | `error_message` | string \| null | Error, when it failed. | | `metadata` | object | Technical metadata. | | `created_at` | string \| null | Creation date (ISO 8601). | | `updated_at` | string \| null | Last change date (ISO 8601). | | `has_file` | boolean | `true` when a file is stored. Default: `false`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "knowledge_base_id": "b2e4c6d8-1a3f-4e5b-9c7d-0f2a4b6c8e10", "name": "Horários", "source_type": "manual", "status": "ready", "extraction_status": "extracted", "indexing_status": "indexed", "content_text": "Abrimos de segunda a sexta, das 8h às 17h.", "original_url": null, "storage_path": null, "mime_type": "text/plain", "size_bytes": 48213, "error_message": "…", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z", "has_file": false } ``` ## Errors | Code | When | | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | Content refused — for example `Ficheiro vazio.` (empty file), `PDF demasiado grande (máx. 25 MB).` (PDF too large), `Apenas ficheiros PDF são aceites.` (only PDFs), `O ficheiro não parece ser um PDF válido.` (not a valid PDF), `Tempo esgotado ao obter a página.` (page timed out), `A página não devolveu texto legível.` (no readable text) or a URL blocked for security. | | `404` | `Base de conhecimento não encontrada.` (knowledge base not found). | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Import a web page ```http POST https://api.diska.ai/v1/knowledge-bases/{knowledge_base_id}/documents/url ``` **Scope:** `knowledge:write` The page must answer within 15 seconds, be up to 2 MB and be HTML, text or JSON. Private or internal addresses are refused, and at most 3 redirects are followed. ## Parameters ### Path | Name | Type | Required | Description | | ------------------- | ------ | -------- | ------------------------ | | `knowledge_base_id` | string | Yes | The knowledge base's ID. | ## Request body `application/json` | Field | Type | Required | Description | | ------ | ------ | -------- | ----------------------------------------------------------------------- | | `name` | string | Yes | Document name. Up to 200 characters. | | `url` | string | Yes | Full `http://` or `https://` address of the page. 8 to 2000 characters. | ```json { "name": "Página de preços", "url": "https://www.exemplo.ao/precos" } ``` ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/knowledge-bases//documents/url" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name":"Página de preços","url":"https://www.exemplo.ao/precos"}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/knowledge-bases//documents/url", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "name": "Página de preços", "url": "https://www.exemplo.ao/precos", }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/knowledge-bases//documents/url', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "name": "Página de preços", "url": "https://www.exemplo.ao/precos" }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /documents/url'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'name' => 'Página de preços', 'url' => 'https://www.exemplo.ao/precos', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: knowledge_base_id in: path required: true body: | { "name": "Página de preços", "url": "https://www.exemplo.ao/precos" } body-type: json locale: en method: POST path: /v1/knowledge-bases/{knowledge_base_id}/documents/url --- :: ## Response `201` | Field | Type | Description | | ------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | ID. | | `organization_id` | string | Organization it belongs to. | | `knowledge_base_id` | string | Base the document belongs to. | | `name` | string | Document name. | | `source_type` | string | `manual` (text), `pdf` or `url`. | | `status` | string | Overall document state. One of: `pending`, `uploading`, `processing`, `ready`, `failed`, `indexing_pending`. Default: `pending`. | | `extraction_status` | string | Text extraction state. One of: `pending`, `extracted`, `skipped`, `failed`. Default: `pending`. | | `indexing_status` | string | Indexing state: `indexed` when the agent can use it. One of: `pending`, `indexing_pending`, `indexed`, `skipped`, `failed`. Default: `indexing_pending`. | | `content_text` | string \| null | The extracted text. | | `original_url` | string \| null | Imported address (`url` documents). | | `storage_path` | string \| null | Internal file location. | | `mime_type` | string \| null | File type. | | `size_bytes` | integer \| null | Size in bytes. | | `error_message` | string \| null | Error, when it failed. | | `metadata` | object | Technical metadata. | | `created_at` | string \| null | Creation date (ISO 8601). | | `updated_at` | string \| null | Last change date (ISO 8601). | | `has_file` | boolean | `true` when a file is stored. Default: `false`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "knowledge_base_id": "b2e4c6d8-1a3f-4e5b-9c7d-0f2a4b6c8e10", "name": "Horários", "source_type": "manual", "status": "ready", "extraction_status": "extracted", "indexing_status": "indexed", "content_text": "Abrimos de segunda a sexta, das 8h às 17h.", "original_url": null, "storage_path": null, "mime_type": "text/plain", "size_bytes": 48213, "error_message": "…", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z", "has_file": false } ``` ## Errors | Code | When | | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | Content refused — for example `Ficheiro vazio.` (empty file), `PDF demasiado grande (máx. 25 MB).` (PDF too large), `Apenas ficheiros PDF são aceites.` (only PDFs), `O ficheiro não parece ser um PDF válido.` (not a valid PDF), `Tempo esgotado ao obter a página.` (page timed out), `A página não devolveu texto legível.` (no readable text) or a URL blocked for security. | | `404` | `Base de conhecimento não encontrada.` (knowledge base not found). | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Upload a PDF ```http POST https://api.diska.ai/v1/knowledge-bases/{knowledge_base_id}/documents/pdf ``` **Scope:** `knowledge:write` ## Parameters ### Path | Name | Type | Required | Description | | ------------------- | ------ | -------- | ------------------------ | | `knowledge_base_id` | string | Yes | The knowledge base's ID. | ## Request body `multipart/form-data` | Field | Type | Required | Description | | ------ | ---- | -------- | ---------------------- | | `file` | file | Yes | The PDF (up to 25 MB). | ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/knowledge-bases//documents/pdf" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -F "file=@tabela-de-precos.pdf;type=application/pdf" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/knowledge-bases//documents/pdf", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, files={"file": ("tabela-de-precos.pdf", open("tabela-de-precos.pdf", "rb"), "application/pdf")}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 20 or later, in a .mjs file import { openAsBlob } from 'node:fs' const form = new FormData() form.append('file', await openAsBlob('tabela-de-precos.pdf', { type: 'application/pdf' }), 'tabela-de-precos.pdf') const response = await fetch('https://api.diska.ai/v1/knowledge-bases//documents/pdf', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` }, body: form }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /documents/pdf'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_POSTFIELDS => ['file' => new CURLFile('tabela-de-precos.pdf', 'application/pdf')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. In Try it, pick a PDF from your computer. ::api-playground --- params: - name: knowledge_base_id in: path required: true body-type: multipart locale: en method: POST path: /v1/knowledge-bases/{knowledge_base_id}/documents/pdf --- :: ## Response `201` | Field | Type | Description | | ------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | ID. | | `organization_id` | string | Organization it belongs to. | | `knowledge_base_id` | string | Base the document belongs to. | | `name` | string | Document name. | | `source_type` | string | `manual` (text), `pdf` or `url`. | | `status` | string | Overall document state. One of: `pending`, `uploading`, `processing`, `ready`, `failed`, `indexing_pending`. Default: `pending`. | | `extraction_status` | string | Text extraction state. One of: `pending`, `extracted`, `skipped`, `failed`. Default: `pending`. | | `indexing_status` | string | Indexing state: `indexed` when the agent can use it. One of: `pending`, `indexing_pending`, `indexed`, `skipped`, `failed`. Default: `indexing_pending`. | | `content_text` | string \| null | The extracted text. | | `original_url` | string \| null | Imported address (`url` documents). | | `storage_path` | string \| null | Internal file location. | | `mime_type` | string \| null | File type. | | `size_bytes` | integer \| null | Size in bytes. | | `error_message` | string \| null | Error, when it failed. | | `metadata` | object | Technical metadata. | | `created_at` | string \| null | Creation date (ISO 8601). | | `updated_at` | string \| null | Last change date (ISO 8601). | | `has_file` | boolean | `true` when a file is stored. Default: `false`. | ```json { "id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "organization_id": "5c2e8a14-7d3b-4f9e-a1c6-0b8d2f4e6a93", "knowledge_base_id": "b2e4c6d8-1a3f-4e5b-9c7d-0f2a4b6c8e10", "name": "Horários", "source_type": "manual", "status": "ready", "extraction_status": "extracted", "indexing_status": "indexed", "content_text": "Abrimos de segunda a sexta, das 8h às 17h.", "original_url": null, "storage_path": null, "mime_type": "text/plain", "size_bytes": 48213, "error_message": "…", "metadata": {}, "created_at": "2026-10-25T18:40:00Z", "updated_at": "2026-10-25T18:40:00Z", "has_file": false } ``` ## Errors | Code | When | | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | Content refused — for example `Ficheiro vazio.` (empty file), `PDF demasiado grande (máx. 25 MB).` (PDF too large), `Apenas ficheiros PDF são aceites.` (only PDFs), `O ficheiro não parece ser um PDF válido.` (not a valid PDF), `Tempo esgotado ao obter a página.` (page timed out), `A página não devolveu texto legível.` (no readable text) or a URL blocked for security. | | `404` | `Base de conhecimento não encontrada.` (knowledge base not found). | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Knowledge For an agent to use a base, assign it in the backoffice. | Method | Endpoint | Description | Scope | | ------ | ------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ----------------- | | `GET` | [`/v1/knowledge-bases`](https://docs.diska.ai/en/api/reference/knowledge/list-knowledge-bases) | List knowledge bases | `knowledge:read` | | `POST` | [`/v1/knowledge-bases`](https://docs.diska.ai/en/api/reference/knowledge/create-knowledge-base) | Create a knowledge base | `knowledge:write` | | `POST` | [`/v1/knowledge-bases/{knowledge_base_id}/documents`](https://docs.diska.ai/en/api/reference/knowledge/add-text-document) | Add a text document | `knowledge:write` | | `POST` | [`/v1/knowledge-bases/{knowledge_base_id}/documents/url`](https://docs.diska.ai/en/api/reference/knowledge/import-url) | Import a web page | `knowledge:write` | | `POST` | [`/v1/knowledge-bases/{knowledge_base_id}/documents/pdf`](https://docs.diska.ai/en/api/reference/knowledge/upload-pdf) | Upload a PDF | `knowledge:write` | # List webhook endpoints ```http GET https://api.diska.ai/v1/webhook-endpoints ``` **Scope:** `webhooks:manage` ## Examples ::code-group ```bash [cURL] curl "https://api.diska.ai/v1/webhook-endpoints" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.get( "https://api.diska.ai/v1/webhook-endpoints", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/webhook-endpoints', { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: [] body-type: none locale: en method: GET path: /v1/webhook-endpoints --- :: ## Response `200` | Field | Type | Description | | ------------------------- | -------------- | ----------------------------------------------------------------- | | `[].id` | string | Endpoint ID. | | `[].url` | string | Delivery destination. | | `[].description` | string \| null | Description. | | `[].events` | array | Subscribed events. | | `[].active` | boolean | `false` when disabled (by you or automatically). Default: `true`. | | `[].disabled_reason` | string \| null | Why it was disabled automatically, or `null`. | | `[].failure_count` | integer | Consecutive failed deliveries. Default: `0`. | | `[].last_delivery_at` | string \| null | Last delivery. | | `[].last_delivery_status` | string \| null | Result of the last delivery, for example `delivered (200)`. | | `[].secret_preview` | string | Start and end of the secret, to identify it. | | `[].created_at` | string \| null | Creation date (ISO 8601). | ```json [ { "id": "e7a1c3f5-9b2d-4f6e-8a0c-3d5f7b9e1c24", "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ], "active": true, "disabled_reason": null, "failure_count": 0, "last_delivery_at": "2026-10-25T18:40:00Z", "last_delivery_status": "delivered (200)", "secret_preview": "dskw_AbC…wXyZ", "created_at": "2026-10-25T18:40:00Z" } ] ``` ## Errors This endpoint has no errors of its own. Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Create a webhook endpoint ```http POST https://api.diska.ai/v1/webhook-endpoints ``` **Scope:** `webhooks:manage` The response carries the `secret` (`dskw_…`) to verify signatures: **it only appears in this response**. Each organization can have up to 10 endpoints. ## Request body `application/json` | Field | Type | Required | Description | | ------------- | -------------- | -------- | ------------------------------------------------------------------------------------------------------- | | `url` | string | Yes | Full `https://` URL of your receiver. Private or internal addresses are refused. 12 to 2000 characters. | | `description` | string \| null | No | Description. Up to 500 characters. | | `events` | array | No | Events to subscribe to: `call.completed`, `booking.created`. Default `["call.completed"]`. | ```json { "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ] } ``` ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/webhook-endpoints" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"url":"https://o-seu-sistema.com/hooks/diska","description":"CRM — produção","events":["call.completed"]}' ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/webhook-endpoints", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": ["call.completed"], }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/webhook-endpoints', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ] }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] 'POST', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'url' => 'https://o-seu-sistema.com/hooks/diska', 'description' => 'CRM — produção', 'events' => ['call.completed'], ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: [] body: | { "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ] } body-type: json locale: en method: POST path: /v1/webhook-endpoints --- :: ## Response `201` | Field | Type | Description | | ------------------------------- | -------------- | ----------------------------------------------------------------------------- | | `endpoint` | object | The created endpoint. | | `endpoint.id` | string | Endpoint ID. | | `endpoint.url` | string | Delivery destination. | | `endpoint.description` | string \| null | Description. | | `endpoint.events` | array | Subscribed events. | | `endpoint.active` | boolean | `false` when disabled (by you or automatically). Default: `true`. | | `endpoint.disabled_reason` | string \| null | Why it was disabled automatically, or `null`. | | `endpoint.failure_count` | integer | Consecutive failed deliveries. Default: `0`. | | `endpoint.last_delivery_at` | string \| null | Last delivery. | | `endpoint.last_delivery_status` | string \| null | Result of the last delivery, for example `delivered (200)`. | | `endpoint.secret_preview` | string | Start and end of the secret, to identify it. | | `endpoint.created_at` | string \| null | Creation date (ISO 8601). | | `secret` | string | The secret (`dskw_…`) to verify signatures. It only appears in this response. | ```json { "endpoint": { "id": "e7a1c3f5-9b2d-4f6e-8a0c-3d5f7b9e1c24", "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ], "active": true, "disabled_reason": null, "failure_count": 0, "last_delivery_at": "2026-10-25T18:40:00Z", "last_delivery_status": "delivered (200)", "secret_preview": "dskw_AbC…wXyZ", "created_at": "2026-10-25T18:40:00Z" }, "secret": "dskw_…" } ``` ## Errors | Code | When | | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | `URL inválido: use um endpoint https:// completo.` (use a full https\:// URL), `URL bloqueado por segurança: …` (blocked for security), `Subscreva pelo menos um evento.` (at least one event), `Eventos desconhecidos: …` (unknown events) or `Limite de 10 endpoints por organização atingido.` (10 endpoints per organization). | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Update a webhook endpoint ```http PATCH https://api.diska.ai/v1/webhook-endpoints/{endpoint_id} ``` **Scope:** `webhooks:manage` `active: true` re-enables a disabled endpoint and resets `failure_count`; `active: false` stops deliveries. The secret does not change. ## Parameters ### Path | Name | Type | Required | Description | | ------------- | ------ | -------- | ------------------ | | `endpoint_id` | string | Yes | The endpoint's ID. | ## Request body `application/json` | Field | Type | Required | Description | | ------------- | --------------- | -------- | ----------------------------------------------------------------------- | | `url` | string \| null | No | New `https://` URL. 12 to 2000 characters. | | `description` | string \| null | No | New description; `""` clears it. Up to 500 characters. | | `events` | array \| null | No | New event list (at least one). | | `active` | boolean \| null | No | `true` re-enables and resets `failure_count`; `false` stops deliveries. | ```json { "active": true } ``` ## Examples ::code-group ```bash [cURL] curl -X PATCH "https://api.diska.ai/v1/webhook-endpoints/" \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"active":true}' ``` ```python [Python] import os import requests response = requests.patch( "https://api.diska.ai/v1/webhook-endpoints/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, json={ "active": True, }, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/webhook-endpoints/', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ "active": true }) }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'PATCH', CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DISKA_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'active' => true, ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: endpoint_id in: path required: true body: | { "active": true } body-type: json locale: en method: PATCH path: /v1/webhook-endpoints/{endpoint_id} --- :: ## Response `200` | Field | Type | Description | | ---------------------- | -------------- | ----------------------------------------------------------------- | | `id` | string | Endpoint ID. | | `url` | string | Delivery destination. | | `description` | string \| null | Description. | | `events` | array | Subscribed events. | | `active` | boolean | `false` when disabled (by you or automatically). Default: `true`. | | `disabled_reason` | string \| null | Why it was disabled automatically, or `null`. | | `failure_count` | integer | Consecutive failed deliveries. Default: `0`. | | `last_delivery_at` | string \| null | Last delivery. | | `last_delivery_status` | string \| null | Result of the last delivery, for example `delivered (200)`. | | `secret_preview` | string | Start and end of the secret, to identify it. | | `created_at` | string \| null | Creation date (ISO 8601). | ```json { "id": "e7a1c3f5-9b2d-4f6e-8a0c-3d5f7b9e1c24", "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ], "active": true, "disabled_reason": null, "failure_count": 0, "last_delivery_at": "2026-10-25T18:40:00Z", "last_delivery_status": "delivered (200)", "secret_preview": "dskw_AbC…wXyZ", "created_at": "2026-10-25T18:40:00Z" } ``` ## Errors | Code | When | | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | `URL inválido: use um endpoint https:// completo.` (use a full https\:// URL), `URL bloqueado por segurança: …` (blocked for security), `Subscreva pelo menos um evento.` (at least one event), `Eventos desconhecidos: …` (unknown events) or `Limite de 10 endpoints por organização atingido.` (10 endpoints per organization). | | `404` | `Endpoint não encontrado.` (endpoint not found). | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Delete a webhook endpoint ```http DELETE https://api.diska.ai/v1/webhook-endpoints/{endpoint_id} ``` **Scope:** `webhooks:manage` Deliveries stop at once. ## Parameters ### Path | Name | Type | Required | Description | | ------------- | ------ | -------- | ------------------ | | `endpoint_id` | string | Yes | The endpoint's ID. | ## Examples ::code-group ```bash [cURL] curl -X DELETE "https://api.diska.ai/v1/webhook-endpoints/" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.delete( "https://api.diska.ai/v1/webhook-endpoints/", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/webhook-endpoints/', { method: 'DELETE', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] '); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'DELETE', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: endpoint_id in: path required: true body-type: none locale: en method: DELETE path: /v1/webhook-endpoints/{endpoint_id} --- :: ## Response `200` | Field | Type | Description | | ---------------------- | -------------- | ----------------------------------------------------------------- | | `id` | string | Endpoint ID. | | `url` | string | Delivery destination. | | `description` | string \| null | Description. | | `events` | array | Subscribed events. | | `active` | boolean | `false` when disabled (by you or automatically). Default: `true`. | | `disabled_reason` | string \| null | Why it was disabled automatically, or `null`. | | `failure_count` | integer | Consecutive failed deliveries. Default: `0`. | | `last_delivery_at` | string \| null | Last delivery. | | `last_delivery_status` | string \| null | Result of the last delivery, for example `delivered (200)`. | | `secret_preview` | string | Start and end of the secret, to identify it. | | `created_at` | string \| null | Creation date (ISO 8601). | ```json { "id": "e7a1c3f5-9b2d-4f6e-8a0c-3d5f7b9e1c24", "url": "https://o-seu-sistema.com/hooks/diska", "description": "CRM — produção", "events": [ "call.completed" ], "active": true, "disabled_reason": null, "failure_count": 0, "last_delivery_at": "2026-10-25T18:40:00Z", "last_delivery_status": "delivered (200)", "secret_preview": "dskw_AbC…wXyZ", "created_at": "2026-10-25T18:40:00Z" } ``` ## Errors | Code | When | | ----- | ------------------------------------------------ | | `404` | `Endpoint não encontrado.` (endpoint not found). | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Test a webhook endpoint ```http POST https://api.diska.ai/v1/webhook-endpoints/{endpoint_id}/test ``` **Scope:** `webhooks:manage` It works even when the endpoint is disabled, and a failed test does not count towards automatic disabling. ## Parameters ### Path | Name | Type | Required | Description | | ------------- | ------ | -------- | ------------------ | | `endpoint_id` | string | Yes | The endpoint's ID. | ## Examples ::code-group ```bash [cURL] curl -X POST "https://api.diska.ai/v1/webhook-endpoints//test" \ -H "Authorization: Bearer $DISKA_API_KEY" ``` ```python [Python] import os import requests response = requests.post( "https://api.diska.ai/v1/webhook-endpoints//test", headers={"Authorization": f"Bearer {os.environ['DISKA_API_KEY']}"}, timeout=30, ) response.raise_for_status() print(response.json()) ``` ```js [JavaScript] // Node.js 18 or later, in a .mjs file const response = await fetch('https://api.diska.ai/v1/webhook-endpoints//test', { method: 'POST', headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) console.log(await response.json()) ``` ```php [PHP] /test'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DISKA_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 400) { throw new RuntimeException("HTTP $status: $body"); } print_r(json_decode($body, true)); ``` :: ## Try it Send the request from this page, with your key. The key stays on this page: it is not stored and is only sent to `api.diska.ai`. Use a test key with the fewest scopes you need. ::api-playground --- params: - name: endpoint_id in: path required: true body-type: none locale: en method: POST path: /v1/webhook-endpoints/{endpoint_id}/test --- :: ## Response `200` | Field | Type | Description | | ------------- | --------------- | ------------------------------------------------------------------------------------------ | | `status` | string | `delivered`, `failed` or `blocked` (the URL now points to an address that is not allowed). | | `attempts` | integer | Attempts made. | | `http_status` | integer \| null | HTTP status your receiver returned. | | `error` | string | Why it failed, only when `status` is not `delivered`. | ```json { "status": "delivered", "attempts": 1, "http_status": 200 } ``` ## Errors | Code | When | | ----- | ------------------------------------------------ | | `404` | `Endpoint não encontrado.` (endpoint not found). | Errors common to every endpoint (`401`, `403`, `422`, `429` and `5xx`) are in [Errors](https://docs.diska.ai/en/api/api-channel#errors). # Webhooks Deliveries, events and signatures are covered in [Webhooks](https://docs.diska.ai/en/api/webhooks). | Method | Endpoint | Description | Scope | | -------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------- | ----------------- | | `GET` | [`/v1/webhook-endpoints`](https://docs.diska.ai/en/api/reference/webhooks/list-webhook-endpoints) | List webhook endpoints | `webhooks:manage` | | `POST` | [`/v1/webhook-endpoints`](https://docs.diska.ai/en/api/reference/webhooks/create-webhook-endpoint) | Create a webhook endpoint | `webhooks:manage` | | `PATCH` | [`/v1/webhook-endpoints/{endpoint_id}`](https://docs.diska.ai/en/api/reference/webhooks/update-webhook-endpoint) | Update a webhook endpoint | `webhooks:manage` | | `DELETE` | [`/v1/webhook-endpoints/{endpoint_id}`](https://docs.diska.ai/en/api/reference/webhooks/delete-webhook-endpoint) | Delete a webhook endpoint | `webhooks:manage` | | `POST` | [`/v1/webhook-endpoints/{endpoint_id}/test`](https://docs.diska.ai/en/api/reference/webhooks/test-webhook-endpoint) | Test a webhook endpoint | `webhooks:manage` | # API reference Every [DISKA API](https://docs.diska.ai/en/api/api-channel) endpoint has a page with its parameters, body and response schemas, examples in cURL, Python, JavaScript and PHP, and a **Try it** form that sends the request from the page. This reference is generated from the [OpenAPI specification](https://api.diska.ai/v1/openapi.json){rel=""nofollow""}. ## Before you start - Base URL: `https://api.diska.ai/v1`. Every request carries the key in the `Authorization: Bearer dsk_…` header — see [Getting started](https://docs.diska.ai/en/api/getting-started). - **Try it** uses your key on this page only: it does not store it and only sends it to `api.diska.ai`. `POST`, `PATCH` and `DELETE` requests change the organization's real data. Use a test key with the fewest scopes you need and revoke it when you are done. - Prefer Postman? Download the collection ([Portuguese](https://docs.diska.ai/api/diska-canal-api.pt.postman_collection.json){rel=""nofollow""} or [English](https://docs.diska.ai/api/diska-canal-api.en.postman_collection.json){rel=""nofollow""}), import it under **Import** and fill in the `apiKey` variable. ## Endpoints ### Identity | Method | Endpoint | Description | Scope | | ------ | ------------------------------------------------------------------------ | ---------------------------- | ----- | | `GET` | [`/v1/me`](https://docs.diska.ai/en/api/reference/identity/get-identity) | Get the key and organization | — | ### Agents | Method | Endpoint | Description | Scope | | ------- | ---------------------------------------------------------------------------------------------- | ---------------- | -------------- | | `GET` | [`/v1/agents`](https://docs.diska.ai/en/api/reference/agents/list-agents) | List agents | `agents:read` | | `GET` | [`/v1/agents/{agent_id}`](https://docs.diska.ai/en/api/reference/agents/get-agent) | Get an agent | `agents:read` | | `PATCH` | [`/v1/agents/{agent_id}`](https://docs.diska.ai/en/api/reference/agents/update-agent) | Update an agent | `agents:write` | | `POST` | [`/v1/agents`](https://docs.diska.ai/en/api/reference/agents/create-agent) | Create an agent | `agents:write` | | `POST` | [`/v1/agents/{agent_id}/publish`](https://docs.diska.ai/en/api/reference/agents/publish-agent) | Publish an agent | `agents:write` | ### Calls | Method | Endpoint | Description | Scope | | ------ | -------------------------------------------------------------------------------------------------- | ---------------------- | ----------------- | | `GET` | [`/v1/calls`](https://docs.diska.ai/en/api/reference/calls/list-calls) | List calls | `calls:read` | | `GET` | [`/v1/calls/{call_id}`](https://docs.diska.ai/en/api/reference/calls/get-call) | Get a call | `calls:read` | | `GET` | [`/v1/calls/{call_id}/recording`](https://docs.diska.ai/en/api/reference/calls/get-call-recording) | Download the recording | `recordings:read` | ### Outbound calls | Method | Endpoint | Description | Scope | | ------ | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------ | ------------- | | `POST` | [`/v1/outbound-calls`](https://docs.diska.ai/en/api/reference/outbound-calls/create-outbound-call) | Make an outbound call | `calls:write` | | `GET` | [`/v1/outbound-calls/{outbound_call_id}`](https://docs.diska.ai/en/api/reference/outbound-calls/get-outbound-call) | Get an outbound call | `calls:read` | | `POST` | [`/v1/outbound-calls/{outbound_call_id}/hangup`](https://docs.diska.ai/en/api/reference/outbound-calls/hang-up-outbound-call) | Hang up an outbound call | `calls:write` | ### Campaigns | Method | Endpoint | Description | Scope | | ------ | --------------------------------------------------------------------------------------------------------------------- | ----------------- | ----------------- | | `GET` | [`/v1/campaigns`](https://docs.diska.ai/en/api/reference/campaigns/list-campaigns) | List campaigns | `campaigns:read` | | `POST` | [`/v1/campaigns`](https://docs.diska.ai/en/api/reference/campaigns/create-campaign) | Create a campaign | `campaigns:write` | | `GET` | [`/v1/campaigns/{campaign_id}`](https://docs.diska.ai/en/api/reference/campaigns/get-campaign) | Get a campaign | `campaigns:read` | | `POST` | [`/v1/campaigns/{campaign_id}/recipients`](https://docs.diska.ai/en/api/reference/campaigns/add-campaign-recipients) | Add recipients | `campaigns:write` | | `GET` | [`/v1/campaigns/{campaign_id}/recipients`](https://docs.diska.ai/en/api/reference/campaigns/list-campaign-recipients) | List recipients | `campaigns:read` | | `POST` | [`/v1/campaigns/{campaign_id}/start`](https://docs.diska.ai/en/api/reference/campaigns/start-campaign) | Start a campaign | `campaigns:write` | | `POST` | [`/v1/campaigns/{campaign_id}/pause`](https://docs.diska.ai/en/api/reference/campaigns/pause-campaign) | Pause a campaign | `campaigns:write` | | `POST` | [`/v1/campaigns/{campaign_id}/resume`](https://docs.diska.ai/en/api/reference/campaigns/resume-campaign) | Resume a campaign | `campaigns:write` | | `POST` | [`/v1/campaigns/{campaign_id}/cancel`](https://docs.diska.ai/en/api/reference/campaigns/cancel-campaign) | Cancel a campaign | `campaigns:write` | ### Chat | Method | Endpoint | Description | Scope | | ------ | ------------------------------------------------------------------------------------------------ | -------------- | ------------- | | `POST` | [`/v1/chats`](https://docs.diska.ai/en/api/reference/chats/create-chat) | Create a chat | `chats:write` | | `POST` | [`/v1/chats/{chat_id}/messages`](https://docs.diska.ai/en/api/reference/chats/send-chat-message) | Send a message | `chats:write` | | `GET` | [`/v1/chats/{chat_id}`](https://docs.diska.ai/en/api/reference/chats/get-chat) | Get a chat | `chats:write` | | `GET` | [`/v1/chats`](https://docs.diska.ai/en/api/reference/chats/list-chats) | List chats | `chats:write` | | `POST` | [`/v1/chats/{chat_id}/end`](https://docs.diska.ai/en/api/reference/chats/end-chat) | End a chat | `chats:write` | ### Analytics | Method | Endpoint | Description | Scope | | ------ | ----------------------------------------------------------------------------------------- | ------------------ | ---------------- | | `GET` | [`/v1/analytics/overview`](https://docs.diska.ai/en/api/reference/analytics/get-overview) | Analytics overview | `analytics:read` | ### Phone numbers | Method | Endpoint | Description | Scope | | ------ | ---------------------------------------------------------------------------------------------- | ------------------ | -------------------- | | `GET` | [`/v1/phone-numbers`](https://docs.diska.ai/en/api/reference/phone-numbers/list-phone-numbers) | List phone numbers | `phone-numbers:read` | ### Knowledge | Method | Endpoint | Description | Scope | | ------ | ------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ----------------- | | `GET` | [`/v1/knowledge-bases`](https://docs.diska.ai/en/api/reference/knowledge/list-knowledge-bases) | List knowledge bases | `knowledge:read` | | `POST` | [`/v1/knowledge-bases`](https://docs.diska.ai/en/api/reference/knowledge/create-knowledge-base) | Create a knowledge base | `knowledge:write` | | `POST` | [`/v1/knowledge-bases/{knowledge_base_id}/documents`](https://docs.diska.ai/en/api/reference/knowledge/add-text-document) | Add a text document | `knowledge:write` | | `POST` | [`/v1/knowledge-bases/{knowledge_base_id}/documents/url`](https://docs.diska.ai/en/api/reference/knowledge/import-url) | Import a web page | `knowledge:write` | | `POST` | [`/v1/knowledge-bases/{knowledge_base_id}/documents/pdf`](https://docs.diska.ai/en/api/reference/knowledge/upload-pdf) | Upload a PDF | `knowledge:write` | ### Webhooks | Method | Endpoint | Description | Scope | | -------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------- | ----------------- | | `GET` | [`/v1/webhook-endpoints`](https://docs.diska.ai/en/api/reference/webhooks/list-webhook-endpoints) | List webhook endpoints | `webhooks:manage` | | `POST` | [`/v1/webhook-endpoints`](https://docs.diska.ai/en/api/reference/webhooks/create-webhook-endpoint) | Create a webhook endpoint | `webhooks:manage` | | `PATCH` | [`/v1/webhook-endpoints/{endpoint_id}`](https://docs.diska.ai/en/api/reference/webhooks/update-webhook-endpoint) | Update a webhook endpoint | `webhooks:manage` | | `DELETE` | [`/v1/webhook-endpoints/{endpoint_id}`](https://docs.diska.ai/en/api/reference/webhooks/delete-webhook-endpoint) | Delete a webhook endpoint | `webhooks:manage` | | `POST` | [`/v1/webhook-endpoints/{endpoint_id}/test`](https://docs.diska.ai/en/api/reference/webhooks/test-webhook-endpoint) | Test a webhook endpoint | `webhooks:manage` | # Sync calls with your CRM In this guide, each completed call reaches your server by [webhook](https://docs.diska.ai/en/api/webhooks), without polling. The receiver: 1. checks the signature; 2. ignores retries; 3. answers right away; 4. in a queue, reads the call's detail and creates or updates the contact and the activity in your CRM. A daily reconciliation catches anything that was missed. ## Before you start - An [API key](https://docs.diska.ai/en/api/authentication) with the **Webhooks — gestão** (`webhooks:manage`) and **Chamadas e transcrições** (`calls:read`) scopes. - A server reachable from the internet over `https://`. - Python 3.11 or later with `flask` and `requests`, or Node.js 18 or later. ## 1. Write the receiver ::code-group ```python [Python] import hashlib import hmac import json import os import queue import threading import time import requests from flask import Flask, request API = "https://api.diska.ai/v1" API_KEY = os.environ["DISKA_API_KEY"] SECRET = os.environ["DISKA_WEBHOOK_SECRET"] app = Flask(__name__) jobs: queue.Queue = queue.Queue() seen: set[str] = set() # in production: a table with X-Diska-Delivery as a unique key def is_valid(timestamp: str, body: bytes, signature: str) -> bool: if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300: return False expected = hmac.new(SECRET.encode(), f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest() return hmac.compare_digest(f"sha256={expected}", signature) @app.post("/hooks/diska") def receive(): body = request.get_data() # the raw body, before parsing the JSON timestamp = request.headers.get("X-Diska-Timestamp", "") if not is_valid(timestamp, body, request.headers.get("X-Diska-Signature", "")): return "", 401 delivery = request.headers.get("X-Diska-Delivery", "") if delivery in seen: return "", 200 # a retry of a delivery you already received seen.add(delivery) event = json.loads(body) if event.get("event") == "call.completed": jobs.put(event) # process outside the request: answer within 10 seconds return "", 200 def crm_upsert(phone: str | None, name: str | None, activity: dict) -> None: # Replace with your CRM's API call: look the contact up by phone, # create it if it does not exist and add the activity with the call id. print("CRM", phone, name, activity) def sync_call(event: dict) -> None: response = requests.get( f"{API}/calls/{event['call_id']}", headers={"Authorization": f"Bearer {API_KEY}"}, timeout=30, ) response.raise_for_status() call = response.json() crm_upsert( phone=event.get("caller_contact"), name=call.get("caller_name"), activity={ "diska_call_id": call["id"], "started_at": call["started_at"], "duration_seconds": call["duration_seconds"], "agent": call["agent_name"], "summary": call["summary"], "sentiment": event.get("sentiment"), "data": event.get("extracted_data", {}), }, ) def worker() -> None: while True: event = jobs.get() try: sync_call(event) except Exception as exc: # the daily reconciliation catches what fails here print("sync failed", event["call_id"], exc) finally: jobs.task_done() threading.Thread(target=worker, daemon=True).start() ``` ```js [Node.js] // Node.js 18 or later, in a .mjs file import crypto from 'node:crypto' import http from 'node:http' const API = 'https://api.diska.ai/v1' const { DISKA_API_KEY, DISKA_WEBHOOK_SECRET } = process.env const seen = new Set() // in production: a table with X-Diska-Delivery as a unique key function isValid(timestamp, rawBody, signature) { if (!/^\d+$/.test(timestamp || '') || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false const expected = 'sha256=' + crypto.createHmac('sha256', DISKA_WEBHOOK_SECRET) .update(`${timestamp}.`).update(rawBody).digest('hex') const a = Buffer.from(expected) const b = Buffer.from(signature || '') return a.length === b.length && crypto.timingSafeEqual(a, b) } async function crmUpsert(phone, name, activity) { // Replace with your CRM's API call: look the contact up by phone, // create it if it does not exist and add the activity with the call id. console.log('CRM', phone, name, activity) } async function syncCall(event) { const response = await fetch(`${API}/calls/${event.call_id}`, { headers: { Authorization: `Bearer ${DISKA_API_KEY}` } }) if (!response.ok) throw new Error(`HTTP ${response.status}`) const call = await response.json() await crmUpsert(event.caller_contact, call.caller_name, { diska_call_id: call.id, started_at: call.started_at, duration_seconds: call.duration_seconds, agent: call.agent_name, summary: call.summary, sentiment: event.sentiment, data: event.extracted_data ?? {} }) } http.createServer((req, res) => { if (req.method !== 'POST' || req.url !== '/hooks/diska') return res.writeHead(404).end() const chunks = [] req.on('data', chunk => chunks.push(chunk)) req.on('end', () => { const rawBody = Buffer.concat(chunks) // the raw body, before parsing the JSON if (!isValid(req.headers['x-diska-timestamp'], rawBody, req.headers['x-diska-signature'])) return res.writeHead(401).end() res.writeHead(200).end() // answer now; process afterwards const delivery = req.headers['x-diska-delivery'] if (seen.has(delivery)) return // a retry of a delivery you already received seen.add(delivery) const event = JSON.parse(rawBody) if (event.event === 'call.completed') { syncCall(event).catch(err => console.error('sync failed', event.call_id, err)) // the reconciliation catches what fails } }) }).listen(Number(process.env.PORT || 3000)) ``` :: What the receiver does, in order: - **Checks the signature** over the raw body, with the endpoint's secret. A request without a valid signature gets `401`. See [Verify the signature](https://docs.diska.ai/en/api/webhooks#verify-the-signature). - **Ignores retries.** A repeated delivery carries the same `X-Diska-Delivery`. - **Answers right away** with `200`, and processes afterwards: Diska waits at most 10 seconds. - **Reads the call's detail** at [`GET /v1/calls/{call_id}`](https://docs.diska.ai/en/api/reference/calls/get-call), for the summary, the duration and the caller's name. The event already carries the sentiment and the extracted data. - **Calls your CRM** in `crm_upsert` / `crmUpsert`. Replace the `print` with your CRM's API, and use `diska_call_id` as the activity's unique key so it is never created twice. The test event (`ping`) also gets `200`, so step 3 works. To run the receiver, with the `DISKA_API_KEY` and `DISKA_WEBHOOK_SECRET` variables set: ```bash pip install flask requests flask --app receiver run --port 3000 # Python node receiver.mjs # Node.js (port 3000) ``` In production, put it behind your web server or proxy, with HTTPS. ## 2. Register the endpoint ```bash curl -X POST https://api.diska.ai/v1/webhook-endpoints \ -H "Authorization: Bearer $DISKA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"url": "https://your-system.com/hooks/diska", "description": "CRM", "events": ["call.completed"]}' ``` The response carries the `secret` (`dskw_…`) **only this once**. Save it in `DISKA_WEBHOOK_SECRET` and restart the receiver. Keep the `endpoint.id` too. ## 3. Test ```bash curl -X POST https://api.diska.ai/v1/webhook-endpoints//test \ -H "Authorization: Bearer $DISKA_API_KEY" ``` The response should carry `"status": "delivered"`. If it says `failed`, the `error` field says why: unreachable URL, invalid certificate, or the receiver answered `401` because the secret is wrong. Then call the agent's number and end the call normally. When post-call processing finishes, the receiver gets `call.completed` and the contact shows up in your CRM. ## 4. Reconcile once a day Deliveries are best effort: if your server is down during the retries, the event is lost. The source of truth is [`GET /v1/calls`](https://docs.diska.ai/en/api/reference/calls/list-calls). This script walks the completed calls of the last few days: ::code-group ```python [Python] import os import time from datetime import datetime, timedelta, timezone import requests API = "https://api.diska.ai/v1" session = requests.Session() session.headers["Authorization"] = f"Bearer {os.environ['DISKA_API_KEY']}" def get(path: str, params: dict | None = None) -> dict: while True: response = session.get(f"{API}{path}", params=params, timeout=60) if response.status_code == 429: # rate limit: wait as long as the API says time.sleep(int(response.headers.get("Retry-After", "5"))) continue response.raise_for_status() return response.json() def calls_since(since: datetime): """Completed calls since `since`, most recent first.""" params = {"cursor": "start", "limit": 200, "status": "completed"} while True: page = get("/calls", params) for call in page["items"]: if call["started_at"] and datetime.fromisoformat(call["started_at"]) < since: return # the list is newest first: you can stop here yield call if not page["next_cursor"]: return params["cursor"] = page["next_cursor"] since = datetime.now(timezone.utc) - timedelta(days=2) # a little more than the time between runs for call in calls_since(since): print("check in the CRM:", call["id"], call["started_at"]) # create the activity if it does not exist yet ``` :: Run it once a day, for example with `cron`, and create the activity in your CRM for any call that is not there. Because the list is newest first, the script stops at the first call older than the cut-off date. ## For production - Keep the processed `X-Diska-Delivery` values in a table, not in memory: the receiver can restart. - Use a persistent queue (for example Redis or SQS) instead of the in-memory one. - Log sync failures: the reconciliation recovers them, but you want to know they happened. - Watch the endpoint: [`GET /v1/webhook-endpoints`](https://docs.diska.ai/en/api/reference/webhooks/list-webhook-endpoints) shows `failure_count` and `active`. After 20 consecutive failures the endpoint is disabled; once fixed, re-enable it with `{"active": true}`. # Export the call history This guide exports the organization's calls with [`GET /v1/calls`](https://docs.diska.ai/en/api/reference/calls/list-calls). It uses [cursor pagination](https://docs.diska.ai/en/api/api-channel#pagination), which costs the same on any page, even with hundreds of thousands of calls. ## Before you start - An [API key](https://docs.diska.ai/en/api/authentication) with the **Chamadas e transcrições** (`calls:read`) scope. - Python 3.11 or later with `requests`, or Node.js 18 or later. ## Export to CSV ::code-group ```python [Python] import csv import os import time import requests API = "https://api.diska.ai/v1" FIELDS = [ "id", "started_at", "ended_at", "duration_seconds", "channel", "direction", "status", "agent_name", "caller_name", "caller_contact", "end_reason", "summary", ] session = requests.Session() session.headers["Authorization"] = f"Bearer {os.environ['DISKA_API_KEY']}" def get(path: str, params: dict | None = None) -> dict: while True: response = session.get(f"{API}{path}", params=params, timeout=60) if response.status_code == 429: # rate limit: wait as long as the API says time.sleep(int(response.headers.get("Retry-After", "5"))) continue response.raise_for_status() return response.json() params = {"cursor": "start", "limit": 200} # optional filters: agent_id, status, channel total = 0 with open("calls.csv", "w", newline="", encoding="utf-8") as file: writer = csv.DictWriter(file, fieldnames=FIELDS, extrasaction="ignore") writer.writeheader() while True: page = get("/calls", params) writer.writerows(page["items"]) total += len(page["items"]) if not page["next_cursor"]: break params["cursor"] = page["next_cursor"] print(f"{total} calls exported to calls.csv") ``` ```js [Node.js] // Node.js 18 or later, in a .mjs file import { createWriteStream } from 'node:fs' import { setTimeout as sleep } from 'node:timers/promises' const API = 'https://api.diska.ai/v1' const FIELDS = ['id', 'started_at', 'ended_at', 'duration_seconds', 'channel', 'direction', 'status', 'agent_name', 'caller_name', 'caller_contact', 'end_reason', 'summary'] async function get(path, params) { for (;;) { const response = await fetch(`${API}${path}?${new URLSearchParams(params)}`, { headers: { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } }) if (response.status === 429) { // rate limit: wait as long as the API says await sleep(1000 * Number(response.headers.get('retry-after') || 5)) continue } if (!response.ok) throw new Error(`${response.status} ${await response.text()}`) return response.json() } } const cell = value => `"${String(value ?? '').replaceAll('"', '""')}"` const out = createWriteStream('calls.csv') out.write(FIELDS.join(',') + '\n') const params = { cursor: 'start', limit: 200 } // optional filters: agent_id, status, channel let total = 0 for (;;) { const page = await get('/calls', params) for (const call of page.items) out.write(FIELDS.map(f => cell(call[f])).join(',') + '\n') total += page.items.length if (!page.next_cursor) break params.cursor = page.next_cursor } out.end() console.log(`${total} calls exported to calls.csv`) ``` :: - The first page asks for `cursor=start`; the next ones use the `next_cursor` received. When `next_cursor` is `null`, you are done. - `limit=200` is the maximum per page. - If the API answers `429`, the script waits as long as the `Retry-After` header says and repeats the request. - To export only part of it, add filters to `params`: `agent_id`, `status` or `channel`. See the [parameters](https://docs.diska.ai/en/api/reference/calls/list-calls#parameters). ## Include transcripts The list does not carry the transcript. To get it, ask for each call's detail and save one JSON line per call: ::code-group ```python [Python] import json import os import time import requests API = "https://api.diska.ai/v1" session = requests.Session() session.headers["Authorization"] = f"Bearer {os.environ['DISKA_API_KEY']}" def get(path: str, params: dict | None = None) -> dict: while True: response = session.get(f"{API}{path}", params=params, timeout=60) if response.status_code == 429: time.sleep(int(response.headers.get("Retry-After", "5"))) continue response.raise_for_status() return response.json() params = {"cursor": "start", "limit": 200, "status": "completed"} with open("calls.jsonl", "w", encoding="utf-8") as file: while True: page = get("/calls", params) for call in page["items"]: detail = get(f"/calls/{call['id']}") # transcript, actions and post-call result file.write(json.dumps(detail, ensure_ascii=False) + "\n") time.sleep(0.5) # at most 120 requests per minute per key if not page["next_cursor"]: break params["cursor"] = page["next_cursor"] ``` :: Each line has the same content as [`GET /v1/calls/{call_id}`](https://docs.diska.ai/en/api/reference/calls/get-call): transcript (`messages`), executed actions and post-call result. The script makes one request per call and waits half a second between them to stay under 120 requests per minute: 10,000 calls take about an hour and a half. ## Export only what is new The API does not filter by date, but the list is newest first. To export only since the last run, stop when `started_at` is older than that date, like the `calls_since` function in [Sync calls with your CRM](https://docs.diska.ai/en/api/guides/sync-calls-crm#4-reconcile-once-a-day). ## Take care - Exports contain personal data: contacts, names and what was said. Store them with the same care as the rest of your customers' data. - Recording audio is not exported by the API. Listen to recordings in [History](https://docs.diska.ai/en/history/recordings). # Feed knowledge from your website This guide creates a [knowledge base](https://docs.diska.ai/en/knowledge-base) with your website's content. The script reads `sitemap.xml`, imports each page by its address and uploads the PDFs. At the end it says how many documents it imported and which ones failed. ## Before you start - An [API key](https://docs.diska.ai/en/api/authentication) with the **Conhecimento — escrita** (`knowledge:write`) scope. - The address of your website's `sitemap.xml`. - Python 3.11 or later with `requests`, or Node.js 18 or later. ## The script ::code-group ```python [Python] import os import re import time from urllib.parse import urlparse import requests API = "https://api.diska.ai/v1" SITEMAP = "https://www.exemplo.ao/sitemap.xml" # your website's sitemap MAX_PAGES = 100 session = requests.Session() session.headers["Authorization"] = f"Bearer {os.environ['DISKA_API_KEY']}" def post(path: str, **kwargs) -> requests.Response: while True: response = session.post(f"{API}{path}", timeout=60, **kwargs) if response.status_code == 429: # rate limit: wait as long as the API says time.sleep(int(response.headers.get("Retry-After", "5"))) continue return response # 1. A new base for the website's content. response = post("/knowledge-bases", json={ "name": "Website", "instruction": "Use this base to answer questions about the company, its products and prices, with the information on the website.", }) response.raise_for_status() base_id = response.json()["id"] # 2. The sitemap's pages. sitemap = requests.get(SITEMAP, timeout=30) sitemap.raise_for_status() urls = re.findall(r"\s*([^<\s]+)\s*", sitemap.text)[:MAX_PAGES] # 3. Each page as a document: web pages by URL, PDFs by upload. imported, failed = 0, [] for url in urls: name = urlparse(url).path.strip("/") or "Home page" if url.lower().endswith(".pdf"): pdf = requests.get(url, timeout=60) result = post(f"/knowledge-bases/{base_id}/documents/pdf", files={"file": (name, pdf.content, "application/pdf")}) else: result = post(f"/knowledge-bases/{base_id}/documents/url", json={"name": name[:200], "url": url}) if result.status_code == 201: imported += 1 else: failed.append((url, result.json().get("detail"))) time.sleep(0.5) # at most 120 requests per minute per key print(f"Base {base_id}: {imported} documents imported") for url, detail in failed: print("failed:", url, "—", detail) ``` ```js [Node.js] // Node.js 18 or later, in a .mjs file import { setTimeout as sleep } from 'node:timers/promises' const API = 'https://api.diska.ai/v1' const SITEMAP = 'https://www.exemplo.ao/sitemap.xml' // your website's sitemap const MAX_PAGES = 100 const auth = { Authorization: `Bearer ${process.env.DISKA_API_KEY}` } async function post(path, init) { for (;;) { const response = await fetch(`${API}${path}`, { method: 'POST', ...init, headers: { ...auth, ...init.headers } }) if (response.status !== 429) return response await sleep(1000 * Number(response.headers.get('retry-after') || 5)) // rate limit } } const json = body => ({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) // 1. A new base for the website's content. const created = await post('/knowledge-bases', json({ name: 'Website', instruction: 'Use this base to answer questions about the company, its products and prices, with the information on the website.' })) if (!created.ok) throw new Error(`${created.status} ${await created.text()}`) const base = await created.json() // 2. The sitemap's pages. const xml = await (await fetch(SITEMAP)).text() const urls = [...xml.matchAll(/\s*([^<\s]+)\s*<\/loc>/g)].map(m => m[1]).slice(0, MAX_PAGES) // 3. Each page as a document: web pages by URL, PDFs by upload. let imported = 0 const failed = [] for (const url of urls) { const name = new URL(url).pathname.replace(/^\/+|\/+$/g, '') || 'Home page' let result if (url.toLowerCase().endsWith('.pdf')) { const form = new FormData() form.append('file', new Blob([await (await fetch(url)).arrayBuffer()], { type: 'application/pdf' }), name) result = await post(`/knowledge-bases/${base.id}/documents/pdf`, { body: form }) } else { result = await post(`/knowledge-bases/${base.id}/documents/url`, json({ name: name.slice(0, 200), url })) } if (result.status === 201) imported++ else failed.push([url, (await result.json()).detail]) await sleep(500) // at most 120 requests per minute per key } console.log(`Base ${base.id}: ${imported} documents imported`) for (const [url, detail] of failed) console.log('failed:', url, '—', detail) ``` :: - Each page is imported with [Import a web page](https://docs.diska.ai/en/api/reference/knowledge/import-url). The page must answer within 15 seconds, be up to 2 MB and be HTML, text or JSON. Private or internal addresses are refused. - PDFs are downloaded and uploaded with [Upload a PDF](https://docs.diska.ai/en/api/reference/knowledge/upload-pdf), up to 25 MB. - Each document is named after the page's path (`products/phones`), so you can recognize it in the backoffice. - `MAX_PAGES` caps how many pages it imports. Start with a few and check the result. - If your sitemap is an index (it lists other sitemaps instead of pages), run the script for each sitemap in the list. Pages that fail are listed at the end, with the reason — for example `A página não devolveu texto legível.` (no readable text) when the page only shows content through JavaScript. ## Link the base to the agent The API creates the base but does not assign it to an agent. In the backoffice: 1. Open the base under **Conhecimento** (Knowledge) and check that the documents were indexed. 2. Assign it to the agent, as in [Assign bases to an agent](https://docs.diska.ai/en/knowledge-base#assign-bases-to-an-agent). 3. Publish the agent, in the backoffice or with [Publish an agent](https://docs.diska.ai/en/api/reference/agents/publish-agent). Calls only use a new base after you publish. ## Update the content The DISKA API does not list, change or delete documents yet. To add new pages, import them into the same base: a new document in a base that is already assigned takes effect at once. To redo everything, run the script into a new base, switch the agent's base and publish it, then delete the old base under **Conhecimento**. # API guides Each guide solves a real case from start to finish, with code ready to adapt. The code was tested against a replica of the API with the same responses as the [reference](https://docs.diska.ai/en/api/reference). ::card-group :::card --- description: Each completed call reaches your server by webhook and creates or updates the contact and the activity in your CRM. icon: i-lucide-refresh-cw title: Sync calls with your CRM to: https://docs.diska.ai/en/api/guides/sync-calls-crm --- ::: :::card --- description: The whole history to CSV, or with transcripts to JSONL, using cursor pagination. icon: i-lucide-download title: Export the call history to: https://docs.diska.ai/en/api/guides/export-call-history --- ::: :::card --- description: Reads your website's sitemap and imports every page and every PDF into a knowledge base. icon: i-lucide-globe title: Feed knowledge from your website to: https://docs.diska.ai/en/api/guides/knowledge-from-website --- ::: :: # Versioning and changelog ## Versioning policy The major version is in the path: `https://api.diska.ai/v1`. Within `/v1`, Diska only makes compatible changes: an integration that works today keeps working without changes. ### Compatible changes They can happen at any time and are recorded in the [changelog](https://docs.diska.ai/#changelog): - new endpoints; - new fields in responses and webhooks; - new optional parameters or request fields; - new values in state or type fields (for example, a new `channel` or `status`); - new webhook events (you only get them if you subscribe); - different wording in error messages (`detail`); - more generous rate limits. For your integration to take these changes: - ignore fields you do not know; - handle unknown state or type values without failing; - decide on the HTTP status code, not on the wording of error messages; - do not rely on field order; - treat IDs as opaque text. ### Breaking changes Removing or renaming an endpoint or a field, changing a type, making an optional parameter required or changing how you authenticate only happens in a new major version (`/v2`). In that case: - the new version is announced on this page, with what changes and how to migrate; - `/v1` keeps working for at least **6 months** after the announcement. The exception is urgent security fixes, which can change a behaviour without prior notice. They are recorded here too. ### Specification version The `info.version` field of the [OpenAPI specification](https://docs.diska.ai/en/api/api-channel#openapi-specification) follows `MAJOR.MINOR.PATCH`: | Part | Goes up when | | ------- | ------------------------------------------------------------------------------- | | `MAJOR` | There is a new major version in the path (`/v2`). | | `MINOR` | There are new features or visible changes to the specification, all compatible. | | `PATCH` | There are fixes with no effect on the contract. | ## Changelog ### 1.4.0 — November 2026 - **OAuth for partner platforms** (pilot): a platform connects to DISKA companies with authorization code + PKCE; the token (`dsk_oat_…`) uses the same `/v1` endpoints, only in the granted company and with the granted permissions. New endpoints `/oauth/token`, `/oauth/revoke`, `/.well-known/oauth-authorization-server` and `GET /v1/oauth/token-info`. See [OAuth for partner platforms](https://docs.diska.ai/en/api/oauth). - `GET /v1/me` with an OAuth token returns `app` (and `key` as `null`). With an API key the response is unchanged. ### 1.3.0 — 1 November 2026 - **Edit agents:** `PATCH /v1/agents/{agent_id}` changes the draft (prompt, greeting, language, personality, objections, notes and knowledge bases). `GET /v1/agents/{agent_id}` now carries `configuration` and `has_unpublished_changes`. - **Recordings:** `GET /v1/calls/{call_id}/recording` redirects to a 5-minute signed link, or returns it as JSON. New scope `recordings:read`. - **Outbound calls:** `POST /v1/outbound-calls`, `GET /v1/outbound-calls/{outbound_call_id}` and `…/hangup`. New scope `calls:write`. - **Campaigns:** `/v1/campaigns` — create, add and list recipients, start, pause, resume and cancel. New scopes `campaigns:read` and `campaigns:write`. - **Chat:** `/v1/chats` — text chat with an agent, with the reply in the same request. Ending the chat sends `call.completed`. New scope `chats:write`. Chats show in `GET /v1/calls` with channel `web_chat`. - Outbound calls, campaigns and chat are switched on by Diska per organization. Keys with full access gain the new scopes. ### 1.2.0 — 1 November 2026 - The OpenAPI specification declares authentication as security schemes (`bearerAuth` and `apiKeyHeader`) instead of repeating the `X-API-Key` header as a parameter on every operation. The API works as before: both ways of sending the key remain valid. - The API accepts browser requests from `docs.diska.ai`, for **Try it** in the [API reference](https://docs.diska.ai/en/api/reference). - The specification's description points to [Getting started](https://docs.diska.ai/en/api/getting-started) and to the reference. ### 11 September 2026 - The transcript of `GET /v1/calls/{call_id}` (`messages`) now comes grouped into full turns. Before, on realtime web calls, each streamed fragment — sometimes a single word — was an entry. The format of each entry does not change. ### 1.1.0 — 6 August 2026 DISKA API launch: - organization API keys, with scopes and an expiry date; - agents: list, read, create and publish; - calls: list with offset and cursor pagination, and the detail with transcript, executed actions and post-call result; - analytics, phone numbers and knowledge bases (text, web page and PDF); - signed `call.completed` webhooks, with retries and automatic disabling; - a limit of 120 requests per minute per key; - the OpenAPI specification at `/v1/openapi.json`. # OAuth for partner platforms If your platform (a sales system, a CRM, an ERP) wants to use DISKA **on behalf of its customers**, use OAuth 2.0. The customer clicks "Connect with DISKA", picks the company and the permissions on a DISKA screen, and your platform receives a token that only works for that company. | | API key | OAuth | | ------------------ | -------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | For whom | A company integrating its own systems | A platform serving many companies | | How it is obtained | The customer copies it from **Definições → Chaves API** (Settings → API keys) and pastes it into your platform | The customer authorizes on a DISKA screen | | Scope | The key's scopes (no scopes = full access) | Only the permissions the customer left checked | | Revoking | The customer deletes the key | The customer disconnects the app in **Definições → Aplicações ligadas** (Settings → Connected apps), or the app revokes | ::callout{type="info"} OAuth apps are in **pilot** . To register your platform, contact DISKA: we switch the feature on for your organization. :: The flow is standard OAuth 2.1: **authorization code with PKCE** (S256, mandatory), one-hour access tokens and **rotating** refresh tokens. ## Endpoints | | URL | | ----------------------- | --------------------------------------------------------------------------------------------------------------- | | Metadata (RFC 8414) | `https://api.diska.ai/.well-known/oauth-authorization-server` | | Authorization (browser) | `https://app.diska.ai/oauth/authorize` | | Token | `POST https://api.diska.ai/oauth/token` | | Revocation (RFC 7009) | `POST https://api.diska.ai/oauth/revoke` | | Token information | `GET https://api.diska.ai/v1/oauth/token-info` | | API | `https://api.diska.ai/v1`, with the same endpoints as the [DISKA API](https://docs.diska.ai/en/api/api-channel) | ## 1. Register the app In **Definições → Apps OAuth** (Settings → OAuth apps; owners and admins of your organization): - **Name**, description, website, privacy policy and logo, shown on the authorization screen. The website, privacy policy and logo must be `https://` addresses. - **Environment**: - **Teste** (test): only members of your organization can authorize it, and only for your organization; `http://localhost` is accepted in redirect URIs. Use it while developing. - **Produção** (live): any DISKA company can authorize it. Until it is **verified by DISKA**, the authorization screen shows a warning and the app is limited to 100 connected companies. Changing a verified app's name, description, logo, website, privacy policy or redirect URIs, or adding permissions, makes it unverified again until DISKA reviews it. - **Redirect URIs**: up to 10, `https://` (or `http://localhost` for test apps). Each request's `redirect_uri` must match one of them **exactly**. - **Permissions**: the ones the app may ask for (see [Permissions](https://docs.diska.ai/#permissions)). You receive the `client_id` (`dsk_app_…`) and the `client_secret` (`dsk_cs_…`). The secret is **shown only once**: keep it on your platform's server, never in a browser or a mobile app. You can generate a new one at any time; the old one stops working immediately, and tokens already issued keep working. ## 2. Send the customer to DISKA For each connection, generate: - a random `state`, stored in the user's session (CSRF protection); - a random `code_verifier` (43 to 128 characters from `A-Z a-z 0-9 - . _ ~`) and its `code_challenge` = base64url(SHA-256(`code_verifier`)), without trailing `=`. Then redirect the browser: ```text https://app.diska.ai/oauth/authorize ?response_type=code &client_id=dsk_app_… &redirect_uri=https://app.example.com/integrations/diska/callback &scope=organization:read agents:read calls:read calls:write &state=… &code_challenge=… &code_challenge_method=S256 ``` | Parameter | | | ----------------------------------------- | ---------------------------------------------------------------------------- | | `response_type` | Always `code`. | | `client_id` | Your app's. | | `redirect_uri` | One of the registered ones, exactly. | | `scope` | Space-separated permissions. Omitted = every permission the app may ask for. | | `state` | Required. Returned unchanged. | | `code_challenge`, `code_challenge_method` | PKCE; `S256` only. | On the DISKA screen the customer signs in (if needed), picks the company (only owners and admins can connect apps) and can **uncheck permissions**. The screen also lists what the app can **never** do: see API keys, manage members, see billing and minutes, change numbers, telephony or WhatsApp, or delete the company. ## 3. Receive the code If the customer approves, the browser returns to your `redirect_uri`: ```text https://app.example.com/integrations/diska/callback?code=dsk_ac_…&state=… ``` Check that `state` is the one you stored. The code is valid for **60 seconds**, **once**. If the customer declines, or the request is wrong once `client_id` and `redirect_uri` have been validated, it returns with an error: ```text …/callback?error=access_denied&error_description=…&state=… ``` An unknown `client_id` or an unregistered `redirect_uri` does **not** return to your app: the error is shown on the DISKA screen. ## 4. Exchange the code for tokens From your server, with HTTP Basic authentication (`client_id:client_secret`) and an `application/x-www-form-urlencoded` body: ```bash curl -X POST https://api.diska.ai/oauth/token \ -u "dsk_app_…:dsk_cs_…" \ -d grant_type=authorization_code \ -d code=dsk_ac_… \ -d redirect_uri=https://app.example.com/integrations/diska/callback \ -d code_verifier=… ``` You may send `client_id` and `client_secret` in the body instead of Basic, but not both. Response `200`: ```json { "access_token": "dsk_oat_…", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "dsk_ort_…", "scope": "organization:read agents:read calls:read calls:write", "organization": { "id": "6f1c…", "name": "Loja Kianda", "nif": "5000000000" } } ``` - `scope` is what the customer **granted**, which may be less than you asked for. - `organization` identifies the company. `nif` is sent only with the `organization:read` permission; without it, it is `null`. Store the tokens against it. One customer may connect several companies; each has its own tokens. - If the same company authorizes the app again, the permissions become the new ones and the previous tokens stop working. ## 5. Call the API Use the access token like an API key, in the same header: ```bash curl https://api.diska.ai/v1/me \ -H "Authorization: Bearer dsk_oat_…" ``` ```json { "organization": { "id": "6f1c…", "name": "Loja Kianda", "slug": "loja-kianda" }, "key": null, "app": { "client_id": "dsk_app_…", "name": "Vende", "scopes": ["organization:read", "agents:read", "calls:read", "calls:write"] } } ``` Every [DISKA API](https://docs.diska.ai/en/api/reference) endpoint works, always in the token's company and only within the granted permissions. Voice minutes, limits and per-company switches (outbound calls, campaigns, chat) are that company's. `GET /v1/oauth/token-info` returns the app, company, permissions and expiry of the token in use. ## 6. Refresh The access token lasts **1 hour**. Before it expires (or on a `401`), exchange the refresh token for a new pair: ```bash curl -X POST https://api.diska.ai/oauth/token \ -u "dsk_app_…:dsk_cs_…" \ -d grant_type=refresh_token \ -d refresh_token=dsk_ort_… ``` The response has the same shape as step 4. Store **both** new tokens: the refresh token also changes on every refresh (**rotation**), and the previous access token stops working. ::callout{type="warning"} A refresh token works **once** . If an already-used refresh token shows up again, DISKA assumes it was stolen: it **disconnects the company** and the app has to ask for authorization again. Refresh from a single process at a time (for example, with a lock per company) and store the new pair before using it. If the same refresh token arrives twice within 10 seconds (two processes refreshing at once), the second request gets `invalid_grant` and the company is **not** disconnected: use the pair the first request received. :: An unused refresh token expires after **90 days**. Each refresh starts 90 days again. On refresh, `scope` may be omitted; if you send it, it must equal what was granted. ## 7. Revoke When the customer disconnects DISKA in your platform: ```bash curl -X POST https://api.diska.ai/oauth/revoke \ -u "dsk_app_…:dsk_cs_…" \ -d token=dsk_ort_… ``` - Revoking the **refresh token** disconnects the company: every token stops working. - Revoking an **access token** ends only that token. - The response is always `200`, even for an unknown token. The customer can also disconnect the app, or take permissions away, in **Definições → Aplicações ligadas**: it takes effect on the next request. Your app is told by [webhook](https://docs.diska.ai/#app-webhooks). ## Permissions | Permission | Grants | | ----------------------------------- | -------------------------------------------------------------------------------------------- | | `organization:read` | The company's tax number (NIF). The company's id and name always come in the token response. | | `agents:read` | List and view agents. | | `agents:write` | Create, edit and publish agents. | | `calls:read` | Calls, transcripts, post-call results and the `call.completed` webhook. | | `calls:write` | [Outbound calls](https://docs.diska.ai/en/api/reference/outbound-calls). | | `analytics:read` | Analytics. | | `phone-numbers:read` | Numbers. | | `knowledge:read`, `knowledge:write` | Knowledge bases. | | `recordings:read` | Recordings. | | `campaigns:read`, `campaigns:write` | [Campaigns](https://docs.diska.ai/en/api/reference/campaigns). | | `chats:write` | [Chat](https://docs.diska.ai/en/api/reference/chats) with agents. | There is no permission to manage the company's own webhooks (`/v1/webhook-endpoints`): the app receives events on its own [webhook](https://docs.diska.ai/#app-webhooks). A token without a permission gets `403` on that endpoint, even if the company has it on other keys. ## Errors On the token and revocation endpoints, errors follow OAuth (`{"error", "error_description"}`): | HTTP | `error` | When | | ---- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | | 401 | `invalid_client` | Wrong `client_id` or `client_secret`, or missing authentication. | | 400 | `invalid_request` | A missing parameter, or an invalid `code_verifier`. | | 400 | `invalid_grant` | Code or refresh token invalid, expired, already used, issued to another app, or a `redirect_uri`/`code_verifier` that does not match. | | 400 | `invalid_scope` | A `scope` different from the grant on refresh. | | 400 | `unsupported_grant_type` | A `grant_type` other than `authorization_code` or `refresh_token`. | | 400 | `unauthorized_client` | The app is suspended by DISKA. | | 403 | `app_connection_limit` | The (unverified) app reached its limit of connected companies. | | 403 | `organization_suspended` | The company is suspended. The connection stays: refresh once it is reactivated. | On the API (`/v1`), with a token: | HTTP | When | | ---- | ------------------------------------------------------------------------------------------------------------------------------ | | 401 | Invalid, expired or revoked token (`WWW-Authenticate: Bearer error="invalid_token"`). Refresh, or ask for authorization again. | | 403 | Missing permission (`WWW-Authenticate: Bearer error="insufficient_scope", scope="…"`). | | 403 | `Organização suspensa.` (company suspended) | | 402 | The company ran out of voice minutes (only on requests that use voice). | ## App webhooks Each app has **one** webhook URL, set in **Definições → Apps OAuth**, which receives events from every connected company. Setting the URL generates a signing secret (`dskw_…`), shown once. | Event | When | | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `app.authorization.created` | A company connected the app (or connected it again). | | `app.authorization.updated` | The company took permissions away. `data.scopes` has those left. | | `app.authorization.revoked` | The connection ended: by the company, by DISKA, or because a refresh token was reused. Not sent when the app itself revoked. | | `call.completed` | A call ended, in companies that granted `calls:read`. `data` is the same content as the [`call.completed` webhook](https://docs.diska.ai/en/api/webhooks). If the company disconnects the app or removes `calls:read`, pending deliveries are cancelled. | | `ping` | Sent by the **Enviar ping** (send ping) button. | Body: ```json { "id": "0b6f…", "event": "app.authorization.revoked", "created_at": "2026-11-19T10:15:02.123456+00:00", "organization_id": "6f1c…", "data": { "connection_id": "a1b2…", "reason": "member", "revoked_at": "2026-11-19T10:15:02.120000+00:00" } } ``` Headers and signature are the same as the [DISKA API webhooks](https://docs.diska.ai/en/api/webhooks#verify-the-signature): `X-Diska-Event`, `X-Diska-Delivery` (equal to `id`), `X-Diska-Timestamp` and `X-Diska-Signature = sha256=`, with the app's webhook secret. Answer `2xx` within 10 seconds. A failed delivery is retried after **1 min, 5 min, 30 min, 2 h and 8 h** (6 attempts). A `410` response stops the retries. Use `id` to ignore repeats. **Ver entregas** (view deliveries) shows the last 25 deliveries with their status and error. ## Full example ::code-group ```python [Python] import base64, hashlib, os, secrets import requests CLIENT_ID = os.environ["DISKA_CLIENT_ID"] CLIENT_SECRET = os.environ["DISKA_CLIENT_SECRET"] REDIRECT_URI = "https://app.example.com/integrations/diska/callback" def start(session: dict) -> str: """Return the URL to redirect the browser to.""" verifier = secrets.token_urlsafe(48) challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode() session["diska_state"] = secrets.token_urlsafe(24) session["diska_verifier"] = verifier params = { "response_type": "code", "client_id": CLIENT_ID, "redirect_uri": REDIRECT_URI, "scope": "organization:read agents:read calls:read", "state": session["diska_state"], "code_challenge": challenge, "code_challenge_method": "S256", } return requests.Request("GET", "https://app.diska.ai/oauth/authorize", params=params).prepare().url def callback(session: dict, query: dict) -> dict: """Exchange the code for tokens; store them against tokens['organization']['id'].""" if query.get("error"): raise RuntimeError(query.get("error_description") or query["error"]) if query.get("state") != session.pop("diska_state", None): raise RuntimeError("invalid state") response = requests.post( "https://api.diska.ai/oauth/token", auth=(CLIENT_ID, CLIENT_SECRET), data={ "grant_type": "authorization_code", "code": query["code"], "redirect_uri": REDIRECT_URI, "code_verifier": session.pop("diska_verifier"), }, timeout=15, ) response.raise_for_status() return response.json() def refresh(refresh_token: str) -> dict: response = requests.post( "https://api.diska.ai/oauth/token", auth=(CLIENT_ID, CLIENT_SECRET), data={"grant_type": "refresh_token", "refresh_token": refresh_token}, timeout=15, ) response.raise_for_status() return response.json() # store the new pair before using it ``` ```js [Node.js] import crypto from 'node:crypto' const CLIENT_ID = process.env.DISKA_CLIENT_ID const CLIENT_SECRET = process.env.DISKA_CLIENT_SECRET const REDIRECT_URI = 'https://app.example.com/integrations/diska/callback' const basic = 'Basic ' + Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64') export function start(session) { const verifier = crypto.randomBytes(48).toString('base64url') const challenge = crypto.createHash('sha256').update(verifier).digest('base64url') session.diskaState = crypto.randomBytes(24).toString('base64url') session.diskaVerifier = verifier const url = new URL('https://app.diska.ai/oauth/authorize') url.search = new URLSearchParams({ response_type: 'code', client_id: CLIENT_ID, redirect_uri: REDIRECT_URI, scope: 'organization:read agents:read calls:read', state: session.diskaState, code_challenge: challenge, code_challenge_method: 'S256' }) return url.toString() } async function token(body) { const response = await fetch('https://api.diska.ai/oauth/token', { method: 'POST', headers: { 'Authorization': basic, 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(body) }) const json = await response.json() if (!response.ok) throw new Error(json.error_description || json.error) return json } export async function callback(session, query) { if (query.error) throw new Error(query.error_description || query.error) if (query.state !== session.diskaState) throw new Error('invalid state') delete session.diskaState return token({ grant_type: 'authorization_code', code: query.code, redirect_uri: REDIRECT_URI, code_verifier: session.diskaVerifier }) // store the tokens against organization.id } export const refresh = refreshToken => token({ grant_type: 'refresh_token', refresh_token: refreshToken }) ``` :: ## Limits - `POST /oauth/token` and `/oauth/revoke`: 60 requests per minute per app and IP address. - `/v1` with a token: 120 requests per minute **per connected company**, so one company never uses up another's limit. - Outbound calls (`POST /v1/outbound-calls`): up to 200 per day (UTC) **per connected company**. Campaign recipients (`POST /v1/campaigns/{id}/recipients`): up to 2000 per day per connected company. These come on top of the company's own limits; above them the API answers `429` and the company sees it in its audit log. Talk to DISKA if you need more. # API Diska has a public API for server-to-server integrations: the **[DISKA API](https://docs.diska.ai/en/api/api-channel)**. With an organization API key, your system can read agents, calls, transcripts, analytics, phone numbers and knowledge bases, create and publish agents, feed knowledge bases, and register webhooks that notify you when a call ends. ## Base URL ```text https://api.diska.ai/v1 ``` First request — confirms the organization and key behind the token: ```bash curl https://api.diska.ai/v1/me \ -H "Authorization: Bearer dsk_…" ``` Step by step, with examples in cURL, Python, JavaScript and PHP: [Getting started with the API](https://docs.diska.ai/en/api/getting-started). The DISKA API's OpenAPI specification is at `https://api.diska.ai/v1/openapi.json` (no authentication). You can import it into Postman or use it to generate a client. ::callout{type="info"} The backoffice ( `app.diska.ai` ) uses its own internal API, authenticated with the signed-in person's session. That API is not an integration contract: it can change without notice and it does not accept API keys. For integrations, use only the DISKA API. :: ## Contents ::card-group :::card --- description: Create a key and make your first request, with examples in several languages. icon: i-lucide-rocket title: Getting started to: https://docs.diska.ai/en/api/getting-started --- ::: :::card --- description: What you can do, scopes, pagination, limits and errors. icon: i-lucide-plug title: DISKA API to: https://docs.diska.ai/en/api/api-channel --- ::: :::card --- description: Create, use, expire and revoke API keys. icon: i-lucide-key-round title: Authentication to: https://docs.diska.ai/en/api/authentication --- ::: :::card --- description: Receive the data of every completed call in your system. icon: i-lucide-webhook title: Webhooks to: https://docs.diska.ai/en/api/webhooks --- ::: :::card --- description: Platforms serving many companies: one-click connection, per-company tokens. to: /en/api/oauth icon: i-lucide-key-square title: OAuth for partners --- ::: :::card --- description: Full reference for every DISKA API endpoint. icon: i-lucide-list title: Endpoints to: https://docs.diska.ai/en/api/endpoints --- ::: :::card --- description: How people talk to an agent, and what is not a public API. icon: i-lucide-audio-waveform title: Realtime to: https://docs.diska.ai/en/api/realtime --- ::: :::card --- description: Every endpoint on its own page: schemas, examples and Try it. to: /en/api/reference icon: i-lucide-book-marked title: API reference --- ::: :::card --- description: Complete integrations with tested code. icon: i-lucide-map title: Guides to: https://docs.diska.ai/en/api/guides --- ::: :::card --- description: Versioning policy and change history. icon: i-lucide-history title: Versioning and changelog to: https://docs.diska.ai/en/api/changelog --- ::: :: # Cal.com With Cal.com connected, the agent can book a meeting in your calendar during the conversation. The connection belongs to the organization: one Cal.com account serves every agent. ![Connected Cal.com panel, with the authorized account and the Desligar (Disconnect) button](https://docs.diska.ai/images/docs/integrations/calcom-drawer.png) ## Connect 1. In Cal.com, generate an API key in the app settings. 2. In Diska, go to **Definições → Integrações** (Settings → Integrations) and click **Cal.com**. 3. Under **Ligar com Cal.com** (Connect with Cal.com), paste the key into the **Chave API** (API key) field. 4. Click **Ligar** (Connect). *Cal.com ligado* (Cal.com connected) appears and the panel shows **Autorizado por** (Authorized by — the account email) and **Ligado em** (Connected on). The key is validated with Cal.com and stored encrypted on the server; it never stays in the browser. Only the **Owner** and **Admins** can connect or disconnect. ## Use it for bookings 1. Under **Acções → Agendamento em tempo real** (Actions → Real-time booking), create an action. Its **Conta Cal.com** (Cal.com account) section shows the connection status. 2. Under **Evento** (Event), pick the event type from your Cal.com account (use the refresh button if you just created one). 3. Attach the action to the agent, or use it in a flow's [Booking](https://docs.diska.ai/en/nodes/booking) node. The booking confirmation email goes to the `` variable: map it when you attach the action to the agent. Automatic suggestion of free slots is still *em breve* (coming soon): for now, the agent books the time the customer asks for and Cal.com checks availability. See [Real-time booking](https://docs.diska.ai/en/actions/real-time-booking) and the [Book meetings](https://docs.diska.ai/en/guides/book-meetings) guide. ## Disconnect In the Cal.com panel, click **Desligar** (Disconnect). *Cal.com desligado* (Cal.com disconnected) appears. Booking actions can no longer book until you connect again, and publishing a flow with the **Agendamento** (Booking) node may be blocked with *Marcação (calendário) ainda não está ligada a um fornecedor.* (calendar booking is not connected to a provider yet). ## Problems | Message | Cause | | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | *Chave API do Cal.com inválida ou sem permissão.* (invalid key or no permission) | The key is wrong, was revoked or lacks permissions. Generate another one in Cal.com. | | *Não foi possível contactar o Cal.com. Tente novamente.* (could not reach Cal.com) | Temporary network failure. | | *Nenhum tipo de evento encontrado na conta Cal.com.* (no event types found) | Create an event type in Cal.com. | More in [Integration not connecting](https://docs.diska.ai/en/troubleshooting/integration-not-connecting). # Integrations Integrations give agents access to services outside Diska. They are managed under **Definições → Integrações** (Settings → Integrations), by the Owner and Admins — see [Integrations in Settings](https://docs.diska.ai/en/settings/integrations). ## Available | Integration | What for | Who sets it up | | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | [Cal.com](https://docs.diska.ai/en/integrations/calcom) | The agent books meetings in your calendar during the call. | Your organization, with a Cal.com API key. | | **SMS (Ombala)** | SMS during and after the call. See [During-call SMS](https://docs.diska.ai/en/actions/during-call-sms) and [Post-call SMS](https://docs.diska.ai/en/actions/post-call-sms). | Diska (**Gerido pela Diska** badge — managed by Diska). | | [WhatsApp](https://docs.diska.ai/en/whatsapp) | Customers chat with an agent over WhatsApp. | Your organization, by authorizing Diska with Meta. | | [DISKA API and webhooks](https://docs.diska.ai/en/api/api-channel) | Your CRM or system reads data from Diska and receives its events. | Your organization, with [API keys](https://docs.diska.ai/en/settings/api-keys). | | [Custom actions](https://docs.diska.ai/en/actions/custom-actions) | The agent calls one of your APIs during the call. | Your organization, under **Acções** (Actions). | To connect phone numbers, see [Telephony](https://docs.diska.ai/en/telephony). ## Not on the list The **Integrações** page only lists what you can already use. Other services (CRMs, for example) do not have a dedicated integration yet; in the meantime, use the DISKA API and custom actions to connect Diska to your systems. # Phone numbers The **Números** (Numbers) page in the side menu lists the organization's phone numbers. Every member can view it; only the **Owner** and **Admins** can buy, import, delete and assign numbers. ## The numbers list The **Número** (Number) button opens two options: - **Comprar um número DISKA** (Buy a DISKA number) — reserve a number from the DISKA network; it becomes active once the payment is confirmed. - **Importar um número personalizado** (Import a custom number) — connect a number you already use to Diska, over a SIP trunk. See [Connect over SIP](https://docs.diska.ai/en/telephony/sip-trunk). The table shows: | Column | What it shows | | -------------------- | ------------------------------------------------------------------------------------------- | | **Número** (Number) | The number, formatted as +244 959 000 000. | | **Nome** (Name) | The friendly name, if you gave it one. | | **Tipo** (Type) | **Comprado** (purchased — a DISKA number) or **Importado** (imported — your own SIP trunk). | | **Chamadas** (Calls) | Whether the number receives calls. | | **Estado** (Status) | The configuration status (see below). Hover it to read the explanation. | | **SMS** | Whether the number has SMS capability. | | **Agentes** (Agents) | How many agents use the number. | | **Preço** (Price) | The monthly fee in Kz/mês (Kz per month); — for imported numbers. | Each row's **⋮** menu has **Copiar** (Copy) and **Eliminar** (Delete). The page refreshes on its own every few seconds, so a confirmed order or a trunk that just became ready shows up without reloading. ## Number status | Status | Meaning | | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | **Configurado** (Configured) | The number has an agent attached. Availability and routing also depend on the carrier. | | **Sem agente** (No agent) | No agent uses the number. Assign it to an agent so it gets answered. | | **A ativar** (Activating) | Imported number waiting to be activated on the SIP server. | | **Credenciais pendentes** (Credentials pending) | Imported number whose SIP configuration is not complete yet (for example, waiting for SIP registration). | | **Não confirmado** (Not confirmed) | The server has not confirmed the SIP configuration yet. | | **Erro SIP** (SIP error) | The SIP configuration failed. Check the number's details. | | **Desativado** (Disabled) | The number is disabled (for example, suspended by DISKA). | | **Sem chamadas** (No calls) | The number has no call capability. | ::callout{type="warning"} **Configurado** only confirms that an agent is attached. To answer calls, that agent must be of type **Inbound** and be **published** with the number. See [Agent not answering](https://docs.diska.ai/en/troubleshooting/agent-not-answering) . :: ## Buy a DISKA number DISKA numbers are Angolan numbers from the DISKA network, on Africell. The payment is confirmed by the DISKA team. 1. In **Números**, click **Número → Comprar um número DISKA**. 2. The window lists the numbers for sale, with the monthly fee (Kz/mês) and the activation fee. Click **Reservar** (Reserve) on the number you want. 3. The window changes to **Número reservado** (Number reserved) and shows **Reservado até** (Reserved until), **Mensalidade** (Monthly fee), **Taxa de ativação** (Activation fee) and **Primeiro pagamento** (First payment — activation plus the first month), with the payment instructions. 4. Click **Concluir** (Done) and pay as instructed (by default, the DISKA team emails you the payment details). 5. When DISKA confirms the payment, the number appears in the list as **Comprado**, with the status **Sem agente**. Next, [assign it to an agent](https://docs.diska.ai/#assign-to-an-agent). If the list is empty you will see *"De momento não há números DISKA à venda."* (no DISKA numbers for sale right now) — in the meantime, you can import a number with a SIP trunk from your carrier. ### Unpaid orders Until the payment is confirmed, the order shows at the top of the page: the number, the date it is reserved until, the first payment, the following monthly fee and the payment instructions. - **Cancelar encomenda** (Cancel order) asks for confirmation (**Cancelar a encomenda?**) and puts the number back on sale. - If the payment is not confirmed by **Reservado até**, the order expires and the number goes back on sale. - Once the order is completed, cancelled or expired, it no longer shows on the page. Messages you may see when reserving: | Message | What to do | | ------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | *Já tem N encomendas por pagar. Conclua ou cancele uma antes.* (you already have N unpaid orders) | There is a limit on open orders at the same time. Pay or cancel one. | | *A organização atingiu o limite de N números DISKA (X em uso e Y por pagar).* (the organization reached its limit of N DISKA numbers) | DISKA set a maximum number of numbers for the organization. Contact DISKA to raise it. | | *Este número já não está disponível.* (this number is no longer available) | Another organization reserved it first. Pick another one. | ## Number details Click a row to open its details: - the **status**, with its explanation; - **Nome amigável** (Friendly name, optional) — saved when you press Enter or leave the field; - **Tipo**, **Chamadas** and **SMS**; - **Usado em agentes** (Used in agents) — the agents with this number, each linked; - for imported numbers, the **SIP trunk** section (see [Connect over SIP](https://docs.diska.ai/en/telephony/sip-trunk#track-the-status)). ## Assign to an agent 1. Open the agent and click **Publicação** (Publishing) in the toolbar. **Definições de publicação** (Publishing settings) opens. 2. On the **Telefone** (Phone) tab, click **Adicionar número de telefone** (Add phone number). 3. Pick the number. The list shows each number's status and has search; the **Importar** (Import) button opens the SIP trunk import. 4. *Número anexado* (Number attached) appears. 5. **Publish the agent** (**Publicar** button). Calls are answered by the published version, so the assignment only counts once you publish. To switch numbers use the pencil (**Alterar número**, Change number); to remove it use **×** (**Remover número**, Remove number). Publish again after any change. Rules: - Each number receives calls on a **single Inbound agent**. If it is already on another one, you will see *Número já anexado a um agente inbound* (number already attached to an inbound agent). - An **Outbound** agent can use the same number as the Inbound agent, as its caller ID. - A DISKA number can only be assigned while it is active in the organization; otherwise you will see *Este número DISKA não está ativo na organização* (this DISKA number is not active in the organization). - Only active numbers are listed. Without permission, the tab shows *Apenas proprietários e administradores podem atribuir números.* (only owners and admins can assign numbers). - The agent's checklist warns **Número de telefone** (Phone number) when a number is missing. It does not block publishing, but without a number the agent neither answers phone calls nor places the test call. ## Delete or return a number - **Imported number**: **⋮ → Eliminar** and confirm in **Eliminar número?** (Delete number?). The number leaves the organization. - **DISKA number**: it cannot be deleted from the page. If you try, you will see *Este número é uma linha da rede DISKA. Para o devolver, contacte o suporte.* (this is a DISKA network line; contact support to return it). - A DISKA number with the status **Desativado** was suspended by DISKA. Contact support. ## Read numbers over the API Numbers can also be read through the DISKA API: `GET /v1/phone-numbers`, with a key that has the `phone-numbers:read` scope. See [DISKA API](https://docs.diska.ai/en/api/api-channel). # Connect over SIP A **SIP trunk** connects your carrier or your phone system (PBX) to Diska, so agents answer calls on an Angolan number you already own. This guide applies to any SIP-capable carrier or PBX. Calls to the number are then answered by the **Inbound** agent published with it. Importing a number requires the **Owner** or **Admin** role. If you don't have a number yet, buy a DISKA number in [Phone numbers](https://docs.diska.ai/en/telephony/numbers): no SIP setup needed. ::callout{type="info"} **What connecting over SIP supports today** - Angolan numbers (+244 followed by 9 digits), for **incoming calls**. - **UDP** or **TCP** transport to a **public IPv4** address. TLS and SRTP are not available. - Transfers go out through your trunk. The imported number does not send SMS. - The test call from the **Testar** (Test) panel only works with DISKA numbers: validate an imported number with a real call. :: ## Prerequisites - The **Owner** or **Admin** role in the organization. - Your carrier's or PBX's **SIP domain**: a domain or public IPv4, with a port if it is not the usual one. - The **public signalling IPs** that send calls to Diska. They may differ from the registration domain. - SIP **username** and **password**, if the carrier requires registration (REGISTER); otherwise IP authentication. - Firewall rules on your side that let Diska's signalling and audio through (see [Diska SIP addresses](https://docs.diska.ai/#diska-sip-addresses)). - An agent of type **Inbound** to answer the number. ## Diska SIP addresses Send calls to the name `sip.diska.ai`, on port **5080**. Use the IP only in firewall rules. | Use | Address | Port | Protocol | | ------------------------- | -------------------------------- | ----------- | ---------- | | SIP signalling for trunks | `sip.diska.ai` (102.219.124.234) | 5080 | UDP or TCP | | Audio (RTP) | 102.219.124.234 | 16384–16639 | UDP | | SIP over TLS | Not available | — | — | Each call is addressed to the imported number, in international format (E.164): ```text sip:+244923456789@sip.diska.ai:5080 ``` This is the **Origination URI** the number's details show once the trunk is ready. Diska's port 5060 does not accept carrier trunks: always use 5080. ## Trunk settings | Setting | Accepted values | Recommendation | | ------------------ | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------- | | **Transport** | UDP or TCP | UDP, unless the carrier requires TCP. | | **Codecs** | G.711 A-law (PCMA), G.711 μ-law (PCMU) or Opus | G.711 A-law at 20 ms, the standard on Angolan networks. G.729 and G.723 are not accepted. | | **DTMF** | RFC 2833 / RFC 4733 (`telephone-event`, payload 101) | Accept RFC 2833 on the carrier or PBX side: Diska does not send keys as SIP INFO. | | **Authentication** | IP-based (static) or SIP REGISTER with digest authentication | IP-based, if the carrier allows it: it does not depend on an active registration. | | **Network** | Public IPv4 | A PBX on a private network needs a public IP or extra connectivity agreed with DISKA. | For a stable connection: - Declare **every** IP the carrier sends calls from, or the whole network (/16 to /32). Diska refuses calls from IPs you did not declare. - If the carrier uses different addresses for audio, the firewall on your side must accept audio to and from 102.219.124.234, on UDP ports 16384–16639. - With SIP registration, Diska registers with the carrier and keeps the registration active. Registration confirms the connection but does not prove the number is routed: always make a real call. ## Import the number 1. In **Números** (Numbers), click **Número → Importar um número personalizado** (Number → Import a custom number). **Importar número de telefone** (Import phone number) opens. 2. Fill in the fields: | Field | Required | Notes | | ------------------------------------------------------------------ | -------------------------- | ------------------------------------------------------------------------------------------------ | | **Phone Provider** | Yes | **Custom**. *Twilio (em breve)* (coming soon) is disabled. | | **Phone Number** | Yes | Angolan number in +244 format, for example +244923456789. | | **Friendly Name** | No | A name to recognise the number in the list. | | **SIP Domain** | Yes | Domain or IP, with an optional port (1–65535). No `sip:` or `http://`. | | **Username** / **Password** | Only with SIP registration | Required when you turn on SIP registration; otherwise fill them in if the carrier requires them. | | **IPs de sinalização da operadora** (Carrier signalling IPs) | Yes | Public IPv4 addresses or /16 to /32 networks, one per line or comma-separated. | | **Transporte SIP** (SIP transport) | Yes | **UDP** (default) or **TCP**. | | **Outbound Proxy** | No | Domain or IP with port, for example `proxy.carrier.ao:5060`. | | **Auth Username** | No | Authentication username, if different from **Username**. | | **Ativar registo SIP outbound** (Enable outbound SIP registration) | No | Tick it if the carrier or PBX requires SIP REGISTER. | 3. Click **Importar** (Import). If the server has already confirmed the configuration, *Número importado* (Number imported) appears; if it is still applying it, *Configuração guardada* (Configuration saved) appears with the current status. Import errors: | Message | Cause | | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | *A sua organização já possui este número.* (Your organization already has this number.) | The number is already in your list. | | *Este número pertence à rede DISKA.* (This number belongs to the DISKA network.) | It is a DISKA number: it is bought, not imported. | | *Username e password são obrigatórios quando o registo SIP está activado.* (Username and password are required when SIP registration is on.) | You turned on SIP registration without credentials. | | *Use IPs públicos da operadora ou redes IPv4 /16 a /32.* (Use the carrier's public IPs or /16 to /32 IPv4 networks.) | You entered private IPs or a network that is too wide. | | *Use um domínio ou IP, sem esquema SIP/HTTP, e uma porta entre 1 e 65535.* (Use a domain or IP, without a SIP/HTTP scheme, and a port between 1 and 65535.) | **SIP Domain** or **Outbound Proxy** has an invalid format. | ## Track the status The list's **Estado** (Status) column and the number's details (**SIP trunk** section) show the progress. The page refreshes by itself; the configuration usually reaches the SIP server in under a minute. | Status in the list | SIP status in the details | What it means | | -------------------------------------------------------- | ------------------------- | -------------------------------------------------------------------------------- | | **A ativar** (Activating) | Activation pending | The configuration is being applied on the SIP server. | | **Credenciais pendentes** (Credentials pending) | Credentials pending | The SIP configuration is not complete, for example waiting for SIP registration. | | **Erro SIP** (SIP error) | Error | The configuration failed. Read the message in the details. | | **Sem agente** (No agent) / **Configurado** (Configured) | Configured | The trunk is ready. It still needs, or already has, an agent. | The details also show the server's message, for example: - *Trunk configurado. Publique o agente associado e teste uma chamada de entrada com a operadora.* (Trunk configured. Publish the attached agent and test an incoming call with the carrier.) - *Registo SIP confirmado. Publique o agente associado e valide uma chamada real.* (SIP registration confirmed. Publish the attached agent and validate a real call.) - *A aguardar registo SIP. Verifique credenciais, domínio e acesso de rede com a operadora.* (Waiting for SIP registration. Check credentials, domain and network access with the carrier.) The **SIP trunk** section of the details also shows **Provider**, **SIP Domain**, **Username**, **Password** (hidden), **Outbound Proxy**, **Auth Username**, **Solicitar registo SIP** (Request SIP registration), the transport, the **IPs de entrada** (inbound IPs) and, once ready, the **Origination URI**. ## Route the number to Diska When the trunk is ready, copy the **Origination URI** from the number's details and send it to the carrier (or set it on your PBX). Calls to the number must reach that destination: - from the IPs you declared; - with the transport you chose; - with the imported number as the destination (in `+244…` format). Diska only accepts a trunk call when it comes from one of the declared IPs **and** is for the imported number. ## Put the number to work 1. Assign the number to an **Inbound** agent under **Publicação → Telefone** (Publishing → Phone) — see [Assign to an agent](https://docs.diska.ai/en/telephony/numbers#assign-to-an-agent). 2. **Publish** the agent. Only the published version answers. 3. Make a real call to the number and confirm the agent answers, that audio flows both ways and that the call shows up in [History](https://docs.diska.ai/en/history/calls). ## Transfers through the trunk On a call received through your trunk, the transfer goes out through the same trunk, with your number as the caller ID. The destination can be a phone number or a SIP URI on the trunk's domain. For transfers to go out, the carrier or PBX must accept calls from Diska (102.219.124.234, port 5080) with the SIP registration credentials or by IP, and route them to the destination. See [Phone and SIP transfers](https://docs.diska.ai/en/telephony/transfers). ## Encryption Connecting over SIP uses SIP signalling over UDP or TCP and RTP audio, without encryption. TLS and SRTP are not available yet. If your policy requires encrypted calls, talk to DISKA before connecting the trunk. ## Compatibility summary | Setting | Supported | Not supported | | -------------- | ------------------------------------- | ---------------------------------------------------------------------- | | Transport | UDP, TCP | TLS | | Codecs | G.711 A-law, G.711 μ-law, Opus | G.729, G.723 | | DTMF | RFC 2833 / RFC 4733 | SIP INFO, in-band DTMF | | Authentication | IP-based, SIP REGISTER with digest | — | | Network | Public IPv4 | IPv6, private IP without extra connectivity, DNS SRV-only destinations | | Numbers | Angolan (+244) | Other countries | | Calls | Incoming; transfers through the trunk | Agent outbound calls, SMS, the panel's test call | ## Change the configuration In the details you can only change the **Nome amigável** (Friendly name). To change the SIP data, delete the number (**⋮ → Eliminar** (Delete)), import it again with the right data and confirm the assignment on the agent. ## Troubleshooting | Symptom | Likely causes | What to do | | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | The call never reaches Diska, or the carrier gets a rejection | The number is not routed to the **Origination URI**; the call comes from an IP you did not declare; the carrier sends to port 5060. | Confirm the routing and port 5080 with the carrier; add the missing IP and import again. | | The call arrives but nobody answers | The number is not assigned to a published **Inbound** agent; the organization reached its simultaneous call limit. | Assign and publish — see [Incoming calls](https://docs.diska.ai/en/telephony/phone-calls#incoming-calls) and [Simultaneous calls](https://docs.diska.ai/en/telephony/concurrency). | | The status stays at **Credenciais pendentes** (Credentials pending) | The SIP registration was not accepted. | Check username, password, **Auth Username**, domain and port with the carrier. | | The status shows **Erro SIP** (SIP error) | The SIP server refused the configuration. | Read the message in the details and fix the field it names. | | The agent answers but audio is missing one way | Audio (RTP) is blocked by a firewall or NAT. | Allow UDP 16384–16639 to and from 102.219.124.234 and make sure the carrier advertises a public IP in the SDP. | | Choppy or noisy audio | Unstable codec or network. | Use G.711 A-law at 20 ms and check packet loss on the carrier's link. | | Keys pressed by the agent are not recognised | The destination expects DTMF as SIP INFO or in-band. | Set the destination to RFC 2833 / RFC 4733. | | Transfers fail on an imported number | The carrier refuses the calls Diska sends through the trunk, or does not route the destination. | Ask the carrier to accept calls from 102.219.124.234 and check the destination format. | See also [Errors and end reasons](https://docs.diska.ai/en/telephony/errors) to read each call's end reason in **History**. ## FAQ **Can I connect a number from another country?** No. Import only accepts Angolan numbers (+244). **Do I need SIP registration?** Only if the carrier requires it. With IP authentication, declaring the signalling IPs is enough. **How many simultaneous calls does the trunk take?** The limit belongs to the organization, for all numbers together. See [Simultaneous calls](https://docs.diska.ai/en/telephony/concurrency). **Can the agent place outbound calls through my trunk?** No. Outbound calls (Outbound agents, campaigns and the test call) use DISKA numbers. Only transfers go out through the trunk. **Can the same number answer with two agents?** No. Each number answers with **one** published Inbound agent. # Phone calls This page describes what happens on a phone call: how it reaches the agent, what the caller hears, transfers and IVR, the end of the call and the processing that follows. It also covers the phone test call and the limits DISKA can set for your organization. ## Incoming calls A call to one of the organization's numbers is answered when **all** of these hold: 1. The number is active in the organization. For a SIP trunk, the SIP status is ready and the call comes from a declared IP. 2. There is **exactly one** agent of type **Inbound** with that number. 3. That agent is published, not archived, and **the published version has the number** — publish after assigning or changing the number. 4. The organization has not reached its limit of simultaneous calls (see [Limits](https://docs.diska.ai/#limits)). If any of them fails, no agent answers the call. A call is never diverted to another agent or another organization. ### What the caller hears - The agent answers with the published version's **greeting**. - If **Gravar chamadas** (Record calls) is on, the agent reads the configured consent message. See [Record calls](https://docs.diska.ai/en/guides/record-calls). - If the caller goes silent, the agent asks whether they are still there; if the silence continues, it says goodbye and ends the call. - If the agent cannot be reached when the call starts, the call ends without a conversation (with a short automatic message or a failed-call tone). The caller's number is attached to the call and can be used by the agent's actions, for example to send an SMS. ## During the call ### Transfers The agent can transfer the caller to someone on your team, with a [Call transfers](https://docs.diska.ai/en/actions/call-transfers) action or with the flow's [Transfer](https://docs.diska.ai/en/nodes/transfer) node. - **Transferência direta** (Direct transfer): the destination rings and, when it answers, the caller is connected with no prior notice. - **Transferência assistida com mensagem** (Warm transfer with message) or **com resumo contextual** (with contextual summary): whoever answers first hears, in the agent's voice, the reason or a summary of the call; only then is the caller connected. Rules per number type: | | DISKA number | Own SIP trunk | | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | | Destination | Angolan mobiles only (Africell or Unitel) | A phone number or a SIP URI on the trunk's domain | | Where the destination comes from | A number set in the action or in the **Lista telefónica** (phone book) — never a number spoken during the conversation | Fixed, or filled in from conversation variables | | Authorization | The organization must be authorized to place outbound calls | Not needed | | Caller ID shown | The DISKA number the caller dialled | Your imported number | A **Transfer** node to a **queue** or **team** does not exist on phone lines: the flow will not publish with that destination (see [Flow not publishing](https://docs.diska.ai/en/troubleshooting/flow-not-publishing)). On a web call there is no line to transfer, and the node takes its failure path. If the destination is busy, switched off, rejects the call or does not answer within about 20 seconds, the transfer fails and the caller stays with the agent, who says «Infelizmente o número está indisponível neste momento.» (unfortunately the number is unavailable right now). For other failures (for example, a destination that is not allowed), the agent says the failure message configured in the action. Once the caller is connected to the destination, the agent leaves the call. From then on: - the conversation with your team member is **not recorded**; - the agent's duration limit does **not** cut the call. ### IVR With the **Tratamento IVR** (IVR handling) action, the agent presses keys (DTMF) on the line to navigate voice menus — for example, when it calls a number answered by an automated menu. After a completed transfer the agent has already left the call, so it presses no keys. On a web call, the agent carries on with the conversation. See [IVR](https://docs.diska.ai/en/actions/ivr). ### SMS and bookings The agent can send SMS during the call and book meetings in Cal.com. See [During-call SMS](https://docs.diska.ai/en/actions/during-call-sms) and [Real-time booking](https://docs.diska.ai/en/actions/real-time-booking). ## End of the call A phone call ends when: - the caller hangs up; - the agent ends the call after saying goodbye (for example, at the caller's request or once the task is done), or the flow reaches an [End call](https://docs.diska.ai/en/nodes/end-call) node; - the silence goes on (the agent says goodbye first); - the maximum duration set in [Call settings](https://docs.diska.ai/en/telephony/call-settings) is reached — the line hangs up with no goodbye; - the transfer completes: the call continues between the caller and the destination, without the agent. ## After the call The call is logged in **Históricos** (History) with the transcript, the summary and the end reason. If recording is on, the audio shows up once the upload finishes: on a phone call, the first 27 minutes of the part with the agent are recorded. See [Calls](https://docs.diska.ai/en/history/calls) and [Recordings](https://docs.diska.ai/en/history/recordings). Then the platform runs the agent's post-call actions: - [Information extractors](https://docs.diska.ai/en/actions/information-extractors); - [Custom evaluations](https://docs.diska.ai/en/actions/custom-evaluations); - [Post-call SMS](https://docs.diska.ai/en/actions/post-call-sms); - the DISKA API's `call.completed` webhook, if you configured one. See [Webhooks](https://docs.diska.ai/en/api/webhooks); - the agent's Data Webhook, if you configured one. See [Agent webhooks](https://docs.diska.ai/en/telephony/webhooks). ## Phone test call In the test panel, the agent calls your mobile from its DISKA number. It is a real call, using real minutes on the DISKA line. Before you start: - the agent has a **DISKA number** assigned and was **published** with it at least once; - the organization is authorized to place outbound calls (see [Limits](https://docs.diska.ai/#limits)); - you have an Angolan mobile (Africell or Unitel). Steps: 1. In the agent, click **Testar → Chamada telefónica** (Test → Phone call). 2. Under **Versão do agente**(Agent version), choose: - **Rascunho — ações simuladas** (Draft — simulated actions): SMS, bookings and transfers are simulated; - **V*n* publicada — ações reais** (Published Vn — real actions): actions run for real, as on a real call. 3. **Chamada de** (Call from) shows the agent's number. 4. Under **Ligar para** (Call to), type your 9-digit mobile number, for example 923 000 000 (the prefix is +244). 5. If the agent has pre-call variables, fill them in. 6. Click **Ligar-me** (Call me) and answer. The panel shows the status: *A preparar a chamada…* (preparing the call), *A tocar no …* (ringing …), *Em chamada · m\:ss* (in call), *Chamada terminada · m\:ss* (call ended) or *Chamada cancelada* (call cancelled). Use **Desligar** (Hang up) to end it. The test call uses the chosen version's **Duração do toque** (ring time) and duration limit, and recording if it is on. Each person can only have one test call at a time, and there is a maximum number of test calls per hour per organization. The call shows up in **Históricos**. Messages you may see: | Message | What to do | | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | *Atribua um número DISKA ao agente e publique-o.* (assign a DISKA number to the agent and publish it) | The agent has no number. Assign a DISKA number and publish. | | *Publique o agente uma vez para testar por telefone.* (publish the agent once to test by phone) | The agent was never published. | | *Atribua ao agente um número DISKA activo e publique-o para testar por telefone.* (assign an active DISKA number and publish it) | The published version has no active DISKA number (for example, it is an imported number, or you assigned the number after publishing). | | *Indique um telemóvel angolano (Africell ou Unitel), por exemplo 923 000 000.* | The number entered is not an Angolan mobile. | | *Indique o seu telemóvel, não o número do agente.* (enter your mobile, not the agent's number) | You dialled the agent's own number. | | *Esta organização ainda não está habilitada para chamadas telefónicas de saída.* (not yet enabled for outbound phone calls) | Ask DISKA to authorize the organization. | | *A organização atingiu o limite de chamadas em simultâneo.* (simultaneous call limit reached) | Wait for another call to end. | | *Já tem uma chamada de teste em curso. Termine-a antes de ligar de novo.* (a test call is already in progress) | Hang up the previous call. | | *Atingiu o limite de chamadas de teste desta hora. Tente mais tarde.* (hourly test call limit reached) | Wait until the next hour. | | *O número está ocupado, desligado ou rejeitou a chamada.* (busy, switched off or rejected) | Check that the phone is on and has signal. | | *A chamada não foi atendida.* (not answered) | Answer before the ringing stops, or increase **Duração do toque**. | | *O agente não conseguiu atender a chamada. Tente novamente.* (the agent could not take the call) | Try again; if it persists, contact support. | | *A linha telefónica não está disponível neste momento.* (the phone line is unavailable) | Try again later. | | *Não foi possível confirmar o estado da chamada.* (could not confirm the call status) | Check the result in **Históricos** and try again. | For the other test modes (web call, chat and simulation) see [Test the agent](https://docs.diska.ai/en/guides/test-agent). ## Limits DISKA configures the following authorizations and limits per organization. They are not changed in the backoffice: talk to DISKA to adjust them. | Limit | What it covers | When it is reached | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Outbound calls** | The test call, transfers on DISKA numbers and Outbound agents' calls. It does not affect incoming calls or transfers through your own SIP trunk. | The test call shows *Esta organização ainda não está habilitada para chamadas telefónicas de saída.*; the transfer fails and the caller stays with the agent. | | **Simultaneous calls** | All of the organization's open phone calls: incoming, test and outbound. | New calls are not answered until one ends; the test call shows *A organização atingiu o limite de chamadas em simultâneo.* | | **DISKA numbers** | DISKA numbers in use plus unpaid orders. | *A organização atingiu o limite de N números DISKA (X em uso e Y por pagar).* | Calls on DISKA numbers use real carrier minutes — including the test call and the leg opened for a transfer. To see what counts towards the simultaneous call limit and how to plan capacity, see [Simultaneous calls](https://docs.diska.ai/en/telephony/concurrency). The end reason of each call is explained in [Errors and end reasons](https://docs.diska.ai/en/telephony/errors). # Call settings Each agent has a **Configuração de chamada** (Call settings) section with the ring time and the duration limit of its phone calls. ## Where to find it 1. Open the agent. 2. Click **Definições** (Settings) in the toolbar. 3. Open the **Configuração de chamada** section. Changes are saved automatically to the draft. Real calls use the published version, so **publish** for them to take effect. In the **Testar → Chamada telefónica** panel, the call uses the settings of the version you choose (draft or published). Changing these settings requires the **Owner**, **Admin** or **Member** role. ## Duração do toque (segundos) — ring time How long the customer's phone rings on calls the agent places — today, the [phone test call](https://docs.diska.ai/en/telephony/phone-calls#phone-test-call) — before the line gives up. - Values: **10 to 60 seconds** (30 by default). - It does not apply to incoming calls or to the ringing of a transfer destination. ## Limitar duração da chamada — limit call duration With the **Limitar duração da chamada** switch on, set the **Máximo (minutos)** (maximum, in minutes), from **1 to 240** (15 by default). - The phone call is hung up automatically when it reaches the maximum, counted from when it was answered. The agent does not say goodbye first: if conversations tend to run long, leave some margin. - A call already transferred to a person is **not cut**. - It applies to the published version's phone calls and to the test call of the version chosen in the test panel. It does not apply to web calls (widget, public link or web test). With the switch off, the agent sets no duration limit. ## Deixar mensagem de voz — leave voicemail The **Deixar mensagem de voz** switch is disabled. The UI explains: *Quando cair em voicemail (outbound). Indisponível: as linhas ainda não detectam atendedores automáticos.* (for outbound calls that reach voicemail; unavailable because the lines do not detect answering machines yet). ## End-of-call reasons The **Motivos de fim de chamada** (End-of-call reasons) section shows, read-only (*Definido no sistema* — set by the system), the reasons the agent can give when it ends the call: | Reason | When | | -------------------- | ------------------------------------- | | `user_requested_end` | The caller asked to end the call. | | `task_completed` | The purpose of the call was achieved. | | `inactivity` | The caller stopped responding. | | `error` | The agent could not continue. | These reasons, and the other ways a call ends (the caller hung up, silence, duration limit), show up in [History](https://docs.diska.ai/en/history/calls). See also [End of the call](https://docs.diska.ai/en/telephony/phone-calls#end-of-the-call). ## Recording Recording is set in the **Segurança e conformidade** (Security and compliance) section of the same **Definições**: when you turn on **Gravar chamadas** (Record calls), the agent tells the caller at the start of the call (unless you turn off **Avisar que a chamada é gravada**). On phone calls (including the test panel's phone call), the first 27 minutes of the part with the agent are recorded. See [Record calls](https://docs.diska.ai/en/guides/record-calls). # Campaigns A **campaign** calls a list of contacts, one by one, with an agent of type **Outbound**, from one of your organisation's DISKA numbers. Diska respects the hours you set, never takes the whole telephone capacity and records the result of every call. The calls appear in **Históricos** like any other, with recording and transcript when those are on. You find it in the **Campanhas** menu, right below **Números**. If the menu is not there, the feature is not active in your organisation yet: ask DISKA. ## Before you start - Your organisation must be enabled for **outbound calls** (DISKA turns this on). - A published agent of type **Outbound** (Prompt Builder or Flow Designer). Campaigns always use the published version. - An active **DISKA number** of the organisation, used as the caller ID. - Contacts who **agreed** to be contacted by your company. Diska asks you to confirm it before starting. ## Create a campaign In **Campanhas**, click **Nova campanha** (New campaign). The wizard has four steps: 1. **Configuração** (Setup) — name, voice agent and caller number. 2. **Destinatários** (Recipients) — import a file or add contacts by hand (see below). Diska shows how many are eligible, invalid, duplicated or excluded before adding them. 3. **Agendamento e limites** (Schedule and limits) — when and how much it may call (see below). 4. **Revisão** (Review) — the summary, the cost estimate (when there is data to compute it) and the confirmation that the contacts agreed to be called. **Iniciar campanha** / **Agendar campanha** starts it; people who can only prepare campaigns save it as a **Rascunho** (draft). ## The recipients file **.csv** (comma or semicolon separated) and **.xlsx** (first sheet) are accepted, up to 5 MB and 10,000 rows per file. The first row is the header: | Column | Purpose | | ---------------------------------------------- | ---------------------------------------------------------------------------------------------- | | `telefone` (or `phone`, `número`, `telemóvel`) | Required. International (+244 923 000 000) or Angolan national format (923 000 000). | | `nome` (or `name`) | Optional. The agent receives it as the contact's name. | | `email` | Optional. | | `id` (or `external_id`) | Optional. Your own contact id: sending the same row twice does not duplicate it. | | any other column | A per-recipient **variable** named after the header (`Produto favorito` → `produto_favorito`). | Example (semicolon-separated CSV): ```text telefone;nome;email;id;produto;cidade 923 000 001;Ana Silva;ana@exemplo.ao;crm-001;Strawberry yogurt;Luanda +244 934 000 002;João Paulo;;crm-002;Skimmed milk;Benguela ``` Here `produto` and `cidade` become variables of each recipient: the agent receives them as information about the contact, like the agent's pre-call variables. Rules: - Only **Angolan mobiles** (Africell and Unitel) can be dialled; other numbers are flagged as "outside the matrix". - A number repeated in the list, or already in the campaign, is added once. - Numbers on the **exclusion list** are skipped. - Variables are **information** for the agent, never instructions: text that tries to give the agent orders and names reserved by the platform are dropped. - Each campaign accepts up to 5,000 recipients (a limit DISKA can change). ## Hours and limits | Option | What it does | | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Start** | Now, or at a date and time. | | **Time zone** | The time zone of the windows (Africa/Luanda by default). | | **Calling windows** | Per weekday, one or several windows a day (for example 09:00–12:00 and 14:00–18:00). Outside them the campaign waits; contacts are **not** marked as failed. Windows must fall inside the legal contact hours (08:00–20:00 local time). | | **Maximum duration** | Days the campaign may run (7 by default, up to 30). At the end, contacts not yet called are cancelled and the campaign is completed. Time paused counts. | | **Simultaneous calls** | How many calls the campaign may have at once. | | **Reserved capacity** | How many of the organisation's simultaneous calls always stay free for inbound and other calls. | | **Attempts** | 1 to 3. Only an **unanswered** or **busy** call is retried, after the interval you choose. A technical failure is never retried on its own. | | **Minutes budget** | Optional. The campaign pauses itself before going over it. | On top of these, Diska never exceeds the platform's and the organisation's telephone capacity, counts **every** call in progress (inbound, test and other campaigns) and never hangs up a call to free capacity. ## Best practices - **Start small.** Run a first campaign with a few numbers from your team, one call at a time, and listen to the recordings before widening it. - **Prepare the agent for outbound calls.** The agent receives the campaign context (that it is your company calling, the campaign name and the contact's name), but the script should state why you are calling and what to do if the person cannot talk. - **Pick windows when people answer.** Avoid early mornings and lunchtime; use your contacts' time zone. - **Keep attempts low.** Two attempts a few hours apart are usually enough. More than that annoys people who don't want to answer. - **Keep the list clean.** Use the `id` column so you can resend the file without duplicates, and add anyone who asks not to be called to the exclusion list. - **Set a minutes budget** for your first campaigns, to learn what each one uses. ## Campaign states | State | Meaning | | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | **Rascunho** (Draft) | Being prepared; not calling yet. | | **Agendada** (Scheduled) | Ready; waiting for the start date, a window or free capacity. | | **Em execução** (Running) | Calling. When it is waiting, the reason shows below the state (for example "Fora do horário — retoma às 09:00"). | | **Pausada** (Paused) | Starts no new calls; calls in progress continue. Paused by a person, by an exhausted budget or monthly quota, or by an emergency stop. | | **Concluída** (Completed) | Every contact reached a final state, or the maximum duration ended. | | **Cancelada** (Cancelled) | Stopped for good; contacts not yet called were cancelled. | - **Pausar** (Pause) stops new calls and keeps the ones in progress. - **Retomar** (Resume) continues with the contacts left, within the hours and capacity. - **Cancelar** (Cancel) cancels the contacts left, without hanging up calls already connected. It cannot be undone. - **Pausar todas** (Pause all, on the campaigns list) is the organisation's emergency stop. ## Recipients and results Each recipient has a state: **Pendente** (pending), **Reservado** (reserved), **A ligar** (calling), **Em chamada** (in a call), **Realizado** (done), **Falhado** (failed), **Cancelado** (cancelled) or **Excluído** (excluded). Diska keeps the **call result** apart from a **technical failure**: - **Realizado** means the call reached the network: **Atendida** (answered), **Não atendida** (not answered) or **Ocupado/indisponível** (busy/unavailable). An answered call that did not sell is a result, not a failure. - **Falhado** means the call could not be placed (line or agent unavailable) or its result could not be confirmed. The reason shows in the list. On the campaign page you can filter by state, open each contact's call in **Históricos** (with recording and transcript when they exist), **Exportar resultados** (CSV export), **Adicionar destinatários** (add recipients) and **Repetir falhadas** (retry the failed ones, optionally the unanswered ones too). If a person asks on the call not to be contacted again ("não me liguem mais"), the number goes on the organisation's exclusion list and is no longer dialled in any campaign. ## Metrics | Metric | How it is computed | | -------------------- | --------------------------------------------------------------------------------------------------------------------------- | | **Progress** | Recipients in a final state (done, failed, cancelled, excluded) ÷ all recipients. | | **Calls started** | Attempts sent to the telephone server (each retry counts). | | **Answer rate** | Answered ÷ (answered + not answered + busy/unavailable). Technical failures are left out. | | **Total duration** | Sum of the answered calls' duration. | | **Accumulated cost** | Duration × price per minute, only when DISKA configured a price; otherwise "Sem tarifa configurada" (no tariff configured). | ## Exclusion list In **Campanhas → Lista de exclusão** you manage the numbers your organisation must never contact. A number added is removed at once from every campaign's contacts not yet called. ## Permissions | Action | Roles | | ------------------------------------------- | -------------------- | | See campaigns and results | All | | Create, edit, import, pause, exclusion list | Owner, Admin, Editor | | Start, resume, retry, cancel, pause all | Owner, Admin | ## Troubleshooting | What you see | What it means | What to do | | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | | **Fora do horário** (Outside the window) | The calling window is closed. | Nothing: the campaign resumes by itself at the next window, at the time shown. | | **Aguarda a data de início** (Waiting for the start date) | The campaign is scheduled. | Nothing, or change the date in **Editar**. | | **A aguardar capacidade livre** (Waiting for free capacity) | So many calls are in progress that there is no room without taking capacity from inbound calls. | Wait, or raise the campaign's simultaneous calls if your organisation has headroom. | | **Capacidade telefónica por configurar** (Telephone capacity not configured) | The platform's outbound capacity is not configured yet. | Contact Diska. | | **Chamadas de saída não activas na organização** (Outbound calls not enabled) | Your organisation is not enabled for outbound calls. | Contact Diska. | | **Agente indisponível** (Agent unavailable) | The agent was archived, is no longer Outbound or has no published version. | Publish the agent. | | **Número de origem indisponível** (Caller number unavailable) | The number is no longer an active DISKA line. | Pick another number or contact Diska. | | **Pausada — orçamento de minutos esgotado** (Paused — minutes budget used up) | The campaign used the budget you set. | Raise the budget and click **Retomar**. | | A recipient **Falhado — sem resultado** (Failed — no result) | The telephone server received the request but did not confirm the result. Diska does not retry it on its own, so it never calls twice. | Check the call in **Históricos** and, if needed, use **Repetir falhadas**. | ## FAQ **Can I change a campaign after it started?** You can change its name, hours and limits while it is scheduled or paused. The agent and the caller number cannot change once it is created. **Are campaign calls normal calls?** Yes. They are calls of the agent like any other: they appear in **Históricos** (you can filter by campaign), with recording and transcript when those are on, and they use [Shared memory](https://docs.diska.ai/en/knowledge-base/shared-memory) if the agent has a group. **What happens to people who don't answer?** They become **Realizado — Não atendida** (done — not answered). If you set more than one attempt, Diska calls again after the interval you chose, within the windows. **Can I pause in the middle of a call?** Yes. Pausing and cancelling never hang up calls in progress: they only stop new calls. **Can I call foreign or landline numbers?** Not yet. For now only Angolan mobiles (Africell and Unitel). ## Privacy and retention - Each organisation only sees its own campaigns. - The audit log records who did what, without numbers, names or variables. - Recipients of a campaign that ended more than 180 days ago are deleted; the campaign keeps its totals. ## API Campaigns can also be managed through the API: create them, add recipients (up to 1000 per request, with `external_id` to avoid duplicates), start, pause, resume, cancel and read the results. See [Campaigns in the API reference](https://docs.diska.ai/en/api/reference/campaigns). Diska switches the campaigns API on when asked. To import contacts without code, export them to CSV or Excel and use **Adicionar destinatários** (Add recipients), with the `id` column to avoid duplicates. # Simultaneous calls Diska limits how many voice calls (phone and WhatsApp) each organization can have open at the same time. The limit protects call quality and line capacity, and DISKA sets it for each organization. There are two different limits: - **Simultaneous calls** — how many of the organization's voice calls can be open at once. - **Outbound calls** — whether the organization may place calls on DISKA lines (test call, Outbound agents, campaigns and transfers on DISKA numbers or WhatsApp calls). See [Limits](https://docs.diska.ai/en/telephony/phone-calls#limits). ## What counts **Every** open voice call of the organization counts, on DISKA numbers, on numbers imported over [SIP](https://docs.diska.ai/en/telephony/sip-trunk) or on WhatsApp: - incoming calls; - phone test calls; - calls placed by Outbound agents, including [Campaigns](https://docs.diska.ai/en/telephony/campaigns); - [WhatsApp voice calls](https://docs.diska.ai/en/whatsapp/calls). These do not count: - web calls (widget, public link and browser test); - WhatsApp messages and chat conversations; - the leg a transfer opens to the destination: a transfer does not take a new call in the limit. The limit belongs to the **organization**, not to each number or agent: all numbers and agents share the same capacity. ## Your limit DISKA sets each organization's limit. It is not changed in the backoffice: to find out yours, or to change it, talk to DISKA. An organization without its own limit is bound only by the platform's capacity. ## When the limit is reached | Call | What happens | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | **Incoming** | The agent does not answer. The caller hears the network's call-failed tone and can call again once there is capacity. | | **Test call** | The **Testar** (Test) panel shows *A organização atingiu o limite de chamadas em simultâneo.* (simultaneous call limit reached). | | **Campaign** | The campaign waits, showing *A aguardar capacidade livre* (Waiting for free capacity), and resumes by itself when a call ends. | | **In progress** | Never hung up to free capacity. | The limit is checked when the call starts. Two calls arriving at the same instant can both get through, so the limit may be exceeded by one call. ## Campaigns and reserved capacity Campaigns share capacity with incoming calls. So that a campaign does not take the lines you need to answer: - **Simultaneous calls** caps how many calls the campaign has at once; - **Reserved capacity** (1 by default) always stays free for incoming and other calls. A campaign only starts a new call when it fits every limit at once: the campaign's, the organization's (minus the reserved capacity and every open call) and the platform's. See [Campaigns](https://docs.diska.ai/en/telephony/campaigns). Example: with an organization limit of 5 calls, reserved capacity 1 and 2 incoming calls in progress, the campaign can have at most 2 calls at once (5 − 1 − 2). ## Plan your capacity To ask DISKA for a limit, estimate: 1. how many calls you receive in your busiest hour; 2. how long they last, on average; 3. how many campaign calls you want in parallel, and when; 4. how many people on your team make test calls. To make the most of your capacity: - set a **maximum duration** in [Call settings](https://docs.diska.ai/en/telephony/call-settings), so a forgotten call does not hold a line; - run campaigns outside your busiest inbound hours; - keep at least 1 of **Reserved capacity** on campaigns. ## FAQ **Do web calls count towards the limit?** No. Only phone calls. **Is the limit per number?** No. It belongs to the organization, for all numbers and agents together. **What does a caller hear when the limit is used up?** The network's call-failed tone: the agent never answers. **Can a campaign block incoming calls?** Not if you keep reserved capacity: the campaign never uses those slots. **How do I raise the limit?** Talk to DISKA with the volume estimate from the previous section. # Phone and SIP transfers A transfer hands the agent's phone call to a person on your team: a mobile, a number on your carrier or an extension on your PBX over SIP. This page explains what happens on the line. To create the action and set its modes and messages, see [Call transfers](https://docs.diska.ai/en/actions/call-transfers). On a WhatsApp voice call, transfers work differently: see [Voice calls](https://docs.diska.ai/en/whatsapp/calls#transfer-to-a-person). ## How it works on the line 1. The agent decides to transfer, when the action's condition is met, and tells the caller. 2. Diska calls the destination over the **same line** the call is on: the DISKA network or your SIP trunk. 3. While the destination rings (up to about 20 seconds), the caller stays with the agent, with no hold music. 4. When the destination answers, Diska joins the two calls and the agent leaves. In warm transfers, whoever answers first hears the briefing in the agent's voice. 5. If the destination does not answer, is busy, switched off or rejects the call, the agent says «Infelizmente o número está indisponível neste momento.» (Unfortunately the number is unavailable right now.) and carries on with the conversation. Diska places a **new call** to the destination and joins it to the caller's call; it does not hand the call over to the carrier (SIP REFER). So: - the destination does not need to support SIP REFER; - the destination sees the line's number, not the caller's (see [Caller ID](https://docs.diska.ai/#caller-id)); - the call keeps flowing through Diska until someone hangs up. Once the two calls are joined, the conversation with your team member is not recorded and the agent's duration limit no longer applies. ## Destinations by number type | | DISKA number | Number imported over SIP | | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | | **Accepted destinations** | Angolan mobiles only (Africell or Unitel) | Phone numbers or SIP URIs on the trunk's domain | | **Where the destination comes from** | A number fixed in the action or the **Lista telefónica** (Phone book) — never a number said during the conversation | Fixed, or filled in from conversation variables | | **Authorization** | The organization must be allowed to place outbound calls | Not needed | | **Goes out through** | The DISKA network | Your SIP trunk | | **Who pays for the leg to the destination** | DISKA line minutes | Your carrier | On a DISKA line you cannot transfer to the line's own number, to landlines, to international numbers or to SIP URIs. ## Accepted SIP URIs On an imported number, a SIP URI must use a **number** and the trunk's **SIP Domain**, exactly as imported (including the port, if you gave one). | Format | Example | Accepted | | ---------------------------- | --------------------------------------- | -------------------------------------------------- | | Number on the trunk's domain | `sip:+244222000000@pbx.company.ao` | Yes, if `pbx.company.ao` is the trunk's SIP Domain | | Numeric extension | `sip:2001@pbx.company.ao` | Yes (3 to 20 digits) | | User with letters | `sip:sales@pbx.company.ao` | No | | Another domain | `sip:2001@other-pbx.ao` | No | | With parameters | `sip:2001@pbx.company.ao;transport=tcp` | No: the transport is the trunk's | A phone number can also have 3 to 20 digits, with an optional `+`: your carrier or PBX decides where it goes. ## Caller ID | The call is on | The destination sees | | ------------------ | -------------------------------------------------------------- | | A DISKA number | The DISKA number the caller dialled (or the agent called from) | | An imported number | Your imported number | The caller's number is never sent to the destination. So that your team member knows who is calling: - use a **warm** transfer, to hear the reason or a summary before talking to the caller; - have the agent collect the name and reason before transferring, with [Information extractors](https://docs.diska.ai/en/actions/information-extractors) to see them later in **History**. ## Hours and availability With **Activar horário de disponibilidade** (Enable availability hours), outside the hours Diska does not call the destination: the agent says the *Humano indisponível* ("Human unavailable") message and carries on. The hours use the action's time zone (`Africa/Luanda` by default). See [Human availability](https://docs.diska.ai/en/actions/call-transfers#disponibilidade-humana-human-availability). ## Not available - Handing the call over to the carrier with SIP REFER. - Sending custom SIP headers (X-headers) or User-to-User (UUI). The headers in the **Simulação** (Simulation) tab are only used by the **Simular** (Simulate) button. - Hold music while the destination rings. - Transferring to a queue or team. - Transfers on web calls: there is no phone line, and the agent carries on with the conversation. ## Troubleshooting | Symptom | Likely causes | What to do | | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | The agent says «Infelizmente o número está indisponível neste momento.» | The destination did not answer within about 20 seconds, was busy, switched off or rejected the call. | Check the destination has signal and answers; consider a [Phone book](https://docs.diska.ai/en/actions/call-transfers#phone-books) with alternatives. | | The agent says the action's failure message | The destination is not allowed on that line: it is not an Angolan mobile, it is a SIP URI on another domain, or the organization is not allowed to place outbound calls. | Fix the destination in the action, or ask DISKA to allow outbound calls. | | The agent says the *Humano indisponível* message | The call was outside the availability hours. | Review the action's hours and time zone. | | The agent does not transfer | The action's condition was not met, or the action is not attached to the agent's published version. | Review the **Descrição da condição** (Condition description) and publish the agent. | | The transfer works in tests but not on real calls | You tested the draft, where the transfer is simulated. | Test with **Testar → Chamada telefónica** (Test → Phone call), choosing the published version. | ## FAQ **Why does the destination see Diska's number and not the caller's?** Because Diska places a new call to the destination over the call's line. The number shown is that line's. **Can I transfer to an extension on my PBX?** Yes, if the call came in on an imported number: use `sip:extension@trunk-domain` or the extension's number. **Can I transfer to a landline on a DISKA line?** No. On a DISKA line you can only transfer to Angolan mobiles. **Does the agent hear the conversation after the transfer?** No. The agent leaves when the destination answers, and that part is not recorded. **Does a transfer count towards the simultaneous call limit?** It does not take a new call in the limit. See [Simultaneous calls](https://docs.diska.ai/en/telephony/concurrency). # Agent webhooks Each agent can have two webhooks, under **Publicação → Telefone** (publish → phone): | | Inbound Webhook | Data Webhook | | ------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | | When | When a call reaches the agent, before it speaks | When the call ends, after post-call processing | | Calls | Inbound, by phone or WhatsApp (**Inbound** agents only) | Inbound and outbound, by phone or WhatsApp, plus public link and widget calls | | Your system | Answers with facts about the caller, which the agent uses in the conversation | Stores the transcript, extracted data, evaluations and actions | | Event | `call.inbound` | `call.completed` | | Response time | Up to 5 seconds | Up to 10 seconds | | Retries | None: the call does not wait | Up to 3 attempts | Both requests are JSON `POST`s and are **signed** with the agent's secret (see [Verify the signature](https://docs.diska.ai/#verify-the-signature)). ## Set up 1. Open the agent and click **Publicação** (publish). 2. In the **Telefone** (phone) tab, enter the URL under **Inbound Webhook** and/or **Data Webhook**. The URL must start with `https://` and be a public address. 3. Click outside the field or press Enter to save. 4. Click **Inicializar** (initialize) to send a test request to the URL (see [Test with Inicializar](https://docs.diska.ai/#test-with-inicializar)). 5. **Publish** the agent. Like the rest of the call settings, the webhooks apply from the published version. To stop using a webhook, clear the URL (the **×** button) and publish again. Anyone who can edit the agent (owners, admins and members) can change the webhooks and see the signing secret. ## Inbound Webhook When an inbound call reaches the agent, Diska sends it to the Inbound Webhook **before the agent speaks**. The answer can carry: - **`variables`**: facts about the caller (name, plan, balance, last order…). The agent receives them as facts about this call and uses them in the conversation. In a flow-mode agent they are available as variables (`{{nome}}`). - **`metadata`**: your system's references (the customer's CRM ID, a session ID…). The agent does not see them; they come back in the [Data Webhook](https://docs.diska.ai/#data-webhook), in the `metadata` field. ### Request ```json { "event": "call.inbound", "test": false, "agent_id": "61e5f9d7-06eb-43ad-a8a5-056ff7b448fd", "organization_id": "0ba43fdf-…", "channel": "phone", "direction": "inbound", "from_number": "+244923000001", "to_number": "+244959092450", "created_at": "2026-11-08T10:15:02.418Z" } ``` | Field | Description | | ------------- | ------------------------------------------------------------------------------------------------- | | `channel` | `phone` (DISKA number or SIP trunk) or `whatsapp` | | `from_number` | The caller's number, as the network delivered it. May be `null` if the caller hides their number. | | `to_number` | The agent's number. On a WhatsApp call it is `null`. | | `test` | `true` only on **Inicializar** requests | ### Response Answer `200` with JSON: ```json { "variables": { "nome": "Ana Silva", "plano": "Gold", "saldo": "12 500 Kz" }, "metadata": { "crm_id": "CL-48213" } } ``` - Variable names are normalized to lowercase, without accents or spaces (`Nome do cliente` → `nome_do_cliente`). - At most 20 variables, up to 200 characters each. Values are kept on one line. - A variable whose value reads like an instruction (for example "ignore the previous instructions") is dropped. The agent receives variables as **facts**, never as orders. - `metadata`: up to 20 pairs, 500 characters per value. - A `200` or `204` with no body is valid: the agent answers without extra facts. - We also accept `{"call_inbound": {"custom_variables": {…}, "metadata": {…}}}`, for integrations moving from another platform. ### If your system does not answer The Inbound Webhook **never refuses a call**. If your system takes longer than 5 seconds, answers with an error, a redirect or something that is not JSON, the agent answers anyway, without those facts. There are no retries: the caller is waiting. Answer fast: every second your system takes is another second of ringing for the caller. ### Example receiver ::code-group ```python [Python (FastAPI)] from fastapi import FastAPI, Request app = FastAPI() @app.post("/diska/inbound") async def inbound(request: Request): call = await request.json() customer = await find_customer(call["from_number"]) # your CRM if customer is None: return {} return { "variables": {"nome": customer.name, "plano": customer.plan}, "metadata": {"crm_id": customer.id}, } ``` ```js [Node.js (Express)] app.post('/diska/inbound', express.json(), async (req, res) => { const customer = await findCustomer(req.body.from_number) // your CRM if (!customer) return res.json({}) res.json({ variables: { nome: customer.name, plano: customer.plan }, metadata: { crm_id: customer.id } }) }) ``` :: Verify the signature before answering with customer data (see [Verify the signature](https://docs.diska.ai/#verify-the-signature)). ## Data Webhook When a call ends and post-call processing finishes (transcript, data extraction, evaluations, SMS and actions), Diska sends the data to the Data Webhook. The body is the same as the `call.completed` event of [organization webhooks](https://docs.diska.ai/en/api/webhooks), with two more fields: `call` and `metadata`. ```json { "event": "call.completed", "test": false, "call_id": "8f1c2d3e-…", "session_id": "sess_…", "agent_id": "61e5f9d7-06eb-43ad-a8a5-056ff7b448fd", "organization_id": "0ba43fdf-…", "ended_at": "2026-11-08T10:18:44.120Z", "caller_contact": "+244923000001", "extracted_data": { "nome": "Ana Silva", "motivo": "Alterar o plano" }, "evaluations": [], "sentiment": "positive", "post_call_sms": [], "custom_actions": [], "executed_actions": [], "transcript": [ { "role": "assistant", "content": "Olá Ana, em que posso ajudar?" }, { "role": "user", "content": "Queria mudar para o plano Gold." } ], "call": { "id": "8f1c2d3e-…", "channel": "phone", "direction": "inbound", "status": "completed", "end_reason": "user_requested_end", "started_at": "2026-11-08T10:15:03.002Z", "ended_at": "2026-11-08T10:18:41.870Z", "duration_seconds": 219, "from_number": "+244923000001", "to_number": "+244959092450" }, "metadata": { "crm_id": "CL-48213" } } ``` | Field | Description | | ----------------- | -------------------------------------------------------------------------------------------------------------- | | `call_id` | The call's ID in [History](https://docs.diska.ai/en/history/calls) and in the DISKA API (`GET /v1/calls/{id}`) | | `extracted_data` | The values of the agent's [information extractors](https://docs.diska.ai/en/actions/information-extractors) | | `evaluations` | The configured post-call evaluations | | `transcript` | The conversation, turn by turn | | `call.end_reason` | The end reason (see [Errors and end reasons](https://docs.diska.ai/en/telephony/errors)) | | `metadata` | What the Inbound Webhook returned in `metadata` (empty if none) | With [Redact personal data](https://docs.diska.ai/en/guides/redact-personal-data) on, the transcript and extracted data arrive already masked (for example `[TELEFONE]`). The caller's line number is kept. ### Which calls are sent - **Completed** calls of published agents: by phone (DISKA number or SIP trunk), WhatsApp, public link and widget, inbound and outbound (including campaigns and DISKA API calls). - Not sent: test calls from the **Testar** (test) panel and the Test Center, DISKA API text chats, and calls that failed or were cancelled. ### Responses and retries - Answer `2xx` within 10 seconds. Queue the event and process it later. - A `5xx`, `408`, `429` or no response is retried, up to 3 attempts, 1 and 2 seconds apart. - A `4xx` (other than `408`/`429`) is not retried: your system refused the request. - Redirects (`3xx`) are not followed. - `X-Diska-Delivery` is the same on every attempt for the same call: use it to avoid processing a call twice. ## Test with Inicializar The **Inicializar** (initialize) button sends a test request to the URL in the field, even before you save it: - **Inbound Webhook**: sends a `call.inbound` with `"test": true` and made-up numbers. Diska shows the response code, the time taken, and the variables the agent would receive, or why a variable was dropped. - **Data Webhook**: sends a `call.completed` with `"test": true`, a sample conversation and zeroed IDs. Test requests are signed like real ones. To tell tests from real calls, check the `test` field. ## Verify the signature Each request carries these headers: ```text Content-Type: application/json User-Agent: Diska-Webhooks/1.0 X-Diska-Event: call.inbound | call.completed X-Diska-Delivery: X-Diska-Timestamp: X-Diska-Signature: sha256= ``` The signature is the hex HMAC-SHA256 of the text `{X-Diska-Timestamp}.{body}` with the agent's **signing secret**. You find the secret under **Publicação → Telefone → Segredo de assinatura** (signing secret); it starts with `whsec_`. Each agent has its own; the same secret signs both webhooks. Compute the signature over the **raw body**, exactly as received. The code is the same as for organization webhooks: see the Python, Node.js and PHP examples in [Webhooks › Verify the signature](https://docs.diska.ai/en/api/webhooks#verify-the-signature). Reject requests older than 5 minutes. ## Agent or organization webhooks? | | Agent webhooks | [Organization webhooks](https://docs.diska.ai/en/api/webhooks) | | ------------------ | ------------------------------------ | -------------------------------------------------------------- | | Where it is set up | **Publicação → Telefone**, per agent | Through the DISKA API (`webhooks:manage`) | | Before the call | Yes: Inbound Webhook | No | | After the call | Data Webhook, for this agent's calls | `call.completed` for every call in the organization | | Signature | The agent's secret (`whsec_…`) | Each endpoint's secret (`dskw_…`) | You can use both: a completed call is sent to every webhook configured. ## Troubleshooting | Symptom | What to check | | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | The agent does not use the Inbound Webhook's facts | Was the agent published after saving the URL? Use **Inicializar** and check that the variables appear and whether any was dropped. | | **Inicializar** says "Sem resposta a tempo" (no response in time) | Your system takes longer than 5 seconds. Answer first with what you have and do the rest afterwards. | | "Este endereço não é público" (this address is not public) | The URL points to a private address (internal network, `localhost`). Use a public `https://` address. | | The Data Webhook does not arrive | Was it a test call? Was the agent published with the URL? Did the call end as completed? | | The signature does not match | Use the raw body, without re-serializing the JSON, and the right agent's secret. | # Errors and end reasons Every phone call in [History](https://docs.diska.ai/en/history/calls) has an **end reason**. This page explains each reason and what to do when a call fails. **History** shows the reason's name or its code, so the tables list both. ## Normal endings | Reason | Code | What it means | | -------------------------------------------------------------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Cliente desligou** (Caller hung up) | `caller_hangup`, `user_hangup` | The caller hung up. | | **Agente terminou a chamada** (Agent ended the call) | `end_call` | The agent said goodbye and hung up (task done, caller's request or end of the flow). | | **Agente terminou a conversa** (Agent ended the conversation) | `live_end_call` | The agent ended the conversation after saying goodbye. | | **Transferida para uma pessoa** (Transferred to a person) | `transferred` | The transfer completed and the agent left the call. See [Phone and SIP transfers](https://docs.diska.ai/en/telephony/transfers). | | **Terminada por silêncio** (Ended by silence) | `silence_timeout` | The caller stopped responding; the agent asked whether they were still there and said goodbye. | | **Limite de duração atingido** (Duration limit reached) | `max_duration` | The call reached the **Máximo (minutos)** (Maximum, minutes) in [Call settings](https://docs.diska.ai/en/telephony/call-settings). The line hangs up without a goodbye. | | **Cliente desligou antes de atender** (Caller hung up before answer) | `abandoned_before_answer` | The caller hung up while the line was ringing, before the agent spoke. | | **Cancelada** (Cancelled) | `cancelled` | The test call was cancelled in the panel before it was answered. | ## Line endings | Reason | Code | What it means | What to do | | ------------------------------------------------ | ------------------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------- | | **Desligada pela linha** (Hung up by the line) | `gateway_hangup` | The phone line ended the call. | If it happens often, check whether it matches the duration limit or network drops. | | **Linha telefónica terminou** (Phone line ended) | `freeswitch_hangup` | The phone server ended the call. | Same as above. | | **Linha sem resposta** (Line not responding) | `timeout_hangup` | The line stopped responding during the call. | Try again; if it persists, contact support with the time of the call. | | **Chamada terminada** (Call ended) | `other_hangup` | The call ended for a reason the line did not specify. | Nothing, if it is a one-off. | ## Agent or audio failures In these cases the caller hears a short automatic message or the call-failed tone, and the call ends. | Reason | Code | What it means | | -------------------------------------------------------------------------------------------------- | ------------------------------------ | -------------------------------------------------------- | | **Agente indisponível** (Agent unavailable) | `runtime_unavailable` | The agent could not be reached at the start of the call. | | **Ligação ao agente perdida** (Connection to the agent lost) | `runtime_disconnect` | The connection to the agent dropped during the call. | | **Desligada pelo motor de voz** (Hung up by the voice engine) | `runtime_hangup` | The voice engine ended the session. | | **Falha a iniciar o áudio** (Audio failed to start) | `media_start_failed` | The call's audio did not start. | | **Falha no áudio** (Audio failure) | `media_stream_failed` | The call's audio failed during the conversation. | | **Falha a atender** (Failed to answer) | `startup_answer_or_media_failed` | The call could not be answered. | | **Falha técnica** (Technical failure) / **Falha técnica na linha** (Technical failure on the line) | `exception`, `gateway_worker_exited` | An internal Diska error. | What to do: call again. If the failure repeats, contact DISKA with the time of the call and the number. See also [Calls drop](https://docs.diska.ai/en/troubleshooting/calls-drop). ## Calls that never reach the agent Some calls never reach an agent, so they have no conversation in **History**. The caller hears the call-failed tone, or nobody answers. | Cause | What to do | | ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | The number is not assigned to an **Inbound** agent, or the agent was not published after getting the number. | Assign the number and publish — see [Incoming calls](https://docs.diska.ai/en/telephony/phone-calls#incoming-calls). | | The organization reached its simultaneous call limit. | See [Simultaneous calls](https://docs.diska.ai/en/telephony/concurrency). | | On an imported number: the call came from an IP you did not declare, to the wrong port, or the trunk is not ready yet. | See the [Connect over SIP troubleshooting](https://docs.diska.ai/en/telephony/sip-trunk#troubleshooting). | | The number is **Desativado** (Disabled), for example suspended by DISKA, or **Sem chamadas** (No calls). | See [Number status](https://docs.diska.ai/en/telephony/numbers#number-status) and contact DISKA. | ## Transfer and test call failures - A failed transfer does not end the call: the agent carries on with the caller. The causes are in [Phone and SIP transfers](https://docs.diska.ai/en/telephony/transfers#troubleshooting). - The messages of the **Testar → Chamada telefónica** (Test → Phone call) panel are in [Phone test call](https://docs.diska.ai/en/telephony/phone-calls#phone-test-call). # Telephony Diska connects your voice agents to the phone network. Someone dials an Angolan number and is answered by the agent published on that number. During the call, the agent can transfer the caller to someone on your team, press keys in an IVR menu, send SMS, book meetings and record the conversation. ## Two ways to get a number | | DISKA number | Your own SIP trunk | | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | What it is | An Angolan number from the DISKA network, on Africell | An Angolan number (+244) you already have with another carrier or on your own PBX | | How you get it | **Números → Número → Comprar um número DISKA** (buy a DISKA number): reservation, with payment confirmed by DISKA | **Números → Número → Importar um número personalizado** (import a custom number): connect your SIP trunk to Diska | | Incoming calls | Yes | Yes | | Test call from the **Testar** (Test) panel | Yes | No | | Transfers | To Angolan mobiles set in the action or the phone book | Through your trunk, to numbers or SIP URIs on the trunk's domain | | Details | [Phone numbers](https://docs.diska.ai/en/telephony/numbers) | [Connect over SIP](https://docs.diska.ai/en/telephony/sip-trunk) | ## How a call reaches the agent A call to your number is answered when: 1. the number is active in the organization (and, for a SIP trunk, the SIP configuration is ready); 2. the number is assigned to **one** agent of type **Inbound**, under **Publicação → Telefone** (Publishing → Phone); 3. that agent was **published** after getting the number — it is the published version that answers; 4. the organization has not reached its [simultaneous call](https://docs.diska.ai/en/telephony/concurrency) limit. If any of these fails, nobody answers the call. See the full path in [Phone calls](https://docs.diska.ai/en/telephony/phone-calls). ## Calls the agent places - **Test call**: in the **Testar → Chamada telefónica** (Test → Phone call) panel, the **Ligar-me** (Call me) button makes the agent call your mobile from its DISKA number. See [Phone calls](https://docs.diska.ai/en/telephony/phone-calls#phone-test-call). - **Outbound agents**: an agent of type **Outbound** can have a DISKA number, which it presents as its caller ID. - **Campaigns**: call a list of contacts automatically with an Outbound agent, within the hours and limits you set. See [Campaigns](https://docs.diska.ai/en/telephony/campaigns). Outbound calls are only available to organizations enabled by DISKA. ## During the call - **Transfers** to a person — direct or warm, where whoever answers first hears the reason or a summary in the agent's voice. See [Phone and SIP transfers](https://docs.diska.ai/en/telephony/transfers), [Call transfers](https://docs.diska.ai/en/actions/call-transfers) and the [Transfer](https://docs.diska.ai/en/nodes/transfer) node. - **IVR**: the agent presses keys (DTMF) on the line to navigate voice menus. See [IVR](https://docs.diska.ai/en/actions/ivr). - **SMS** during and after the call. See [During-call SMS](https://docs.diska.ai/en/actions/during-call-sms) and [Post-call SMS](https://docs.diska.ai/en/actions/post-call-sms). - **Recording**: with **Gravar chamadas** (Record calls) on, phone calls are recorded too (the first 27 minutes). See [Record calls](https://docs.diska.ai/en/guides/record-calls). - **Limits**: maximum call duration and ring time, per agent — see [Call settings](https://docs.diska.ai/en/telephony/call-settings); and simultaneous calls, per organization — see [Simultaneous calls](https://docs.diska.ai/en/telephony/concurrency). - **Agent webhooks**: your system receives each call before the agent answers and can give it facts about the caller; at the end, it receives the call's data. See [Agent webhooks](https://docs.diska.ai/en/telephony/webhooks). ## Who can do what | Action | Owner | Admin | Member | Viewer | | -------------------------------------------------------------- | :---: | :---: | :----: | :----: | | See the **Números** (Numbers) page | ✓ | ✓ | ✓ | ✓ | | Buy, import and delete numbers | ✓ | ✓ | | | | Assign a number to an agent | ✓ | ✓ | | | | Change the agent's **Configuração de chamada** (Call settings) | ✓ | ✓ | ✓ | | | Place the phone test call | ✓ | ✓ | ✓ | ✓ | ## In this section ::card-group :::card --- description: Buy a DISKA number, statuses and assigning it to an agent. icon: i-lucide-phone title: Phone numbers to: https://docs.diska.ai/en/telephony/numbers --- ::: :::card --- description: Point your carrier's or PBX's trunk at Diska — addresses, codecs and import. icon: i-lucide-cable title: Connect over SIP to: https://docs.diska.ai/en/telephony/sip-trunk --- ::: :::card --- description: From reaching the agent to the end of the call, testing and limits. icon: i-lucide-phone-call title: Phone calls to: https://docs.diska.ai/en/telephony/phone-calls --- ::: :::card --- description: Ring time, maximum duration and end-of-call reasons. icon: i-lucide-timer title: Call settings to: https://docs.diska.ai/en/telephony/call-settings --- ::: :::card --- description: Call a list of contacts automatically with an Outbound agent. icon: i-lucide-megaphone title: Campaigns to: https://docs.diska.ai/en/telephony/campaigns --- ::: :::card --- description: Your organization's open-call limit and how to plan capacity. icon: i-lucide-layers title: Simultaneous calls to: https://docs.diska.ai/en/telephony/concurrency --- ::: :::card --- description: What happens on the line when a call is handed to a person, by phone or SIP. icon: i-lucide-phone-forwarded title: Transfers to: https://docs.diska.ai/en/telephony/transfers --- ::: :::card --- description: Inbound Webhook before the agent answers and Data Webhook at the end of each call. icon: i-lucide-webhook title: Agent webhooks to: https://docs.diska.ai/en/telephony/webhooks --- ::: :::card --- description: What each end reason in History means and what to do. icon: i-lucide-triangle-alert title: Errors and end reasons to: https://docs.diska.ai/en/telephony/errors --- ::: :: # Personal profile In **Definições → Conta → Perfil** (Settings → Account → Profile) you manage your account's personal information. You can also get there from the user menu at the bottom of the side menu (**Ver perfil pessoal**, View personal profile). The profile is yours: it does not change the organization's details. ## Avatar 1. Click **Alterar avatar** (Change avatar). 2. Pick a JPG, PNG or WebP image of up to 2 MB. 3. The avatar is saved immediately (*Avatar atualizado*). ## Profile information | Field | Notes | | ----------------------------------------- | ------------------------------------------------------- | | **Nome completo** (Full name) | The name shown on the platform and in the members list. | | **Username** | Optional. | | **Cargo** (Job title) | Optional. | | **Telefone** (Phone) | Optional. | | **Idioma preferido** (Preferred language) | Português or English. | | **Fuso horário** (Time zone) | Africa/Luanda, Africa/Maputo, Europe/Lisbon or UTC. | | **Biografia** (Bio) | Free text. | After editing, click **Guardar perfil** (Save profile). *Perfil atualizado* (profile updated) appears. The account email is not changed here: see [Credentials](https://docs.diska.ai/en/settings/credentials). # Credentials The **Definições → Conta → Credenciais** (Settings → Account → Credentials) page gathers your account security. These settings follow you across every organization you belong to. The page has four cards: - **Email** — the account address and its status; - **Password** — see [Password](https://docs.diska.ai/en/settings/password); - **Autenticação de dois fatores** (Two-factor authentication) — still *Em breve* (coming soon), see [Two-factor authentication](https://docs.diska.ai/en/settings/two-factor); - **Sessões ativas** (Active sessions) — see [Active sessions](https://docs.diska.ai/en/settings/sessions). ## Email The card shows the email and a **Verificado** (Verified) or **Por verificar** (Not verified) badge. - **Reenviar verificação** (Resend verification) sends the verification email again (only while the email is not verified). - **Alterar email** (Change email) asks for the **Novo email** (new email) and the **Password atual** (current password). Click **Enviar confirmação** (Send confirmation) and follow the instructions sent to both the current and the new address. ## Accounts that sign in with Google If you signed in with Google, the page shows *Acesso com Google* (Google access): your email and password are managed in your Google account, and the **Alterar email** and **Alterar password** buttons are not shown. To manage a Diska password, sign in with email and password. # Password ## Change your password 1. Go to **Definições → Conta → Credenciais** (Settings → Account → Credentials). 2. On the **Password** card, click **Alterar password** (Change password). 3. Fill in **Password atual** (current password), **Nova password** (new password) and **Confirmar nova password** (confirm new password). You can tick **Mostrar passwords** (Show passwords) to see what you typed. 4. Click **Alterar password**. *Password alterada* (password changed) appears. The new password must have: - at least 10 characters; - an uppercase letter; - a number; - a special character. The indicator under the field shows which requirements are met. If the current password is wrong, you will see *Password atual incorreta.* ## Forgot your password On the sign-in screen, click **Esqueceu-se da palavra-passe?** (Forgot your password?), enter your email and follow the instructions you receive. ## Accounts that sign in with Google If you sign in with Google, your password is managed in your Google account and the **Alterar password** button is not shown. # Two-factor authentication ::callout{type="warning"} **Not available yet.** The **Autenticação de dois fatores** (Two-factor authentication) card under **Definições → Conta → Credenciais** shows *Em breve* (coming soon) and has no button to turn it on. :: The card announces extra protection with an authenticator app (Google Authenticator, 1Password, Authy or Microsoft Authenticator). It stays *Em breve* until sign-in requires the second factor. ## In the meantime Your account is protected by: - a **password** with strength rules — see [Password](https://docs.diska.ai/en/settings/password); - **Google sign-in**, if you use it; - **active sessions**, which you can end at any time — see [Active sessions](https://docs.diska.ai/en/settings/sessions). # Active sessions The **Sessões ativas** (Active sessions) card under **Definições → Conta → Credenciais** lists the devices where your account was used recently. Each session shows: - the browser and operating system (for example, *Chrome em Windows*); - the country, or *Localização indisponível* (location unavailable), and the IP; - **Última atividade** (Last activity); - the **Sessão atual** (Current session) badge on the device you are using. ## End a session Click **Terminar** (End) next to a device you do not recognise. That device can no longer use Diska and has to sign in again. The current session has no **Terminar** button: to sign out of this device, use **Terminar sessão** (Sign out) in the user menu. ## End all other sessions **Terminar todas as outras sessões** (End all other sessions) keeps only the current device. The other sessions end immediately. If you suspect unauthorized access, end the other sessions and change your [password](https://docs.diska.ai/en/settings/password). # Company The **Definições → Empresa** (Settings → Company) page, titled **Preferências da empresa** (Company preferences), shows and edits the active company's details. Only the **Owner** and **Admins** can see it and save changes. ## Fields | Field | Notes | | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Nome** (Name) | The company name shown on the platform and in communications. Between 2 and 120 characters. | | **Website** | The company's public URL, starting with `http://` or `https://`. Can be left empty. | | **NIF** (tax ID) | Angolan tax identification number: 9 or 10 digits for a company, or the BI number for a sole trader. Spaces, dots and hyphens are ignored. Can be left empty. | | **Tipo de negócio** (Business type) | Saúde, Imobiliário, Educação, Restauração, Retalho, Serviços, Seguros, Recrutamento, Hotelaria, Call Center or Outro (Other). Agent templates open filtered by this type. | | **Região do cliente** (Customer region) | Read-only. The region is set in the configuration and cannot be changed. | Click **Guardar alterações** (Save changes), enabled once something changed. *Preferências guardadas* (preferences saved) appears. The name, business type, website and NIF are first asked once, on the **Bem-vindo à Diska** (Welcome to Diska) screen the owner sees on their first visit. Agents created once the company has a name use it as the company they speak for. At the top of the page, **ID da empresa** (Company ID) shows the organization's identifier; click it to copy it (useful when talking to support). ## Recording retention The maximum period for which call recordings are kept is set for the whole organization: **90 days** by default. On each agent, in the **Segurança e conformidade** (Security and compliance) section of its **Definições**, you can shorten that period (7, 30, 90, 180 or 365 days, never above the organization's). This page does not show the organization's period yet. See [Record calls](https://docs.diska.ai/en/guides/record-calls). ## Switch company If you belong to several organizations, pick the company in the selector at the top of the side menu. *Empresa alterada para …* (company changed to …) appears, and the agents, numbers, flows and history switch to the selected company's. # Organization The **Definições → Organização** (Settings → Organization) page shows a summary of the active organization. Only the **Owner** and **Admins** can see it. It shows: - the organization's name; - **Slug** and **Estado** (Status); - **A sua função** (Your role) in this organization. Its buttons take you to the pages where management happens: - **Preferências da empresa** (Company preferences) → [Company](https://docs.diska.ai/en/settings/company); - **Membros da empresa** (Company members) → [Members](https://docs.diska.ai/en/settings/members). To switch organizations, use the selector at the top of the side menu. What an organization is, and what belongs to it, is explained in [Organization](https://docs.diska.ai/en/concepts/organization). # Members The **Definições → Membros** (Settings → Members) page manages who has access to the organization. Only the **Owner** and **Admins** can see it. ## Roles | Role | What it can do | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Proprietário** (Owner) | Everything an Admin does, plus assigning the Owner role. | | **Administrador** (Admin) | Manage members, invitations, company, integrations and API keys; buy, import and assign numbers; archive agents; delete knowledge documents and recordings. Also creates, edits and publishes. | | **Membro** (Member) | Create, edit and publish agents and flows; add and edit knowledge; create and edit actions and tests. Does not see the organization pages under Settings and cannot assign numbers. | | **Visualizador** (Viewer) | View agents, knowledge, actions, history and analytics, and test agents. Changes nothing. | ::callout{type="info"} Testing is open to every role, including **Viewer** . A test call of the published version runs real actions (SMS, bookings, transfers) — see [Phone calls](https://docs.diska.ai/en/telephony/phone-calls#phone-test-call) . :: ## Invite a user 1. Click **Convidar utilizador** (Invite user). 2. In **Convidar para a minha empresa** (Invite to my company), enter the **Endereço de email** (email address). 3. Choose the **Função** (Role): **Membro** or **Admin**. 4. Click either: - **Enviar convite** (Send invitation) — Diska emails the invitation (*Email de convite enviado*); or - **Gerar link** (Generate link) — creates a unique link that you copy and send however you like (*Link de convite gerado*). If the email cannot be sent, *Convite criado* (invitation created) appears with the link to copy. The invitation is valid for **14 days**. The recipient opens the link, sees the **Empresa** (Company), **Email** and **Função** (Role), and clicks **Aceitar convite** (Accept invitation); they must sign in with the invited email. To give someone the **Viewer** or **Owner** role, invite them as Member and change the role once they accept. ## Pending invitations The **Convites** (Invitations) tab lists invitations with **Email**, **Função** and **Estado** (Status). You can copy an invitation's link or **Revogar** (Revoke) it. ## Manage members On the **Utilizadores** (Users) tab: - **Change the role**: pick the new role in the **Função** column and confirm in **Alterar função?** (Change role?). If you change your own role, you may lose access to this page. - **Remove**: click **Remover** (Remove) and confirm in **Remover membro?** (Remove member?). The person loses access to the organization immediately. Rules: - Only an **Owner** can assign the Owner role. - The organization always keeps at least one Owner: the last one cannot be removed or demoted. # Integrations The **Definições → Integrações** (Settings → Integrations) page (*Ligue serviços externos e canais à sua organização.* — connect external services and channels to your organization) lists the services you can use with your agents. Only the **Owner** and **Admins** can see it. ## What the page shows | Category | Service | Status | What it does | | ------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | **Calendário e agendamentos** (Calendar and scheduling) | **Cal.com** | **Ligado** (Connected) once you connect your account | Bookings during the call. Click it to connect or disconnect — see [Cal.com](https://docs.diska.ai/en/integrations/calcom). | | **Mensagens** (Messaging) | **SMS (Ombala)** | **Ligado** or **Não configurado** (Not configured), with the **Gerido pela Diska** (Managed by Diska) badge | Sends SMS during and after the call. Diska configures it; there is nothing to connect on your side. | Below them, the **WhatsApp** section connects the organization's WhatsApp Business number and picks the agents that answer messages and calls. See [Connect WhatsApp](https://docs.diska.ai/en/whatsapp/connect). Only the services you can already use are shown. Other services are not available yet and are not listed. ## Statuses - **Ligado** (Connected) — the integration is configured and can be used by actions and flows. - **Não configurado** (Not configured) — on a **Gerido pela Diska** service, the service is not configured on the platform. Contact DISKA. - No badge — Cal.com has not been connected yet. ## See also - [Integrations](https://docs.diska.ai/en/integrations) — what each integration lets you do. - [Integration not connecting](https://docs.diska.ai/en/troubleshooting/integration-not-connecting). # API keys API keys authenticate the [DISKA API](https://docs.diska.ai/en/api/api-channel): programmatic access to the organization's data (agents, calls, analytics, numbers, knowledge and webhooks) at `https://api.diska.ai/v1`. Only the **Owner** and **Admins** can see the **Definições → Chaves API** (Settings → API keys) page. ## Create a key 1. Click **Criar nova chave API** (Create new API key). 2. Fill in: - **Nome** (Name, required); - **Descrição** (Description, optional); - **Âmbitos** (Scopes) — with nothing selected, the key has full access; - **Expira em** (Expires on, optional). 3. Click **Gerar** (Generate). 4. In the **A sua chave API** (Your API key) window, copy the key and store it somewhere safe. *Não voltará a ser mostrado.* (it will not be shown again). Available scopes: | Scope | In the UI | | -------------------- | ------------------------------------------------- | | `agents:read` | Agentes — leitura (agents, read) | | `agents:write` | Agentes — criar/publicar (agents, create/publish) | | `calls:read` | Chamadas e transcrições (calls and transcripts) | | `analytics:read` | Análises (analytics) | | `phone-numbers:read` | Números (numbers) | | `knowledge:read` | Conhecimento — leitura (knowledge, read) | | `knowledge:write` | Conhecimento — escrita (knowledge, write) | | `webhooks:manage` | Webhooks — gestão (webhooks, manage) | ## The keys list | Column | What it shows | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------- | | **Nome** (Name) | Name and description. | | **Chave** (Key) | A preview (it starts with `dsk_`). The copy button copies only the preview: the full value is only shown at creation. | | **Âmbitos** (Scopes) | *Acesso total* (full access) or the chosen scopes. | | **Data de criação** (Created) | | | **Expira** (Expires) | — when it does not expire. | | **Último uso** (Last used) | Helps you find forgotten keys. | ## Use the key ```bash curl https://api.diska.ai/v1/me \ -H "Authorization: Bearer dsk_…" ``` Endpoints are listed in [Endpoints](https://docs.diska.ai/en/api/endpoints) and authentication is covered in [Authentication](https://docs.diska.ai/en/api/authentication). ## Revoke a key Click the trash icon and confirm in **Revogar chave API** (Revoke API key) → **Revogar chave**. The key is disabled immediately and can no longer access the API. ## Good practices - Keep keys in environment variables or a secrets vault, never in code or the frontend. - Give each integration its own key, with only the scopes it needs. - If a key is compromised, generate a new one and revoke the old one. # Connected apps and OAuth apps Other platforms (a sales system, a CRM) can use DISKA on your company's behalf without being given an API key: in the platform you click "Connect with DISKA", pick the company and the permissions on a DISKA screen, and the platform is connected. If you build the integration, see [OAuth for partner platforms](https://docs.diska.ai/en/api/oauth). ## Connecting an app On the DISKA authorization screen: 1. Check the app's name and its publisher. An app **not yet verified by DISKA** shows a warning: connect it only if you know it. 2. Pick the company. Only the company's **Owner** and **Admins** can connect it. 3. Uncheck the permissions you do not want to give. 4. Click **Ligar** (connect). You return to the platform, already connected. No app can, whatever the permission: see or create API keys, manage members and invites, see billing and minutes, change numbers, telephony or WhatsApp, or delete the company. ## Connected apps **Definições → Aplicações ligadas** (Settings → Connected apps; Owner and Admins) shows, for each app: its publisher, who connected it and when, and when it was last used. - **Retirar permissões** (take permissions away): uncheck and click the button. It applies to the app's very next request. To give more permissions, the app has to ask again. - **Desligar** (disconnect): the app loses access immediately. To use it again, authorize it again. Connecting, taking permissions away and disconnecting are recorded in the activity log. ## OAuth apps (partners) If your organization is a DISKA partner platform, **Definições → Apps OAuth** (Settings → OAuth apps) lets you register the app your customers will connect. The page appears once DISKA switches the feature on for your organization. 1. Click **Registar aplicação** (register app) and fill in the name, the environment (**Teste**/test or **Produção**/live), the redirect URIs and the permissions the app may ask for. 2. Copy the **Client ID** and the **Client secret**. The secret is shown only once; **Gerar novo secret** (new secret) creates another and the old one stops working. 3. Optional: under **Webhook**, set the URL that receives events from every connected company, send a **ping** and look at the latest deliveries. Each app shows how many companies connected it and its status: **Não verificada** (unverified, up to 100 companies), **Verificada** (verified) or **Suspensa** (suspended). A verified app becomes unverified again if its name, description, logo, pages or redirect URIs change, or if it asks for new permissions. Deleting an app disconnects every company. # Settings The **Definições** (Settings) area in the side menu brings together your account settings and the active organization's settings. | Menu group | Pages | Who sees it | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | | **Conta** (Account) | **Perfil** (Profile), **Credenciais** (Credentials) | Every member | | Organization | **Empresa** (Company), **Organização** (Organization), **Integrações** (Integrations), **Chaves API** (API keys), **Aplicações ligadas** (Connected apps; plus **Apps OAuth** for partners) | Owner and Admins | | People | **Membros** (Members) | Owner and Admins | Account pages follow you across every organization you belong to. The others apply only to the organization selected at the top of the side menu. ::card-group :::card --- description: Name, avatar, job title, language and time zone. icon: i-lucide-user title: Profile to: https://docs.diska.ai/en/settings/personal-profile --- ::: :::card --- description: Email, password, two-factor authentication and sessions. icon: i-lucide-key-round title: Credentials to: https://docs.diska.ai/en/settings/credentials --- ::: :::card --- description: The company's name, website and region. icon: i-lucide-building-2 title: Company to: https://docs.diska.ai/en/settings/company --- ::: :::card --- description: Summary of the active organization and your role. icon: i-lucide-users title: Organization to: https://docs.diska.ai/en/settings/organization --- ::: :::card --- description: Invitations, roles and access. icon: i-lucide-user-plus title: Members to: https://docs.diska.ai/en/settings/members --- ::: :::card --- description: Cal.com, SMS and WhatsApp. icon: i-lucide-puzzle title: Integrations to: https://docs.diska.ai/en/settings/integrations --- ::: :::card --- description: Create and revoke DISKA API keys. icon: i-lucide-code-xml title: API keys to: https://docs.diska.ai/en/settings/api-keys --- ::: :::card --- description: Platforms that use DISKA on the company's behalf; OAuth apps for partners. icon: i-lucide-plug title: Connected apps to: https://docs.diska.ai/en/settings/connected-apps --- ::: :: # Agent not answering ## Phone calls Check, in this order: ### 1. The number is ready In **Números** (Numbers), look at the number's **Estado** (Status) column: | Status | What to do | | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | **Sem agente** (No agent) | Assign the number to an agent (step 2). | | **A ativar**, **Credenciais pendentes**, **Não confirmado** | Imported number whose SIP configuration is not ready yet. See [Connect over SIP](https://docs.diska.ai/en/telephony/sip-trunk#track-the-status). | | **Erro SIP** (SIP error) | Read the message in the number's details and fix the settings with the carrier. | | **Desativado** (Disabled) | The number was suspended. Contact DISKA support. | | **Configurado** (Configured) | Carry on: this status does not confirm the agent is published. | An unpaid DISKA number order does not answer: the number only joins the list once DISKA confirms the payment. ### 2. The number is on an Inbound agent In the agent, open **Publicação → Telefone** (Publishing → Phone) and check the number. Only an agent of type **Inbound** answers calls; an **Outbound** agent uses the number only to call out. Each number answers on a single Inbound agent. ### 3. The agent was published after getting the number Calls are answered by the **published version**. If you assigned or changed the number after the last publish, click **Publicar** (Publish). Also check that the agent is not archived. ### 4. The SIP trunk routes to Diska (imported numbers) - The carrier routes the number to the **Origination URI** shown in the number's details. - Calls come from one of the **IPs de sinalização da operadora** (carrier signalling IPs) you entered. - The transport (UDP or TCP) matches on both sides. Diska refuses trunk calls that come from other IPs. ### 5. The organization has not reached its simultaneous call limit If DISKA set a limit, new calls are not answered while that many calls are open. See [Limits](https://docs.diska.ai/en/telephony/phone-calls#limits). ### You heard an automatic message and the call ended The agent could not be reached when the call started. Try again; if it keeps happening, contact support with the time of the call. ## Web calls, widget and public link - The agent has a **published** version. The widget and the public link always use the published version. - The **Link público** (Public link) is on under **Publicação → Link público**. - The browser is allowed to use the microphone. - To narrow the problem down, test the agent in **Testar → Chamada web** (Test → Web call) or **Testar → Chat**. See [Test the agent](https://docs.diska.ai/en/guides/test-agent). ## The agent answers but does not respond well - The agent editor's checklist shows the errors and warnings still to fix. - Publish again after changing the prompt, flow, actions or knowledge. - See [Knowledge not answering](https://docs.diska.ai/en/troubleshooting/kb-not-answering) and [Flow not publishing](https://docs.diska.ai/en/troubleshooting/flow-not-publishing). # Calls drop Start by opening the call in [History](https://docs.diska.ai/en/history/calls): the end reason, the duration and the transcript almost always tell you why it ended. ## The phone call always ends after the same amount of time The agent has **Limitar duração da chamada** (Limit call duration) on. When it reaches the **Máximo (minutos)**, the line hangs up with no goodbye. Raise the maximum or turn the limit off under **Definições → Configuração de chamada** (Settings → Call settings) and publish. See [Call settings](https://docs.diska.ai/en/telephony/call-settings). ## The agent said goodbye and hung up - **Silence**: the caller stopped talking; the agent asked whether they were still there and then said goodbye. - **End requested or task done**: the agent ended the call with one of its end reasons (for example, `user_requested_end` or `task_completed`). If it ends too early, review the prompt or the flow's **Terminar chamada** (End call) node. ## The call dropped during a transfer - **The transfer worked**: once the caller is connected to the destination, the agent leaves the call. This is expected; the conversation with your team member continues and is not recorded. - **The transfer failed**: if the destination was busy, switched off or did not answer within about 20 seconds, the caller stays with the agent. Check the destination in [Call transfers](https://docs.diska.ai/en/actions/call-transfers). - **On a DISKA number**, transfers only go to Angolan mobiles (Africell or Unitel) set in the action or the phone book, and the organization must be authorized to place outbound calls. A number spoken during the conversation, or a landline, is refused. See [Transfers](https://docs.diska.ai/en/telephony/phone-calls#transfers). ## The call ended right at the start The agent could not be reached at start-up: the call ends with a short automatic message or a failed-call tone. Try again; if it keeps happening, contact support with the time of the call. ## Audio cuts or a mid-call drop with no clear reason - **Caller's network**: test from another phone or another network. - **Own SIP trunk**: confirm the agreed IPs, transport and codecs with the carrier, and that no network equipment closes long sessions. - **Web call**: an unstable internet connection, closing the browser tab or the microphone stopping all end the call. The reason shows in History (for example, *Ligação perdida* — connection lost — or *Página fechada* — page closed). If drops keep happening with no visible cause, contact support with the time and number of each call. ## The recording stopped but the call went on That is not a drop: on a phone call only the first 27 minutes of the part with the agent are recorded. See [Record calls](https://docs.diska.ai/en/guides/record-calls). # Flow not publishing When you click **Publicar** (Publish) and the flow has errors, publishing is refused with a **Fluxo inválido** (Invalid flow) notice and the description of the first error. If you only see *Não foi possível publicar* (could not publish), try again; if it repeats, contact support. ## Where to see every error Open the **Lista de verificação** (Checklist) in the agent editor. It shows *N problemas · X erros · Y avisos* (problems, errors, warnings): - flow **errors** block publishing; - **warnings** (for example, a missing phone number) do not. Click an item to jump to the node with the problem. Errors also show on the node itself, on the canvas. See [Validation and publishing](https://docs.diska.ai/en/flow-builder/validation-publishing). ## Common errors | Message | How to fix it | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | | *O fluxo precisa de pelo menos um nó End alcançável para terminar a chamada.* (needs at least one reachable End node) | Connect at least one path to a **Terminar chamada** (End call) node. | | *O ciclo … não tem saída: nenhum caminho a partir dele termina a chamada.* (the loop has no exit) | Give the loop an exit that reaches **Terminar chamada**. | | *A ligação referencia um nó que não existe.* (the edge points to a node that does not exist) | Delete the broken edge and reconnect the nodes. | | *Conversation precisa de uma instrução clara para o agente.* | Write the instruction of the **Conversação** (Conversation) node. | | *End precisa de um motivo de fim de chamada.* / *End precisa de uma despedida antes de terminar a chamada.* | Complete the **Terminar chamada** node (end reason, goodbye). | | *Cada caminho do Branch precisa de variável e operador.* / *Cada caminho LLM Prompt precisa de uma descrição da condição.* | Complete the conditions of the **Dividir o caminho** (Split path) node. | | *Jump precisa de um nó de destino.* / *O destino do Jump já não existe.* | Pick a valid target in the **Saltar para** (Jump to) node. | | *Trigger Subflow precisa de um subflow de destino.* / *Este subflow ainda não tem triggers de entrada ativos.* | Pick the subflow and turn on an entry trigger in it. | | *Este nó não tem nenhuma acção anexada. Anexe uma acção para o usar.* (This node has no action attached.) | Attach to the agent the action the node uses (for example, a custom action). | | *There are no during-call SMS actions attached to this agent.* | Attach a [During-call SMS](https://docs.diska.ai/en/actions/during-call-sms) action to the agent. | | *Transfer para telefone precisa de um número.* (and the equivalents for SIP URI, phone book or action) | Complete the **Transferência** (Transfer) node's destination. | | *Transferir para uma fila ou equipa não existe nas linhas telefónicas. Escolha um telefone, SIP URI, lista telefónica ou acção de transferência.* (queues and teams do not exist on phone lines) | Change the **Transferência** node's destination: phone lines transfer to a number, not to a queue. | | *Seleccione uma acção de Agendamento em tempo real (Acções → Agendamento em tempo real).* | Create or pick the booking action in the **Agendamento** (Booking) node. | | *Booking deve receber uma variável de contacto antes de publicar.* | Collect the contact (for example, the email) before the **Agendamento** node. | | *Marcação (calendário) ainda não está ligada a um fornecedor. …* (calendar not connected) | Connect [Cal.com](https://docs.diska.ai/en/integrations/calcom) under **Definições → Integrações**, or remove the node. | | *… ainda não implementado. Remova-o antes de publicar.* (not implemented yet) | The node belongs to a channel that is not available yet. Remove it. | | *A transferência de chamadas não está disponível neste servidor …* (call transfer not available on this server) | Telephony is not available in this environment. Contact support. | ::callout{type="tip"} Some of these errors only block publishing. In the **Testar** panel with the **Rascunho** (Draft), you can try out a flow that is still incomplete (no **Terminar chamada** , a transfer to a queue, or booking without a connected calendar). :: ## After publishing - The phone number and the knowledge bases are also frozen in the published version: if you change them, publish again. - A transfer that publishes can still fail on a real call if the destination is not allowed on the line. See [Transfers](https://docs.diska.ai/en/telephony/phone-calls#transfers). # Knowledge not answering Check, in this order: ## 1. The base is assigned to the agent 1. Open the agent → **Definições** (Settings) → **Conhecimento e memória** (Knowledge and memory) section. 2. Under **Bases de conhecimento atribuídas** (Assigned knowledge bases), tick the bases the agent should use. 3. Click **Guardar atribuições** (Save assignments). ## 2. The agent was published afterwards Real calls use the bases that were assigned when you published. If you assigned or removed a base afterwards, click **Publicar** (Publish). In the **Testar** panel with the **Rascunho** (Draft), changes apply right away. ## 3. The documents are ready Open the base under **Conhecimento** (Knowledge) and check each document's status: | Status | What to do | | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | **Indexado** (Indexed) / **Pronto** (Ready) | The document is available. | | **A carregar** (Uploading) / **A processar** (Processing) / **Indexação pendente** (Indexing pending) | Wait. | | **Sem texto / indexação pendente** (No text / indexing pending) | The PDF has no selectable text (for example, it is scanned). Upload a version with text or copy the content into a blank document. | | **Extração falhou** / **Indexação falhou** / **Falhou** (extraction, indexing or processing failed) | Read the document's message and use **Reindexar** (Reindex) in the document's menu. | | **Sem indexação** (Not indexed) | The document does not have enough text to index. | **Reindexar tudo** (Reindex all) reprocesses every document in the base. See [Sources](https://docs.diska.ai/en/knowledge-base/sources). ## 4. The question is covered - Check that the answer really is in the documents, written clearly. - For web pages, check that the page has text (not only images or content loaded by scripts). - Use the base's instruction to tell the agent when to consult it. - Tell the agent in its prompt to answer from the knowledge and to admit when it does not know. ## 5. Test and check the diagnostics Run a case in the [Test Center](https://docs.diska.ai/en/test-center) with a question whose answer is in the documents. In the run history, the case details may show the **Diagnóstico da base de conhecimento** (Knowledge base diagnostics), with what the agent found. # Integration not connecting Integrations are managed under **Definições → Integrações** (Settings → Integrations), which only the **Owner** and **Admins** can see. If you cannot find the page, ask one of them. ## Cal.com | Symptom or message | What to do | | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | *Chave API do Cal.com inválida ou sem permissão.* (invalid key or no permission) | Generate a new key in the Cal.com app settings and connect again. | | *Não foi possível contactar o Cal.com. Tente novamente.* (could not reach Cal.com) | Temporary failure. Try again in a moment. | | *Ligação não confirmada* (connection not confirmed) in the panel | Diska could not read the status. Click **Tentar novamente** (Try again). | | *Nenhum tipo de evento encontrado na conta Cal.com.* (no event types) or the **Evento** list is empty | Create an event type in Cal.com and use the refresh button next to **Evento** in the booking action. | | The booking action says *Ligue o Cal.com em Definições → Integrações para seleccionar tipos de evento.* | Cal.com is not connected. See [Cal.com](https://docs.diska.ai/en/integrations/calcom). | | The flow does not publish with *Marcação (calendário) ainda não está ligada a um fornecedor.* | Connect Cal.com, or remove the **Agendamento** (Booking) node. | | The booking fails during the call | The requested time may not be free in Cal.com, or the customer's email (``) may be missing. Check the action under [Real-time booking](https://docs.diska.ai/en/actions/real-time-booking). | To switch Cal.com accounts, click **Desligar** (Disconnect) and connect with the other account's key. ## SMS (Ombala) SMS is **Gerido pela Diska** (managed by Diska): there is nothing to connect on your side. - If the **SMS (Ombala)** card shows **Não configurado** (Not configured), sending SMS is not available on the platform. Contact DISKA. - If it shows **Ligado** (Connected) and an SMS does not arrive, check the destination number and the action's variables in [During-call SMS](https://docs.diska.ai/en/actions/during-call-sms) or [Post-call SMS](https://docs.diska.ai/en/actions/post-call-sms). ## WhatsApp The **WhatsApp** section, on the same page, shows the status of your connections: - *WhatsApp ainda não configurado* (WhatsApp not configured yet) — you have not connected any account yet. - *Novas ligações em preparação* (new connections being prepared) — connecting new accounts is not available yet; the message gives the reason. See [Connect WhatsApp](https://docs.diska.ai/en/whatsapp/connect). ## Other services The page only lists the integrations that are available. To connect other systems (a CRM, for example), use the [DISKA API](https://docs.diska.ai/en/api/api-channel) or [Custom actions](https://docs.diska.ai/en/actions/custom-actions). # Tests failing ## Test Center suites Open the run under **Centro de Testes → Histórico** (Test Center → History) and the case that failed. ### Reading the result - Each criterion shows **Passou** (Passed) or **Falhou** (Failed), with the evaluator's explanation. - **Erro** (Error) on a case means the case run did not finish (for example, a technical failure), not that the agent answered badly. Run it again. - The run is a **Simulação de texto** (Text simulation): it uses no voice and runs no real tools. The line *Não exercitado nesta simulação: …* (not exercised in this simulation) says what was left out. - **Pronto para publicar** (Ready to publish) or **Publicação com pendências** (Publishing has pending issues) summarizes the agent's state at test time. - For flow agents, **Percurso do fluxo** (Flow path) shows the visited nodes and whether the conversation **Chegou ao fim** (Reached the end). ### Common causes | Symptom | What to do | | --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Criteria fail but the conversation looks fine | Rewrite vague criteria in an observable way ("the agent asks for the email" rather than "the agent is helpful"). | | The agent cannot answer | Check the knowledge base — see [Knowledge not answering](https://docs.diska.ai/en/troubleshooting/kb-not-answering). | | The result does not reflect your latest changes | The suite runs against the draft or the published version, depending on **Correr por defeito contra o rascunho (não o publicado)** (run against the draft by default, not the published version). Publish, or adjust this suite option. | | The flow **Não terminou** (Did not finish) | Follow the **Percurso do fluxo** to the last node and fix the path that never reaches **Terminar chamada** (End call). | | *Perdemos a ligação ao teste — atualize a página.* (we lost the connection to the test) | Reload the page; the run carries on on the server. | See [Test Center](https://docs.diska.ai/en/test-center) and [Evaluations](https://docs.diska.ai/en/test-center/evaluations). ## Phone test call In the **Testar → Chamada telefónica** (Test → Phone call) panel, the **Ligar-me** (Call me) button makes the agent call your mobile. If it does not work: ### The Ligar-me button is disabled | Hint | What to do | | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | *Atribua um número DISKA ao agente e publique-o.* (assign a DISKA number and publish) | Assign a DISKA number under **Publicação → Telefone** and publish. | | *Publique o agente uma vez para testar por telefone.* (publish once to test by phone) | Publish the agent. | | *Indique um telemóvel angolano (Africell ou Unitel) com 9 dígitos, ex.: 923 000 000.* | Fix the number under **Ligar para** (Call to). Angolan mobiles (+244) only. | ### The call does not start | Message | What to do | | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | *Atribua ao agente um número DISKA activo e publique-o para testar por telefone.* | The published version has no active DISKA number. Numbers imported over a SIP trunk do not place test calls. Assign a DISKA number and publish. | | *Esta organização ainda não está habilitada para chamadas telefónicas de saída.* (not enabled for outbound calls) | Ask DISKA to authorize the organization. | | *A organização atingiu o limite de chamadas em simultâneo.* (simultaneous call limit reached) | Wait for another call to end. | | *Já tem uma chamada de teste em curso. Termine-a antes de ligar de novo.* (a test call is already in progress) | Hang up the previous call. | | *Atingiu o limite de chamadas de teste desta hora. Tente mais tarde.* (hourly test call limit reached) | Wait until the next hour. | | *Indique o seu telemóvel, não o número do agente.* (enter your mobile, not the agent's number) | Dial your own mobile. | ### The call starts but fails | Message in the panel | What to do | | ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | | *O número está ocupado, desligado ou rejeitou a chamada.* (busy, switched off or rejected) | Check that the phone is on, has signal and is not on another call. | | *A chamada não foi atendida.* (not answered) | Answer sooner, or increase **Duração do toque** (ring time) in [Call settings](https://docs.diska.ai/en/telephony/call-settings). | | *O agente não conseguiu atender a chamada. Tente novamente.* (the agent could not take the call) | Try again. If it repeats, test with **Chamada web** (Web call) to confirm the agent starts. | | *A linha telefónica não está disponível neste momento.* (the phone line is unavailable) | The line is temporarily unavailable. Try later. | | *Não foi possível confirmar o estado da chamada.* (could not confirm the call status) | Check the call in **Históricos** (History) and try again. | ### The call went through but the actions did not happen With **Rascunho — ações simuladas** (Draft — simulated actions), SMS, bookings and transfers are simulated. Choose **V*n* publicada — ações reais** (Published Vn — real actions) to run them for real. See [Phone calls](https://docs.diska.ai/en/telephony/phone-calls#phone-test-call). # Troubleshooting Each page starts from the symptom, lists the causes in the order worth checking and says what to do. Messages in quotes are the ones the backoffice shows (in Portuguese, with an English gloss). First of all, open the call in [History](https://docs.diska.ai/en/history/calls): the transcript, the actions run and the end reason show how far the conversation got. If the problem started suddenly or affects every agent, check [status.diska.ai](https://status.diska.ai){rel=""nofollow""} first: it shows the status of the API, the backoffice and telephony, with ongoing incidents and planned maintenance. ::card-group :::card --- description: Nobody answers when you call the number. icon: i-lucide-phone-off title: Agent not answering to: https://docs.diska.ai/en/troubleshooting/agent-not-answering --- ::: :::card --- description: The call ends earlier than expected. icon: i-lucide-phone-missed title: Calls drop to: https://docs.diska.ai/en/troubleshooting/calls-drop --- ::: :::card --- description: Publishing is refused with flow errors. icon: i-lucide-alert-triangle title: Flow not publishing to: https://docs.diska.ai/en/troubleshooting/flow-not-publishing --- ::: :::card --- description: The agent ignores the knowledge base. icon: i-lucide-book-x title: Knowledge not answering to: https://docs.diska.ai/en/troubleshooting/kb-not-answering --- ::: :::card --- description: Cal.com, SMS or WhatsApp do not work. icon: i-lucide-unplug title: Integration not connecting to: https://docs.diska.ai/en/troubleshooting/integration-not-connecting --- ::: :::card --- description: Test Center suites and test calls with errors. icon: i-lucide-x-circle title: Tests failing to: https://docs.diska.ai/en/troubleshooting/tests-failing --- ::: :: # Privacy Policy ::alert{type="warning"} **Pending legal review.** This text describes accurately how the platform works today, but has not yet been validated by a lawyer. Before presenting it to customers or regulators as a contractual commitment, have it reviewed — particularly the retention, international transfer and data subject rights sections. :: **Last updated:** 24 October 2026 Diska builds AI voice agents that answer calls, qualify contacts and carry out processes over the phone. This policy explains what personal data we process, on what basis, for how long, and who we pass it to. It is written to be read. Where the technical reality matters — for example, that a call is only recorded after the caller is told — we say so concretely rather than in generic terms. ## Who we are Diska is the controller of the data described in this policy. - **Privacy contact:** - **Scope:** the `diska.ai` website, the application at `app.diska.ai`, the API at `api.diska.ai`, the embeddable voice widget, and the calls conducted by the agents our customers configure. ## Two different roles This distinction determines who to approach to exercise your rights. **When you are our customer** (you created an account and configured agents), we are the **controller** of your account, billing and usage data. **When you speak to a customer's agent**, that customer decides why the call happens and what it is for. In that case Diska acts as a **processor**: we handle the call data on the customer's instructions and within the limits they set. If you want to access or delete what was said on a call, the request goes to the company that answered you; we help them respond. ## What we process ### Account data Name, email address, password (stored only as a hash), company, role, phone, language and time zone. If you sign in with Google, we receive your name, email and profile picture from Google — never your Google password. ### Agent configuration Instructions, conversation flows, variables, actions, and documents you upload to the knowledge base. Those documents are split into passages and converted into numeric representations (embeddings) so the agent can consult them during a call. ### Call data This is the core of the service, and worth being precise about: - **Real-time audio.** While the call runs, audio is streamed to the voice provider to be transcribed and answered. It is processed in transit. - **Transcript.** The text of what was said, kept in the call history. - **Metadata.** Start time, duration, status, outcome, the agent involved and — on telephone calls — the phone number. - **Collected variables.** Whatever the agent was configured to ask for: name, contact details, reason for calling, preferred times. - **Audio recording**, only where applicable — see below. ### Recordings are never silent Recording is **off by default**. It is a per-agent decision made by the customer, and the platform enforces two technical guarantees: 1. An agent with no notice wording configured **does not record**, even if recording is switched on. Recording without a notice is not possible. 2. The notice is spoken by the agent at the start of the call. In **explicit** mode, the agent waits for spoken confirmation before continuing. The exact wording used is stored alongside the recording, so it is later possible to know what the caller was told — not merely that "consent existed". ### Website and widget data - **Contact form:** the name, email, company and phone you send us. - **Public demo:** you can speak to Ísis, our demo agent, without an account. That conversation is treated like any other call. - **Analytics:** we use Google Analytics to understand how the site is used. Parameters are filtered before they are sent — emails, phone numbers, identifiers and opaque strings are stripped, and paths containing identifiers are anonymised. - **Technical data:** IP address and user agent, used for security and abuse limiting. ## Legal bases | Purpose | Basis | | ------------------------------------------ | -------------------------------------------------------- | | Providing the service to account holders | Performance of a contract | | Conducting calls on customers' behalf | Customer instructions (as processor) | | Recording calls | Consent of the caller, obtained at the start of the call | | Security, abuse prevention, technical logs | Legitimate interest | | Responding to enquiries | Pre-contractual steps | | Meeting legal and tax obligations | Legal obligation | ## Who we share with We do not sell personal data. We rely on providers who process it on our behalf, under contract, and only for the stated function: | Provider | Function | Data involved | | -------------- | ----------------------------------------------------- | ----------------------------------------------- | | **OpenAI** | Real-time voice, transcription, synthesis, embeddings | Call audio and text, knowledge base passages | | **Inworld AI** | Real-time speech-to-speech, transcription, synthesis | Call audio and text | | **xAI** | Real-time speech-to-speech, transcription, synthesis | Call audio and text | | **ElevenLabs** | Speech synthesis | Text the agent is to speak | | **Cartesia** | Speech synthesis | Text the agent is to speak | | **Supabase** | Database, storage and authentication | Account, configuration, transcripts, recordings | | **Google** | Sign-in and site analytics | Email and profile; navigation events | | **Twilio** | Telephony, where the customer enables phone calls | Phone number and call audio | We may also disclose data where the law requires it, or to defend legal claims. ## International transfers The providers above operate mainly outside Angola, which means data is transferred to other jurisdictions — chiefly the United States and the European Union. We require appropriate contractual safeguards for those transfers. ## How long we keep it - **Account data:** while the account exists, and up to 12 months afterwards for accounting and legal purposes. - **Transcripts and call metadata:** while the customer's account is active, unless deletion is requested earlier. - **Audio recordings:** for the period the customer sets; absent a setting, the same period as transcripts. - **Technical and security logs:** up to 12 months. - **Contact form submissions:** up to 24 months after the last contact. A customer can request early deletion of any call. ## Your rights Under Angola's Law no. 22/11 of 17 June (Personal Data Protection Law) and, where applicable, the GDPR, you have the right to access your data, correct it, delete it, object to processing, request its restriction, and receive it in a portable format. You may withdraw recording consent at any time, without affecting what was lawfully recorded beforehand. Write to . We respond within the statutory period. Where we hold the data on a customer's behalf, we route the request to that customer and help them answer. You also have the right to lodge a complaint with Angola's **Data Protection Agency (APD)**. ## Security Security is covered in detail in the [security documentation](https://docs.diska.ai/en/concepts). In short: connections are encrypted in transit, third-party credentials stay server-side and never reach the browser, each organisation's data is isolated, and the session credentials used by anonymous calls are short-lived and scoped to that call alone. No system is immune. If we detect an incident affecting you, we notify the customers concerned and, where the law requires, the competent authority. ## Children The service is not intended for anyone under 18 and we do not knowingly collect their data. If you believe a minor has provided us with data, contact us and we will delete it. ## Changes We may update this policy. Material changes are communicated to customers by email or in the application, with reasonable notice. The date at the top marks the version in force. # Terms and Conditions ::alert{type="warning"} **Pending legal review.** This accurately describes how the platform works and the rules that apply, but it has not been validated by a lawyer. Before relying on it as a binding contract — particularly the liability, payment and termination sections — have it reviewed. :: **Last updated:** 9 August 2026 These terms govern your use of the Diska platform: the `diska.ai` website, the `app.diska.ai` application, the `api.diska.ai` API, the voice widget and everything associated with them. By creating an account or using the service, you accept them. If you accept on behalf of a company, you confirm you have authority to bind it. In that case "you" means that company. ## What Diska does Diska lets you build voice agents that answer calls, hold conversations according to instructions you define, consult documents you upload, and carry out actions you configure — booking appointments, sending messages, calling external systems. The agent is yours. We provide the platform that runs it. ## Account and access You need an account to use the service. You are responsible for keeping your credentials safe and for everything that happens under your account. Tell us as soon as you suspect unauthorised access. Credentials must not be shared between people: invite your colleagues into the organisation instead, with the appropriate access level. You must be at least 18 years old. ## Your content stays yours The instructions you write, the flows you design, the documents you upload and your call data remain yours. We claim no ownership of them. You grant us only the licence needed to operate the service: to host, process and transmit that content to the providers listed in the [Privacy Policy](https://docs.diska.ai/en/legal/privacy), so the agent can work. You confirm you have the right to use what you upload and that it does not infringe third-party rights. ## What we expect of you Responsibility for what your agents say is yours. Specifically, you agree to: - **Comply with recording and communications law.** The rules vary by jurisdiction. The platform gives you the tools — spoken notice, explicit consent — but using them correctly is your decision. - **Not use Diska for unsolicited bulk calling**, or for campaigns that breach the rules applicable to telephone marketing. - **Not have an agent pass as human** where the law requires it to identify itself as an automated system. - **Not use the service for fraud, harassment, unlawful content, or to try to extract credentials or third-party data.** - **Not attempt to bypass technical limits**, probe the infrastructure, reach another organisation's data, or place artificial load on the platform. - **Obtain the necessary permissions** from the people whose data your agents collect. We may suspend an account that is causing harm — to third parties, to the platform or to other customers — and, wherever reasonable, we warn you first. ## Third-party services The service depends on external providers (language models, speech synthesis and transcription, telephony, hosting). A failure, change or outage at those providers can affect the service. We choose and manage them carefully, but we do not control their availability. ## The limits of AI This deserves saying plainly: a voice agent produces probabilistic answers. It can misunderstand, it can answer incorrectly, and it can fail on a call that mattered. We do not warrant that responses are accurate, complete or fit for a particular purpose. It is on you to test agents before they answer real customers — the Test Center exists for that — and to supervise the results. Do not use Diska as the sole mechanism in critical health, safety, legal or financial decisions without human review. ## Payment Commercial terms — price, billing cycle, usage limits — are those agreed in your plan or proposal. Unless stated otherwise, amounts exclude taxes, which are your responsibility. Non-payment may lead to suspension, after notice. ## Availability We work to keep the service available, but we do not provide it without interruption. There may be planned maintenance, failures and degradations. Unless you hold a written service level agreement, the service is provided "as is". ## Liability To the maximum extent permitted by law, Diska is not liable for lost profits, lost data, lost business opportunities or indirect damages arising from use of the service. Our total liability, on any basis, is limited to the amount you paid us in the 12 months before the event giving rise to it. Nothing in these terms excludes liability that the law does not allow to be excluded. ## Suspension and termination You may close your account at any time. We may terminate or suspend access if you breach these terms, if your usage endangers the platform or others, or for non-payment. After termination you may export your data for **30 days**. After that we delete it in line with the periods in the [Privacy Policy](https://docs.diska.ai/en/legal/privacy). ## Changes We may change these terms. Material changes are communicated with reasonable notice, by email or in the application. Continuing to use the service after they take effect means accepting them; if you disagree, you may close your account. ## Governing law These terms are governed by the law of the Republic of Angola. Disputes not resolved by agreement will be submitted to the competent courts of Luanda. ## Contact Questions about these terms: .