szchat

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 16 Imported by: 0

README

SZChat API (Não oficial)

Go Reference Go Version License

Uma biblioteca cliente em Go para a API do SZChat Chat Center.

Cobre a API pública documentada em /docs/pt-br do seu tenant SZChat, em sua totalidade: Contatos (+ campos customizados, filtro de palavras, mesclagem), Grupos de Contatos, Canais, Agentes (perfil, pausas, tags, HSM, galeria, copilot, WebRTC, tradução simultânea, click-to-call, placeholders), Mensagens entre Agentes, Atendimentos (ciclo completo: iniciar, aceitar, transferir, finalizar, conferência, histórico, busca), Equipes, Administradores, Grupos de Horário, Grupos de Usuário, Mensagens (+ canal genérico + API WhatsApp), Configuração da Aplicação, Tabulações, Pausas, Números Bloqueados, Multicanal, Mensagens Predefinidas e Relatórios.

Aviso: este é um projeto de código aberto independente e não possui qualquer vínculo, patrocínio ou endosso por parte da Fortics, fornecedora oficial do SZChat. "SZChat" é uma marca de sua respectiva proprietária, citada aqui apenas para fins de identificação da API consumida por esta biblioteca.


Instalação

go get github.com/raykavin/szchat-go

Requer Go 1.26+. Única dependência externa: github.com/raykavin/gobox.


Início Rápido

import szchat "github.com/raykavin/szchat-go"

// baseURL é obrigatório e deve ser apenas a URL do seu tenant SZChat, sem o
// path de versão — o "/api/v4" é adicionado automaticamente pela biblioteca.
client, err := szchat.NewClient("https://seu-tenant.sz.chat", "agente@example.com", "sua-senha")
if err != nil {
    log.Fatal(err)
}

ctx := context.Background()

// Listar contatos (primeira página)
page, err := client.ContactAPI.List(ctx, szchat.ContactListFilter{})
if err != nil {
    log.Fatal(err)
}

for _, c := range page.Data {
    fmt.Println(c.ID, c.Name, c.Email)
}

Configuração

A URL base não possui valor padrão e deve ser sempre informada explicitamente como o primeiro argumento de NewClient. Ela é específica de cada tenant e não deve incluir o path de versão da API: a biblioteca anexa /api/v4 automaticamente para manter a compatibilidade interna com a versão da API suportada (ex: passe https://seu-tenant.sz.chat, e a biblioteca chamará https://seu-tenant.sz.chat/api/v4/...).

// URL base obrigatória — apenas o host do tenant, sem "/api/v4"
client, err := szchat.NewClient("https://seu-tenant.sz.chat", "agente@example.com", "sua-senha")

// Device token enviado no login, usado pelo SZChat para push notifications
client, err = szchat.NewClient("https://seu-tenant.sz.chat", "agente@example.com", "sua-senha",
    szchat.WithDeviceToken("meu-device-token"),
)

// Cliente HTTP customizado (TLS, proxies, timeouts customizados, etc.)
httpClient := &http.Client{Timeout: 60 * time.Second}
client, err = szchat.NewClient("https://seu-tenant.sz.chat", "agente@example.com", "sua-senha",
    szchat.WithHTTPClient(httpClient),
)

// Política de retry customizada para falhas transitórias (429/502/503/504 e erros de rede)
client, err = szchat.NewClient("https://seu-tenant.sz.chat", "agente@example.com", "sua-senha",
    szchat.WithRetry(5, 200*time.Millisecond, 2*time.Second),
)

Autenticação

O Client se autentica de forma lazy: a primeira requisição dispara um login usando as credenciais passadas para NewClient, e o token bearer é renovado automaticamente sempre que uma requisição retorna não autorizada — nenhuma configuração adicional é necessária.

client, err := szchat.NewClient("https://seu-tenant.sz.chat", "agente@example.com", "sua-senha")

// Chamar Login explicitamente normalmente não é necessário, mas está disponível:
loginResp, err := client.Login(ctx)

// Obter o perfil do usuário autenticado
me, err := client.Me(ctx)

// Encerrar a sessão atual ("api", "web" ou "all")
err = client.Logout(ctx, "api")

Módulos

Contatos
// Listar contatos (paginado)
page, err := client.ContactAPI.List(ctx, szchat.ContactListFilter{
    ListOptions: szchat.ListOptions{Limit: 20},
})

// Buscar com filtros
page, err = client.ContactAPI.Search(ctx, szchat.ContactListFilter{
    Name:     "Maria",
    Platform: "Whatsapp",
})

// Obter um contato
contact, err := client.ContactAPI.Get(ctx, contactID)

// Criar um contato (Extra mescla campos de canal específicos do tenant no payload)
contact, err = client.ContactAPI.Create(ctx, szchat.ContactRequest{
    Name:     "Maria Silva",
    Whatsapp: "5511999999999",
    Extra:    map[string]any{"Generic_MyBot": "external-id-123"},
})

// Atualizar um contato
contact, err = client.ContactAPI.Update(ctx, contactID, szchat.ContactRequest{
    Name: "Maria S. Silva",
})

// Atualizar apenas campos customizados
fields, err := client.ContactAPI.UpdateFields(ctx, contactID, map[string]any{
    "cpf": "123.456.789-00",
})

// Excluir um contato
err = client.ContactAPI.Delete(ctx, contactID)

// Salvar/atualizar uma anotação
annotation, err := client.ContactAPI.SaveAnnotation(ctx, szchat.ContactAnnotationRequest{
    ContactID:   contactID,
    Observation: "Retornar ligação na segunda-feira",
    AgentID:     agentID,
})

// Estatísticas de atendimento em uma plataforma
stats, err := client.ContactAPI.AttendanceStats(ctx, contactID, "Whatsapp")

Grupos de Contatos
// Listar grupos (paginado)
page, err := client.ContactGroupAPI.List(ctx, szchat.ListOptions{Limit: 20})

// Criar, renomear, excluir
group, err := client.ContactGroupAPI.Create(ctx, "Clientes VIP")
group, err = client.ContactGroupAPI.Update(ctx, group.ID, "Clientes VIP 2026")
err = client.ContactGroupAPI.Delete(ctx, group.ID)

// Grupos aos quais um contato específico pertence
groups, err := client.ContactGroupAPI.ListByContact(ctx, contactID)

Canais
// Listar canais configurados
channels, err := client.ChannelAPI.List(ctx)
for _, ch := range channels {
    fmt.Println(ch.ID, ch.Platform, ch.Number)
}

// Todas as plataformas disponíveis para novos canais
platforms, err := client.ChannelAPI.ListPlatforms(ctx)

// Apenas plataformas com pelo menos um canal ativo
active, err := client.ChannelAPI.ListActivePlatforms(ctx)

Agentes
// Listar agentes (paginado)
page, err := client.AgentAPI.List(ctx, szchat.AgentListFilter{
    ListOptions: szchat.ListOptions{Limit: 20},
    Name:        "João",
})

// Criar, obter, atualizar, excluir (Delete aceita múltiplos ids para exclusão em lote)
agent, err := client.AgentAPI.Create(ctx, szchat.AgentRequest{
    Name:     "João Souza",
    Email:    "joao@example.com",
    Password: "s3cr3t",
})
agent, err = client.AgentAPI.Get(ctx, agent.ID)
agent, err = client.AgentAPI.GetByEmail(ctx, "joao@example.com")
agent, err = client.AgentAPI.Update(ctx, agent.ID, szchat.AgentRequest{Name: "João S."})
err = client.AgentAPI.Delete(ctx, agent.ID)

// Status online entre agentes/administradores
online, err := client.AgentAPI.ListOnlineStatus(ctx, "Whatsapp", "")
online2, err := client.AgentAPI.ListOnlineAgents(ctx, true, "1")

// Dados do próprio agente autenticado
teams, err := client.AgentAPI.MyTeams(ctx)
attendances, err := client.AgentAPI.MyAttendances(ctx)
attendancesPlus, err := client.AgentAPI.MyAttendancesPlus(ctx)
grades, err := client.AgentAPI.MyGrades(ctx)

// Alternar a equipe ativa e atualizar o timestamp de última interação
msg, err := client.AgentAPI.ToggleTeam(ctx, teamID)
err = client.AgentAPI.UpdateLastInteraction(ctx)

Mensagens entre Agentes
// Enviar uma mensagem interna para outro agente
resp, err := client.AgentTalkAPI.SendMessage(ctx, szchat.AgentTalkMessageRequest{
    AgentTo: peerAgentID,
    Type:    "text",
    Message: "Pode assumir esse contato?",
})

// Listar todas as conversas
conversations, err := client.AgentTalkAPI.ListConversations(ctx)

// Histórico paginado com um agente específico
history, err := client.AgentTalkAPI.SearchConversation(ctx, peerAgentID, szchat.ListOptions{
    Limit: 30,
})
for _, msg := range history.Data {
    fmt.Println(msg.AgentFrom, "->", msg.AgentTo, ":", msg.Message)
}

Equipes
// Listar equipes (paginado)
page, err := client.TeamAPI.List(ctx, szchat.TeamListFilter{Limit: 20})

// Resumo leve {_id, name} de todas as equipes
summaries, err := client.TeamAPI.Resume(ctx, true)

// Filtrar equipes por ids
page, err = client.TeamAPI.FilterByIDs(ctx, szchat.TeamFilterByIDsRequest{
    CampaignIDs: []string{teamID1, teamID2},
})

// Criar, atualizar, excluir
team, err := client.TeamAPI.Create(ctx, szchat.Team{
    Name:           "Suporte",
    RuleAttendance: "sequential",
})
updateResp, err := client.TeamAPI.Update(ctx, team.ID, team)
err = client.TeamAPI.Delete(ctx, team.ID)

Administradores
// Listar administradores e grupos de permissão (ambos paginados)
page, err := client.AdminAPI.List(ctx, szchat.ListOptions{Limit: 20})
groups, err := client.AdminAPI.ListGroups(ctx, szchat.ListOptions{})

// Criar, obter, atualizar (parcial), excluir
admin, err := client.AdminAPI.Create(ctx, szchat.AdminRequest{
    Name:    "Usuário Admin",
    Email:   "admin@example.com",
    GroupID: groupID,
})
admin, err = client.AdminAPI.Get(ctx, admin.ID)
updateResp, err := client.AdminAPI.Update(ctx, admin.ID, map[string]any{"name": "Admin U."})
err = client.AdminAPI.Delete(ctx, admin.ID)

Mensagens
// Enviar uma mensagem
resp, err := client.MessageAPI.Send(ctx, szchat.SendMessageRequest{
    PlatformID: contactPlatformID,
    ChannelID:  channelID,
    Type:       "text",
    Message:    "Olá!",
})

// Enviar e criar/atualizar o contato de destino na mesma chamada
resp, err = client.MessageAPI.SendPlus(ctx, szchat.SendMessagePlusRequest{
    SendMessageRequest: szchat.SendMessageRequest{
        PlatformID: "5511999999999",
        ChannelID:  channelID,
        Type:       "text",
        Message:    "Seja bem-vindo!",
    },
    ContactVariables: &szchat.SendMessageContactVariables{
        Name: "Maria Silva",
    },
})

// Anotar/remover uma nota em uma mensagem
note, err := client.MessageAPI.AddAnnotation(ctx, messageID, map[string]any{"note": "Escalado"})
err = client.MessageAPI.RemoveAnnotation(ctx, messageID)

MessageAPI.Read, MessageAPI.Pending e MessageAPI.ReplaceVars envolvem endpoints cujo formato de payload não é documentado publicamente pelo SZChat, por isso aceitam e retornam map[string]any sem tipagem adicional.


Configuração da Aplicação
// Configuração geral do tenant
config, err := client.ApplicationAPI.Get(ctx)
updated, err := client.ApplicationAPI.Update(ctx, szchat.ApplicationUpdateRequest{
    Timezone: "America/Sao_Paulo",
    Language: "pt-BR",
})

// Faixa de notas de atendimento
grades, err := client.ApplicationAPI.GetAttendanceGrades(ctx)
updated, err = client.ApplicationAPI.UpdateAttendanceGrades(ctx, szchat.ApplicationAttendanceGrades{
    InitialGrade: 1,
    FinalGrade:   5,
})

// Mensagens automáticas (opção inválida, atendimento iniciado/concluído)
messages, err := client.ApplicationAPI.GetAutoMessages(ctx)
updated, err = client.ApplicationAPI.UpdateAutoMessages(ctx, szchat.ApplicationMessages{
    StartedService: &szchat.ApplicationAutoMessage{Enable: true, Message: "Já estamos atendendo você!"},
})

Tabulações
// Listar tabulações (paginado)
page, err := client.TabulationAPI.List(ctx, szchat.ListOptions{Limit: 20})

// Criar, renomear, excluir
tab, err := client.TabulationAPI.Create(ctx, "Resolvido")
tab, err = client.TabulationAPI.Update(ctx, tab.ID, "Resolvido - Acompanhar")
err = client.TabulationAPI.Delete(ctx, tab.ID)

Pausas
// Listar motivos de pausa (paginado)
page, err := client.PauseAPI.List(ctx, szchat.ListOptions{Limit: 20})

// Criar, atualizar, excluir
pause, err := client.PauseAPI.Create(ctx, szchat.Pause{
    Name:    "Almoço",
    MaxTime: 3600,
    Active:  true,
})
pause, err = client.PauseAPI.Update(ctx, pause.ID, pause)
err = client.PauseAPI.Delete(ctx, pause.ID)

Paginação

Endpoints paginados retornam *PaginatedResponse[T], um tipo genérico que envolve o formato de paginação estilo Laravel usado em toda a API do SZChat.

type PaginatedResponse[T any] struct {
    CurrentPage  int
    Data         []T
    Total        int
    PerPage      int
    LastPage     int
    From         int
    To           int
    Path         string
    FirstPageURL string
    LastPageURL  string
    NextPageURL  *string
    PrevPageURL  *string
}

Os parâmetros de paginação seguem uma convenção de nomes consistente entre os filtros de listagem, através do ListOptions embutido:

Campo Parâmetro Descrição
Page page Número da página
Limit limit Quantidade de itens por página
Paginate paginate Se deve paginar ("0" ou "1")

Padrão completo de iteração:

opts := szchat.ListOptions{Limit: 50}
for {
    page, err := client.ContactAPI.List(ctx, szchat.ContactListFilter{ListOptions: opts})
    if err != nil {
        log.Fatal(err)
    }
    // processar page.Data ...
    if page.CurrentPage >= page.LastPage {
        break
    }
    opts.Page = page.CurrentPage + 1
}

Tratamento de Erros

Todos os métodos retornam *APIError em falhas no nível HTTP.

page, err := client.ContactAPI.List(ctx, szchat.ContactListFilter{})
if err != nil {
    switch {
    case szchat.IsUnauthorized(err):
        // HTTP 401 - credenciais inválidas ou sessão expirada
    case szchat.IsNotFound(err):
        // HTTP 404 - recurso não encontrado
    case szchat.IsValidationError(err):
        // HTTP 422 - falha de validação
    case szchat.IsConflict(err):
        // HTTP 409 - recurso em conflito
    case szchat.IsRateLimited(err):
        // HTTP 429 - muitas requisições, aguarde e tente novamente
    default:
        var apiErr *szchat.APIError
        if errors.As(err, &apiErr) {
            fmt.Printf("Status: %d\n", apiErr.StatusCode)
            fmt.Printf("Mensagem: %s\n", apiErr.Message)
            fmt.Printf("Erros de campo: %v\n", apiErr.FieldErrors)
        }
    }
}

O client também retenta automaticamente falhas transitórias (429/502/503/504 e erros de rede) e renova o token bearer automaticamente em um único 401, então a maioria dos chamadores só precisa tratar o erro final e definitivo.


Executando os Testes

go test ./... -v

Todos os testes usam net/http/httptest — nenhum serviço externo ou variável de ambiente é necessário.


Cobertura de Endpoints

Auditoria completa contra a documentação oficial do SZChat (/docs/pt-br), última verificação: 2026-08-11.

Autenticação
  • GET /api/version — Obter versão da API (sem autenticação)
  • POST /auth/login — Login
  • POST /auth/login-v2 — Login (variante com motivos de falha 403 detalhados)
  • GET /auth/me — Obter perfil do usuário autenticado
  • GET /auth/logout — Logout
  • GET /auth/refresh — Renovar token
Contatos
  • GET /contacts — Listar contatos (paginado, com filtros)
  • GET /contacts/search — Buscar contatos
  • GET /contacts/{id} — Obter um contato
  • POST /contacts — Criar um contato
  • PUT /contacts/{id} — Atualizar um contato
  • PUT /contacts/update_fields/{id} — Atualizar campos customizados de um contato
  • DELETE /contacts/{id} — Excluir um contato
  • POST /contacts/annotation — Salvar anotação de contato
  • GET /contacts/{id}/attendances — Obter estatísticas de atendimento do contato
  • GET /contacts/recents — Contatos recentes do agente autenticado
  • GET /contacts/merge/similar — Candidatos a mesclagem de um contato
  • GET /contacts/related — Contatos já vinculados a um contato
  • POST /contacts/merge/link — Vincular dois contatos
  • POST /contacts/unmerge — Desvincular um contato
Campos de Contatos
  • GET /contacts/fields — Listar campos customizados
  • POST /contacts/fields — Criar campo customizado
  • PUT /contacts/fields/{id} — Atualizar campo customizado
  • DELETE /contacts/fields/{id} — Excluir campo customizado
Grupos de Contatos
  • GET /contacts/groups — Listar grupos de contatos
  • POST /contacts/groups — Criar grupo de contatos
  • PUT /contacts/groups/{id} — Atualizar grupo de contatos
  • DELETE /contacts/groups/{id} — Excluir grupo de contatos
  • GET /contacts/groups/contact/{contact_id} — Listar grupos por contato
Filtro de Palavras
  • GET /wordFilter/agents — Listar palavras filtradas para agentes
  • POST /wordFilter/agents — Adicionar palavra filtrada (agente)
  • PUT /wordFilter/agents/{id} — Atualizar palavra filtrada (agente)
  • DELETE /wordFilter/agents/{id} — Excluir palavra filtrada (agente)
  • GET /wordFilter/contacts — Listar palavras filtradas para contatos
  • POST /wordFilter/contacts — Adicionar palavra filtrada (contato)
  • PUT /wordFilter/contacts/{id} — Atualizar palavra filtrada (contato)
  • DELETE /wordFilter/contacts/{id} — Excluir palavra filtrada (contato)
Grupo de Horários
  • GET /timeGroup — Listar grupos de horário
  • POST /timeGroup — Criar grupo de horário
  • PUT /timeGroup/{id} — Atualizar grupo de horário
  • DELETE /timeGroup/{id} — Excluir grupo de horário
Grupo de Usuários
  • GET /userGroup — Listar grupos de usuário
  • POST /userGroup — Criar grupo de usuário
  • PUT /userGroup/{id} — Atualizar grupo de usuário
  • DELETE /userGroup/{id} — Excluir grupo de usuário
Mensagens Predefinidas
  • GET /predefined_messages — Listar mensagens predefinidas
  • GET /predefined_messages/{id} — Obter uma mensagem predefinida
  • POST /predefined_messages — Criar mensagem predefinida
  • PUT /predefined_messages/{id} — Atualizar mensagem predefinida
  • DELETE /predefined_messages/{id} — Excluir mensagem predefinida
Multicanal
  • GET /multichannel — Listar links multicanal
  • POST /multichannel — Criar link multicanal
  • PUT /multichannel/{id} — Atualizar link multicanal
  • DELETE /multichannel/{id} — Excluir link multicanal
Números Bloqueados
  • GET /blockedNumbers — Listar números bloqueados
  • POST /blockedNumbers — Bloquear um número
  • PUT /blockedNumbers/{id} — Atualizar um número bloqueado
  • DELETE /blockedNumbers/{id} — Desbloquear um número
Canais
  • GET /channels — Listar canais
  • GET /channels/platforms — Listar plataformas disponíveis
  • GET /channels/platforms/active — Listar plataformas ativas
Agentes
  • GET /agents — Listar agentes (paginado, com filtros)
  • POST /agents — Criar um agente
  • GET /agents/{id} — Obter um agente
  • GET /agents/email/{email} — Obter um agente por email
  • PUT /agents/{id} — Atualizar um agente
  • DELETE /agents/{id} — Excluir um ou mais agentes
  • GET /online-status — Listar status online dos agentes
  • GET /user/agents/online — Listar agentes/administradores online
  • GET /user/agents/campaigns — Obter minhas equipes
  • GET /user/agents/attendances — Obter meus atendimentos
  • GET /user/agents/attendances_plus — Obter meus atendimentos (detalhado)
  • GET /user/agents/sessions/attendances — Meus atendimentos em andamento (paginado)
  • GET /user/agents/sessions/waits — Meus atendimentos em espera (paginado)
  • GET /user/agents/grades — Obter minhas notas
  • POST /user/agents/toggle/campaign — Alternar minha equipe ativa
  • POST /user/agents/updateLastInteraction — Atualizar meu timestamp de última interação
  • POST /agents/photo — Enviar foto de perfil do agente
  • PUT /user/agents/update — Editar meu perfil (nome, ramal, senha, idioma)
Pausas do Agente
  • GET /user/agents/pauses — Listar motivos de pausa disponíveis
  • POST /user/agents/pauses/start — Iniciar uma pausa
  • POST /user/agents/pauses/stop — Encerrar a pausa atual
  • GET /user/agents/pauses/progress — Progresso da pausa atual
Mensagens entre Agentes
  • POST /user/agents/messages/send — Enviar mensagem interna
  • GET /user/agents/messages — Listar minhas conversas
  • GET /user/agents/messages/read/{agent_id} — Obter histórico de conversa com um par
Tags
  • GET /user/agents/list/tagsCategory — Listar categorias de tag
  • POST /user/agents/session/setTagCategory — Atribuir tag a uma sessão
  • POST /user/agents/session/deleteTagCategory — Remover tag de uma sessão
Modelos de Mensagem (HSM)
  • POST /hsm/listAll — Listar modelos HSM disponíveis
Galeria
  • GET /agent/historic/medias — Listar mídias trocadas com um contato
Placeholders
  • POST /user/agent/placeholders — Resolver placeholders para um contato/agente/sessão
Copilot
  • GET /user/agent/copilot/list — Listar assistentes de copilot
  • POST /user/agent/copilot/execute — Executar um assistente de copilot
WebRTC
  • GET /user/agent/webrtc/{agent_id} — Obter configuração de WebRTC de um agente
Tradução Simultânea
  • POST /user/agent/stt/translate — Traduzir uma mensagem
  • POST /user/agent/stt/translate/detect — Detectar idioma de uma mensagem
  • POST /user/agent/stt/translate/activeAutoTranslate — Alternar tradução automática de uma sessão
Click to Call
  • POST /user/agent/call — Ligar para um contato pelo ramal do agente
Atendimentos (ciclo de vida)
  • POST /session/init — Iniciar um atendimento
  • POST /attendances/accept — Aceitar um atendimento em espera
  • POST /attendances/finish — Finalizar um atendimento
  • POST /attendances/transfer — Transferir um atendimento (equipe ou agente)
  • GET /attendances — Pesquisar atendimentos
  • GET /attendances/phase/{phase} — Listar atendimentos por fase
  • POST /attendances/show — Exibir uma sessão
  • POST /attendances/historic — Histórico recente de um contato
  • POST /attendances/historic/period — Histórico por período
  • GET /attendances/historic/interval — Histórico por intervalo de datas (paginado)
  • POST /attendances/historic/messages — Mensagens de uma sessão finalizada
  • POST /attendances/historic/protocol — Sessão completa por protocolo
Conferência entre Agentes
  • POST /attendances/conference/invite — Convidar agente para conferência
  • POST /attendances/conference/accept — Aceitar/recusar convite de conferência
  • POST /attendances/conference/finish — Finalizar participação em conferência
Equipes
  • GET /campaigns — Listar equipes (paginado)
  • GET /campaigns/resume/{paginate} — Listar resumo de equipes
  • POST /campaigns/filterByIds — Filtrar equipes por ids
  • POST /campaigns — Criar uma equipe
  • PUT /campaigns/{id} — Atualizar uma equipe
  • PUT /campaigns/{id}?scanFields=true — Atualizar uma equipe migrando campos legados
  • DELETE /campaigns/{id} — Excluir uma equipe
Administradores
  • GET /admins — Listar administradores (paginado)
  • GET /admins/groups — Listar grupos de permissão de administradores
  • POST /admins — Criar um administrador
  • GET /admins/{id} — Obter um administrador
  • PUT /admins/{id} — Atualizar um administrador
  • DELETE /admins/{id} — Excluir um administrador
Mensagens
  • POST /message/send — Enviar uma mensagem
  • POST /message/send_plus — Enviar mensagem e criar/atualizar contato
  • POST /message/read — Ler mensagens de uma sessão
  • POST /message/pending — Obter contagem de mensagens pendentes
  • GET /config/storage/view/{storage_id} — Baixar uma mídia armazenada
  • POST /message/replace_vars — Substituir variáveis de template
  • POST /message/{id}/annotation — Adicionar anotação a uma mensagem
  • DELETE /message/{id}/annotation — Remover anotação de uma mensagem
Canal Genérico
  • POST /generic/messages/send — Encaminhar mensagem entrante (texto/mídia/localização/contato)
  • POST /generic/messages/send — Encaminhar notificação de status do dispositivo
API WhatsApp
  • POST /whatsapp/attendances — Encaminhar conversa/transferir para atendimento humano
Configuração da Aplicação
  • GET /application — Obter configuração do tenant
  • PUT /application — Atualizar configuração do tenant
  • GET /application/attendance — Obter faixa de notas de atendimento
  • PUT /application/attendance — Atualizar faixa de notas de atendimento
  • GET /application/messages — Obter configuração de mensagens automáticas
  • PUT /application/messages — Atualizar configuração de mensagens automáticas
Tabulações
  • GET /tabulations — Listar tabulações (paginado)
  • POST /tabulations — Criar uma tabulação
  • PUT /tabulations/{id} — Atualizar uma tabulação
  • DELETE /tabulations/{id} — Excluir uma tabulação
Pausas (catálogo do tenant)
  • GET /pauses — Listar pausas (paginado)
  • POST /pauses — Criar uma pausa
  • PUT /pauses/{id} — Atualizar uma pausa
  • DELETE /pauses/{id} — Excluir uma pausa
Relatórios
  • GET /reports/attendances — Relatório de atendimentos (analítico/sintético)

Total: 153 endpoints cobertos


Contribuindo

Contribuições para o szchat-go são bem-vindas! Aqui estão algumas formas de ajudar:

  • Reportar bugs e sugerir funcionalidades abrindo issues no GitHub
  • Enviar pull requests com correções de bugs ou novas funcionalidades
  • Melhorar a documentação para ajudar outros usuários e desenvolvedores

Licença

O szchat-go é distribuído sob a Licença MIT. Para os termos e condições completos da licença, veja o arquivo LICENSE no repositório.

Documentation

Overview

Package szchat is a Go SDK for the SZChat Chat Center API (see the official SZChat API documentation, available under the "/docs/pt-br" path of your tenant's SZChat host).

A Client authenticates lazily: the first request triggers a login using the credentials passed to NewClient, and the bearer token is refreshed automatically whenever a request comes back unauthorized.

baseURL is tenant-specific (e.g. "https://your-tenant.sz.chat") and must not include the API version path: NewClient appends "/api/v4" to it automatically to keep internal compatibility with the API version this library targets.

client, err := szchat.NewClient(baseURL, email, password)
if err != nil {
	return err
}

contacts, err := client.ContactAPI.List(ctx, szchat.ContactListFilter{})
if err != nil {
	if szchat.IsRateLimited(err) {
		// back off and retry later
	}
	return err
}

for _, contact := range contacts.Data {
	fmt.Println(contact.Name)
}

Every resource lives under its own Client field (ContactAPI, AgentAPI, TeamAPI, ChannelAPI, and so on), each wrapping a single business domain of the SZChat API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsConflict

func IsConflict(err error) bool

IsConflict reports whether err is an *APIError with a 409 status.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is an *APIError with a 404 status.

func IsRateLimited

func IsRateLimited(err error) bool

IsRateLimited reports whether err is an *APIError with a 429 status.

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized reports whether err is an *APIError with a 401 status.

func IsValidationError

func IsValidationError(err error) bool

IsValidationError reports whether err is an *APIError with a 422 status.

Types

type APIError

type APIError struct {
	StatusCode  int
	Message     string
	FieldErrors map[string][]string
	Body        []byte
}

APIError represents a non-2xx response from the SZChat API. The response body shape is not fully uniform across endpoints, so FieldErrors and Message are populated on a best-effort basis; Body always holds the raw response for callers that need the original payload.

func (*APIError) Error

func (e *APIError) Error() string

type APIVersionResponse added in v0.1.0

type APIVersionResponse struct {
	Version string `json:"version"`
}

APIVersionResponse is the payload returned by Client.APIVersion.

type Admin

type Admin struct {
	ID                        string `json:"_id,omitempty"`
	Type                      string `json:"type,omitempty"`
	Name                      string `json:"name"`
	Email                     string `json:"email"`
	EmailForgotPassword       string `json:"email_forgot_password,omitempty"`
	GroupID                   string `json:"groupId"`
	Language                  string `json:"language,omitempty"`
	SessionToken              string `json:"session_token,omitempty"`
	LoggedAt                  string `json:"logged_at,omitempty"`
	Status                    string `json:"status,omitempty"`
	HasAuthToken              bool   `json:"hasAuthToken,omitempty"`
	SessionAgent              string `json:"session_agent,omitempty"`
	EnableLoginWithRemoteAuth bool   `json:"enable_login_with_remote_auth,omitempty"`
	CreatedAt                 string `json:"created_at,omitempty"`
	UpdatedAt                 string `json:"updated_at,omitempty"`
}

Admin is a SZChat administrator account.

type AdminAPI

type AdminAPI struct {
	// contains filtered or unexported fields
}

AdminAPI groups the /admins endpoints.

func (*AdminAPI) Create

func (a *AdminAPI) Create(ctx context.Context, req AdminRequest) (*Admin, error)

Create creates an administrator via POST /admins.

func (*AdminAPI) Delete

func (a *AdminAPI) Delete(ctx context.Context, id string) error

Delete deletes an administrator via DELETE /admins/{id}.

func (*AdminAPI) Get

func (a *AdminAPI) Get(ctx context.Context, id string) (*Admin, error)

Get returns a single administrator via GET /admins/{id}.

func (*AdminAPI) List

List returns a paginated list of administrators via GET /admins.

func (*AdminAPI) ListGroups

func (a *AdminAPI) ListGroups(ctx context.Context, opts ListOptions) (*PaginatedResponse[AdminGroup], error)

ListGroups returns a paginated list of administrator groups via GET /admins/groups.

func (*AdminAPI) Update

func (a *AdminAPI) Update(ctx context.Context, id string, fields map[string]any) (*AdminUpdateResponse, error)

Update partially updates an administrator via PUT /admins/{id}.

type AdminGroup

type AdminGroup struct {
	ID          string   `json:"_id"`
	Name        string   `json:"name"`
	Master      int      `json:"master,omitempty"`
	Permissions []string `json:"permissions,omitempty"`
	CreatedAt   string   `json:"created_at,omitempty"`
	UpdatedAt   string   `json:"updated_at,omitempty"`
}

AdminGroup is a permission group administrators can belong to.

type AdminRequest

type AdminRequest struct {
	Email                     string `json:"email"`
	Name                      string `json:"name"`
	Password                  string `json:"password,omitempty"`
	EmailForgotPassword       string `json:"email_forgot_password,omitempty"`
	EnableLoginWithRemoteAuth *bool  `json:"enable_login_with_remote_auth,omitempty"`
	GroupID                   string `json:"groupId"`
}

AdminRequest is the payload for AdminAPI.Create.

type AdminUpdateResponse

type AdminUpdateResponse struct {
	Success bool `json:"success"`
	Date    struct {
		Date         string `json:"date"`
		TimezoneType int    `json:"timezone_type"`
		Timezone     string `json:"timezone"`
	} `json:"date"`
}

AdminUpdateResponse is the ack returned by AdminAPI.Update.

type Agent

type Agent struct {
	ID                        string           `json:"_id"`
	Type                      string           `json:"type,omitempty"`
	Name                      string           `json:"name"`
	Email                     string           `json:"email"`
	Codename                  string           `json:"codename,omitempty"`
	Ramal                     string           `json:"ramal,omitempty"`
	Begin                     string           `json:"begin,omitempty"`
	End                       string           `json:"end,omitempty"`
	Campaigns                 []string         `json:"campaigns,omitempty"`
	Groups                    []string         `json:"groups,omitempty"`
	Photo                     string           `json:"photo,omitempty"`
	History                   string           `json:"history,omitempty"`
	UsernameCallcenter        string           `json:"username_callcenter,omitempty"`
	EmailForgotPassword       string           `json:"email_forgot_password,omitempty"`
	EnableLoginWithRemoteAuth bool             `json:"enable_login_with_remote_auth,omitempty"`
	AgentPermission           *AgentPermission `json:"agentPermission,omitempty"`
	Status                    string           `json:"status,omitempty"`
	LoggedAt                  string           `json:"logged_at,omitempty"`
	CreatedAt                 string           `json:"created_at,omitempty"`
	UpdatedAt                 string           `json:"updated_at,omitempty"`
}

Agent is a SZChat attendant account.

type AgentAPI

type AgentAPI struct {
	// contains filtered or unexported fields
}

AgentAPI groups the /agents and current-agent (/user/agents/*) endpoints.

func (*AgentAPI) Create

func (a *AgentAPI) Create(ctx context.Context, req AgentRequest) (*Agent, error)

Create creates an agent via POST /agents.

func (*AgentAPI) Delete

func (a *AgentAPI) Delete(ctx context.Context, ids ...string) error

Delete deletes one or more agents via DELETE /agents/{id}, accepting several ids for a bulk delete.

func (*AgentAPI) Get

func (a *AgentAPI) Get(ctx context.Context, id string) (*Agent, error)

Get returns a single agent via GET /agents/{id}.

func (*AgentAPI) GetByEmail

func (a *AgentAPI) GetByEmail(ctx context.Context, email string) (*Agent, error)

GetByEmail returns a single agent via GET /agents/email/{email}.

func (*AgentAPI) List

List returns a paginated list of agents via GET /agents.

func (*AgentAPI) ListOnlineAgents

func (a *AgentAPI) ListOnlineAgents(ctx context.Context, allUsers bool, paginate string) (*PaginatedResponse[AgentOnline], error)

ListOnlineAgents lists online agents (and admins, if allUsers is true) via GET /user/agents/online.

func (*AgentAPI) ListOnlineStatus

func (a *AgentAPI) ListOnlineStatus(ctx context.Context, platform, status string) ([]AgentOnline, error)

ListOnlineStatus lists agents' online status via GET /online-status, optionally filtered by platform and/or status. Pass an empty string to leave a filter unset.

func (*AgentAPI) MyAttendances

func (a *AgentAPI) MyAttendances(ctx context.Context) (*AgentAttendances, error)

MyAttendances returns the authenticated agent's active/waiting contacts via GET /user/agents/attendances.

func (*AgentAPI) MyAttendancesPlus

func (a *AgentAPI) MyAttendancesPlus(ctx context.Context) (*AgentAttendances, error)

MyAttendancesPlus is like MyAttendances but with extended contact details via GET /user/agents/attendances_plus.

func (*AgentAPI) MyGrades

func (a *AgentAPI) MyGrades(ctx context.Context) (*AgentGrades, error)

MyGrades returns the authenticated agent's attendance grades via GET /user/agents/grades.

func (*AgentAPI) MyTeams

func (a *AgentAPI) MyTeams(ctx context.Context) (*AgentTeamsResponse, error)

MyTeams returns the authenticated agent's teams via GET /user/agents/campaigns.

func (*AgentAPI) SessionAttendances added in v0.1.0

func (a *AgentAPI) SessionAttendances(ctx context.Context, filter AgentSessionListFilter) (*PaginatedResponse[Attendance], error)

SessionAttendances returns a paginated list of the authenticated agent's in-progress attendance sessions via GET /user/agents/sessions/attendances.

func (*AgentAPI) SessionWaits added in v0.1.0

SessionWaits returns a paginated list of the authenticated agent's waiting attendance sessions via GET /user/agents/sessions/waits.

func (*AgentAPI) ToggleTeam

func (a *AgentAPI) ToggleTeam(ctx context.Context, teamID string) (string, error)

ToggleTeam toggles the authenticated agent's active team/campaign via POST /user/agents/toggle/campaign.

func (*AgentAPI) Update

func (a *AgentAPI) Update(ctx context.Context, id string, req AgentRequest) (*Agent, error)

Update updates an agent via PUT /agents/{id}.

func (*AgentAPI) UpdateLastInteraction

func (a *AgentAPI) UpdateLastInteraction(ctx context.Context) error

UpdateLastInteraction refreshes the authenticated agent's last-interaction timestamp via POST /user/agents/updateLastInteraction.

func (*AgentAPI) UpdateProfile added in v0.1.0

UpdateProfile edits the authenticated agent's own name, extension, password, or default language via PUT /user/agents/update.

func (*AgentAPI) UploadPhoto added in v0.1.0

func (a *AgentAPI) UploadPhoto(ctx context.Context, filename string, photo io.Reader) (*AgentPhotoUploadResponse, error)

UploadPhoto uploads the authenticated agent's profile photo via POST /agents/photo. filename should include the image extension (jpeg/jpg/png).

type AgentAttendanceContact

type AgentAttendanceContact struct {
	ID             string   `json:"_id"`
	Status         string   `json:"status,omitempty"`
	Phase          string   `json:"phase,omitempty"`
	Email          string   `json:"email,omitempty"`
	Phone          string   `json:"phone,omitempty"`
	UserSince      string   `json:"user_since,omitempty"`
	RecentContacts []string `json:"recent_contacts,omitempty"`
}

AgentAttendanceContact is a contact currently or awaiting attendance by the authenticated agent.

type AgentAttendances

type AgentAttendances struct {
	Attendance []AgentAttendanceContact `json:"attendance"`
	Wait       []AgentAttendanceContact `json:"wait"`
}

AgentAttendances is the payload returned by AgentAPI.MyAttendances and MyAttendancesPlus.

type AgentConversation

type AgentConversation struct {
	AgentID string             `json:"agent_id"`
	Talks   []AgentTalkMessage `json:"talks"`
}

AgentConversation groups the messages exchanged with a single peer agent.

type AgentGrades

type AgentGrades struct {
	Average struct {
		Average float64 `json:"average"`
		Message string  `json:"message"`
	} `json:"average"`
}

AgentGrades is the payload returned by AgentAPI.MyGrades.

type AgentListFilter

type AgentListFilter struct {
	ListOptions
	Name       string
	CampaignID string
}

AgentListFilter holds the query parameters accepted by AgentAPI.List.

type AgentOnline

type AgentOnline struct {
	ID                 string        `json:"_id"`
	Type               string        `json:"type,omitempty"`
	Email              string        `json:"email,omitempty"`
	Name               string        `json:"name"`
	Codename           string        `json:"codename,omitempty"`
	Ramal              string        `json:"ramal,omitempty"`
	Begin              string        `json:"begin,omitempty"`
	End                string        `json:"end,omitempty"`
	Status             string        `json:"status,omitempty"`
	LoggedAt           string        `json:"logged_at,omitempty"`
	Campaigns          []string      `json:"campaigns,omitempty"`
	CampaignsOnline    []TeamSummary `json:"campaigns_online,omitempty"`
	Groups             []string      `json:"groups,omitempty"`
	Attendances        int           `json:"attendances,omitempty"`
	Phone              string        `json:"phone,omitempty"`
	UserSince          string        `json:"user_since,omitempty"`
	RecentContacts     []string      `json:"recent_contacts,omitempty"`
	Photo              string        `json:"photo,omitempty"`
	Language           string        `json:"language,omitempty"`
	History            string        `json:"history,omitempty"`
	Pause              any           `json:"pause,omitempty"`
	MsTeams            any           `json:"msTeams,omitempty"`
	SessionToken       string        `json:"session_token,omitempty"`
	UsernameCallcenter string        `json:"username_callcenter,omitempty"`
	PasswordCallcenter string        `json:"password_callcenter,omitempty"`
	CreatedAt          string        `json:"created_at,omitempty"`
	UpdatedAt          string        `json:"updated_at,omitempty"`
}

AgentOnline is an agent/admin entry as returned by the online-status endpoints.

type AgentPauseAPI added in v0.1.0

type AgentPauseAPI struct {
	// contains filtered or unexported fields
}

AgentPauseAPI groups the authenticated agent's own pause endpoints (/user/agents/pauses*), distinct from PauseAPI which manages the tenant's pause reason catalog.

func (*AgentPauseAPI) List added in v0.1.0

List returns the pause reason catalog available to the authenticated agent via GET /user/agents/pauses.

func (*AgentPauseAPI) Progress added in v0.1.0

func (a *AgentPauseAPI) Progress(ctx context.Context, newVersion bool) (*AgentPauseProgress, error)

Progress returns the authenticated agent's current pause progress via GET /user/agents/pauses/progress.

func (*AgentPauseAPI) Start added in v0.1.0

Start begins a pause for the authenticated agent via POST /user/agents/pauses/start.

func (*AgentPauseAPI) Stop added in v0.1.0

func (a *AgentPauseAPI) Stop(ctx context.Context, pauseID string) (string, error)

Stop ends the authenticated agent's current pause via POST /user/agents/pauses/stop.

type AgentPauseProgress added in v0.1.0

type AgentPauseProgress struct {
	Status int `json:"status"`
	Pause  struct {
		Pause
		StartTime      string `json:"startTime,omitempty"`
		CumulativeTime string `json:"cumulative_time,omitempty"`
	} `json:"pause"`
}

AgentPauseProgress is the payload returned by AgentPauseAPI.Progress.

type AgentPauseStartRequest added in v0.1.0

type AgentPauseStartRequest struct {
	PauseID             string `json:"pause_id"`
	IsPausePersonalized bool   `json:"isPausePersonalized,omitempty"`
	IsNewPause          bool   `json:"is_new_pause,omitempty"`
}

AgentPauseStartRequest is the payload for AgentPauseAPI.Start.

type AgentPauseStartResponse added in v0.1.0

type AgentPauseStartResponse struct {
	Message string `json:"message"`
	Pause   Pause  `json:"pause"`
}

AgentPauseStartResponse is the payload returned by AgentPauseAPI.Start.

type AgentPermission

type AgentPermission struct {
	HideReviewStars               bool `json:"hideReviewStars,omitempty"`
	HandleSimultaneousAttendances bool `json:"handleSimultaneousAttendances,omitempty"`
	SimultaneousAttendancesLimit  int  `json:"simultaneousAttendancesLimit,omitempty"`
}

AgentPermission holds per-agent capability overrides.

type AgentPhotoUploadResponse added in v0.1.0

type AgentPhotoUploadResponse struct {
	Success bool   `json:"success"`
	Date    string `json:"date"`
}

AgentPhotoUploadResponse is the payload returned by AgentAPI.UploadPhoto.

type AgentProfileUpdateRequest added in v0.1.0

type AgentProfileUpdateRequest struct {
	Name            string `json:"name,omitempty"`
	Ramal           int    `json:"ramal,omitempty"`
	Password        string `json:"password,omitempty"`
	NewPassword     string `json:"new_password,omitempty"`
	DefaultLanguage string `json:"default_language,omitempty"`
}

AgentProfileUpdateRequest is the payload for AgentAPI.UpdateProfile.

type AgentProfileUpdateResponse added in v0.1.0

type AgentProfileUpdateResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

AgentProfileUpdateResponse is the payload returned by AgentAPI.UpdateProfile.

type AgentRequest

type AgentRequest struct {
	Name                      string           `json:"name"`
	Password                  string           `json:"password,omitempty"`
	Email                     string           `json:"email"`
	Codename                  string           `json:"codename,omitempty"`
	Begin                     string           `json:"begin,omitempty"`
	End                       string           `json:"end,omitempty"`
	Campaigns                 []string         `json:"campaigns,omitempty"`
	Photo                     string           `json:"photo,omitempty"`
	Groups                    []string         `json:"groups,omitempty"`
	History                   string           `json:"history,omitempty"`
	Ramal                     string           `json:"ramal,omitempty"`
	UsernameCallcenter        string           `json:"username_callcenter,omitempty"`
	PasswordCallcenter        string           `json:"password_callcenter,omitempty"`
	EmailForgotPassword       string           `json:"email_forgot_password,omitempty"`
	EnableLoginWithRemoteAuth *bool            `json:"enable_login_with_remote_auth,omitempty"`
	AgentPermission           *AgentPermission `json:"agentPermission,omitempty"`
}

AgentRequest is the payload for creating/updating an Agent.

type AgentSessionListFilter added in v0.1.0

type AgentSessionListFilter struct {
	Name        string
	Paginate    bool
	Page        int
	ContactPlus bool
}

AgentSessionListFilter holds the query parameters accepted by AgentAPI.SessionAttendances and AgentAPI.SessionWaits.

type AgentTalkAPI

type AgentTalkAPI struct {
	// contains filtered or unexported fields
}

AgentTalkAPI groups the internal agent-to-agent messaging endpoints (/user/agents/messages*).

func (*AgentTalkAPI) ListConversations

func (a *AgentTalkAPI) ListConversations(ctx context.Context) ([]AgentConversation, error)

ListConversations lists the authenticated agent's internal conversations via GET /user/agents/messages.

func (*AgentTalkAPI) SearchConversation

func (a *AgentTalkAPI) SearchConversation(ctx context.Context, agentID string, opts ListOptions) (*PaginatedResponse[AgentTalkMessage], error)

SearchConversation returns the paginated message history with a peer agent via GET /user/agents/messages/read/{agent_id}.

func (*AgentTalkAPI) SendMessage

SendMessage sends an internal message to another agent via POST /user/agents/messages/send.

type AgentTalkMessage

type AgentTalkMessage struct {
	ID        string `json:"_id,omitempty"`
	Message   string `json:"message,omitempty"`
	AgentFrom string `json:"agent_from,omitempty"`
	AgentTo   string `json:"agent_to,omitempty"`
	Type      string `json:"type,omitempty"`
	Filename  string `json:"filename,omitempty"`
	MimeType  string `json:"mime_type,omitempty"`
	Mimetype  string `json:"mimetype,omitempty"`
	Legend    string `json:"legend,omitempty"`
	StorageID string `json:"storage_id,omitempty"`
	CreatedAt string `json:"created_at,omitempty"`
	UpdatedAt string `json:"updated_at,omitempty"`
}

AgentTalkMessage is an internal agent-to-agent chat message. The API is inconsistent about the mime-type field name across endpoints, so both MimeType ("mime_type", used on send) and Mimetype ("mimetype", used on read) are populated depending on which endpoint returned it.

type AgentTalkMessageRequest

type AgentTalkMessageRequest struct {
	AgentTo string `json:"agent_to"`
	Type    string `json:"type"`
	Message string `json:"message,omitempty"`
	File    string `json:"file,omitempty"`
	Legend  string `json:"legend,omitempty"`
}

AgentTalkMessageRequest is the payload for AgentTalkAPI.SendMessage.

type AgentTalkSendResponse

type AgentTalkSendResponse struct {
	Event   string           `json:"event"`
	Content AgentTalkMessage `json:"content"`
}

AgentTalkSendResponse is the payload returned by AgentTalkAPI.SendMessage.

type AgentTeam added in v0.1.0

type AgentTeam struct {
	ID             string `json:"_id"`
	Name           string `json:"name"`
	History        string `json:"history,omitempty"`
	Timer          any    `json:"timer,omitempty"`
	Transhipment   string `json:"transhipment,omitempty"`
	MessageEnd     string `json:"messageEnd,omitempty"`
	MessageAgent   string `json:"messageAgent,omitempty"`
	RuleAttendance string `json:"ruleAttendance,omitempty"`
	Tabulations    string `json:"tabulations,omitempty"`
	CreatedAt      string `json:"created_at,omitempty"`
	UpdatedAt      string `json:"updated_at,omitempty"`
}

AgentTeam is a team/campaign entry as returned by AgentAPI.MyTeams, richer than TeamSummary since /user/agents/campaigns embeds most of the team's own configuration. Timer is typed any because this endpoint returns its days/hours/minutes as strings, unlike Team.Timer's ints.

type AgentTeamsResponse

type AgentTeamsResponse struct {
	Success bool `json:"success"`
	Agent   struct {
		ID        string   `json:"_id"`
		Type      string   `json:"type,omitempty"`
		Email     string   `json:"email,omitempty"`
		Name      string   `json:"name,omitempty"`
		Codename  string   `json:"codename,omitempty"`
		Begin     string   `json:"begin,omitempty"`
		End       string   `json:"end,omitempty"`
		Campaigns []string `json:"campaigns"`
		Groups    []string `json:"groups,omitempty"`
		CreatedAt string   `json:"created_at,omitempty"`
		UpdatedAt string   `json:"updated_at,omitempty"`
	} `json:"agent"`
	Campaigns []AgentTeam `json:"campaigns"`
}

AgentTeamsResponse is the payload returned by AgentAPI.MyTeams.

type ApplicationAPI

type ApplicationAPI struct {
	// contains filtered or unexported fields
}

ApplicationAPI groups the /application endpoints.

func (*ApplicationAPI) Get

Get returns the tenant configuration via GET /application.

func (*ApplicationAPI) GetAttendanceGrades

func (a *ApplicationAPI) GetAttendanceGrades(ctx context.Context) (*ApplicationAttendanceGrades, error)

GetAttendanceGrades returns the attendance grade range via GET /application/attendance.

func (*ApplicationAPI) GetAutoMessages

func (a *ApplicationAPI) GetAutoMessages(ctx context.Context) (*ApplicationMessages, error)

GetAutoMessages returns the automatic messages configuration via GET /application/messages.

func (*ApplicationAPI) Update

Update updates the tenant configuration via PUT /application.

func (*ApplicationAPI) UpdateAttendanceGrades

func (a *ApplicationAPI) UpdateAttendanceGrades(ctx context.Context, req ApplicationAttendanceGrades) (*ApplicationConfig, error)

UpdateAttendanceGrades updates the attendance grade range via PUT /application/attendance.

func (*ApplicationAPI) UpdateAutoMessages

func (a *ApplicationAPI) UpdateAutoMessages(ctx context.Context, req ApplicationMessages) (*ApplicationConfig, error)

UpdateAutoMessages updates the automatic messages configuration via PUT /application/messages.

type ApplicationAttendanceGrades

type ApplicationAttendanceGrades struct {
	InitialGrade any `json:"initial_grade,omitempty"`
	FinalGrade   any `json:"final_grade,omitempty"`
}

ApplicationAttendanceGrades is the request/response payload for the /application/attendance grade range endpoints.

type ApplicationAutoMessage

type ApplicationAutoMessage struct {
	Message string `json:"message"`
	Enable  bool   `json:"enable"`
}

ApplicationAutoMessage is an automatic message toggle (wrong option, service started/completed).

type ApplicationConfig

type ApplicationConfig struct {
	ID               string                  `json:"_id,omitempty"`
	Pagination       int                     `json:"pagination,omitempty"`
	Timezone         string                  `json:"timezone,omitempty"`
	Language         string                  `json:"language,omitempty"`
	DDI              int                     `json:"ddi,omitempty"`
	ClosingCommand   string                  `json:"closingCommand,omitempty"`
	APIToken         string                  `json:"apiToken,omitempty"`
	CompletedService *ApplicationAutoMessage `json:"completed_service,omitempty"`
	StartedService   *ApplicationAutoMessage `json:"started_service,omitempty"`
	WrongOption      *ApplicationAutoMessage `json:"wrong_option,omitempty"`
	Distribuition    any                     `json:"distribuition,omitempty"`
	FinalGrade       any                     `json:"final_grade,omitempty"`
	InitialGrade     any                     `json:"initial_grade,omitempty"`
	StorageID        string                  `json:"storage_id,omitempty"`
	CreatedAt        string                  `json:"created_at,omitempty"`
	UpdatedAt        string                  `json:"updated_at,omitempty"`
}

ApplicationConfig is the tenant-wide configuration object. FinalGrade and InitialGrade are typed any because the API returns them as strings from some endpoints and numbers from others.

type ApplicationConfigList

type ApplicationConfigList struct {
	Configurations []ApplicationConfig `json:"configurations"`
}

ApplicationConfigList is the payload returned by ApplicationAPI.Get.

type ApplicationMessages

type ApplicationMessages struct {
	WrongOption      *ApplicationAutoMessage `json:"wrong_option,omitempty"`
	StartedService   *ApplicationAutoMessage `json:"started_service,omitempty"`
	CompletedService *ApplicationAutoMessage `json:"completed_service,omitempty"`
}

ApplicationMessages is the request/response payload for the /application/messages automatic message endpoints.

type ApplicationUpdateRequest

type ApplicationUpdateRequest struct {
	Pagination int    `json:"pagination,omitempty"`
	Timezone   string `json:"timezone,omitempty"`
	Language   string `json:"language,omitempty"`
	DDI        int    `json:"ddi,omitempty"`
	StorageID  string `json:"storage_id,omitempty"`
}

ApplicationUpdateRequest is the payload for ApplicationAPI.Update.

type Attendance added in v0.1.0

type Attendance struct {
	ID                    string            `json:"_id,omitempty"`
	Name                  string            `json:"name,omitempty"`
	ContactID             string            `json:"contact_id,omitempty"`
	ChannelID             string            `json:"channel_id,omitempty"`
	AgentID               string            `json:"agent_id,omitempty"`
	CampaignID            string            `json:"campaign_id,omitempty"`
	PlatformID            string            `json:"platform_id,omitempty"`
	Platform              string            `json:"platform,omitempty"`
	Status                string            `json:"status,omitempty"`
	Protocol              string            `json:"protocol,omitempty"`
	Phase                 string            `json:"phase,omitempty"`
	Group                 string            `json:"group,omitempty"`
	Position              int               `json:"position,omitempty"`
	LastInteraction       string            `json:"lastInteraction,omitempty"`
	IsAttendance          bool              `json:"isAttendance,omitempty"`
	ContactAlreadyStarted bool              `json:"contactAlreadyStarted,omitempty"`
	CreatedAt             string            `json:"created_at,omitempty"`
	TimerOnWait           string            `json:"timerOnWait,omitempty"`
	TimerAccept           string            `json:"timerAccept,omitempty"`
	WaitingByCodename     bool              `json:"waitingByCodename,omitempty"`
	Wait                  string            `json:"wait,omitempty"`
	ContinueFlow          bool              `json:"continueFlow,omitempty"`
	CampaignFinishMessage string            `json:"campaignFinishMessage,omitempty"`
	MenuAttempts          int               `json:"menuAttempts,omitempty"`
	AgentsConference      []string          `json:"agents_conference,omitempty"`
	Tags                  []AttendanceTag   `json:"tags,omitempty"`
	Events                []AttendanceEvent `json:"events,omitempty"`
	Talks                 []AttendanceTalk  `json:"talks,omitempty"`
	FinishedAt            string            `json:"finished_at,omitempty"`
}

Attendance is a session/attendance record, as returned by AttendanceAPI's Find, FindByPhase, and Show operations. Fields not present on a given endpoint's response are simply left zero-valued.

type AttendanceAPI added in v0.1.0

type AttendanceAPI struct {
	// contains filtered or unexported fields
}

AttendanceAPI groups the /attendances, /session/init and /attendances/conference endpoints covering the full attendance/session lifecycle: creation, acceptance, transfer, conferencing, search, and history.

func (*AttendanceAPI) Accept added in v0.1.0

Accept accepts a waiting session into attendance via POST /attendances/accept.

func (*AttendanceAPI) ConferenceAccept added in v0.1.0

ConferenceAccept accepts or declines a conference invite via POST /attendances/conference/accept.

func (*AttendanceAPI) ConferenceFinish added in v0.1.0

ConferenceFinish ends the authenticated agent's participation in a session's conference via POST /attendances/conference/finish.

func (*AttendanceAPI) ConferenceInvite added in v0.1.0

ConferenceInvite invites an online agent to join a session's conference via POST /attendances/conference/invite.

func (*AttendanceAPI) Find added in v0.1.0

Find searches attendances via GET /attendances.

func (*AttendanceAPI) FindByPhase added in v0.1.0

func (a *AttendanceAPI) FindByPhase(ctx context.Context, phase string) ([]Attendance, error)

FindByPhase lists attendances in a given phase ("auto", "wait", or "human") via GET /attendances/phase/{phase}.

func (*AttendanceAPI) Finish added in v0.1.0

Finish closes an attendance session via POST /attendances/finish.

func (*AttendanceAPI) Historic added in v0.1.0

func (a *AttendanceAPI) Historic(ctx context.Context, contactID string) (*AttendanceHistoricResponse, error)

Historic returns a contact's most recent attendances and the list of periods with history available via POST /attendances/historic.

func (*AttendanceAPI) HistoricByInterval added in v0.1.0

HistoricByInterval returns a paginated list of attendances within a date interval via GET /attendances/historic/interval.

func (*AttendanceAPI) HistoricByPeriod added in v0.1.0

HistoricByPeriod returns a contact's attendances within a given period (format "YYYY_MM" or "YYYY_MM_DD") via POST /attendances/historic/period.

func (*AttendanceAPI) HistoricByProtocol added in v0.1.0

func (a *AttendanceAPI) HistoricByProtocol(ctx context.Context, protocolID string) (*AttendanceDetail, error)

HistoricByProtocol returns the full session record for a given protocol number via POST /attendances/historic/protocol.

func (*AttendanceAPI) HistoricMessages added in v0.1.0

HistoricMessages returns the messages exchanged in a finished session via POST /attendances/historic/messages.

func (*AttendanceAPI) Init added in v0.1.0

Init starts a new attendance session via POST /session/init.

func (*AttendanceAPI) Show added in v0.1.0

Show returns a single session by session_id or contact_id via POST /attendances/show.

func (*AttendanceAPI) Transfer added in v0.1.0

Transfer transfers a session to another team or agent via POST /attendances/transfer.

type AttendanceAcceptRequest added in v0.1.0

type AttendanceAcceptRequest struct {
	SessionID    string `json:"session_id"`
	Agent        string `json:"agent,omitempty"`
	AttendanceID string `json:"attendance_id,omitempty"`
}

AttendanceAcceptRequest is the payload for AttendanceAPI.Accept.

type AttendanceConferenceAcceptRequest added in v0.1.0

type AttendanceConferenceAcceptRequest struct {
	SessionID string `json:"session_id"`
	Accept    bool   `json:"accept"`
}

AttendanceConferenceAcceptRequest is the payload for AttendanceAPI.ConferenceAccept.

type AttendanceConferenceFinishRequest added in v0.1.0

type AttendanceConferenceFinishRequest struct {
	SessionID string `json:"session_id"`
}

AttendanceConferenceFinishRequest is the payload for AttendanceAPI.ConferenceFinish.

type AttendanceConferenceInviteRequest added in v0.1.0

type AttendanceConferenceInviteRequest struct {
	SessionID string `json:"session_id"`
	AgentID   string `json:"agent_id"`
}

AttendanceConferenceInviteRequest is the payload for AttendanceAPI.ConferenceInvite.

type AttendanceDetail added in v0.1.0

type AttendanceDetail struct {
	Attendance
	Contact         *Contact `json:"contact,omitempty"`
	Campaign        *Team    `json:"campaign,omitempty"`
	Channel         *Channel `json:"channel,omitempty"`
	Tabulation      any      `json:"tabulation,omitempty"`
	AttendanceTimer struct {
		TTA  float64 `json:"tta,omitempty"`
		TMA  float64 `json:"tma,omitempty"`
		TME  float64 `json:"tme,omitempty"`
		TTA2 float64 `json:"tta2,omitempty"`
	} `json:"attendance_timer,omitempty"`
	ReportAt string `json:"report_at,omitempty"`
	Lite     bool   `json:"lite,omitempty"`
}

AttendanceDetail is the full session record returned by AttendanceAPI.HistoricByProtocol and AttendanceAPI.Show, including the denormalized contact/campaign/channel snapshots the API embeds.

type AttendanceEvent added in v0.1.0

type AttendanceEvent struct {
	Event      string `json:"event"`
	CreatedAt  string `json:"created_at,omitempty"`
	AgentFrom  string `json:"agent_from,omitempty"`
	AgentTo    string `json:"agent_to,omitempty"`
	CampaignTo string `json:"campaign_to,omitempty"`
}

AttendanceEvent is a lifecycle event recorded on an attendance session (e.g. "waitStart", "humanStart").

type AttendanceFindFilter added in v0.1.0

type AttendanceFindFilter struct {
	Name       string
	ContactID  string
	ChannelID  string
	AgentID    string
	CampaignID string
	PlatformID string
	Platform   string
	Status     string
	Protocol   string
}

AttendanceFindFilter holds the query parameters accepted by AttendanceAPI.Find.

type AttendanceFinishRequest added in v0.1.0

type AttendanceFinishRequest struct {
	SessionID    string `json:"session_id"`
	TabulationID string `json:"tabulation_id,omitempty"`
}

AttendanceFinishRequest is the payload for AttendanceAPI.Finish.

type AttendanceHistoricByPeriodEntry added in v0.1.0

type AttendanceHistoricByPeriodEntry struct {
	ID               string   `json:"_id"`
	SessionID        string   `json:"session_id,omitempty"`
	PlatformID       string   `json:"platform_id,omitempty"`
	Protocol         string   `json:"protocol,omitempty"`
	ChannelPlatform  string   `json:"channel_platform,omitempty"`
	ChannelID        string   `json:"channel_id,omitempty"`
	TME              float64  `json:"tme,omitempty"`
	CreatedAt        string   `json:"createdAt,omitempty"`
	AgentName        []string `json:"agentName,omitempty"`
	CampaignName     []string `json:"campaign_name,omitempty"`
	FinishedAt       string   `json:"finishedAt,omitempty"`
	StatusAttendance string   `json:"statusAttendance,omitempty"`
}

AttendanceHistoricByPeriodEntry is a single item in AttendanceAPI.HistoricByPeriod's response.

type AttendanceHistoricByPeriodRequest added in v0.1.0

type AttendanceHistoricByPeriodRequest struct {
	ContactID        string `json:"contact_id"`
	Period           string `json:"period"`
	Platform         string `json:"platform,omitempty"`
	StatusAttendance string `json:"statusAttendance,omitempty"`
}

AttendanceHistoricByPeriodRequest is the payload for AttendanceAPI.HistoricByPeriod.

type AttendanceHistoricByPeriodResponse added in v0.1.0

type AttendanceHistoricByPeriodResponse struct {
	Attendances []AttendanceHistoricByPeriodEntry `json:"attendances"`
}

AttendanceHistoricByPeriodResponse is the payload returned by AttendanceAPI.HistoricByPeriod.

type AttendanceHistoricEntry added in v0.1.0

type AttendanceHistoricEntry struct {
	ID         string `json:"_id"`
	Protocol   string `json:"protocol,omitempty"`
	CreatedAt  string `json:"created_at,omitempty"`
	FinishedAt string `json:"finished_at,omitempty"`
}

AttendanceHistoricEntry is a single item in AttendanceAPI.Historic's response.

type AttendanceHistoricIntervalEntry added in v0.1.0

type AttendanceHistoricIntervalEntry struct {
	ID               string `json:"_id"`
	Protocol         string `json:"protocol,omitempty"`
	PlatformID       string `json:"platform_id,omitempty"`
	CreatedAt        string `json:"created_at,omitempty"`
	FinishedAt       string `json:"finished_at,omitempty"`
	Email            string `json:"email,omitempty"`
	StatusAttendance string `json:"statusAttendance,omitempty"`
}

AttendanceHistoricIntervalEntry is a single item in AttendanceAPI.HistoricByInterval's response.

type AttendanceHistoricIntervalFilter added in v0.1.0

type AttendanceHistoricIntervalFilter struct {
	InitialDate      string
	EndDate          string
	ContactID        string
	PlatformID       string
	Email            string
	StatusAttendance string
	PerPage          int
}

AttendanceHistoricIntervalFilter holds the query parameters accepted by AttendanceAPI.HistoricByInterval.

type AttendanceHistoricMessage added in v0.1.0

type AttendanceHistoricMessage struct {
	MessageID  string `json:"message_id"`
	RequestID  string `json:"request_id,omitempty"`
	Origin     string `json:"origin,omitempty"`
	Type       string `json:"type,omitempty"`
	CreatedAt  string `json:"created_at,omitempty"`
	Blocked    bool   `json:"blocked,omitempty"`
	Message    string `json:"message,omitempty"`
	Privacy    string `json:"privacy,omitempty"`
	MessageRef string `json:"message_ref,omitempty"`
}

AttendanceHistoricMessage is a single item in AttendanceAPI.HistoricMessages's response.

type AttendanceHistoricMessagesRequest added in v0.1.0

type AttendanceHistoricMessagesRequest struct {
	SessionID  string `json:"session_id"`
	CreatedAt  string `json:"created_at"`
	FinishedAt string `json:"finished_at"`
}

AttendanceHistoricMessagesRequest is the payload for AttendanceAPI.HistoricMessages.

type AttendanceHistoricProtocolRequest added in v0.1.0

type AttendanceHistoricProtocolRequest struct {
	ProtocolID string `json:"protocol_id"`
}

AttendanceHistoricProtocolRequest is the payload for AttendanceAPI.HistoricByProtocol.

type AttendanceHistoricResponse added in v0.1.0

type AttendanceHistoricResponse struct {
	Attendances []AttendanceHistoricEntry `json:"attendances"`
	Periods     []string                  `json:"periods"`
}

AttendanceHistoricResponse is the payload returned by AttendanceAPI.Historic.

type AttendanceInitRequest added in v0.1.0

type AttendanceInitRequest struct {
	ContactID          string   `json:"contact_id"`
	Platform           string   `json:"platform"`
	ChannelID          string   `json:"channel_id"`
	TeamID             string   `json:"team_id"`
	AgentID            string   `json:"agent_id"`
	HSMID              string   `json:"hsm_id,omitempty"`
	TagMessage         string   `json:"tagMessage,omitempty"`
	TagType            string   `json:"tagType,omitempty"`
	PlaceholdersParams []string `json:"placeholders_params,omitempty"`
}

AttendanceInitRequest is the payload for AttendanceAPI.Init.

type AttendanceInitResponse added in v0.1.0

type AttendanceInitResponse struct {
	Success  bool   `json:"success"`
	Message  string `json:"message"`
	Response struct {
		SessionID string `json:"session_id"`
	} `json:"response"`
}

AttendanceInitResponse is the payload returned by AttendanceAPI.Init.

type AttendanceMessage added in v0.1.0

type AttendanceMessage struct {
	Message   string `json:"message"`
	AgentTo   string `json:"agent_to,omitempty"`
	CreatedAt string `json:"created_at,omitempty"`
}

AttendanceMessage is a message reply.

type AttendanceShowRequest added in v0.1.0

type AttendanceShowRequest struct {
	SessionID string `json:"session_id,omitempty"`
	ContactID string `json:"contact_id,omitempty"`
}

AttendanceShowRequest is the payload for AttendanceAPI.Show.

type AttendanceTag added in v0.1.0

type AttendanceTag struct {
	Question  string `json:"question,omitempty"`
	Answer    string `json:"answer,omitempty"`
	Tag       string `json:"tag,omitempty"`
	Type      string `json:"type,omitempty"`
	CreatedAt string `json:"created_at,omitempty"`
}

AttendanceTag is a tag applied to an attendance session.

type AttendanceTalk added in v0.1.0

type AttendanceTalk struct {
	MessageID  string `json:"message_id,omitempty"`
	RequestID  string `json:"request_id,omitempty"`
	Origin     string `json:"origin,omitempty"`
	Type       string `json:"type,omitempty"`
	CreatedAt  string `json:"created_at,omitempty"`
	Blocked    bool   `json:"blocked,omitempty"`
	Message    string `json:"message,omitempty"`
	MessageRef string `json:"message_ref,omitempty"`
}

AttendanceTalk is a message exchanged within an attendance session, as returned by history/detail endpoints.

type AttendanceTransferRequest added in v0.1.0

type AttendanceTransferRequest struct {
	SessionID    string `json:"session_id"`
	Type         string `json:"type"`
	AttendanceID string `json:"attendance_id,omitempty"`
	AgentID      string `json:"agent_id,omitempty"`
	TransferWait bool   `json:"transfer_wait,omitempty"`
}

AttendanceTransferRequest is the payload for AttendanceAPI.Transfer.

type BlockedNumber added in v0.1.0

type BlockedNumber struct {
	ID        string `json:"_id,omitempty"`
	Number    string `json:"number"`
	CreatedAt string `json:"created_at,omitempty"`
	UpdatedAt string `json:"updated_at,omitempty"`
}

BlockedNumber is a phone number blocked from starting new attendances.

type BlockedNumberAPI added in v0.1.0

type BlockedNumberAPI struct {
	// contains filtered or unexported fields
}

BlockedNumberAPI groups the /blockedNumbers endpoints.

func (*BlockedNumberAPI) Create added in v0.1.0

func (a *BlockedNumberAPI) Create(ctx context.Context, number string) (*BlockedNumber, error)

Create blocks a number via POST /blockedNumbers.

func (*BlockedNumberAPI) Delete added in v0.1.0

func (a *BlockedNumberAPI) Delete(ctx context.Context, id string) error

Delete unblocks a number via DELETE /blockedNumbers/{id}.

func (*BlockedNumberAPI) List added in v0.1.0

List returns a paginated list of blocked numbers via GET /blockedNumbers.

func (*BlockedNumberAPI) Update added in v0.1.0

func (a *BlockedNumberAPI) Update(ctx context.Context, id, number string) (*BlockedNumber, error)

Update updates a blocked number via PUT /blockedNumbers/{id}.

type Channel

type Channel struct {
	ID             string `json:"_id"`
	Platform       string `json:"platform"`
	FlowID         string `json:"flow_id,omitempty"`
	Receptive      bool   `json:"receptive,omitempty"`
	Description    string `json:"description,omitempty"`
	Number         string `json:"number,omitempty"`
	BotToken       string `json:"bot_token,omitempty"`
	MessengerToken string `json:"messenger_token,omitempty"`
	CreatedAt      string `json:"created_at,omitempty"`
	UpdatedAt      string `json:"updated_at,omitempty"`
}

Channel is a configured messaging channel (a WhatsApp number, a Telegram bot, a web chat widget, etc).

type ChannelAPI

type ChannelAPI struct {
	// contains filtered or unexported fields
}

ChannelAPI groups the /channels endpoints.

func (*ChannelAPI) List

func (a *ChannelAPI) List(ctx context.Context) ([]Channel, error)

List returns all configured channels via GET /channels.

func (*ChannelAPI) ListActivePlatforms

func (a *ChannelAPI) ListActivePlatforms(ctx context.Context) (map[string]ChannelPlatform, error)

ListActivePlatforms returns only the platforms with at least one active channel via GET /channels/platforms/active.

func (*ChannelAPI) ListPlatforms

func (a *ChannelAPI) ListPlatforms(ctx context.Context) (map[string]ChannelPlatform, error)

ListPlatforms returns all messaging platforms available for new channels via GET /channels/platforms.

type ChannelPlatform

type ChannelPlatform struct {
	Platform   string `json:"platform"`
	Name       string `json:"name"`
	Color      string `json:"color,omitempty"`
	PlatformID string `json:"platform_id,omitempty"`
	SaveRedis  bool   `json:"save_redis,omitempty"`
	Icon       string `json:"icon,omitempty"`
}

ChannelPlatform describes a messaging platform SZChat can create channels for.

type ClickToCallAPI added in v0.1.0

type ClickToCallAPI struct {
	// contains filtered or unexported fields
}

ClickToCallAPI groups the agent click-to-call endpoint.

func (*ClickToCallAPI) Call added in v0.1.0

func (a *ClickToCallAPI) Call(ctx context.Context, contactID string) (*ClickToCallResponse, error)

Call places a call from the authenticated agent's extension to a contact via POST /user/agent/call.

type ClickToCallResponse added in v0.1.0

type ClickToCallResponse struct {
	Status  bool   `json:"status"`
	Message string `json:"message"`
}

ClickToCallResponse is the payload returned by ClickToCallAPI.Call.

type Client

type Client struct {
	ContactAPI           *ContactAPI
	ContactGroupAPI      *ContactGroupAPI
	ContactFieldAPI      *ContactFieldAPI
	ChannelAPI           *ChannelAPI
	AgentAPI             *AgentAPI
	AgentTalkAPI         *AgentTalkAPI
	AgentPauseAPI        *AgentPauseAPI
	TeamAPI              *TeamAPI
	AdminAPI             *AdminAPI
	MessageAPI           *MessageAPI
	ApplicationAPI       *ApplicationAPI
	TabulationAPI        *TabulationAPI
	PauseAPI             *PauseAPI
	AttendanceAPI        *AttendanceAPI
	TagAPI               *TagAPI
	HSMAPI               *HSMAPI
	GalleryAPI           *GalleryAPI
	PlaceholderAPI       *PlaceholderAPI
	CopilotAPI           *CopilotAPI
	WebRTCAPI            *WebRTCAPI
	TranslationAPI       *TranslationAPI
	ClickToCallAPI       *ClickToCallAPI
	TimeGroupAPI         *TimeGroupAPI
	UserGroupAPI         *UserGroupAPI
	WordFilterAgentAPI   *WordFilterAgentAPI
	WordFilterContactAPI *WordFilterContactAPI
	MultichannelAPI      *MultichannelAPI
	BlockedNumberAPI     *BlockedNumberAPI
	PredefinedMessageAPI *PredefinedMessageAPI
	GenericChannelAPI    *GenericChannelAPI
	WhatsAppAPI          *WhatsAppAPI
	ReportAPI            *ReportAPI
	// contains filtered or unexported fields
}

Client is the main SZChat SDK client. It is safe for concurrent use.

func NewClient

func NewClient(baseURL, email, password string, opts ...Option) (*Client, error)

NewClient creates a new Client authenticating as the given agent/admin email and password against the SZChat API hosted at baseURL. baseURL is tenant-specific (e.g. "https://your-tenant.sz.chat") and must not include the API version path: NewClient appends "/api/v4" automatically to keep internal compatibility with the version of the SZChat API this library targets. There is no default baseURL. Options can override the HTTP client, device token, and retry policy.

func (*Client) APIVersion added in v0.1.0

func (c *Client) APIVersion(ctx context.Context) (*APIVersionResponse, error)

APIVersion returns the API version reported by GET /api/version. This endpoint sits outside the versioned /api/v4 path this client otherwise targets and requires no authentication.

func (*Client) Login

func (c *Client) Login(ctx context.Context) (*LoginResponse, error)

Login authenticates against POST /auth/login using the credentials the Client was created with, and stores the returned bearer token for subsequent requests. It is normally unnecessary to call this directly: the Client authenticates lazily on the first request and re-authenticates automatically when the token expires.

func (*Client) LoginV2 added in v0.1.0

func (c *Client) LoginV2(ctx context.Context) (*LoginResponse, error)

LoginV2 authenticates against POST /auth/login-v2 using the credentials the Client was created with, and stores the returned bearer token for subsequent requests. login-v2 returns the same payload shape as Login but surfaces more specific 403 failure reasons (expired password, disabled login, simultaneous agent limit reached, agent outside working hours, no active team) instead of a generic error.

func (*Client) Logout

func (c *Client) Logout(ctx context.Context, scope string) error

Logout closes the current session via GET /auth/logout. scope selects which sessions to close: "api" (default when empty), "web", or "all".

func (*Client) Me

func (c *Client) Me(ctx context.Context) (*User, error)

Me returns the authenticated user's profile via GET /auth/me.

func (*Client) Refresh added in v0.1.0

func (c *Client) Refresh(ctx context.Context) (*RefreshResponse, error)

Refresh renews the bearer token via GET /auth/refresh and stores it for subsequent requests. Calling this directly is normally unnecessary since do() already refreshes automatically on a single 401 response; it is exposed for callers that want to proactively renew the token.

type Contact

type Contact struct {
	ID              string            `json:"_id"`
	Name            string            `json:"name"`
	Email           string            `json:"email,omitempty"`
	DDI             string            `json:"ddi,omitempty"`
	DDD             string            `json:"ddd,omitempty"`
	Number          string            `json:"number,omitempty"`
	FinalNumber     string            `json:"final_number,omitempty"`
	Group           []string          `json:"group,omitempty"`
	Platforms       []ContactPlatform `json:"platforms,omitempty"`
	DefaultLanguage string            `json:"default_language,omitempty"`
	OptIn           string            `json:"opt_in,omitempty"`
	Observation     string            `json:"observation,omitempty"`
	Author          *ContactAuthor    `json:"author,omitempty"`
	StatusWhatsapp  int               `json:"statusWhatsapp,omitempty"`
	CreatedAt       string            `json:"created_at,omitempty"`
	UpdatedAt       string            `json:"updated_at,omitempty"`

	Extra map[string]any `json:"-"`
}

Contact is a SZChat contact/lead record.

func (Contact) MarshalJSON added in v0.0.2

func (c Contact) MarshalJSON() ([]byte, error)

MarshalJSON merges Extra into the encoded object, mirroring ContactRequest.MarshalJSON.

func (*Contact) UnmarshalJSON added in v0.0.2

func (c *Contact) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the known Contact fields and collects every other top-level key into Extra, so tenant-specific custom fields survive a round trip through this struct instead of being silently dropped.

ddi and ddd are normalized to JSON strings first: SZChat's own schema types them as strings, but some contact records come back with them encoded as JSON numbers instead, which would otherwise fail the decode below (e.g. while paging through GET /contacts).

type ContactAPI

type ContactAPI struct {
	// contains filtered or unexported fields
}

ContactAPI groups the /contacts endpoints.

func (*ContactAPI) AttendanceStats

func (a *ContactAPI) AttendanceStats(ctx context.Context, contactID, platform string) (*ContactAttendanceStats, error)

AttendanceStats returns a contact's attendance stats on a platform via GET /contacts/{id}/attendances.

func (*ContactAPI) Create

func (a *ContactAPI) Create(ctx context.Context, req ContactRequest) (*Contact, error)

Create creates a contact via POST /contacts.

func (*ContactAPI) Delete

func (a *ContactAPI) Delete(ctx context.Context, id string) error

Delete deletes a contact via DELETE /contacts/{id}.

func (*ContactAPI) Get

func (a *ContactAPI) Get(ctx context.Context, id string) (*Contact, error)

Get returns a single contact via GET /contacts/{id}.

func (*ContactAPI) List

List returns a paginated list of contacts via GET /contacts.

func (a *ContactAPI) MergeLink(ctx context.Context, mainContactID, mergeContactID string) (*ContactMergeLinkResponse, error)

MergeLink links two contacts as a merge pair via POST /contacts/merge/link.

func (*ContactAPI) MergeSimilar added in v0.1.0

MergeSimilar returns contacts similar to the given contact, candidates for merging, via GET /contacts/merge/similar.

func (*ContactAPI) Recents added in v0.1.0

func (a *ContactAPI) Recents(ctx context.Context, search string) ([]RecentContact, error)

Recents returns the authenticated agent's recently contacted contacts via GET /contacts/recents.

func (*ContactAPI) Related added in v0.1.0

func (a *ContactAPI) Related(ctx context.Context, contactID string) (*PaginatedResponse[Contact], error)

Related returns contacts already linked to the given contact via GET /contacts/related.

func (*ContactAPI) SaveAnnotation

SaveAnnotation creates/updates a contact's annotation via POST /contacts/annotation.

func (*ContactAPI) Search

Search returns contacts matching filter via GET /contacts/search.

func (*ContactAPI) Unmerge added in v0.1.0

func (a *ContactAPI) Unmerge(ctx context.Context, contactID string) (bool, error)

Unmerge removes a contact's merge links via POST /contacts/unmerge.

func (*ContactAPI) Update

func (a *ContactAPI) Update(ctx context.Context, id string, req ContactRequest) (*Contact, error)

Update updates a contact via PUT /contacts/{id}.

func (*ContactAPI) UpdateFields

func (a *ContactAPI) UpdateFields(ctx context.Context, id string, fields map[string]any) (map[string]any, error)

UpdateFields updates a contact's custom fields via PUT /contacts/update_fields/{id}.

type ContactAnnotation

type ContactAnnotation struct {
	Observation string         `json:"observation"`
	Author      *ContactAuthor `json:"author,omitempty"`
	CreatedAt   string         `json:"created_at,omitempty"`
	UpdatedAt   string         `json:"updated_at,omitempty"`
}

ContactAnnotation is the stored annotation returned by SaveAnnotation.

type ContactAnnotationRequest

type ContactAnnotationRequest struct {
	ContactID   string `json:"_id"`
	Observation string `json:"observation"`
	AgentID     string `json:"agent_id"`
}

ContactAnnotationRequest is the payload for ContactAPI.SaveAnnotation.

type ContactAttendanceStats

type ContactAttendanceStats struct {
	TotalMonthAttendances int    `json:"total_month_attendances"`
	WeeklyAttendances     int    `json:"weekly_attendances"`
	LastAttendanceDate    string `json:"last_attendance_date"`
}

ContactAttendanceStats summarizes a contact's attendance history on a given platform.

type ContactAuthor

type ContactAuthor struct {
	Name    string `json:"name,omitempty"`
	AgentID string `json:"agent_id,omitempty"`
	Date    struct {
		CreatedAt string `json:"created_at,omitempty"`
		UpdatedAt string `json:"updated_at,omitempty"`
	} `json:"date,omitzero"`
}

ContactAuthor identifies who created/annotated a Contact.

type ContactField added in v0.1.0

type ContactField struct {
	ID               string `json:"_id,omitempty"`
	Name             string `json:"name"`
	Description      string `json:"description"`
	Identifier       bool   `json:"identifier"`
	Required         bool   `json:"required,omitempty"`
	Confidential     bool   `json:"confidential,omitempty"`
	Encrypted        bool   `json:"encrypted,omitempty"`
	AllowSearch      bool   `json:"allow_search,omitempty"`
	DescriptionAgent bool   `json:"description_agent,omitempty"`
	Validation       string `json:"validation,omitempty"`
	Conditional      string `json:"conditional,omitempty"`
	TotalCharacters  string `json:"total_characters,omitempty"`
	CreatedAt        string `json:"created_at,omitempty"`
	UpdatedAt        string `json:"updated_at,omitempty"`
}

ContactField is a tenant-defined custom contact field.

type ContactFieldAPI added in v0.1.0

type ContactFieldAPI struct {
	// contains filtered or unexported fields
}

ContactFieldAPI groups the /contacts/fields endpoints, which manage the custom field definitions used by ContactAPI.UpdateFields.

func (*ContactFieldAPI) Create added in v0.1.0

func (a *ContactFieldAPI) Create(ctx context.Context, field ContactField) (*ContactField, error)

Create creates a custom contact field via POST /contacts/fields.

func (*ContactFieldAPI) Delete added in v0.1.0

Delete deletes a custom contact field via DELETE /contacts/fields/{id}.

func (*ContactFieldAPI) List added in v0.1.0

func (a *ContactFieldAPI) List(ctx context.Context) ([]ContactField, error)

List returns all custom contact field definitions via GET /contacts/fields.

func (*ContactFieldAPI) Update added in v0.1.0

func (a *ContactFieldAPI) Update(ctx context.Context, id string, field ContactField) (*ContactField, error)

Update updates a custom contact field via PUT /contacts/fields/{id}.

type ContactFieldDeleteResponse added in v0.1.0

type ContactFieldDeleteResponse struct {
	Success []bool `json:"success"`
	Message string `json:"message"`
	Date    string `json:"date"`
}

ContactFieldDeleteResponse is the payload returned by ContactFieldAPI.Delete.

type ContactGroup

type ContactGroup struct {
	ID        string `json:"_id"`
	NameGroup string `json:"nameGroup"`
	OptIn     any    `json:"opt_in,omitempty"`
	CreatedAt string `json:"created_at,omitempty"`
	UpdatedAt string `json:"updated_at,omitempty"`
}

ContactGroup is a contact segmentation group.

type ContactGroupAPI

type ContactGroupAPI struct {
	// contains filtered or unexported fields
}

ContactGroupAPI groups the /contacts/groups endpoints.

func (*ContactGroupAPI) Create

func (a *ContactGroupAPI) Create(ctx context.Context, name string) (*ContactGroup, error)

Create creates a contact group via POST /contacts/groups.

func (*ContactGroupAPI) Delete

func (a *ContactGroupAPI) Delete(ctx context.Context, id string) error

Delete deletes a contact group via DELETE /contacts/groups/{id}.

func (*ContactGroupAPI) List

List returns a paginated list of contact groups via GET /contacts/groups.

func (*ContactGroupAPI) ListByContact

func (a *ContactGroupAPI) ListByContact(ctx context.Context, contactID string) ([]ContactGroupSummary, error)

ListByContact returns the groups a contact belongs to via GET /contacts/groups/contact/{contact_id}.

func (*ContactGroupAPI) Update

func (a *ContactGroupAPI) Update(ctx context.Context, id, name string) (*ContactGroup, error)

Update renames a contact group via PUT /contacts/groups/{id}.

type ContactGroupSummary

type ContactGroupSummary struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

ContactGroupSummary is the lightweight shape returned when listing the groups a specific contact belongs to.

type ContactListFilter

type ContactListFilter struct {
	ListOptions
	Name           string
	Email          string
	Platform       string
	PlatformID     string
	StartCreatedAt string
	EndCreatedAt   string
	UpdatedAt      string
}

ContactListFilter holds the query parameters accepted by List and Search.

type ContactMergeCandidateFilter added in v0.1.0

type ContactMergeCandidateFilter struct {
	ContactID string
	Search    string
	PerPage   int
	Page      int
}

ContactMergeCandidateFilter holds the query parameters accepted by ContactAPI.MergeSimilar and ContactAPI.Related.

type ContactMergeLinkResponse added in v0.1.0

type ContactMergeLinkResponse struct {
	MainContact string `json:"main_contact"`
	MergeWith   string `json:"merge_with"`
	LinkTo      string `json:"link_to"`
}

ContactMergeLinkResponse is the payload returned by ContactAPI.MergeLink.

type ContactPlatform

type ContactPlatform struct {
	Platform   string `json:"platform"`
	PlatformID string `json:"platform_id"`
}

ContactPlatform links a Contact to an identifier on a messaging platform.

type ContactRequest

type ContactRequest struct {
	Name            string   `json:"name"`
	Email           string   `json:"email,omitempty"`
	Number          string   `json:"number,omitempty"`
	Group           []string `json:"group,omitempty"`
	DDI             string   `json:"ddi,omitempty"`
	DefaultLanguage string   `json:"default_language,omitempty"`
	FinalNumber     string   `json:"final_number,omitempty"`
	OptIn           string   `json:"opt_in,omitempty"`
	OptinGupshup    *bool    `json:"optin_gupshup,omitempty"`
	ContactToMerge  []string `json:"contactToMerge,omitempty"`

	Whatsapp         string `json:"Whatsapp,omitempty"`
	WhatsappBusiness string `json:"WhatsappBusiness,omitempty"`
	Instagram        string `json:"Instagram,omitempty"`
	InstagramDirect  string `json:"InstagramDirect,omitempty"`
	Telegram         string `json:"Telegram,omitempty"`
	Messenger        string `json:"Messenger,omitempty"`
	GoogleChat       string `json:"GoogleChat,omitempty"`
	ChatWeb          string `json:"ChatWeb,omitempty"`
	MercadoLivre     string `json:"MercadoLivre,omitempty"`
	SMS              string `json:"SMS,omitempty"`

	Extra map[string]any `json:"-"`
}

ContactRequest is the payload for creating/updating a Contact. Extra carries tenant-specific channel identifiers not covered by the named fields (e.g. a custom "Generic_MyBot" channel) and is merged into the top-level JSON object.

func (ContactRequest) MarshalJSON

func (r ContactRequest) MarshalJSON() ([]byte, error)

MarshalJSON merges Extra into the encoded object.

type CopilotAPI added in v0.1.0

type CopilotAPI struct {
	// contains filtered or unexported fields
}

CopilotAPI groups the agent copilot endpoints.

func (*CopilotAPI) Execute added in v0.1.0

Execute runs a copilot assistant against content via POST /user/agent/copilot/execute.

func (*CopilotAPI) List added in v0.1.0

func (a *CopilotAPI) List(ctx context.Context, search string) ([]CopilotAssistant, error)

List returns the copilot assistants available to the authenticated agent via GET /user/agent/copilot/list.

type CopilotAssistant added in v0.1.0

type CopilotAssistant struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

CopilotAssistant describes an available copilot assistant.

type CopilotExecuteRequest added in v0.1.0

type CopilotExecuteRequest struct {
	RestID            string `json:"restId"`
	Content           string `json:"content"`
	ShowSourceContent bool   `json:"showSourceContent,omitempty"`
}

CopilotExecuteRequest is the payload for CopilotAPI.Execute.

type CopilotExecuteResponse added in v0.1.0

type CopilotExecuteResponse struct {
	Status        string            `json:"status,omitempty"`
	Result        string            `json:"result,omitempty"`
	SourceContent string            `json:"sourceContent,omitempty"`
	Items         map[string]string `json:"-"`
}

CopilotExecuteResponse is the payload returned by CopilotAPI.Execute. The SZChat API documents two response shapes for this endpoint (a flat status/result/sourceContent object, or a map of numbered result items), so both are represented here; callers should check which one is populated (Result != "" vs. len(Items) > 0).

func (*CopilotExecuteResponse) UnmarshalJSON added in v0.1.0

func (r *CopilotExecuteResponse) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes either of CopilotAPI.Execute's two documented response shapes into CopilotExecuteResponse.

type DetectLanguageRequest added in v0.1.0

type DetectLanguageRequest struct {
	Message   string `json:"message"`
	ContactID string `json:"contact_id"`
}

DetectLanguageRequest is the payload for TranslationAPI.DetectLanguage.

type DetectLanguageResponse added in v0.1.0

type DetectLanguageResponse struct {
	Confidence float64 `json:"confidence"`
	Language   string  `json:"language"`
	Message    string  `json:"message"`
}

DetectLanguageResponse is the payload returned by TranslationAPI.DetectLanguage.

type GalleryAPI added in v0.1.0

type GalleryAPI struct {
	// contains filtered or unexported fields
}

GalleryAPI groups the contact media gallery endpoint.

func (*GalleryAPI) Medias added in v0.1.0

func (a *GalleryAPI) Medias(ctx context.Context, contactID, mediaType string, limit int) (*GalleryMediasResponse, error)

Medias returns the media exchanged with a contact, across the current and historic sessions, via GET /agent/historic/medias. mediaType filters by kind (e.g. "images", "videos", "sounds", "files"); pass "" for all types. limit caps historic_sessions entries (1-50, defaults to 5 server-side).

type GalleryMedia added in v0.1.0

type GalleryMedia struct {
	MessageID string `json:"message_id,omitempty"`
	RequestID string `json:"request_id,omitempty"`
	Origin    string `json:"origin,omitempty"`
	Type      string `json:"type,omitempty"`
	CreatedAt string `json:"created_at,omitempty"`
	Blocked   bool   `json:"blocked,omitempty"`
	StorageID string `json:"storage_id,omitempty"`
	Filename  string `json:"filename,omitempty"`
	MimeType  string `json:"mime_type,omitempty"`
	Legend    string `json:"legend,omitempty"`
	UserID    string `json:"user_id,omitempty"`
	User      struct {
		Name  string `json:"name,omitempty"`
		Photo string `json:"photo,omitempty"`
	} `json:"user,omitempty"`
	SessionID        string `json:"session_id,omitempty"`
	SessionCreatedAt string `json:"session_created_at,omitempty"`
	FinishedAt       string `json:"finished_at,omitempty"`
	Status           string `json:"status,omitempty"`
	AgentName        string `json:"agent_name,omitempty"`
	Protocol         string `json:"protocol,omitempty"`
}

GalleryMedia is a single media item as returned by GalleryAPI.Medias.

type GalleryMediasResponse added in v0.1.0

type GalleryMediasResponse struct {
	CurrentSession   []GalleryMedia                  `json:"current_session"`
	HistoricSessions PaginatedResponse[GalleryMedia] `json:"historic_sessions"`
}

GalleryMediasResponse is the payload returned by GalleryAPI.Medias.

type GenericChannelAPI added in v0.1.0

type GenericChannelAPI struct {
	// contains filtered or unexported fields
}

GenericChannelAPI groups the /generic/messages/send endpoint used by generic-channel integrations to forward inbound messages and device status changes into Chat Center. Authentication is a per-channel API key (the "API-KEY" header), not the client's agent bearer token.

func (*GenericChannelAPI) SendDeviceNotification added in v0.1.0

SendDeviceNotification reports a device/connection status change (e.g. QR code pending, low battery, connected/disconnected) via POST /generic/messages/send. apiKey is the channel's configured API key.

func (*GenericChannelAPI) SendMessage added in v0.1.0

SendMessage forwards an inbound message (or set of messages) from a generic-channel integration via POST /generic/messages/send. apiKey is the channel's configured API key.

type GenericChannelContact added in v0.1.0

type GenericChannelContact struct {
	Profile    GenericChannelContactProfile `json:"profile"`
	PlatformID string                       `json:"platform_id"`
	VCard      string                       `json:"vcard,omitempty"`
}

GenericChannelContact identifies the contact a GenericChannelMessage is from. VCard is only used when the accompanying message's Type is "contact".

type GenericChannelContactProfile added in v0.1.0

type GenericChannelContactProfile struct {
	Name  string `json:"name"`
	Photo string `json:"photo,omitempty"`
}

GenericChannelContactProfile is a generic-channel contact's display profile.

type GenericChannelDeviceNotificationRequest added in v0.1.0

type GenericChannelDeviceNotificationRequest struct {
	Type   string                     `json:"type"`
	Device GenericChannelDeviceStatus `json:"device"`
}

GenericChannelDeviceNotificationRequest is the payload for GenericChannelAPI.SendDeviceNotification.

type GenericChannelDeviceStatus added in v0.1.0

type GenericChannelDeviceStatus struct {
	ID        string `json:"id"`
	Status    string `json:"status"`
	Timestamp int64  `json:"timestamp"`
}

GenericChannelDeviceStatus is the payload for GenericChannelAPI.SendDeviceNotification.

type GenericChannelLocation added in v0.1.0

type GenericChannelLocation struct {
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
}

GenericChannelLocation is a generic-channel location message body.

type GenericChannelMedia added in v0.1.0

type GenericChannelMedia struct {
	URL      string `json:"url"`
	MimeType string `json:"mime_type"`
	Caption  string `json:"caption,omitempty"`
	Filename string `json:"filename,omitempty"`
}

GenericChannelMedia is a generic-channel media message body. Caption only applies to image/video messages; Filename only applies to document messages.

type GenericChannelMessage added in v0.1.0

type GenericChannelMessage struct {
	From      string                  `json:"from"`
	ID        string                  `json:"id"`
	Timestamp string                  `json:"timestamp"`
	Type      string                  `json:"type"`
	Text      *GenericChannelText     `json:"text,omitempty"`
	Image     *GenericChannelMedia    `json:"image,omitempty"`
	Document  *GenericChannelMedia    `json:"document,omitempty"`
	Audio     *GenericChannelMedia    `json:"audio,omitempty"`
	Video     *GenericChannelMedia    `json:"video,omitempty"`
	Location  *GenericChannelLocation `json:"location,omitempty"`
}

GenericChannelMessage is a single inbound message forwarded to Chat Center by a generic-channel integration. Exactly one of Text, Image, Document, Audio, Video, or Location should be set, matching Type.

type GenericChannelOutboundMessage added in v0.1.0

type GenericChannelOutboundMessage struct {
	To        string                  `json:"to"`
	SessionID string                  `json:"session_id"`
	ContactID string                  `json:"contact_id"`
	ChannelID string                  `json:"channel_id"`
	Type      string                  `json:"type"`
	Text      *GenericChannelText     `json:"text,omitempty"`
	Image     *GenericChannelMedia    `json:"image,omitempty"`
	Document  *GenericChannelMedia    `json:"document,omitempty"`
	Audio     *GenericChannelMedia    `json:"audio,omitempty"`
	Video     *GenericChannelMedia    `json:"video,omitempty"`
	Location  *GenericChannelLocation `json:"location,omitempty"`
	Contact   *struct {
		VCard string `json:"vcard"`
	} `json:"contact,omitempty"`
}

GenericChannelOutboundMessage is the payload Chat Center POSTs to a generic channel's configured host to deliver an outbound message. Like the receptive-API webhooks above, this is not something the SDK calls — it documents the shape a generic-channel integration's own HTTP server receives, for callers that need to decode it.

type GenericChannelSendRequest added in v0.1.0

type GenericChannelSendRequest struct {
	Contacts []GenericChannelContact `json:"contacts"`
	Messages []GenericChannelMessage `json:"messages"`
}

GenericChannelSendRequest is the payload for GenericChannelAPI.SendMessage.

type GenericChannelSendResponse added in v0.1.0

type GenericChannelSendResponse struct {
	Status bool `json:"status"`
}

GenericChannelSendResponse is the payload returned by GenericChannelAPI.SendMessage and GenericChannelAPI.SendDeviceNotification.

type GenericChannelText added in v0.1.0

type GenericChannelText struct {
	Body string `json:"body"`
}

GenericChannelText is a generic-channel text message body.

type HSMAPI added in v0.1.0

type HSMAPI struct {
	// contains filtered or unexported fields
}

HSMAPI groups the WhatsApp message template listing endpoint.

func (*HSMAPI) ListAll added in v0.1.0

func (a *HSMAPI) ListAll(ctx context.Context, req HSMListRequest) ([]HSMTemplate, error)

ListAll lists the HSM templates available to the authenticated agent via POST /hsm/listAll.

type HSMBroker added in v0.1.0

type HSMBroker struct {
	Name   string `json:"name,omitempty"`
	Status string `json:"status,omitempty"`
}

HSMBroker describes an HSM template's broker approval state.

type HSMListRequest added in v0.1.0

type HSMListRequest struct {
	AttendanceID string `json:"attendance_id,omitempty"`
	ChannelID    string `json:"channel_id,omitempty"`
}

HSMListRequest is the payload for HSMAPI.ListAll.

type HSMTag added in v0.1.0

type HSMTag struct {
	Placeholder string `json:"placeholder"`
	TagsValue   string `json:"tags_value"`
}

HSMTag is a placeholder/value pair usable within an HSM template.

type HSMTemplate added in v0.1.0

type HSMTemplate struct {
	Name       string   `json:"name"`
	Tags       []HSMTag `json:"tags,omitempty"`
	Message    []string `json:"message"`
	Category   string   `json:"category,omitempty"`
	Broker     any      `json:"broker,omitempty"`
	Visibility string   `json:"visibility,omitempty"`
}

HSMTemplate is a WhatsApp message template ("HSM").

type ListOptions

type ListOptions struct {
	Page     int
	Limit    int
	Paginate string
}

ListOptions holds the pagination query parameters accepted by most list endpoints.

type LoginResponse

type LoginResponse struct {
	User  User   `json:"user"`
	Token string `json:"token"`
}

LoginResponse is the payload returned by POST /auth/login.

type MessageAPI

type MessageAPI struct {
	// contains filtered or unexported fields
}

MessageAPI groups the /message endpoints.

func (*MessageAPI) AddAnnotation

func (a *MessageAPI) AddAnnotation(ctx context.Context, messageID string, note map[string]any) (map[string]any, error)

AddAnnotation adds a note to a message via POST /message/{id}/annotation.

func (*MessageAPI) DownloadMedia added in v0.1.0

func (a *MessageAPI) DownloadMedia(ctx context.Context, storageID string) (data []byte, contentType string, err error)

DownloadMedia downloads a stored media file's raw bytes via GET /config/storage/view/{storage_id}, returning the content and its Content-Type header. This endpoint requires no authentication.

func (*MessageAPI) Pending

func (a *MessageAPI) Pending(ctx context.Context, params map[string]any) (map[string]any, error)

Pending returns the count of messages awaiting delivery via POST /message/pending. See the note on Read regarding the undocumented payload shape.

func (*MessageAPI) Read

func (a *MessageAPI) Read(ctx context.Context, params map[string]any) (map[string]any, error)

Read retrieves a session's messages via POST /message/read. The SZChat documentation does not publish the exact request/response shape for this endpoint, so params/the result are passed through as free-form JSON.

func (*MessageAPI) RemoveAnnotation

func (a *MessageAPI) RemoveAnnotation(ctx context.Context, messageID string) error

RemoveAnnotation removes a message's note via DELETE /message/{id}/annotation.

func (*MessageAPI) ReplaceVars

func (a *MessageAPI) ReplaceVars(ctx context.Context, params map[string]any) (map[string]any, error)

ReplaceVars substitutes template placeholders in a message via POST /message/replace_vars. See the note on Read regarding the undocumented payload shape.

func (*MessageAPI) Send

Send sends a message via POST /message/send.

func (*MessageAPI) SendPlus

SendPlus sends a message and creates/updates the target contact via POST /message/send_plus.

type MessageEmailAttachment

type MessageEmailAttachment struct {
	Filename string `json:"filename"`
	Content  string `json:"content"`
	MimeType string `json:"mime_type,omitempty"`
}

MessageEmailAttachment is a base64-encoded email attachment accepted by SendMessageRequest.Attachments.

type Multichannel added in v0.1.0

type Multichannel struct {
	ID              string   `json:"_id,omitempty"`
	Channels        []string `json:"channels"`
	ColorBackground string   `json:"colorBackground"`
	ColorButtons    string   `json:"colorButtons"`
	ColorButtonText string   `json:"colorButtonText"`
	Link            string   `json:"link,omitempty"`
	CreatedAt       string   `json:"created_at,omitempty"`
	UpdatedAt       string   `json:"updated_at,omitempty"`
}

Multichannel is a "link multicanal" configuration: a shareable link that lets a contact pick from a set of channels.

type MultichannelAPI added in v0.1.0

type MultichannelAPI struct {
	// contains filtered or unexported fields
}

MultichannelAPI groups the /multichannel endpoints.

func (*MultichannelAPI) Create added in v0.1.0

Create creates a multichannel link via POST /multichannel.

func (*MultichannelAPI) Delete added in v0.1.0

func (a *MultichannelAPI) Delete(ctx context.Context, id string) error

Delete deletes a multichannel link via DELETE /multichannel/{id}.

func (*MultichannelAPI) List added in v0.1.0

List returns a paginated list of multichannel links via GET /multichannel.

func (*MultichannelAPI) Update added in v0.1.0

Update updates a multichannel link via PUT /multichannel/{id}.

type Option

type Option func(*Client)

Option is a function that configures a Client.

func WithDeviceToken

func WithDeviceToken(deviceToken string) Option

WithDeviceToken sets the device token sent on login, used by SZChat for push notifications.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient sets the HTTP client used for all requests.

func WithRetry

func WithRetry(maxRetries int, waitMin, waitMax time.Duration) Option

WithRetry configures the retry policy applied to transient failures (429/502/503/504 and network errors).

type PaginatedResponse

type PaginatedResponse[T any] struct {
	CurrentPage  int     `json:"current_page"`
	Data         []T     `json:"data"`
	Total        int     `json:"total"`
	PerPage      int     `json:"per_page"`
	LastPage     int     `json:"last_page,omitempty"`
	From         int     `json:"from,omitempty"`
	To           int     `json:"to,omitempty"`
	Path         string  `json:"path,omitempty"`
	FirstPageURL string  `json:"first_page_url,omitempty"`
	LastPageURL  string  `json:"last_page_url,omitempty"`
	NextPageURL  *string `json:"next_page_url,omitempty"`
	PrevPageURL  *string `json:"prev_page_url,omitempty"`
}

PaginatedResponse is the Laravel-style paginator envelope returned by most SZChat list endpoints.

type Pause

type Pause struct {
	ID                 string `json:"_id,omitempty"`
	Name               string `json:"name"`
	Description        string `json:"description,omitempty"`
	InitialTime        int    `json:"initialTime,omitempty"`
	MaxTime            int    `json:"maxTime,omitempty"`
	Active             bool   `json:"active,omitempty"`
	Productive         bool   `json:"productive,omitempty"`
	Message            string `json:"message,omitempty"`
	Cumulative         bool   `json:"cumulative,omitempty"`
	Supervisioned      bool   `json:"supervisioned,omitempty"`
	ContinueAttendance bool   `json:"continue_attendance,omitempty"`
	CreatedAt          string `json:"created_at,omitempty"`
	UpdatedAt          string `json:"updated_at,omitempty"`
}

Pause is an agent break/pause reason configuration.

type PauseAPI

type PauseAPI struct {
	// contains filtered or unexported fields
}

PauseAPI groups the /pauses endpoints.

func (*PauseAPI) Create

func (a *PauseAPI) Create(ctx context.Context, pause Pause) (*Pause, error)

Create creates a pause via POST /pauses.

func (*PauseAPI) Delete

func (a *PauseAPI) Delete(ctx context.Context, id string) error

Delete deletes a pause via DELETE /pauses/{id}.

func (*PauseAPI) List

List returns a paginated list of pauses via GET /pauses.

func (*PauseAPI) Update

func (a *PauseAPI) Update(ctx context.Context, id string, pause Pause) (*Pause, error)

Update updates a pause via PUT /pauses/{id}.

type PlaceholderAPI added in v0.1.0

type PlaceholderAPI struct {
	// contains filtered or unexported fields
}

PlaceholderAPI groups the message placeholder resolution endpoint.

func (*PlaceholderAPI) Resolve added in v0.1.0

Resolve resolves a list of placeholders (e.g. "{{NAME}}") to their values for a given contact/agent/session via POST /user/agent/placeholders. The returned slice preserves the order of req.PlaceholdersParams.

type PlaceholderResolveRequest added in v0.1.0

type PlaceholderResolveRequest struct {
	ContactID          string   `json:"contact_id"`
	AgentID            string   `json:"agent_id,omitempty"`
	SessionID          string   `json:"session_id,omitempty"`
	PlaceholdersParams []string `json:"placeholders_params"`
}

PlaceholderResolveRequest is the payload for PlaceholderAPI.Resolve.

type PredefinedMessage added in v0.1.0

type PredefinedMessage struct {
	ID          string                  `json:"_id,omitempty"`
	Message     []PredefinedMessagePart `json:"message"`
	Description string                  `json:"description"`
	CreatedAt   string                  `json:"created_at,omitempty"`
	UpdatedAt   string                  `json:"updated_at,omitempty"`
}

PredefinedMessage is a canned reply agents can insert into a conversation.

type PredefinedMessageAPI added in v0.1.0

type PredefinedMessageAPI struct {
	// contains filtered or unexported fields
}

PredefinedMessageAPI groups the /predefined_messages endpoints.

func (*PredefinedMessageAPI) Create added in v0.1.0

Create creates a predefined message via POST /predefined_messages.

func (*PredefinedMessageAPI) Delete added in v0.1.0

func (a *PredefinedMessageAPI) Delete(ctx context.Context, id string) error

Delete deletes a predefined message via DELETE /predefined_messages/{id}.

func (*PredefinedMessageAPI) Get added in v0.1.0

Get returns a single predefined message via GET /predefined_messages/{id}.

func (*PredefinedMessageAPI) List added in v0.1.0

List returns a paginated list of predefined messages via GET /predefined_messages.

func (*PredefinedMessageAPI) Update added in v0.1.0

Update updates a predefined message via PUT /predefined_messages/{id}.

type PredefinedMessagePart added in v0.1.0

type PredefinedMessagePart struct {
	Type    string `json:"type,omitempty"`
	Message string `json:"message"`
}

PredefinedMessagePart is a single part of a predefined message. Type is set by the server (observed values: "text") and is not sent on create/update.

type RecentContact added in v0.1.0

type RecentContact struct {
	ID              string `json:"_id"`
	Name            string `json:"name,omitempty"`
	AgentID         string `json:"agent_id,omitempty"`
	CampaignID      string `json:"campaign_id,omitempty"`
	ContactID       string `json:"contact_id,omitempty"`
	ChannelID       string `json:"channel_id,omitempty"`
	Platform        string `json:"platform,omitempty"`
	PlatformID      string `json:"platform_id,omitempty"`
	Status          string `json:"status,omitempty"`
	IsAttendance    bool   `json:"isAttendance,omitempty"`
	Photo           string `json:"photo,omitempty"`
	CreatedAt       string `json:"created_at,omitempty"`
	ReportAt        string `json:"report_at,omitempty"`
	LastInteraction string `json:"lastInteraction,omitempty"`
	LastChannel     string `json:"lastChannel,omitempty"`
	SessionID       string `json:"session_id,omitempty"`
}

RecentContact is a single item returned by ContactAPI.Recents.

type RefreshResponse

type RefreshResponse struct {
	Token string `json:"token"`
}

RefreshResponse is the payload returned by GET /auth/refresh.

type ReportAPI added in v0.1.0

type ReportAPI struct {
	// contains filtered or unexported fields
}

ReportAPI groups the /reports endpoints. All operations require an administrator account.

func (*ReportAPI) Attendances added in v0.1.0

Attendances returns the attendances report for a date range via GET /reports/attendances. initial_date and end_date must fall within the same month.

type ReportAttendanceEntry added in v0.1.0

type ReportAttendanceEntry struct {
	ChannelDescription   string `json:"channel_description,omitempty"`
	CampaignName         string `json:"campaign_name,omitempty"`
	Attendances          int    `json:"attendances,omitempty"`
	TotalMessages        int    `json:"total_messages,omitempty"`
	TotalSessionMessages int    `json:"total_session_messages,omitempty"`
	TotalHSM             int    `json:"total_hsm,omitempty"`
	AgentName            string `json:"agent_name,omitempty"`
	AgentLogin           string `json:"agent_login,omitempty"`
}

ReportAttendanceEntry is a single row of ReportAPI.Attendances's response. AgentName and AgentLogin are only populated for the analytic ("a") report type.

type ReportAttendancesFilter added in v0.1.0

type ReportAttendancesFilter struct {
	InitialDate string
	EndDate     string
	Campaigns   string
	// Type selects the report shape: "a" (analytic, per-agent) or "s"
	// (synthetic, aggregated). Defaults to "a" server-side when empty.
	Type      string
	ChannelID string
	Page      int
}

ReportAttendancesFilter holds the query parameters accepted by ReportAPI.Attendances.

type ReportAttendancesResponse added in v0.1.0

type ReportAttendancesResponse struct {
	Results  []ReportAttendanceEntry `json:"results"`
	Total    int                     `json:"total"`
	Page     int                     `json:"page"`
	LastPage int                     `json:"last_page"`
}

ReportAttendancesResponse is the payload returned by ReportAPI.Attendances.

type SendMessageContactVariables

type SendMessageContactVariables struct {
	Name     string            `json:"name,omitempty"`
	Email    string            `json:"email,omitempty"`
	Groups   []string          `json:"groups,omitempty"`
	Channels map[string]string `json:"channels,omitempty"`
	Fields   map[string]any    `json:"-"`
}

SendMessageContactVariables creates/updates the target contact as part of a send_plus call. Fields carries any additional custom-field keys the tenant has configured.

func (SendMessageContactVariables) MarshalJSON

func (v SendMessageContactVariables) MarshalJSON() ([]byte, error)

MarshalJSON merges Fields into the encoded object.

type SendMessagePlusRequest

type SendMessagePlusRequest struct {
	SendMessageRequest
	ContactVariables *SendMessageContactVariables `json:"contact_variables,omitempty"`
}

SendMessagePlusRequest is the payload for MessageAPI.SendPlus.

type SendMessageRequest

type SendMessageRequest struct {
	PlatformID      string                   `json:"platform_id"`
	ChannelID       string                   `json:"channel_id"`
	Type            string                   `json:"type"`
	Message         string                   `json:"message,omitempty"`
	File            string                   `json:"file,omitempty"`
	ContactName     string                   `json:"contact_name,omitempty"`
	Agent           string                   `json:"agent,omitempty"`
	AttendanceID    string                   `json:"attendance_id,omitempty"`
	CloseSession    int                      `json:"close_session,omitempty"`
	IsHSM           bool                     `json:"is_hsm,omitempty"`
	HSMTemplateName string                   `json:"hsm_template_name,omitempty"`
	Attachments     []MessageEmailAttachment `json:"attachments,omitempty"`
}

SendMessageRequest is the payload for MessageAPI.Send and (embedded) MessageAPI.SendPlus.

type SendMessageResponse

type SendMessageResponse struct {
	Messages SentMessage `json:"messages"`
	Message  string      `json:"message"`
}

SendMessageResponse is the payload returned by MessageAPI.Send and MessageAPI.SendPlus.

type SendMessageUser

type SendMessageUser struct {
	Name string `json:"name"`
}

SendMessageUser identifies the agent shown as the sender of a message.

type SentMessage

type SentMessage struct {
	MessageID string          `json:"message_id"`
	Type      string          `json:"type"`
	CreatedAt string          `json:"created_at"`
	Message   string          `json:"message"`
	User      SendMessageUser `json:"user"`
}

SentMessage is the message envelope returned after a successful send.

type StringSlice

type StringSlice []string

StringSlice decodes a JSON array of strings, a single JSON string, or null into a []string: some SZChat fields that can hold multiple values are only wrapped in an array once there's more than one, coming back as a bare string otherwise.

func (*StringSlice) UnmarshalJSON

func (s *StringSlice) UnmarshalJSON(data []byte) error

type Tabulation

type Tabulation struct {
	ID        string `json:"_id,omitempty"`
	Name      string `json:"name"`
	CreatedAt string `json:"created_at,omitempty"`
	UpdatedAt string `json:"updated_at,omitempty"`
}

Tabulation is a classification label applied when closing an attendance.

type TabulationAPI

type TabulationAPI struct {
	// contains filtered or unexported fields
}

TabulationAPI groups the /tabulations endpoints.

func (*TabulationAPI) Create

func (a *TabulationAPI) Create(ctx context.Context, name string) (*Tabulation, error)

Create creates a tabulation via POST /tabulations.

func (*TabulationAPI) Delete

func (a *TabulationAPI) Delete(ctx context.Context, id string) error

Delete deletes a tabulation via DELETE /tabulations/{id}.

func (*TabulationAPI) List

List returns a paginated list of tabulations via GET /tabulations.

func (*TabulationAPI) Update

func (a *TabulationAPI) Update(ctx context.Context, id, name string) (*Tabulation, error)

Update renames a tabulation via PUT /tabulations/{id}.

type TagAPI added in v0.1.0

type TagAPI struct {
	// contains filtered or unexported fields
}

TagAPI groups the session tag endpoints (/user/agents/list/tagsCategory, /user/agents/session/*TagCategory).

func (*TagAPI) ListCategories added in v0.1.0

func (a *TagAPI) ListCategories(ctx context.Context, name string, paginate bool) ([]TagCategory, error)

ListCategories lists the available tag categories via GET /user/agents/list/tagsCategory.

func (*TagAPI) RemoveSessionTag added in v0.1.0

func (a *TagAPI) RemoveSessionTag(ctx context.Context, sessionID, tagID string) (string, error)

RemoveSessionTag removes a session's assigned tag via POST /user/agents/session/deleteTagCategory.

func (*TagAPI) SetSessionTag added in v0.1.0

func (a *TagAPI) SetSessionTag(ctx context.Context, sessionID, tagID string) (string, error)

SetSessionTag assigns a tag to a session via POST /user/agents/session/setTagCategory.

type TagCategory added in v0.1.0

type TagCategory struct {
	ID        string   `json:"_id"`
	Name      string   `json:"name"`
	Type      string   `json:"type,omitempty"`
	Campaigns []string `json:"campaigns,omitempty"`
	CreatedAt string   `json:"created_at,omitempty"`
	UpdatedAt string   `json:"updated_at,omitempty"`
}

TagCategory is a tag category available to agents/sessions.

type Team

type Team struct {
	ID                        string                      `json:"_id,omitempty"`
	CanBeDisabled             bool                        `json:"can_be_disabled,omitempty"`
	Name                      string                      `json:"name"`
	History                   string                      `json:"history"`
	Timer                     TeamTimer                   `json:"timer"`
	MessageEnd                string                      `json:"messageEnd,omitempty"`
	MessageAgent              string                      `json:"messageAgent,omitempty"`
	Predefined                []string                    `json:"predefined,omitempty"`
	RuleAttendance            string                      `json:"ruleAttendance"`
	Sequence                  []TeamAgentRef              `json:"sequence,omitempty"`
	Transhipment              string                      `json:"transhipment,omitempty"`
	TranshipmentName          string                      `json:"transhipmentName,omitempty"`
	Tabulations               []string                    `json:"tabulations,omitempty"`
	Permissions               TeamPermissions             `json:"permissions"`
	OptinStart                bool                        `json:"optin_start,omitempty"`
	Agents                    []string                    `json:"agents,omitempty"`
	Tags                      []string                    `json:"tags,omitempty"`
	RestrictedTeam            *TeamRestriction            `json:"restricted_team,omitempty"`
	RestrictedTeamForTransfer *TeamRestrictionForTransfer `json:"restricted_team_for_transfer,omitempty"`
	ContactActiveByGroup      *TeamGroupRestriction       `json:"contact_active_by_group,omitempty"`
	RestrictMessageTemplates  *TeamGroupRestriction       `json:"restrict_message_templates,omitempty"`
	EndingFlow                *TeamEndingFlow             `json:"ending_flow,omitempty"`
	Copilot                   *TeamCopilot                `json:"copilot,omitempty"`
	ValidatedAgents           bool                        `json:"validatedAgents,omitempty"`
	SummaryAttendance         *TeamAIFeature              `json:"summary_attendance,omitempty"`
	SentimentAnalysis         *TeamAIFeature              `json:"sentiment_analysis,omitempty"`
	AfterAttendance           *TeamAfterAttendance        `json:"after_attendance,omitempty"`
	NotifyPendingResponse     *TeamNotifyPendingResponse  `json:"notify_pending_response,omitempty"`
	NotifyWaitingPosition     *TeamNotifyWaitingPosition  `json:"notifyWaitingPosition,omitempty"`
	TimerWait                 *TeamTimerWait              `json:"timer_wait,omitempty"`
	TransferSession           bool                        `json:"transferSession,omitempty"`
	TransferSessionToHold     []string                    `json:"transferSessionToHold,omitempty"`
	SelectAgentsType          string                      `json:"selectAgentsType,omitempty"`
	HasOnlineAgents           bool                        `json:"hasOnlineAgents,omitempty"`
	HasOfflineAttendance      bool                        `json:"hasOfflineAttendance,omitempty"`
	CreatedAt                 string                      `json:"created_at,omitempty"`
	UpdatedAt                 string                      `json:"updated_at,omitempty"`
}

Team ("equipe") groups agents under shared distribution rules, permissions, and automation settings. The same struct is used both to send create/update requests and to decode list/detail responses.

type TeamAIFeature

type TeamAIFeature struct {
	Enabled bool   `json:"enabled"`
	RestID  string `json:"rest_id,omitempty"`
}

TeamAIFeature is the shared shape for the summary_attendance and sentiment_analysis toggles.

type TeamAPI

type TeamAPI struct {
	// contains filtered or unexported fields
}

TeamAPI groups the /campaigns ("equipes"/teams) endpoints.

func (*TeamAPI) Create

func (a *TeamAPI) Create(ctx context.Context, team Team) (*Team, error)

Create creates a team via POST /campaigns.

func (*TeamAPI) Delete

func (a *TeamAPI) Delete(ctx context.Context, id string) error

Delete deletes a team via DELETE /campaigns/{id}.

func (*TeamAPI) FilterByIDs

FilterByIDs returns teams matching the given ids via POST /campaigns/filterByIds.

func (*TeamAPI) List

func (a *TeamAPI) List(ctx context.Context, filter TeamListFilter) (*PaginatedResponse[Team], error)

List returns a paginated list of teams via GET /campaigns.

func (*TeamAPI) Resume

func (a *TeamAPI) Resume(ctx context.Context, paginate bool) ([]TeamSummary, error)

Resume returns a lightweight {_id, name} summary of every team via GET /campaigns/resume/{paginate}.

func (*TeamAPI) Update

func (a *TeamAPI) Update(ctx context.Context, id string, team Team) (*TeamUpdateResponse, error)

Update updates a team via PUT /campaigns/{id}.

func (*TeamAPI) UpdateAndScanFields added in v0.1.0

func (a *TeamAPI) UpdateAndScanFields(ctx context.Context, id string, team Team) (*TeamUpdateResponse, error)

UpdateAndScanFields updates a team via PUT /campaigns/{id}, setting the scanFields option so the API scans and migrates any legacy field layout on the stored team document before applying the update.

type TeamAfterAttendance

type TeamAfterAttendance struct {
	Summary                bool   `json:"summary,omitempty"`
	SentimentAnalysis      bool   `json:"sentiment_analysis,omitempty"`
	SentimentAnalysisScore bool   `json:"sentiment_analysis_score,omitempty"`
	RestID                 string `json:"rest_id,omitempty"`
}

TeamAfterAttendance configures post-attendance AI processing.

type TeamAgentRef

type TeamAgentRef struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

TeamAgentRef is a lightweight agent reference used in a Team's sequence.

type TeamCopilot

type TeamCopilot struct {
	RestID            StringSlice `json:"rest_id,omitempty"`
	ShowSourceContent bool        `json:"show_source_content,omitempty"`
}

TeamCopilot configures the AI copilot integration for a team.

type TeamEndingFlow

type TeamEndingFlow struct {
	Enabled bool   `json:"enabled"`
	FlowID  string `json:"flow_id,omitempty"`
}

TeamEndingFlow triggers a bot flow after an attendance ends.

type TeamFilterByIDsRequest

type TeamFilterByIDsRequest struct {
	CampaignIDs []string `json:"campaings"`
	Paginate    bool     `json:"paginate,omitempty"`
	Limit       int      `json:"limit,omitempty"`
	Page        int      `json:"page,omitempty"`
}

TeamFilterByIDsRequest is the payload for TeamAPI.FilterByIDs. CampaignIDs maps to the wire field "campaings", a misspelling in the SZChat API that is preserved here intentionally.

type TeamGroupRestriction

type TeamGroupRestriction struct {
	Enabled bool     `json:"enabled"`
	Groups  []string `json:"groups,omitempty"`
}

TeamGroupRestriction toggles a list of allowed contact/template groups.

type TeamListFilter

type TeamListFilter struct {
	Limit    int
	Name     string
	Paginate string
}

TeamListFilter holds the query parameters accepted by TeamAPI.List.

type TeamNotifyPendingResponse

type TeamNotifyPendingResponse struct {
	Contacts struct {
		Message string                   `json:"message,omitempty"`
		Timer   TeamPendingResponseTimer `json:"timer"`
	} `json:"contacts"`
	Agents struct {
		Timer TeamPendingResponseTimer `json:"timer"`
	} `json:"agents"`
}

TeamNotifyPendingResponse configures pending-response notifications for contacts and agents.

type TeamNotifyWaitingPosition

type TeamNotifyWaitingPosition struct {
	InitialWaitPosition TeamWaitPositionNotice `json:"initialWaitPosition"`
	UpdateWaitPosition  TeamWaitPositionNotice `json:"updateWaitPosition"`
}

TeamNotifyWaitingPosition configures queue-position notifications.

type TeamPendingResponseTimer

type TeamPendingResponseTimer struct {
	Enabled bool   `json:"enabled"`
	Limit   int    `json:"limit,omitempty"`
	Type    string `json:"type,omitempty"`
}

TeamPendingResponseTimer configures the pending-response notification delay.

type TeamPermissions

type TeamPermissions struct {
	ContactEdit              bool `json:"contact_edit,omitempty"`
	FinishAttendance         bool `json:"finish_attendance,omitempty"`
	ShowNumber               bool `json:"show_number,omitempty"`
	OfflineAttendance        bool `json:"offline_attendance,omitempty"`
	AgentChat                bool `json:"agent_chat,omitempty"`
	CampaignsChat            bool `json:"campaigns_chat,omitempty"`
	SendEmojis               bool `json:"send_emojis,omitempty"`
	OptinGupshup             bool `json:"optin_gupshup,omitempty"`
	ShowPreviewMessages      bool `json:"show_preview_messages,omitempty"`
	AutoAttendance           bool `json:"auto_attendance,omitempty"`
	HideContactOnHold        bool `json:"hideContactOnHold,omitempty"`
	HideContactOnAgentScreen bool `json:"hideContactOnAgentScreen,omitempty"`
	VoiceRecordEnabled       bool `json:"voice_record_enabled,omitempty"`
}

TeamPermissions holds the per-team agent capability flags.

type TeamRestriction

type TeamRestriction struct {
	Enabled  bool     `json:"enabled"`
	Channels []string `json:"channels,omitempty"`
}

TeamRestriction toggles a list of allowed channels for a team.

type TeamRestrictionForTransfer

type TeamRestrictionForTransfer struct {
	Enabled bool     `json:"enabled"`
	Teams   []string `json:"teams,omitempty"`
}

TeamRestrictionForTransfer restricts which teams an attendance can be transferred to.

type TeamSummary

type TeamSummary struct {
	ID   string `json:"_id"`
	Name string `json:"name"`
}

TeamSummary is the lightweight {_id, name} shape returned by TeamAPI.Resume and AgentAPI.MyTeams.

type TeamTimer

type TeamTimer struct {
	Days    int `json:"days"`
	Hours   int `json:"hours"`
	Minutes int `json:"minutes"`
}

TeamTimer configures how long an attendance can remain idle before it is recycled.

type TeamTimerWait

type TeamTimerWait struct {
	Enabled  bool   `json:"enabled"`
	Limit    int    `json:"limit,omitempty"`
	Type     string `json:"type,omitempty"`
	Redirect string `json:"redirect,omitempty"`
}

TeamTimerWait redirects an attendance to another team after waiting too long in queue.

type TeamUpdateResponse

type TeamUpdateResponse struct {
	Success bool   `json:"success"`
	Date    string `json:"date"`
}

TeamUpdateResponse is the ack returned by TeamAPI.Update.

type TeamWaitPositionNotice

type TeamWaitPositionNotice struct {
	Enabled bool   `json:"enabled"`
	Message string `json:"message,omitempty"`
}

TeamWaitPositionNotice is a single queue-position notification message.

type TimeGroup added in v0.1.0

type TimeGroup struct {
	ID        string           `json:"_id,omitempty"`
	Name      string           `json:"name"`
	Group     []TimeGroupRange `json:"group"`
	CreatedAt string           `json:"created_at,omitempty"`
	UpdatedAt string           `json:"updated_at,omitempty"`
}

TimeGroup ("grupo de horários") is a named set of time ranges used to gate channel/flow availability.

type TimeGroupAPI added in v0.1.0

type TimeGroupAPI struct {
	// contains filtered or unexported fields
}

TimeGroupAPI groups the /timeGroup endpoints.

func (*TimeGroupAPI) Create added in v0.1.0

func (a *TimeGroupAPI) Create(ctx context.Context, group TimeGroup) (*TimeGroup, error)

Create creates a time group via POST /timeGroup.

func (*TimeGroupAPI) Delete added in v0.1.0

func (a *TimeGroupAPI) Delete(ctx context.Context, id string) error

Delete deletes a time group via DELETE /timeGroup/{id}.

func (*TimeGroupAPI) List added in v0.1.0

List returns a paginated list of time groups via GET /timeGroup.

func (*TimeGroupAPI) Update added in v0.1.0

func (a *TimeGroupAPI) Update(ctx context.Context, id string, group TimeGroup) (*TimeGroup, error)

Update updates a time group via PUT /timeGroup/{id}.

type TimeGroupRange added in v0.1.0

type TimeGroupRange struct {
	Hour         string `json:"hour"`
	Description  string `json:"description"`
	InitialDay   string `json:"initialDay"`
	FinalDay     string `json:"finalDay"`
	InitialMonth int    `json:"initialMonth"`
	FinalMonth   int    `json:"finalMonth"`
	InitialWeek  int    `json:"initialWeek"`
	FinalWeek    int    `json:"finalWeek"`
	InitialTime  string `json:"initialTime"`
	FinalTime    string `json:"finalTime"`
}

TimeGroupRange is a single day/week/month/time range within a TimeGroup.

type ToggleAutoTranslateResponse added in v0.1.0

type ToggleAutoTranslateResponse struct {
	Success       bool `json:"success"`
	AutoTranslate bool `json:"auto_translate"`
}

ToggleAutoTranslateResponse is the payload returned by TranslationAPI.ToggleAutoTranslate.

type TranslateRequest added in v0.1.0

type TranslateRequest struct {
	Language  string `json:"language"`
	Message   string `json:"message"`
	SessionID string `json:"session_id,omitempty"`
	MessageID string `json:"message_id,omitempty"`
}

TranslateRequest is the payload for TranslationAPI.Translate.

type TranslateResponse added in v0.1.0

type TranslateResponse struct {
	DetectedSourceLanguage string `json:"detectedSourceLanguage"`
	TranslatedText         string `json:"translatedText"`
}

TranslateResponse is the payload returned by TranslationAPI.Translate.

type TranslationAPI added in v0.1.0

type TranslationAPI struct {
	// contains filtered or unexported fields
}

TranslationAPI groups the agent simultaneous-translation endpoints (/user/agent/stt/translate*).

func (*TranslationAPI) DetectLanguage added in v0.1.0

DetectLanguage detects the source language of a message via POST /user/agent/stt/translate/detect.

func (*TranslationAPI) ToggleAutoTranslate added in v0.1.0

func (a *TranslationAPI) ToggleAutoTranslate(ctx context.Context, sessionID string) (*ToggleAutoTranslateResponse, error)

ToggleAutoTranslate toggles automatic translation for a session via POST /user/agent/stt/translate/activeAutoTranslate.

func (*TranslationAPI) Translate added in v0.1.0

Translate translates a message to the target language via POST /user/agent/stt/translate.

type User

type User struct {
	ID           string   `json:"_id"`
	Type         string   `json:"type"`
	Email        string   `json:"email"`
	Name         string   `json:"name"`
	Codename     string   `json:"codename,omitempty"`
	Ramal        string   `json:"ramal,omitempty"`
	Begin        string   `json:"begin,omitempty"`
	End          string   `json:"end,omitempty"`
	Campaigns    []string `json:"campaigns,omitempty"`
	SessionToken string   `json:"session_token,omitempty"`
	Status       string   `json:"status,omitempty"`
	GroupID      string   `json:"groupId,omitempty"`
	Photo        string   `json:"photo,omitempty"`
	UpdatedAt    string   `json:"updated_at,omitempty"`
	CreatedAt    string   `json:"created_at,omitempty"`
}

User represents an authenticated agent or admin, as returned by the authentication endpoints.

type UserGroup added in v0.1.0

type UserGroup struct {
	ID                   string   `json:"_id,omitempty"`
	Name                 string   `json:"name"`
	Master               bool     `json:"master"`
	Permissions          []string `json:"permissions,omitempty"`
	ViewByTeams          bool     `json:"view_by_teams,omitempty"`
	GeneralSelectedTeams []string `json:"general_selected_teams,omitempty"`
	CreatedAt            string   `json:"created_at,omitempty"`
	UpdatedAt            string   `json:"updated_at,omitempty"`
}

UserGroup ("grupo de usuários") is a permission group assignable to admins/agents, distinct from AdminGroup which is read-only from AdminAPI.ListGroups.

type UserGroupAPI added in v0.1.0

type UserGroupAPI struct {
	// contains filtered or unexported fields
}

UserGroupAPI groups the /userGroup endpoints.

func (*UserGroupAPI) Create added in v0.1.0

func (a *UserGroupAPI) Create(ctx context.Context, group UserGroup) (*UserGroup, error)

Create creates a user group via POST /userGroup.

func (*UserGroupAPI) Delete added in v0.1.0

func (a *UserGroupAPI) Delete(ctx context.Context, id string) error

Delete deletes a user group via DELETE /userGroup/{id}.

func (*UserGroupAPI) List added in v0.1.0

List returns a paginated list of user groups via GET /userGroup.

func (*UserGroupAPI) Update added in v0.1.0

func (a *UserGroupAPI) Update(ctx context.Context, id string, group UserGroup) (*UserGroup, error)

Update updates a user group via PUT /userGroup/{id}.

type WebRTCAPI added in v0.1.0

type WebRTCAPI struct {
	// contains filtered or unexported fields
}

WebRTCAPI groups the agent WebRTC configuration endpoint.

func (*WebRTCAPI) Get added in v0.1.0

func (a *WebRTCAPI) Get(ctx context.Context, agentID string) (*WebRTCConfig, error)

Get returns an agent's WebRTC (Callcenter) configuration via GET /user/agent/webrtc/{agent_id}.

type WebRTCConfig added in v0.1.0

type WebRTCConfig struct {
	Enabled             bool   `json:"enabled"`
	URL                 string `json:"url,omitempty"`
	Width               int    `json:"width,omitempty"`
	Height              int    `json:"height,omitempty"`
	RefreshWindowButton bool   `json:"refreshWindowButton,omitempty"`
	CloseWindowButton   bool   `json:"closeWindowButton,omitempty"`
}

WebRTCConfig is the payload returned by WebRTCAPI.Get.

type WebhookAgentMessageData added in v0.1.0

type WebhookAgentMessageData struct {
	Message   string `json:"message,omitempty"`
	AgentFrom string `json:"agent_from"`
	AgentTo   string `json:"agent_to"`
	Type      string `json:"type"`
	Legend    string `json:"legend,omitempty"`
	StorageID string `json:"storage_id,omitempty"`
	CreatedAt string `json:"created_at"`
}

WebhookAgentMessageData is the "data.content" shape for the "agent_message" webhook (event "messageAgent").

type WebhookAgentPauseData added in v0.1.0

type WebhookAgentPauseData struct {
	Pause  WebhookPause `json:"pause"`
	UserID string       `json:"user_id"`
}

WebhookAgentPauseData is the "data" shape for the "agent_pause" webhook (event "adminPauseAgent") and "agent_resume" webhook (event "agentResume").

type WebhookAgentSessionData added in v0.1.0

type WebhookAgentSessionData struct {
	Session struct {
		ID        string              `json:"_id,omitempty"`
		Agent     WebhookSessionAgent `json:"agent"`
		SessionID string              `json:"session_id,omitempty"`
	} `json:"session"`
	SessionID string `json:"session_id"`
}

WebhookAgentSessionData is the "data" shape for the "agent_login" webhook (event "agentSignIn") and "agent_logoff" webhook (event "agentSignOut").

type WebhookConferenceData added in v0.1.0

type WebhookConferenceData struct {
	WebhookSessionData
	AgentInvited        string   `json:"agent_invited,omitempty"`
	AgentsConference    []string `json:"agents_conference,omitempty"`
	AgentAcceptedConfer string   `json:"agent_accepted_confer,omitempty"`
	AgentExitConfer     string   `json:"agent_exit_confer,omitempty"`
}

WebhookConferenceData is the "data" shape shared by the conference webhooks: "conference_invite" (humanInviteConfer), "conference_accept" (humanStartConfer), and "conference_finish" (humanFinishConfer).

type WebhookEnvelope added in v0.1.0

type WebhookEnvelope struct {
	Data    map[string]any `json:"data"`
	Webhook WebhookInfo    `json:"webhook"`
}

WebhookEnvelope is the outer shape of every receptive-API webhook delivery. Decode into this first, then decode the raw Data into the concrete type matching Webhook.Key (see the Webhook* Data types below).

type WebhookInfo added in v0.1.0

type WebhookInfo struct {
	App   string `json:"app"`
	Host  string `json:"host"`
	Key   string `json:"key"`
	Label string `json:"label"`
}

WebhookInfo identifies which webhook configuration delivered an event.

type WebhookMessageData added in v0.1.0

type WebhookMessageData struct {
	MessageID  string `json:"message_id"`
	Type       string `json:"type"`
	StorageID  string `json:"storage_id,omitempty"`
	Legend     string `json:"legend,omitempty"`
	PlatformID string `json:"platform_id"`
	Message    string `json:"message,omitempty"`
	Origin     string `json:"origin"`
	CreatedAt  string `json:"created_at"`
}

WebhookMessageData is the "data.content" shape for the "client_message" webhook (event "message").

type WebhookPause added in v0.1.0

type WebhookPause struct {
	Pause
	StartedAt string `json:"started_at,omitempty"`
}

WebhookPause is the pause snapshot embedded in the "agent_pause" and "agent_resume" webhooks.

type WebhookSessionAgent added in v0.1.0

type WebhookSessionAgent struct {
	ID        string `json:"_id"`
	Codename  string `json:"codename,omitempty"`
	CreatedAt string `json:"created_at,omitempty"`
	Email     string `json:"email"`
	Name      string `json:"name"`
	Status    string `json:"status,omitempty"`
	OriginWeb bool   `json:"origin_web,omitempty"`
	OriginApp bool   `json:"origin_app,omitempty"`
	IP        string `json:"ip,omitempty"`
}

WebhookSessionAgent is the agent snapshot embedded in the "agent_login"/"agent_logoff" webhooks.

type WebhookSessionData added in v0.1.0

type WebhookSessionData struct {
	ID                        string `json:"_id"`
	Name                      string `json:"name"`
	CampaignID                string `json:"campaign_id"`
	ContactID                 string `json:"contact_id"`
	ChannelID                 string `json:"channel_id"`
	Platform                  string `json:"platform"`
	PlatformID                string `json:"platform_id"`
	Status                    string `json:"status"`
	IsAttendance              string `json:"isAttendance"`
	CreatedAt                 string `json:"created_at"`
	LastInteraction           string `json:"lastInteraction,omitempty"`
	CountMessagesNotification int    `json:"count_messages_notification,omitempty"`
	Protocol                  string `json:"protocol,omitempty"`
	AgentID                   string `json:"agent_id,omitempty"`
	TabulationID              string `json:"tabulation_id,omitempty"`
	TabulationName            string `json:"tabulation_name,omitempty"`
}

WebhookSessionData is the "data" shape shared by the session lifecycle webhooks: "enter_queue" (waitStart), "accept_attendance" (humanStart), "attendance_finish" (humanFinish), and "attendance_transfer" (humanTransferAgent). Not every field is populated by every event; see the SZChat "API Receptiva" documentation for the exact set per event.

type WhatsAppAPI added in v0.1.0

type WhatsAppAPI struct {
	// contains filtered or unexported fields
}

WhatsAppAPI groups the WhatsApp receptive API endpoint, used by a BOT integration to hand a WhatsApp conversation off into Chat Center. Authentication is a per-channel API key (the "apiKey" header, holding the channel id), not the client's agent bearer token.

func (*WhatsAppAPI) CreateAttendance added in v0.1.0

CreateAttendance forwards a WhatsApp conversation (and optionally hands it off to a human agent) via POST /whatsapp/attendances. apiKey is the target channel's id.

type WhatsAppCreateAttendanceRequest added in v0.1.0

type WhatsAppCreateAttendanceRequest struct {
	Messages      []WhatsAppMessage `json:"messages"`
	ChatUserID    string            `json:"chatUserId"`
	AgentHandoff  bool              `json:"agentHandoff"`
	AgentsGroupID string            `json:"agentsGroupId,omitempty"`
	ChatUserPhoto string            `json:"chatUserPhoto,omitempty"`
	ChatUserName  string            `json:"chatUserName,omitempty"`
	CustomerID    string            `json:"customerId,omitempty"`
}

WhatsAppCreateAttendanceRequest is the payload for WhatsAppAPI.CreateAttendance.

type WhatsAppCreateAttendanceResponse added in v0.1.0

type WhatsAppCreateAttendanceResponse struct {
	Status  bool   `json:"status"`
	Message string `json:"message"`
}

WhatsAppCreateAttendanceResponse is the payload returned by WhatsAppAPI.CreateAttendance.

type WhatsAppMessage added in v0.1.0

type WhatsAppMessage struct {
	MessageID  string                 `json:"messageId"`
	SenderType string                 `json:"senderType"`
	EventAt    int64                  `json:"eventAt"`
	Message    WhatsAppMessageContent `json:"message"`
}

WhatsAppMessage is a single message within a WhatsAppAPI.CreateAttendance request.

type WhatsAppMessageContent added in v0.1.0

type WhatsAppMessageContent struct {
	Type     string `json:"type"`
	Text     string `json:"text,omitempty"`
	MediaURL string `json:"mediaUrl,omitempty"`
	MimeType string `json:"mimeType,omitempty"`
	Caption  string `json:"caption,omitempty"`
	FileName string `json:"fileName,omitempty"`
}

WhatsAppMessageContent is a single WhatsApp message's content, as forwarded via WhatsAppAPI.CreateAttendance. Fields used depend on Type ("TEXT", "IMAGE", "VIDEO", "AUDIO", "DOCUMENT").

type WordFilter added in v0.1.0

type WordFilter struct {
	ID        string `json:"_id,omitempty"`
	Word      string `json:"word"`
	Type      string `json:"type,omitempty"`
	CreatedAt string `json:"created_at,omitempty"`
	UpdatedAt string `json:"updated_at,omitempty"`
}

WordFilter is a filtered word entry, applied either to agent messages ("agent") or to messages that should not (re)trigger a bot flow ("contact").

type WordFilterAgentAPI added in v0.1.0

type WordFilterAgentAPI struct {
	// contains filtered or unexported fields
}

WordFilterAgentAPI groups the /wordFilter/agents endpoints, which filter words agents are not allowed to send.

func (*WordFilterAgentAPI) Create added in v0.1.0

func (a *WordFilterAgentAPI) Create(ctx context.Context, word string) (*WordFilter, error)

Create adds a filtered agent word via POST /wordFilter/agents.

func (*WordFilterAgentAPI) Delete added in v0.1.0

func (a *WordFilterAgentAPI) Delete(ctx context.Context, id string) error

Delete removes a filtered agent word via DELETE /wordFilter/agents/{id}.

func (*WordFilterAgentAPI) List added in v0.1.0

List returns a paginated list of filtered agent words via GET /wordFilter/agents.

func (*WordFilterAgentAPI) Update added in v0.1.0

func (a *WordFilterAgentAPI) Update(ctx context.Context, id, word string) (*WordFilter, error)

Update updates a filtered agent word via PUT /wordFilter/agents/{id}.

type WordFilterContactAPI added in v0.1.0

type WordFilterContactAPI struct {
	// contains filtered or unexported fields
}

WordFilterContactAPI groups the /wordFilter/contacts endpoints, which filter words that should not (re)trigger a bot flow when sent by a contact.

func (*WordFilterContactAPI) Create added in v0.1.0

func (a *WordFilterContactAPI) Create(ctx context.Context, word string) (*WordFilter, error)

Create adds a filtered contact word via POST /wordFilter/contacts.

func (*WordFilterContactAPI) Delete added in v0.1.0

func (a *WordFilterContactAPI) Delete(ctx context.Context, id string) error

Delete removes a filtered contact word via DELETE /wordFilter/contacts/{id}.

func (*WordFilterContactAPI) List added in v0.1.0

List returns a paginated list of filtered contact words via GET /wordFilter/contacts.

func (*WordFilterContactAPI) Update added in v0.1.0

func (a *WordFilterContactAPI) Update(ctx context.Context, id, word string) (*WordFilter, error)

Update updates a filtered contact word via PUT /wordFilter/contacts/{id}.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL