npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

evolution-go-sdk

v1.1.0

Published

TypeScript SDK for Evolution Go WhatsApp API

Readme

Evolution Go SDK

Documentação completa do SDK TypeScript para a Evolution Go — API WhatsApp de código aberto.

Este SDK é um Facade completo: esconde toda a complexidade HTTP. Você só precisa criar um cliente e chamar métodos.


Índice


Instalação

npm install evolution-go-sdk

# peer dependency recomendhada para Node.js
npm install undici
yarn add evolution-go-sdk undici
pnpm add evolution-go-sdk undici

Quick Start

import { EvolutionClient } from 'evolution-go-sdk';

// 1. Crie o client
const client = new EvolutionClient('http://localhost:8080', 'SUA_API_KEY', {
  instanceId: 'minha-instancia',
});

// 2. Envie uma mensagem — pronto!
await client.send.sendText('5511999999999', 'Olá do SDK! 🚀');

Configuração do Cliente

Básico

import { EvolutionClient } from 'evolution-go-sdk';

const client = new EvolutionClient(
  'http://localhost:8080',  // URL da sua Evolution Go
  'SUA_API_KEY'             // Global API Key ou token da instância
);

Com todas as opções

const client = new EvolutionClient('http://localhost:8080', 'API_KEY', {
  instanceId: 'meu-bot',       // Define a instância padrão para todas as requisições
  timeout: 60_000,             // Timeout em ms (padrão: 30000)
});

Trocar instância em runtime

// Criar sem instância definida
const client = new EvolutionClient('http://localhost:8080', 'GLOBAL_API_KEY');

// Definir depois
client.setInstanceId('bot-vendas');

await client.send.sendText('5511999999999', 'Mensagem do bot de vendas');

// Trocar para outra instância
client.setInstanceId('bot-suporte');

await client.send.sendText('5511888888888', 'Mensagem do bot de suporte');

// Ver qual está ativa
console.log(client.getInstanceId()); // 'bot-suporte'

Custom fetch (Node.js com undici)

import { EvolutionClient } from 'evolution-go-sdk';
import { fetch } from 'undici';

const client = new EvolutionClient('http://localhost:8080', 'API_KEY', {
  fetch,
  timeout: 60_000,
});

Com proxy personalizado

const client = new EvolutionClient('http://localhost:8080', 'API_KEY', {
  fetch: (url, init) => {
    return fetch(url, {
      ...init,
      dispatcher: new ProxyAgent('http://proxy.empresa.com:8080'),
    });
  },
});

Instance — Gerenciamento de Instâncias

Todas as instâncias representam uma conexão WhatsApp independente. Cada instância tem seu próprio QR code, token e webhook.

Criar uma instância

// Mínimo
const result = await client.instance.create({
  name: 'meu-bot',
  token: 'token-seguro-123',
});

console.log(result.data);
// {
//   instance: { id: 'meu-bot', name: 'meu-bot', token: 'token-seguro-123' }
// }

Criar com proxy

await client.instance.create({
  name: 'bot-com-proxy',
  token: 'token-123',
  proxy: {
    host: 'proxy.example.com',
    port: '3128',
    username: 'usuario',
    password: 'senha',
  },
});

Criar com configurações avançadas

await client.instance.create({
  name: 'bot-completo',
  token: 'token-123',
  advancedSettings: {
    reject_call: true,             // Rejeitar chamadas automaticamente
    msg_call: 'Chamada recusada',  // Mensagem ao recusar
    time_out: 60,                  // Timeout em segundos
    groups_ignore: false,          // Ignorar grupos
    always_online: true,           // Manter sempre online
    read_messages: true,           // Ler mensagens automaticamente
    read_status: true,             // Ler status automaticamente
    sync_full_history: true,       // Sincronizar histórico completo
    ignore_chat_messages: false,   // Ignorar mensagens de chat
  },
});

Criar com webhook

const result = await client.instance.connect({
  webhookUrl: 'https://meu-servidor.com/webhook/whatsapp',
  subscribe: true,          // Inscrever no webhook
  immediate: true,          // Retornar imediatamente
  rabbitmqEnable: false,    // Habilitar RabbitMQ
  webSocketEnable: true,    // Habilitar WebSocket
});

console.log(result.data);
// {
//   jid: '[email protected]',
//   webhookUrl: 'https://meu-servidor.com/webhook/whatsapp',
//   eventString: '...'
// }

Obter QR Code para pareamento

const qr = await client.instance.getQr();

console.log(qr.data);
// {
//   qrcode: 'data:image/png;base64,iVBORw0KG...',
//   code: '12345678'
// }

// Exibir no terminal (com qrcode-terminal)
import qrcode from 'qrcode-terminal';
qrcode.generate(qr.data.qrcode);

Obter código de pareamento por telefone

const pair = await client.instance.pair({
  phone: '5511999999999',   // Número com código do país
  subscribe: true,          // Receber eventos
});

console.log(pair.data);
// { pairingCode: 'ABCD-1234' }

Verificar status da conexão

const status = await client.instance.getStatus();

console.log(status.data);
// {
//   connected: true,
//   loggedIn: true,
//   myJid: '[email protected]',
//   name: 'meu-bot'
// }

Reconectar

await client.instance.reconnect();

Desconectar

await client.instance.disconnect();

Logout (desparear)

await client.instance.logout();

Obter todas as instâncias (admin)

const all = await client.instance.getAll();

console.log(all.data);
// [
//   { id: 'bot-vendas', name: 'bot-vendas', status: 'connected' },
//   { id: 'bot-suporte', name: 'bot-suporte', status: 'disconnected' }
// ]

Obter info de uma instância (admin)

const info = await client.instance.getInfo('bot-vendas');

console.log(info.data);

Deletar uma instância (admin)

await client.instance.delete('bot-vendas');

Configurar proxy (admin)

await client.instance.setProxy('bot-vendas', {
  host: 'proxy.example.com',
  port: '3128',
  username: 'user',
  password: 'pass',
});

Remover proxy (admin)

await client.instance.deleteProxy('bot-vendas');

Forçar reconexão (admin)

await client.instance.forceReconnect('bot-vendas', {
  number: '5511999999999',
});

Obter logs (admin)

const logs = await client.instance.getLogs('bot-vendas', {
  startDate: '2025-01-01',
  endDate: '2025-01-31',
  level: 'error',
  limit: 50,
});

console.log(logs.data);

Obter configurações avançadas

const settings = await client.instance.getAdvancedSettings();
console.log(settings.data);

Atualizar configurações avançadas

await client.instance.updateAdvancedSettings({
  reject_call: true,
  always_online: true,
  read_messages: false,
  groups_ignore: true,
});

Send — Envio de Mensagens

Todas as mensagens exigem que a instância esteja conectada e autenticada. O número deve estar no formato internacional sem + ou espaços.

Mensagem de Texto Simples

const result = await client.send.sendText('5511999999999', 'Olá! Como posso ajudar?');

console.log(result.data);

Texto mencionando participantes

await client.send.text({
  number: '[email protected]',  // JID do grupo
  text: '@5511999999999 @5511888888888 olhem isso!',
  mentionedJid: ['5511999999999', '5511888888888'],
});

Mencionar todos do grupo

await client.send.text({
  number: '[email protected]',
  text: '⚠️ Atenção todos!',
  mentionAll: true,
});

Responder uma mensagem (quote)

await client.send.text({
  number: '5511999999999',
  text: 'Essa é minha resposta!',
  quoted: {
    messageId: 'ABC123DEF456',   // ID da mensagem original
    participant: '5511888888888', // Quem enviou (opcional)
  },
});

Atalho: texto com quote

await client.send.sendTextWithQuote(
  '5511999999999',
  'Entendi!',
  'ABC123DEF456',
  '5511888888888',
);

Enviar com delay (antes de cada mensagem)

await client.send.text({
  number: '5511999999999',
  text: 'Mensagem com delay',
  delay: 2000,  // 2 segundos
});

Enviar Imagem (URL)

await client.send.sendImage(
  '5511999999999',
  'https://exemplo.com/foto.jpg',
  'Olha que foto bonita! 📸',
);

Enviar Imagem (completo)

await client.send.media({
  number: '5511999999999',
  url: 'https://exemplo.com/foto.jpg',
  type: 'image',
  caption: 'Foto do produto',
  filename: 'produto.jpg',  // opcional para image
  quoted: { messageId: 'MSG_ID' },
});

Enviar Vídeo

await client.send.sendVideo(
  '5511999999999',
  'https://exemplo.com/video.mp4',
  'Assista esse vídeo! 🎬',
);

Enviar Áudio

await client.send.sendAudio(
  '5511999999999',
  'https://exemplo.com/audio.ogg',
);

Enviar Documento

await client.send.sendDocument(
  '5511999999999',
  'https://exemplo.com/relatorio.pdf',
  'Relatório Mensal.pdf',
  'Segue o relatório do mês',
);

Media com tipos completos

await client.send.media({
  number: '5511999999999',
  url: 'https://exemplo.com/arquivo.pdf',
  type: 'document',       // 'image' | 'video' | 'audio' | 'document'
  caption: 'Documento importante',
  filename: 'doc.pdf',
  delay: 1000,
  quoted: { messageId: 'MSG_ID' },
});

Enviar Localização

await client.send.sendLocation(
  '5511999999999',
  'Escritório Central',   // Nome
  'Av. Paulista, 1000',   // Endereço
  -23.561414,             // Latitude
  -46.655881,             // Longitude
);

Enviar Enquete (Poll)

await client.send.sendPoll(
  '5511999999999',
  'Qual o melhor framework frontend?',
  ['React', 'Vue.js', 'Angular', 'Svelte'],
  1,  // Máximo de respostas (1 = única escolha)
);

Enquete com múltiplas escolhas

await client.send.sendPoll(
  '[email protected]',
  'Quais dias prefere para a reunião?',
  ['Segunda', 'Quarta', 'Sexta'],
  3,  // Pode marcar até 3
);

Enviar Sticker

await client.send.sendSticker(
  '5511999999999',
  'https://exemplo.com/sticker.webp',
);

Enviar Link Preview

await client.send.sendLink(
  '5511999999999',
  'https://github.com',
  'Confira esse repositório incrível!',
  'GitHub',              // Título
);

Link preview completo

await client.send.link({
  number: '5511999999999',
  url: 'https://youtube.com/watch?v=abc123',
  text: 'Video novo saindo!',
  title: 'Novo Vídeo',
  description: 'Assista agora',
  imgUrl: 'https://img.youtube.com/vi/abc123/maxresdefault.jpg',
});

Enviar Contato (vCard)

await client.send.contact({
  number: '5511999999999',
  vcard: {
    fullName: 'João Silva',
    phone: '5511888888888',
    email: '[email protected]',
    url: 'https://joaosilva.com.br',
  },
});

Enviar múltiplos contatos em sequência

const contatos = [
  { fullName: 'João Silva', phone: '5511111111111' },
  { fullName: 'Maria Santos', phone: '5511222222222' },
  { fullName: 'Pedro Costa', phone: '5511333333333' },
];

for (const c of contatos) {
  await client.send.contact({
    number: '5511999999999',
    vcard: c,
  });
  await new Promise(r => setTimeout(r, 1000)); // Delay entre envios
}

Enviar Botão

await client.send.button({
  number: '5511999999999',
  title: '🤖 Menu Principal',
  description: 'Escolha uma opção abaixo:',
  footer: 'Bot de Atendimento',
  buttons: [
    { type: 'reply', displayText: '📦 Ver Produtos', id: 'btn_produtos' },
    { type: 'reply', displayText: '💬 Falar com Atendente', id: 'btn_atendente' },
    { type: 'reply', displayText: '❓ Ajuda', id: 'btn_ajuda' },
  ],
});

Enviar Lista

await client.send.list({
  number: '5511999999999',
  title: '🛒 Catálogo de Produtos',
  description: 'Navegue pelas categorias:',
  buttonText: 'Ver Produtos',
  footerText: 'Loja Virtual',
  sections: [
    {
      title: '📱 Eletrônicos',
      rows: [
        { title: 'Smartphones', description: 'Celulares e acessórios', rowId: 'cat_smartphones' },
        { title: 'Notebooks', description: 'Computadores portáteis', rowId: 'cat_notebooks' },
        { title: 'Tablets', description: 'Tablets e e-readers', rowId: 'cat_tablets' },
      ],
    },
    {
      title: '👕 Vestuário',
      rows: [
        { title: 'Camisetas', rowId: 'cat_camisetas' },
        { title: 'Calças', rowId: 'cat_calcas' },
      ],
    },
  ],
});

User — Operações de Usuário

Verificar se número existe no WhatsApp

const exists = await client.user.isOnWhatsApp('5511999999999');

console.log(exists); // true ou false

Verificar múltiplos números

const result = await client.user.check({
  number: ['5511999999999', '5511888888888', '5511777777777'],
});

console.log(result.data);
// {
//   users: [
//     { jid: '[email protected]', exists: true },
//     { jid: '[email protected]', exists: false },
//     { jid: '[email protected]', exists: true }
//   ]
// }

Obter informações de um usuário

const info = await client.user.getInfo({
  number: ['5511999999999'],
});

console.log(info.data);
// {
//   users: {
//     "[email protected]": {
//       verifiedName: "Empresa XYZ",
//       status: "Disponível",
//       pictureId: "...",
//       devices: [...]
//     }
//   }
// }

Obter avatar/foto de perfil

const avatar = await client.user.getAvatar({
  number: '5511999999999',
  preview: false,  // true = thumbnail, false = imagem completa
});

console.log(avatar.data);
// { url: 'https://pps.whatsapp.net/v/...' }

Atalho: obter URL do avatar

const avatarUrl = await client.user.getAvatarUrl('5511999999999');
console.log(avatarUrl); // 'https://pps.whatsapp.net/v/...' ou null

Obter todos os contatos

const contacts = await client.user.getContacts();

console.log(contacts.data);
// {
//   contacts: [
//     { jid: '[email protected]', name: 'João', pushName: 'João' },
//     ...
//   ]
// }

Bloquear contato

await client.user.blockContact('5511888888888');

Desbloquear contato

await client.user.unblockContact('5511888888888');

Obter lista de bloqueados

const blocked = await client.user.getBlockList();

console.log(blocked.data);
// { blocked: ['[email protected]', ...] }

Configurar privacidade

await client.user.setPrivacy({
  groupAdd: 'contacts',              // all, contacts, contact_blacklist, none
  lastSeen: 'contacts',              // all, contacts, contact_blacklist, none
  status: 'contacts',                // all, contacts, contact_blacklist, none
  profile: 'all',                    // all, contacts, contact_blacklist, none
  readReceipts: 'all',               // all, none
  callAdd: 'contacts',               // all, contacts, contact_blacklist, none
  online: 'contacts',                // all, contacts, contact_blacklist, none
});

Obter configurações de privacidade

const privacy = await client.user.getPrivacy();
console.log(privacy.data);

Alterar foto de perfil

await client.user.setProfilePicture({
  image: 'https://exemplo.com/minha-foto.jpg',
});

// Ou com base64
const base64Image = 'data:image/jpeg;base64,/9j/4AAQSkZJRg...';
await client.user.setProfilePicture({ image: base64Image });

Alterar nome de perfil

await client.user.setMyName('Meu Bot de Vendas');

Alterar status de perfil

await client.user.setMyStatus('🟢 Online | Atendimento 24h');

Message — Operações de Mensagem

Reagir a uma mensagem

await client.message.reactWith(
  '5511999999999',   // Número/chat
  'ABC123DEF456',    // ID da mensagem
  '❤️',              // Emoji
);

Reação completa (com fromMe/participant)

await client.message.react({
  number: '5511999999999',
  reaction: '👍',
  id: 'ABC123DEF456',
  fromMe: false,        // Se a mensagem foi enviada por mim
  participant: '5511888888888',  // Em grupos, quem enviou
});

Indicador de digitação (typing)

// Mostrar "digitando..."
await client.message.typing('5511999999999');

// Esperar 3 segundos
await new Promise(r => setTimeout(r, 3000));

// Parar
await client.message.stopTyping('5511999999999');

Indicador de gravando áudio

await client.message.recording('5511999999999');

// Parar depois de gravar
await new Promise(r => setTimeout(r, 5000));
await client.message.stopTyping('5511999999999');

Marcar como lida

// Mensagem única
await client.message.markAsRead('5511999999999', 'MSG_ID_1');

// Múltiplas mensagens
await client.message.markManyAsRead('5511999999999', [
  'MSG_ID_1',
  'MSG_ID_2',
  'MSG_ID_3',
]);

Editar mensagem

await client.message.editMessage(
  '5511999999999',          // Chat
  'ABC123DEF456',           // ID da mensagem original
  'Texto corrigido! ✅',    // Novo texto
);

Deletar mensagem para todos

await client.message.deleteForEveryone(
  '5511999999999',   // Chat
  'ABC123DEF456',    // ID da mensagem
);

Baixar mídia de uma mensagem

const media = await client.message.downloadMedia({
  message: {
    // Objeto da mensagem recebido via webhook
    imageMessage: {
      url: '...',
      mimetype: 'image/jpeg',
      fileSha256: '...',
      // ...
    },
  },
});

console.log(media.data);
// { base64: 'data:image/jpeg;base64,...', timestamp: 1234567890 }

Verificar status de entrega

const status = await client.message.getStatus({
  id: 'ABC123DEF456',
});

console.log(status.data);
// { result: 'Read', timestamp: 1234567890 }
// result pode ser: 'Sent', 'Delivered', 'Read', 'Played'

Chat — Operações de Chat

⚠️ Algumas operações de chat podem não estar totalmente implementadas no servidor.

Fixar chat

await client.chat.pinChat('[email protected]');

// Atalho
await client.chat.pinChat('[email protected]');

Desfixar chat

await client.chat.unpinChat('[email protected]');

Arquivar chat

await client.chat.archiveChat('[email protected]');

desarquivar chat

await client.chat.unarchiveChat('[email protected]');

Silenciar chat (mute)

await client.chat.muteChat('[email protected]');

Dessilenciar chat (unmute)

await client.chat.unmuteChat('[email protected]');

Solicitar sincronização de histórico

await client.chat.historySync({
  count: 100,  // Número de mensagens para sincronizar
});

Group — Operações de Grupos

Listar todos os grupos

const groups = await client.group.list();

console.log(groups.data);
// {
//   groups: [
//     {
//       id: '[email protected]',
//       subject: 'Grupo de Trabalho',
//       owner: '[email protected]',
//       creation: 1234567890,
//       participants: [...]
//     }
//   ]
// }

Obter grupos que participo

const myGroups = await client.group.getMyGroups();
console.log(myGroups.data);

Obter informações de um grupo

const info = await client.group.getInfoByJid('[email protected]');

console.log(info.data);
// {
//   id: '[email protected]',
//   subject: 'Nome do Grupo',
//   description: 'Descrição do grupo',
//   owner: '[email protected]',
//   creation: 1234567890,
//   participants: [
//     { jid: '[email protected]', admin: 'superadmin' },
//     { jid: '[email protected]', admin: null }
//   ],
//   size: 25,
//   announce: false,
//   restrict: false
// }

Criar um grupo

const created = await client.group.createGroup(
  'Grupo de Projeto',
  ['5511999999999', '5511888888888', '5511777777777'],
);

console.log(created.data);
// {
//   groupJid: '[email protected]',
//   ...
// }

Obter link de convite

const invite = await client.group.getGroupLink('[email protected]');

console.log(invite.data);
// { inviteUrl: 'https://chat.whatsapp.com/ABC123XYZ' }

Resetar link de convite (gerar novo)

const newLink = await client.group.getGroupLink('[email protected]', true); // reset = true

Entrar em grupo por código

await client.group.joinByCode('ABC123XYZ');

Adicionar participantes

await client.group.addParticipants('[email protected]', [
  '5511666666666',
  '5511555555555',
]);

Remover participantes

await client.group.removeParticipants('[email protected]', [
  '5511666666666',
]);

Promover a admin

await client.group.promoteParticipants('[email protected]', [
  '5511999999999',
]);

Rebaixar de admin

await client.group.demoteParticipants('[email protected]', [
  '5511999999999',
]);

Atualização completa de participante

await client.group.updateParticipant({
  groupJid: '[email protected]',
  participants: ['5511999999999'],
  action: 'promote',  // 'add' | 'remove' | 'promote' | 'demote'
});

Alterar nome do grupo

await client.group.setGroupName('[email protected]', 'Novo Nome do Grupo');

Alterar descrição do grupo

await client.group.setGroupDescription(
  '[email protected]',
  'Grupo para discussão de projetos e tarefas.'
);

Limpar descrição do grupo

await client.group.setGroupDescription('[email protected]', '');

Alterar foto do grupo

await client.group.setGroupPhoto(
  '[email protected]',
  'https://exemplo.com/foto-grupo.jpg',
);

Sair do grupo

await client.group.leaveByJid('[email protected]');

Call — Operações de Chamada

Rejeitar chamada recebida

await client.call.rejectCall(
  '[email protected]',  // callCreator
  'ABC123DEF456',                  // callId
);

Rejeitar chamada automaticamente via webhook

Quando receber um evento de chamada via webhook:

// No seu handler de webhook
app.post('/webhook', async (req, res) => {
  const event = req.body;

  if (event.event === 'call' && event.data.status === 'ringing') {
    await client.call.rejectCall(
      event.data.from,      // Quem ligou
      event.data.callId,    // ID da chamada
    );
  }

  res.status(200).send();
});

Community — Operações de Comunidade

Criar comunidade

const community = await client.community.createCommunity('Minha Comunidade');

console.log(community.data);

Adicionar grupos à comunidade

await client.community.addGroupsToCommunity(
  '120363xxx@community',     // Community JID
  ['[email protected]', '[email protected]'],  // Grupos para adicionar
);

Remover grupos da comunidade

await client.community.removeGroupsFromCommunity(
  '120363xxx@community',
  ['[email protected]'],
);

Label — Operações de Etiquetas

Labels funcionam com WhatsApp Business para organização de conversas.

Listar todas as etiquetas

const labels = await client.label.list();

console.log(labels.data);
// [
//   { id: '1', name: 'Lead', color: 0xFF0000 },
//   { id: '2', name: 'Cliente', color: 0x00FF00 },
//   { id: '3', name: 'Pendente', color: 0xFFFF00 }
// ]

Criar/Editar etiqueta

await client.label.saveLabel('4', 'Novo Lead', 0x0000FF);
// Ou direto:
await client.label.editLabel({
  labelId: '4',
  name: 'Novo Lead',
  color: 0x0000FF,  // Azul
  deleted: false,
});

Adicionar etiqueta a um chat

const jid = '[email protected]';

await client.label.labelChat(jid, '1');  // Label ID '1' = Lead

Remover etiqueta de um chat

await client.label.unlabelChat(jid, '1');

Adicionar etiqueta a uma mensagem

await client.label.labelMessage(
  jid,
  '2',             // Label ID
  'ABC123DEF456',  // Message ID
);

Remover etiqueta de uma mensagem

await client.label.unlabelMessage(jid, '2', 'ABC123DEF456');

Newsletter — Operações de Newsletter

Criar newsletter

const newsletter = await client.newsletter.createNewsletter(
  'Ofertas Diárias',
  'As melhores ofertas todo dia!',
);

console.log(newsletter.data);
// {
//   id: 'newsletter_jid@newsletter',
//   name: 'Ofertas Diárias',
//   description: 'As melhores ofertas todo dia!',
//   ...
// }

Listar newsletters

const list = await client.newsletter.list();

console.log(list.data);

Obter informações de uma newsletter

const info = await client.newsletter.getInfoByJid('newsletter_jid@newsletter');

console.log(info.data);

Obter link de convite

const invite = await client.newsletter.getInviteByKey('ABC123KEY');

console.log(invite.data);

Se inscrever em uma newsletter

await client.newsletter.subscribeByJid('newsletter_jid@newsletter');

Obter mensagens de uma newsletter

const messages = await client.newsletter.getMessagesByJid(
  'newsletter_jid@newsletter',
  20,  // Quantidade de mensagens
);

console.log(messages.data);

Poll — Resultados de Enquetes

Obter resultados de uma enquete

const results = await client.poll.getResults('POLL_MESSAGE_ID');

console.log(results.data);
// {
//   pollMessageId: 'POLL_MESSAGE_ID',
//   question: 'Qual o melhor framework?',
//   totalVotes: 42,
//   options: [
//     { name: 'React', votes: 20, percentage: 47.6 },
//     { name: 'Vue.js', votes: 12, percentage: 28.6 },
//     { name: 'Angular', votes: 6, percentage: 14.3 },
//     { name: 'Svelte', votes: 4, percentage: 9.5 }
//   ]
// }

Tratamento de Erros

Básico

import { EvolutionClient, EvolutionError } from 'evolution-go-sdk';

try {
  await client.send.sendText('5511999999999', 'Olá!');
} catch (err) {
  if (err instanceof EvolutionError) {
    console.error(`Erro ${err.status}: ${err.message}`);
  } else {
    console.error('Erro desconhecido:', err);
  }
}

Com retry automático

async function sendWithRetry(
  client: EvolutionClient,
  number: string,
  text: string,
  maxRetries = 3,
): Promise<void> {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      await client.send.sendText(number, text);
      console.log(`✅ Enviado na tentativa ${attempt}`);
      return;
    } catch (err) {
      if (err instanceof EvolutionError && err.status >= 500) {
        console.warn(`⚠️ Tentativa ${attempt}/${maxRetries} falhou`);
        if (attempt === maxRetries) throw err;
        await new Promise(r => setTimeout(r, 2000 * attempt)); // Backoff
      } else {
        throw err;
      }
    }
  }
}

await sendWithRetry(client, '5511999999999', 'Mensagem importante');

Tratamento específico por status

try {
  await client.send.sendText(number, text);
} catch (err) {
  if (err instanceof EvolutionError) {
    switch (err.status) {
      case 400:
        console.error('Dados inválidos:', err.message);
        break;
      case 401:
        console.error('Não autorizado — verifique a API key');
        break;
      case 404:
        console.error('Instância não encontrada');
        break;
      case 500:
        console.error('Erro interno do servidor');
        break;
      default:
        console.error(`Erro ${err.status}:`, err.message);
    }
  }
}

Error wrapper genérico

async function safeApi<T>(
  fn: () => Promise<ApiResponse<T>>,
): Promise<ApiResponse<T> | null> {
  try {
    return await fn();
  } catch (err) {
    if (err instanceof EvolutionError) {
      console.error(`API Error [${err.status}]:`, err.message);
    } else {
      console.error('Unexpected error:', err);
    }
    return null;
  }
}

// Uso
const result = await safeApi(() => client.send.sendText(number, text));
if (result) {
  console.log('Sucesso:', result.data);
}

Receber Eventos via Webhook

O SDK envia mensagens, mas para receber eventos do WhatsApp, configure um webhook:

Exemplo com Express

import express from 'express';
import { EvolutionClient } from 'evolution-go-sdk';

const app = express();
app.use(express.json());

const client = new EvolutionClient('http://localhost:8080', 'API_KEY');

// Endpoint do webhook
app.post('/webhook', async (req, res) => {
  const event = req.body;

  console.log('Evento recebido:', event.event);
  console.log('Dados:', event.data);

  switch (event.event) {
    case 'messages.upsert':
      // Nova mensagem recebida
      const msg = event.data;
      console.log(`Mensagem de ${msg.key.remoteJid}: ${msg.message?.conversation}`);

      // Auto-resposta
      if (msg.message?.conversation?.startsWith('/oi')) {
        await client.send.sendText(
          msg.key.remoteJid!.split('@')[0],
          'Olá! Como posso ajudar?',
        );
      }
      break;

    case 'connection.update':
      // Status da conexão mudou
      console.log('Conexão:', event.data);
      break;

    case 'qrcode.updated':
      // QR Code atualizado
      console.log('QR Code:', event.data.qrcode);
      break;

    case 'call':
      // Chamada recebida
      console.log('Chamada de:', event.data.from);
      break;

    case 'group.update':
      // Atualização de grupo
      console.log('Grupo atualizado:', event.data);
      break;
  }

  res.status(200).json({ received: true });
});

app.listen(3000, () => {
  console.log('Webhook rodando na porta 3000');
});

Exemplo com Fastify

import Fastify from 'fastify';
import { EvolutionClient } from 'evolution-go-sdk';

const fastify = Fastify();
const client = new EvolutionClient('http://localhost:8080', 'API_KEY');

fastify.post('/webhook', async (request, reply) => {
  const event = request.body as any;

  if (event.event === 'messages.upsert') {
    const msg = event.data;
    const from = msg.key.remoteJid?.split('@')[0];

    if (from && msg.message?.conversation) {
      const text = msg.message.conversation;

      if (text === '/help') {
        await client.send.sendText(from, 'Comandos: /oi, /help, /status');
      }
    }
  }

  return { received: true };
});

fastify.listen({ port: 3000 });

Exemplo com Hono (Edge/Deno)

import { Hono } from 'hono';
import { EvolutionClient } from 'evolution-go-sdk';

const hono = new Hono();
const client = new EvolutionClient('http://localhost:8080', 'API_KEY');

hono.post('/webhook', async (c) => {
  const event = await c.req.json();

  if (event.event === 'messages.upsert') {
    // Processar mensagem
  }

  return c.json({ received: true });
});

export default hono;

Exemplos Práticos Completos

Bot de Atendimento

import { EvolutionClient, EvolutionError } from 'evolution-go-sdk';
import express from 'express';

const client = new EvolutionClient('http://localhost:8080', 'API_KEY', {
  instanceId: 'bot-atendimento',
});

const app = express();
app.use(express.json());

// Fila de mensagens
const messageQueue: Array<{ from: string; text: string }> = [];

// Menu principal
const MENU = `
🤖 *Bot de Atendimento*

1️⃣ - Ver produtos
2️⃣ - Falar com atendente
3️⃣ - Horário de funcionamento
4️⃣ - Endereço
5️⃣ - Status do pedido

_Digite o número da opção desejada_
`;

app.post('/webhook', async (req, res) => {
  const { event, data, instance } = req.body;

  if (event !== 'messages.upsert') {
    return res.json({ ok: true });
  }

  const msg = data;
  if (!msg?.message?.conversation) {
    return res.json({ ok: true });
  }

  const from = msg.key.remoteJid!.split('@')[0];
  const text = msg.message.conversation.trim();

  try {
    // Reagir com emoji
    await client.message.reactWith(from, msg.key.id!, '👍');

    // Marcar como lida
    await client.message.markAsRead(from, msg.key.id!);

    // Menu principal
    if (text === '1' || text === '/menu') {
      await client.send.text({
        number: from,
        text: '📦 *Nossos Produtos:*\n\n1. Plano Basic - R$29,90/mês\n2. Plano Pro - R$59,90/mês\n3. Plano Enterprise - R$99,90/mês\n\n_Responda com o número do plano_',
        quoted: { messageId: msg.key.id! },
      });
    } else if (text === '2') {
      await client.send.sendText(
        from,
        '📞 Vou transferir para um atendente. Aguarde um momento...',
      );
      // Adicionar à fila de atendimento
      messageQueue.push({ from, text: 'Solicitou atendente' });
    } else if (text === '3') {
      await client.send.sendText(
        from,
        '🕐 *Horário de Funcionamento:*\n\nSeg-Sex: 8h às 18h\nSáb: 8h às 12h\nDom: Fechado',
      );
    } else if (text === '4') {
      await client.send.sendText(
        from,
        '📍 *Endereço:*\n\nAv. Paulista, 1000 - São Paulo, SP',
      );
      // Enviar localização
      await client.send.sendLocation(
        from,
        'Escritório Central',
        'Av. Paulista, 1000',
        -23.561414,
        -46.655881,
      );
    } else if (text === '5') {
      await client.send.text({
        number: from,
        text: '📋 Digite o número do seu pedido:',
        quoted: { messageId: msg.key.id! },
      });
    } else if (text.startsWith('/oi') || text.startsWith('/ola') || text.startsWith('/olá')) {
      await client.send.sendText(
        from,
        `Olá! 👋\n\n${MENU}`,
      );
    } else {
      await client.send.sendText(
        from,
        `Desculpe, não entendi. Digite /menu para ver as opções.`,
      );
    }
  } catch (err) {
    console.error('Erro ao processar mensagem:', err);
  }

  res.json({ ok: true });
});

app.listen(3000, () => {
  console.log('🤖 Bot de atendimento rodando!');
});

Sistema de Notificações

import { EvolutionClient } from 'evolution-go-sdk';

const client = new EvolutionClient('http://localhost:8080', 'API_KEY', {
  instanceId: 'notificacoes',
});

interface Notificacao {
  usuario: string;
  telefone: string;
  tipo: 'pedido' | 'entrega' | 'pagamento' | 'promocao';
  mensagem: string;
}

class NotificationService {
  private client: EvolutionClient;

  constructor(client: EvolutionClient) {
    this.client = client;
  }

  async enviar(notificacao: Notificacao): Promise<void> {
    const emojis: Record<Notificacao['tipo'], string> = {
      pedido: '📦',
      entrega: '🚚',
      pagamento: '💰',
      promocao: '🎉',
    };

    const emoji = emojis[notificacao.tipo];

    try {
      await this.client.send.sendText(
        notificacao.telefone,
        `${emoji} *${notificacao.tipo.toUpperCase()}*\n\n${notificacao.mensagem}\n\n_Obrigado, ${notificacao.usuario}!_`,
      );
      console.log(`✅ Notificação enviada para ${notificacao.usuario}`);
    } catch (err) {
      console.error(`❌ Falha ao enviar para ${notificacao.usuario}:`, err);
      throw err;
    }
  }

  async enviarEmMassa(
    notificacoes: Notificacao[],
    delayMs = 1000,
  ): Promise<{ success: number; failed: number }> {
    let success = 0;
    let failed = 0;

    for (const n of notificacoes) {
      try {
        await this.enviar(n);
        success++;
      } catch {
        failed++;
      }
      await new Promise(r => setTimeout(r, delayMs));
    }

    return { success, failed };
  }
}

// Uso
const service = new NotificationService(client);

// Notificação individual
await service.enviar({
  usuario: 'João',
  telefone: '5511999999999',
  tipo: 'entrega',
  mensagem: 'Seu pedido #12345 saiu para entrega! Previsão: hoje até 18h.',
});

// Notificação em massa
const notificacoes: Notificacao[] = [
  { usuario: 'João', telefone: '5511999999999', tipo: 'promocao', mensagem: 'Black Friday! 50% OFF em todos os produtos!' },
  { usuario: 'Maria', telefone: '5511888888888', tipo: 'promocao', mensagem: 'Black Friday! 50% OFF em todos os produtos!' },
  { usuario: 'Pedro', telefone: '5511777777777', tipo: 'promocao', mensagem: 'Black Friday! 50% OFF em todos os produtos!' },
];

const resultado = await service.enviarEmMassa(notificacoes, 2000);
console.log(`Enviadas: ${resultado.success}, Falhas: ${resultado.failed}`);

Bot de Vendas com Carrinho

import { EvolutionClient } from 'evolution-go-sdk';

const client = new EvolutionClient('http://localhost:8080', 'API_KEY', {
  instanceId: 'bot-vendas',
});

interface CartItem {
  productId: string;
  name: string;
  price: number;
  qty: number;
}

// Carrinhos em memória
const carts = new Map<string, CartItem[]>();

const PRODUCTS = [
  { id: '1', name: 'Camiseta Preta', price: 49.90 },
  { id: '2', name: 'Calça Jeans', price: 129.90 },
  { id: '3', name: 'Tênis Esportivo', price: 299.90 },
  { id: '4', name: 'Boné', price: 39.90 },
];

async function showProducts(phone: string) {
  const text = PRODUCTS.map(p =>
    `*${p.id}* - ${p.name} — R$ ${p.price.toFixed(2)}`
  ).join('\n');

  await client.send.sendText(phone, `🛒 *Produtos Disponíveis:*\n\n${text}\n\n_Para comprar, digite: comprar <id> <qtd>_`);
}

async function showCart(phone: string) {
  const cart = carts.get(phone) || [];

  if (cart.length === 0) {
    await client.send.sendText(phone, '🛒 Seu carrinho está vazio!');
    return;
  }

  const items = cart.map(i => `• ${i.name} x${i.qty} — R$ ${(i.price * i.qty).toFixed(2)}`).join('\n');
  const total = cart.reduce((sum, i) => sum + i.price * i.qty, 0);

  await client.send.sendText(phone, `🛒 *Seu Carrinho:*\n\n${items}\n\n💰 *Total: R$ ${total.toFixed(2)}*\n\n_Para finalizar, digite: finalizar_`);
}

async function addToCart(phone: string, productId: string, qty: number) {
  const product = PRODUCTS.find(p => p.id === productId);
  if (!product) {
    await client.send.sendText(phone, '❌ Produto não encontrado!');
    return;
  }

  const cart = carts.get(phone) || [];
  const existing = cart.find(i => i.productId === productId);

  if (existing) {
    existing.qty += qty;
  } else {
    cart.push({ productId: product.id, name: product.name, price: product.price, qty });
  }

  carts.set(phone, cart);
  await client.send.sendText(phone, `✅ ${product.name} adicionado ao carrinho!`);
  await showCart(phone);
}

// Webhook handler
app.post('/webhook', async (req, res) => {
  const { event, data } = req.body;
  if (event !== 'messages.upsert' || !data?.message?.conversation) {
    return res.json({ ok: true });
  }

  const phone = data.key.remoteJid!.split('@')[0];
  const text = data.message.conversation.trim().toLowerCase();

  if (text === 'produtos' || text === '/produtos') {
    await showProducts(phone);
  } else if (text === 'carrinho' || text === '/carrinho') {
    await showCart(phone);
  } else if (text === 'finalizar') {
    const cart = carts.get(phone) || [];
    if (cart.length === 0) {
      await client.send.sendText(phone, '❌ Carrinho vazio! Adicione produtos primeiro.');
    } else {
      const total = cart.reduce((sum, i) => sum + i.price * i.qty, 0);
      await client.send.sendText(
        phone,
        `🎉 *Pedido Finalizado!*\n\nTotal: R$ ${total.toFixed(2)}\n\nEntraremos em contato para confirmar o pagamento.`,
      );
      carts.delete(phone);
    }
  } else if (text.startsWith('comprar')) {
    const parts = text.split(' ');
    if (parts.length >= 3) {
      const productId = parts[1];
      const qty = parseInt(parts[2], 10);
      if (!isNaN(qty) && qty > 0) {
        await addToCart(phone, productId, qty);
      } else {
        await client.send.sendText(phone, '❌ Quantidade inválida! Use: comprar <id> <qtd>');
      }
    } else {
      await client.send.sendText(phone, '❌ Use: comprar <id> <qtd>');
    }
  }

  res.json({ ok: true });
});

Agendamento de Mensagens

import { EvolutionClient } from 'evolution-go-sdk';
import cron from 'node-cron';

const client = new EvolutionClient('http://localhost:8080', 'API_KEY', {
  instanceId: 'agendador',
});

// Lista de clientes
const CLIENTES = [
  { nome: 'João', telefone: '5511999999999' },
  { nome: 'Maria', telefone: '5511888888888' },
];

// Bom dia todo dia às 8h
cron.schedule('0 8 * * *', async () => {
  console.log('Enviando bom dia...');

  for (const c of CLIENTES) {
    await client.send.sendText(
      c.telefone,
      `☀️ *Bom dia, ${c.nome}!*\n\nQue seu dia seja incrível! 🚀`,
    );
    await new Promise(r => setTimeout(r, 1000));
  }
});

// Lembreto de pagamento toda segunda às 10h
cron.schedule('0 10 * * 1', async () => {
  console.log('Enviando lembrete de pagamento...');

  for (const c of CLIENTES) {
    await client.send.sendText(
      c.telefone,
      `💰 *Olá ${c.nome}!*\n\nLembrete: sua fatura vence hoje.\n\nEvite juros!`,
    );
    await new Promise(r => setTimeout(r, 1000));
  }
});

// Feliz aniversário
const ANIVERSARIOS: Record<string, string> = {
  '01-15': '5511999999999',  // João - 15/01
  '03-22': '5511888888888',  // Maria - 22/03
};

cron.schedule('0 9 * * *', async () => {
  const hoje = new Date();
  const key = `${String(hoje.getMonth() + 1).padStart(2, '0')}-${String(hoje.getDate()).padStart(2, '0')}`;

  const telefone = ANIVERSARIOS[key];
  if (telefone) {
    await client.send.sendText(telefone, `🎂 *Parabéns!*\n\nFeliz aniversário! Muitas felicidades! 🎉🎈`);
  }
});

console.log('⏰ Agendador iniciado!');

Disparador em Massa com Delay

import { EvolutionClient } from 'evolution-go-sdk';
import { readFileSync } from 'fs';

const client = new EvolutionClient('http://localhost:8080', 'API_KEY', {
  instanceId: 'disparador',
});

interface Contact {
  name: string;
  phone: string;
}

// Ler contatos de um CSV
function loadContacts(csvPath: string): Contact[] {
  const csv = readFileSync(csvPath, 'utf-8');
  return csv
    .split('\n')
    .slice(1) // pular header
    .filter(Boolean)
    .map(line => {
      const [name, phone] = line.split(',');
      return { name: name.trim(), phone: phone.trim() };
    });
}

async function dispararEmMassa(
  contacts: Contact[],
  message: string,
  delayMin: number,
  delayMax: number,
): Promise<{ success: number; failed: number }> {
  let success = 0;
  let failed = 0;

  console.log(`📤 Iniciando disparo para ${contacts.length} contatos...`);

  for (let i = 0; i < contacts.length; i++) {
    const contact = contacts[i];

    try {
      // Verificar se está no WhatsApp
      const exists = await client.user.isOnWhatsApp(contact.phone);
      if (!exists) {
        console.log(`⏭️  [${i + 1}/${contacts.length}] ${contact.name} - Não está no WhatsApp`);
        continue;
      }

      // Mensagem personalizada
      const personalizedMsg = message.replace(/\{nome\}/g, contact.name);
      await client.send.sendText(contact.phone, personalizedMsg);

      success++;
      console.log(`✅ [${i + 1}/${contacts.length}] ${contact.name} - Enviado`);
    } catch (err) {
      failed++;
      console.error(`❌ [${i + 1}/${contacts.length}] ${contact.name} - Erro:`, err);
    }

    // Delay aleatório entre as mensagens (para não ser detectado como spam)
    const delay = Math.floor(Math.random() * (delayMax - delayMin) + delayMin);
    console.log(`⏳ Aguardando ${delay}ms...`);
    await new Promise(r => setTimeout(r, delay));
  }

  return { success, failed };
}

// Uso
const contacts = loadContacts('./contatos.csv');

const message = `Olá {nome}! 👋

Temos uma oferta especial para você!
Acesse: https://exemplo.com/promo

Aproveite! 🎉`;

dispararEmMassa(contacts, message, 5000, 15000)
  .then(result => {
    console.log(`\n📊 Resultado final:`);
    console.log(`   ✅ Enviados: ${result.success}`);
    console.log(`   ❌ Falhas: ${result.failed}`);
  });

Uso Avançado

Acessar o HttpClient diretamente

const http = client.getHttpClient();

// Requisição customizada para um endpoint que não existe no SDK
const response = await http.post('/custom/endpoint', { customBody: 'data' });

Usar serviços individualmente

import { SendService, HttpClient } from 'evolution-go-sdk';

const http = new HttpClient('http://localhost:8080', 'API_KEY');
http.setInstanceId('minha-instancia');

const send = new SendService(http);
await send.sendText('5511999999999', 'Olá!');

Middleware de logging

// Wrapper com logging
class LoggedClient extends EvolutionClient {
  async logAndExecute<T>(name: string, fn: () => Promise<T>): Promise<T> {
    const start = Date.now();
    try {
      const result = await fn();
      console.log(`✅ ${name} (${Date.now() - start}ms)`);
      return result;
    } catch (err) {
      console.error(`❌ ${name} (${Date.now() - start}ms):`, err);
      throw err;
    }
  }
}

// Uso
await client.logAndExecute('sendText', () =>
  client.send.sendText('5511999999999', 'Olá!')
);

Pool de múltiplas instâncias

import { EvolutionClient } from 'evolution-go-sdk';

// Pool de instâncias para load balancing
const instances = [
  new EvolutionClient('http://localhost:8080', 'API_KEY', { instanceId: 'bot-1' }),
  new EvolutionClient('http://localhost:8080', 'API_KEY', { instanceId: 'bot-2' }),
  new EvolutionClient('http://localhost:8080', 'API_KEY', { instanceId: 'bot-3' }),
];

let currentIndex = 0;

function getNextClient(): EvolutionClient {
  const client = instances[currentIndex];
  currentIndex = (currentIndex + 1) % instances.length;
  return client;
}

// Usar o próximo cliente do pool
async function sendMessageRotated(number: string, text: string) {
  const c = getNextClient();
  return c.send.sendText(number, text);
}

Referência Completa da API

Retorno padrão

Todos os métodos retornam Promise<ApiResponse<T>>:

interface ApiResponse<T = any> {
  message?: string;   // Mensagem de sucesso
  data?: T;           // Dados retornados pela API
  error?: string;     // Mensagem de erro (se houver)
}

EvoultionError

class EvolutionError extends Error {
  readonly status: number;     // HTTP status code
  readonly message: string;    // Mensagem de erro
  readonly response?: Response; // Response original
}

InstanceService

| Método | Descrição | Endpoint | |--------|-----------|----------| | create(data) | Criar instância | POST /instance/create | | connect(data?) | Conectar instância | POST /instance/connect | | reconnect() | Reconectar | POST /instance/reconnect | | disconnect() | Desconectar | POST /instance/disconnect | | logout() | Logout | DELETE /instance/logout | | getStatus() | Status da conexão | GET /instance/status | | getQr() | Obter QR Code | GET /instance/qr | | pair(data) | Código de pareamento | POST /instance/pair | | getAll() | Listar todas (admin) | GET /instance/all | | getInfo(id) | Info de instância (admin) | GET /instance/info/:id | | delete(id) | Deletar (admin) | DELETE /instance/delete/:id | | setProxy(id, data) | Configurar proxy (admin) | POST /instance/proxy/:id | | deleteProxy(id) | Remover proxy (admin) | DELETE /instance/proxy/:id | | forceReconnect(id, data) | Forçar reconexão (admin) | POST /instance/forcereconnect/:id | | getLogs(id, params?) | Obter logs (admin) | GET /instance/logs/:id | | getAdvancedSettings() | Obter settings avançados | GET /:instanceId/advanced-settings | | updateAdvancedSettings(data) | Atualizar settings | PUT /:instanceId/advanced-settings |

SendService

| Método | Descrição | Endpoint | |--------|-----------|----------| | text(data) | Enviar texto | POST /send/text | | link(data) | Enviar link preview | POST /send/link | | media(data) | Enviar mídia (URL) | POST /send/media | | poll(data) | Enviar enquete | POST /send/poll | | sticker(data) | Enviar sticker | POST /send/sticker | | location(data) | Enviar localização | POST /send/location | | contact(data) | Enviar contato | POST /send/contact | | button(data) | Enviar botões | POST /send/button | | list(data) | Enviar lista | POST /send/list | | Conveniência | | | | sendText(number, text) | Texto simples | — | | sendTextWithQuote(number, text, msgId, participant?) | Texto com quote | — | | sendImage(number, url, caption?) | Imagem | — | | sendVideo(number, url, caption?) | Vídeo | — | | sendAudio(number, url) | Áudio | — | | sendDocument(number, url, filename, caption?) | Documento | — | | sendLocation(number, name, address, lat, lng) | Localização | — | | sendPoll(number, question, options, maxAnswers?) | Enquete | — | | sendSticker(number, url) | Sticker | — | | sendLink(number, url, text, title?) | Link preview | — |

UserService

| Método | Descrição | Endpoint | |--------|-----------|----------| | getInfo(data) | Info do usuário | POST /user/info | | check(data) | Verificar existência | POST /user/check | | getAvatar(data) | Foto de perfil | POST /user/avatar | | getContacts() | Lista de contatos | GET /user/contacts | | getPrivacy() | Configurações de privacidade | GET /user/privacy | | setPrivacy(data) | Definir privacidade | POST /user/privacy | | block(data) | Bloquear | POST /user/block | | unblock(data) | Desbloquear | POST /user/unblock | | getBlockList() | Lista de bloqueados | GET /user/blocklist | | setProfilePicture(data) | Foto de perfil | POST /user/profilePicture | | setProfileName(data) | Nome de perfil | POST /user/profileName | | setProfileStatus(data) | Status de perfil | POST /user/profileStatus | | Conveniência | | | | isOnWhatsApp(number) | Verificar se está no WA | — | | getAvatarUrl(number, preview?) | URL do avatar | — | | setMyName(name) | Meu nome | — | | setMyStatus(status) | Meu status | — | | blockContact(number) | Bloquear | — | | unblockContact(number) | Desbloquear | — |

MessageService

| Método | Descrição | Endpoint | |--------|-----------|----------| | react(data) | Reagir | POST /message/react | | presence(data) | Presença (typing/recording) | POST /message/presence | | markRead(data) | Marcar como lida | POST /message/markread | | downloadMedia(data) | Baixar mídia | POST /message/downloadmedia | | getStatus(data) | Status de entrega | POST /message/status | | deleteEveryone(data) | Deletar p/ todos | POST /message/delete | | edit(data) | Editar mensagem | POST /message/edit | | Conveniência | | | | reactWith(number, msgId, emoji) | Reagir | — | | typing(number) | Digitando | — | | stopTyping(number) | Parar digitação | — | | recording(number) | Gravando áudio | — | | markAsRead(number, msgId) | Marcar lida | — | | markManyAsRead(number, msgIds) | Marcar várias lidas | — | | editMessage(chat, msgId, text) | Editar | — | | deleteForEveryone(chat, msgId) | Deletar | — |

ChatService

| Método | Descrição | Endpoint | |--------|-----------|----------| | pin(data) | Fixar chat | POST /chat/pin | | unpin(data) | Desfixar | POST /chat/unpin | | archive(data) | Arquivar | POST /chat/archive | | unarchive(data) | Desarquivar | POST /chat/unarchive | | mute(data) | Silenciar | POST /chat/mute | | unmute(data) | Dessilenciar | POST /chat/unmute | | historySync(data?) | Sincronizar histórico | POST /chat/history-sync | | Conveniência | | | | pinChat(chat) | Fixar | — | | unpinChat(chat) | Desfixar | — | | archiveChat(chat) | Arquivar | — | | unarchiveChat(chat) | Desarquivar | — | | muteChat(chat) | Silenciar | — | | unmuteChat(chat) | Dessilenciar | — |

GroupService

| Método | Descrição | Endpoint | |--------|-----------|----------| | list() | Listar grupos | GET /group/list | | getInfo(data) | Info do grupo | POST /group/info | | getInviteLink(data) | Link de convite | POST /group/invitelink | | setPhoto(data) | Foto do grupo | POST /group/photo | | setName(data) | Nome do grupo | POST /group/name | | setDescription(data) | Descrição | POST /group/description | | create(data) | Criar grupo | POST /group/create | | updateParticipant(data) | Gerenciar participante | POST /group/participant | | getMyGroups() | Grupos que participo | GET /group/myall | | join(data) | Entrar por link | POST /group/join | | leave(data) | Sair do grupo | POST /group/leave | | Conveniência | | | | getInfoByJid(jid) | Info por JID | — | | getGroupLink(jid, reset?) | Link de convite | — | | addParticipants(jid, numbers) | Adicionar | — | | removeParticipants(jid, numbers) | Remover | — | | promoteParticipants(jid, numbers) | Promover admin | — | | demoteParticipants(jid, numbers) | Rebaixar admin | — | | createGroup(name, participants) | Criar | — | | joinByCode(code) | Entrar por código | — | | leaveByJid(jid) | Sair | — | | setGroupPhoto(jid, image) | Foto | — | | setGroupName(jid, name) | Nome | — | | setGroupDescription(jid, desc) | Descrição | — |

CallService

| Método | Descrição | Endpoint | |--------|-----------|----------| | reject(data) | Rejeitar chamada | POST /call/reject | | rejectCall(creator, callId) | Rejeitar (conveniência) | — |

CommunityService

| Método | Descrição | Endpoint | |--------|-----------|----------| | create(data) | Criar comunidade | POST /community/create | | add(data) | Adicionar grupos | POST /community/add | | remove(data) | Remover grupos | POST /community/remove | | Conveniência | | | | createCommunity(name) | Criar | — | | addGroupsToCommunity(cjid, gjids) | Adicionar grupos | — | | removeGroupsFromCommunity(cjid, gjids) | Remover grupos | — |

LabelService

| Método | Descrição | Endpoint | |--------|-----------|----------| | addChatLabel(data) | Etiqueta no chat | POST /label/chat | | addMessageLabel(data) | Etiqueta na mensagem | POST /label/message | | editLabel(data) | Editar etiqueta | POST /label/edit | | list() | Listar etiquetas | GET /label/list | | removeChatLabel(data) | Remover do chat | POST /unlabel/chat | | removeMessageLabel(data) | Remover da mensagem | POST /unlabel/message | | Conveniência | | | | labelChat(jid, labelId) | Etiquetar chat | — | | unlabelChat(jid, labelId) | Desetiquetar chat | — | | labelMessage(jid, labelId, msgId) | Etiquetar msg | — | | unlabelMessage(jid, labelId, msgId) | Desetiquetar msg | — | | saveLabel(id, name, color?) | Criar/editar label | — |

NewsletterService

| Método | Descrição | Endpoint | |--------|-----------|----------| | create(data) | Criar newsletter | POST /newsletter/create | | list() | Listar newsletters | GET /newsletter/list | | getInfo(data) | Informações | POST /newsletter/info | | getInvite(data) | Link de convite | POST /newsletter/link | | subscribe(data) | Inscrever-se | POST /newsletter/subscribe | | getMessages(data) | Mensagens | POST /newsletter/messages | | Conveniência | | | | createNewsletter(name, desc?) | Criar | — | | getInfoByJid(jid) | Info por JID | — | | subscribeByJid(jid) | Inscrever | — | | getInviteByKey(key) | Link por key | — | | getMessagesByJid(jid, count?) | Mensagens | — |

PollService

| Método | Descrição | Endpoint | |--------|-----------|----------| | getResults(pollMessageId) | Resultados da enquete | GET /polls/:id/results |


Licença

MIT