@systemzero/baileys 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,561 +1,419 @@
1
- # 📦 @systemzero/baileys `v1.0.4`
1
+ <div align="center">
2
2
 
3
- > Biblioteca WhatsApp Web API em Node.js fork ultra customizado com funções avançadas de envio de mensagens, grupos, mídias, IA e muito mais.
3
+ <img src="https://files.catbox.moe/w1m2q4.jpg" width="120" style="border-radius:16px" />
4
4
 
5
- ---
5
+ # @systemzero/baileys
6
+
7
+ **v1.0.5** · Fork avançado do Baileys com suporte nativo a todos os tipos de mensagens do WhatsApp
6
8
 
7
- ## 📋 Sumário
8
-
9
- - [Instalação](#instalação)
10
- - [Conexão Básica](#conexão-básica)
11
- - [📨 Envio de Mensagens](#-envio-de-mensagens)
12
- - [Texto](#texto)
13
- - [Imagem](#imagem)
14
- - [Vídeo](#vídeo)
15
- - [Áudio](#áudio)
16
- - [Documento](#documento)
17
- - [Sticker](#sticker)
18
- - [Localização](#localização)
19
- - [Contato](#contato)
20
- - [Enquete (Poll)](#enquete-poll)
21
- - [Reação](#reação)
22
- - [Menção](#menção)
23
- - [Link com Preview](#link-com-preview)
24
- - [Resposta (Quoted)](#resposta-quoted)
25
- - [Mensagem Editada](#mensagem-editada)
26
- - [Mensagem Deletada](#mensagem-deletada)
27
- - [Fixar Mensagem](#fixar-mensagem)
28
- - [View Once](#view-once)
29
- - [Modo Efêmero (Desaparecimento)](#modo-efêmero-desaparecimento)
30
- - [🎨 Mensagens Interativas (Botões)](#-mensagens-interativas-botões)
31
- - [Botões Rápidos (Quick Reply)](#botões-rápidos-quick-reply)
32
- - [Lista](#lista)
33
- - [Botões Nativos (interactiveButtons)](#botões-nativos-interactivebuttons)
34
- - [Pagamento Nativo](#pagamento-nativo)
35
- - [Produto](#produto)
36
- - [🤖 Funções Rich (Meta AI Style)](#-funções-rich-meta-ai-style)
37
- - [Texto Rico](#texto-rico)
38
- - [Código Rico](#código-rico)
39
- - [Lista Rica](#lista-rica)
40
- - [Tabela Rica](#tabela-rica)
41
- - [Rich Completo](#rich-completo)
42
- - [Reels Ricos](#reels-ricos)
43
- - [Perplexity IA](#perplexity-ia)
44
- - [📁 Tipos Especiais de Mensagem](#-tipos-especiais-de-mensagem)
45
- - [Álbum de Fotos/Vídeos](#álbum-de-fotosvídeos)
46
- - [Evento](#evento)
47
- - [Resultado de Enquete](#resultado-de-enquete)
48
- - [Story de Grupo](#story-de-grupo)
49
- - [Pagamento (requestPayment)](#pagamento-requestpayment)
50
- - [👥 Funções de Grupo](#-funções-de-grupo)
51
- - [💬 Funções de Chat](#-funções-de-chat)
52
- - [🔒 Privacidade](#-privacidade)
53
- - [🏷️ Labels](#️-labels)
54
- - [📡 Presença](#-presença)
9
+ [![NPM](https://img.shields.io/npm/v/@systemzero/baileys?color=7c3aed&style=flat-square&label=npm)](https://www.npmjs.com/package/@systemzero/baileys)
10
+ [![License](https://img.shields.io/badge/license-MIT-6366f1?style=flat-square)](LICENSE)
11
+ [![Author](https://img.shields.io/badge/by-Josué%20%3C%2F%3E-ec4899?style=flat-square)](https://t.me/blackhzx)
12
+
13
+ </div>
55
14
 
56
15
  ---
57
16
 
58
17
  ## Instalação
59
18
 
60
19
  ```bash
61
- npm install @systemzero/baileys
20
+ npm i @systemzero/baileys
21
+ ```
22
+
23
+ Dependências opcionais para sticker pack e thumbnail:
24
+ ```bash
25
+ npm i sharp
62
26
  # ou
63
- yarn add @systemzero/baileys
27
+ npm i @napi-rs/image
64
28
  ```
65
29
 
66
- > **Requisito:** Node.js >= 20.0.0
30
+ ---
31
+
32
+ ## Índice
33
+
34
+ 1. [Conexão](#1-conexão)
35
+ 2. [Mensagens de mídia](#2-mensagens-de-mídia)
36
+ 3. [Mensagens especiais](#3-mensagens-especiais)
37
+ 4. [Botões e interativos](#4-botões-e-interativos)
38
+ 5. [Sticker Pack nativo](#5-sticker-pack-nativo)
39
+ 6. [Canais Newsletter](#6-canais-newsletter)
40
+ 7. [Enquetes com decrypt](#7-enquetes-com-decrypt)
41
+ 8. [AI Rich](#8-ai-rich)
42
+ 9. [Grupos](#9-grupos)
43
+ 10. [Perfil e privacidade](#10-perfil-e-privacidade)
44
+ 11. [Eventos do socket](#11-eventos-do-socket)
45
+ 12. [Utilitários](#12-utilitários)
67
46
 
68
47
  ---
69
48
 
70
- ## Conexão Básica
49
+ ## 1. Conexão
50
+
51
+ ### Setup básico
71
52
 
72
53
  ```js
73
- import makeWASocket, { useMultiFileAuthState, DisconnectReason } from '@systemzero/baileys'
54
+ const {
55
+ default: makeWASocket,
56
+ useMultiFileAuthState,
57
+ DisconnectReason,
58
+ Browsers,
59
+ fetchLatestWaWebVersion
60
+ } = require('@systemzero/baileys')
74
61
 
75
- const { state, saveCreds } = await useMultiFileAuthState('./auth_info')
62
+ const { state, saveCreds } = await useMultiFileAuthState('./session')
63
+ const { version } = await fetchLatestWaWebVersion()
76
64
 
77
65
  const sock = makeWASocket({
78
- auth: state,
79
- printQRInTerminal: true
66
+ version,
67
+ auth: state,
68
+ browser: Browsers.ubuntu('Chrome'),
69
+ printQRInTerminal: false,
70
+ logger: require('pino')({ level: 'silent' }),
71
+ getMessage: async (key) => {
72
+ const msg = await store.loadMessage(key.remoteJid, key.id)
73
+ return msg?.message || undefined
74
+ }
80
75
  })
81
76
 
82
77
  sock.ev.on('creds.update', saveCreds)
83
78
 
84
79
  sock.ev.on('connection.update', ({ connection, lastDisconnect }) => {
85
80
  if (connection === 'close') {
86
- const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut
87
- if (shouldReconnect) conectar()
88
- } else if (connection === 'open') {
89
- console.log('✅ Conectado ao WhatsApp!')
81
+ const code = lastDisconnect?.error?.output?.statusCode
82
+ if (code !== DisconnectReason.loggedOut) startBot()
90
83
  }
91
84
  })
92
85
  ```
93
86
 
94
- ---
87
+ ### Pairing Code
88
+
89
+ ```js
90
+ // Código gerado automaticamente (ex: ABCD-EFGH)
91
+ const code = await sock.requestPairingCode('5511999999999')
95
92
 
96
- ## 📨 Envio de Mensagens
93
+ // Código personalizado exatamente 8 caracteres
94
+ const code = await sock.requestPairingCode('5511999999999', 'MYBOT001')
95
+ ```
97
96
 
98
- Todas as funções de envio usam `sock.sendMessage(jid, conteúdo, opções?)`.
97
+ ### Store em memória
99
98
 
100
- O `jid` é o identificador do destinatário:
101
- - **Privado:** `'5511999999999@s.whatsapp.net'`
102
- - **Grupo:** `'120363xxxxxxxx@g.us'`
103
- - **Status:** `'status@broadcast'`
99
+ ```js
100
+ const store = {
101
+ messages: {},
102
+ bind: (ev) => {
103
+ ev.on('messages.upsert', ({ messages }) => {
104
+ for (const msg of messages) {
105
+ if (!msg.key?.remoteJid) continue
106
+ store.messages[msg.key.remoteJid] ??= {}
107
+ store.messages[msg.key.remoteJid][msg.key.id] = msg
108
+ }
109
+ })
110
+ },
111
+ loadMessage: async (jid, id) => store.messages[jid]?.[id] || null
112
+ }
113
+
114
+ store.bind(sock.ev)
115
+ ```
104
116
 
105
117
  ---
106
118
 
107
- ### Texto
119
+ ## 2. Mensagens de mídia
108
120
 
109
- Envia uma mensagem de texto simples.
121
+ Todos os campos de mídia aceitam `Buffer`, `{ url: 'https://...' }` ou `{ stream: ReadableStream }`.
110
122
 
111
- ```js
112
- await sock.sendMessage('5511999999999@s.whatsapp.net', {
113
- text: 'Olá, mundo! 👋'
114
- })
115
- ```
123
+ ### Texto
116
124
 
117
- Com formatação WhatsApp:
118
125
  ```js
126
+ await sock.sendMessage(jid, { text: 'Olá!' })
127
+
128
+ // Com menção
119
129
  await sock.sendMessage(jid, {
120
- text: '*negrito* _itálico_ ~tachado~ `monoespaçado`'
130
+ text: '@55119...!',
131
+ mentions: ['5511999999999@s.whatsapp.net']
121
132
  })
122
133
  ```
123
134
 
124
- ---
125
-
126
135
  ### Imagem
127
136
 
128
- Envia uma imagem com legenda opcional. Aceita **Buffer**, **URL** ou **caminho local**.
129
-
130
137
  ```js
131
- // Por URL
132
138
  await sock.sendMessage(jid, {
133
- image: { url: 'https://exemplo.com/foto.jpg' },
134
- caption: 'Uma linda foto 🖼️'
135
- })
136
-
137
- // Por Buffer
138
- import { readFileSync } from 'fs'
139
- await sock.sendMessage(jid, {
140
- image: readFileSync('./imagem.jpg'),
141
- caption: 'Foto do arquivo'
139
+ image: { url: 'https://exemplo.com/foto.jpg' },
140
+ caption: 'Legenda'
142
141
  })
143
142
  ```
144
143
 
145
- ---
146
-
147
144
  ### Vídeo
148
145
 
149
- Envia um vídeo com legenda opcional. Aceita **Buffer**, **URL** ou **caminho local**.
150
-
151
146
  ```js
152
- // Por URL
153
- await sock.sendMessage(jid, {
154
- video: { url: 'https://exemplo.com/video.mp4' },
155
- caption: 'Assista esse vídeo! 🎬',
156
- mimetype: 'video/mp4'
157
- })
158
-
159
- // Como GIF animado
160
147
  await sock.sendMessage(jid, {
161
- video: readFileSync('./animacao.mp4'),
162
- gifPlayback: true, // Reproduz como GIF
163
- caption: 'Olha esse gif!'
148
+ video: { url: 'https://exemplo.com/video.mp4' },
149
+ caption: 'Legenda',
150
+ gifPlayback: false // true envia como GIF silencioso
164
151
  })
165
152
  ```
166
153
 
167
- ---
168
-
169
154
  ### Áudio
170
155
 
171
- Envia um áudio. Use `ptt: true` para enviar como mensagem de voz (PTT).
172
-
173
156
  ```js
174
- // Áudio normal (arquivo de música)
157
+ // Música
175
158
  await sock.sendMessage(jid, {
176
- audio: { url: 'https://exemplo.com/musica.mp3' },
177
- mimetype: 'audio/mp4'
159
+ audio: buffer,
160
+ mimetype: 'audio/mpeg',
161
+ ptt: false
178
162
  })
179
163
 
180
- // Mensagem de voz (PTT)
164
+ // Nota de voz (PTT)
181
165
  await sock.sendMessage(jid, {
182
- audio: readFileSync('./audio.ogg'),
166
+ audio: buffer,
183
167
  mimetype: 'audio/ogg; codecs=opus',
184
- ptt: true // Aparece como áudio de voz
168
+ ptt: true
185
169
  })
186
170
  ```
187
171
 
188
- ---
189
-
190
172
  ### Documento
191
173
 
192
- Envia um arquivo/documento com nome customizado.
193
-
194
174
  ```js
195
175
  await sock.sendMessage(jid, {
196
- document: { url: 'https://exemplo.com/arquivo.pdf' },
176
+ document: buffer,
197
177
  mimetype: 'application/pdf',
198
- fileName: 'Relatório Mensal.pdf',
199
- caption: 'Segue o relatório em anexo 📄'
200
- })
201
-
202
- // Por Buffer
203
- await sock.sendMessage(jid, {
204
- document: readFileSync('./contrato.docx'),
205
- mimetype: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
206
- fileName: 'Contrato.docx'
178
+ fileName: 'relatorio.pdf',
179
+ caption: 'Segue o relatório'
207
180
  })
208
181
  ```
209
182
 
210
- ---
211
-
212
- ### Sticker
213
-
214
- Envia um sticker (figurinha). Deve ser WebP ou convertido previamente.
183
+ ### Figurinha
215
184
 
216
185
  ```js
217
- await sock.sendMessage(jid, {
218
- sticker: readFileSync('./figurinha.webp')
219
- })
220
-
221
- // Por URL
222
- await sock.sendMessage(jid, {
223
- sticker: { url: 'https://exemplo.com/sticker.webp' }
224
- })
186
+ await sock.sendMessage(jid, { sticker: buffer })
225
187
  ```
226
188
 
227
- ---
189
+ ### Album (múltiplas mídias agrupadas)
228
190
 
229
- ### Localização
230
-
231
- Envia uma localização no mapa.
191
+ Mínimo 2 itens.
232
192
 
233
193
  ```js
234
194
  await sock.sendMessage(jid, {
235
- location: {
236
- degreesLatitude: -23.5505,
237
- degreesLongitude: -46.6333,
238
- name: 'São Paulo, SP',
239
- address: 'Av. Paulista, 1000'
240
- }
195
+ album: [
196
+ { image: buffer1 },
197
+ { image: buffer2, caption: 'Segunda foto' },
198
+ { video: bufferVideo },
199
+ ]
241
200
  })
242
201
  ```
243
202
 
244
- ---
245
-
246
203
  ### Contato
247
204
 
248
- Envia um contato (vCard).
249
-
250
205
  ```js
251
- const vcard = `BEGIN:VCARD
252
- VERSION:3.0
253
- FN:João Silva
254
- ORG:Empresa LTDA;
255
- TEL;type=CELL;type=VOICE;waid=5511999999999:+55 11 99999-9999
256
- END:VCARD`
257
-
258
206
  await sock.sendMessage(jid, {
259
207
  contacts: {
260
- displayName: 'João Silva',
261
- contacts: [{ vcard }]
208
+ displayName: 'João',
209
+ contacts: [{
210
+ vcard: `BEGIN:VCARD\nVERSION:3.0\nFN:João Silva\nTEL:+5511999999999\nEND:VCARD`
211
+ }]
262
212
  }
263
213
  })
264
214
  ```
265
215
 
266
- ---
267
-
268
- ### Enquete (Poll)
269
-
270
- Cria uma enquete interativa no WhatsApp.
216
+ ### Localização
271
217
 
272
218
  ```js
273
219
  await sock.sendMessage(jid, {
274
- poll: {
275
- name: 'Qual sua linguagem favorita?',
276
- values: ['JavaScript', 'Python', 'TypeScript', 'Go'],
277
- selectableCount: 1 // Quantas opções o usuário pode escolher
220
+ location: {
221
+ degreesLatitude: -23.550520,
222
+ degreesLongitude: -46.633308,
223
+ name: 'São Paulo',
224
+ address: 'SP, Brasil'
278
225
  }
279
226
  })
280
227
  ```
281
228
 
282
229
  ---
283
230
 
284
- ### Reação
231
+ ## 3. Mensagens especiais
285
232
 
286
- Reage a uma mensagem com um emoji.
233
+ ### Reação
287
234
 
288
235
  ```js
289
236
  await sock.sendMessage(jid, {
290
- react: {
291
- text: '❤️', // Emoji da reação (string vazia para remover)
292
- key: mensagem.key // Key da mensagem que será reagida
293
- }
237
+ react: { text: '❤️', key: message.key }
238
+ // text: '' remove a reação
294
239
  })
295
240
  ```
296
241
 
297
- Para remover uma reação:
242
+ ### Deletar mensagem
243
+
298
244
  ```js
299
- await sock.sendMessage(jid, {
300
- react: { text: '', key: mensagem.key }
301
- })
245
+ await sock.sendMessage(jid, { delete: message.key })
302
246
  ```
303
247
 
304
- ---
305
-
306
- ### Menção
307
-
308
- Menciona um ou mais usuários no texto.
248
+ ### Editar mensagem
309
249
 
310
250
  ```js
311
251
  await sock.sendMessage(jid, {
312
- text: 'Oi @5511999999999, tudo bem?',
313
- mentions: ['5511999999999@s.whatsapp.net']
252
+ edit: message.key,
253
+ text: 'Texto editado'
314
254
  })
315
255
  ```
316
256
 
317
- ---
318
-
319
- ### Link com Preview
320
-
321
- Envia uma mensagem de texto — o preview do link é gerado automaticamente se `generateHighQualityLinkPreview: true` estiver ativado na config.
257
+ ### Fixar mensagem
322
258
 
323
259
  ```js
324
260
  await sock.sendMessage(jid, {
325
- text: 'Confira: https://github.com'
261
+ pin: {
262
+ type: 1, // 1 = fixar, 2 = desfixar
263
+ time: 86400, // duração em segundos
264
+ messageKey: message.key
265
+ }
326
266
  })
327
267
  ```
328
268
 
329
- ---
269
+ ### Encaminhar
330
270
 
331
- ### Resposta (Quoted)
271
+ ```js
272
+ const { generateForwardMessageContent, generateWAMessageFromContent } = require('@systemzero/baileys')
332
273
 
333
- Responde a uma mensagem específica.
274
+ const content = generateForwardMessageContent(message, false)
275
+ const msg = generateWAMessageFromContent(jid, content, { quoted: m })
276
+ await sock.relayMessage(jid, msg.message, { messageId: msg.key.id })
277
+ ```
278
+
279
+ ### View Once
334
280
 
335
281
  ```js
336
- // Dentro do handler de mensagens:
337
- sock.ev.on('messages.upsert', async ({ messages }) => {
338
- const msg = messages[0]
339
-
340
- await sock.sendMessage(msg.key.remoteJid, {
341
- text: 'Essa é minha resposta!'
342
- }, {
343
- quoted: msg // Passa a mensagem original para responder
344
- })
345
- })
346
- ```
282
+ await sock.sendMessage(jid, { image: buffer, viewOnce: true })
347
283
 
348
- ---
284
+ // V2
285
+ await sock.sendMessage(jid, { image: buffer, viewOnceV2: true })
349
286
 
350
- ### Mensagem Editada
287
+ // V2 Extension
288
+ await sock.sendMessage(jid, { image: buffer, viewOnceV2Extension: true })
289
+ ```
351
290
 
352
- Edita o conteúdo de uma mensagem já enviada.
291
+ ### Spoiler
353
292
 
354
293
  ```js
355
294
  await sock.sendMessage(jid, {
356
- text: 'Texto corrigido ✏️',
357
- edit: mensagemOriginal.key // Key da mensagem a ser editada
295
+ image: buffer,
296
+ caption: 'Spoiler!',
297
+ spoiler: true
358
298
  })
359
299
  ```
360
300
 
361
- ---
362
-
363
- ### Mensagem Deletada
364
-
365
- Deleta uma mensagem (para todos).
301
+ ### Status de grupo
366
302
 
367
303
  ```js
368
304
  await sock.sendMessage(jid, {
369
- delete: mensagem.key // Key da mensagem a deletar
305
+ image: buffer,
306
+ caption: 'Status do grupo',
307
+ groupStatus: true
370
308
  })
371
309
  ```
372
310
 
373
- ---
374
-
375
- ### Fixar Mensagem
376
-
377
- Fixa uma mensagem no chat ou grupo.
311
+ ### Mensagem efêmera
378
312
 
379
313
  ```js
380
314
  await sock.sendMessage(jid, {
381
- pin: mensagem.key, // Key da mensagem a fixar
382
- type: 1 // 1 = fixar, 2 = desfixar
315
+ image: buffer,
316
+ ephemeral: true
383
317
  })
384
318
  ```
385
319
 
386
- ---
387
-
388
- ### View Once
389
-
390
- Envia mídia que some após ser visualizada uma vez.
320
+ ### Lottie (sticker animado especial)
391
321
 
392
322
  ```js
393
323
  await sock.sendMessage(jid, {
394
- image: readFileSync('./foto_secreta.jpg'),
395
- viewOnce: true,
396
- caption: 'Esta foto vai sumir! 🔥'
324
+ sticker: buffer,
325
+ isLottie: true
397
326
  })
398
327
  ```
399
328
 
400
- ---
401
-
402
- ### Modo Efêmero (Desaparecimento)
403
-
404
- Ativa ou desativa mensagens temporárias em grupos.
329
+ ### Keep (salvar mensagem)
405
330
 
406
331
  ```js
407
- // Ativar (86400 = 24h, 604800 = 7 dias, 7776000 = 90 dias)
408
332
  await sock.sendMessage(jid, {
409
- disappearingMessagesInChat: 604800 // 7 dias em segundos
333
+ keep: message.key,
334
+ type: 1 // 1 = salvar, 2 = remover
410
335
  })
336
+ ```
337
+
338
+ ### Evento
411
339
 
412
- // Desativar
340
+ ```js
413
341
  await sock.sendMessage(jid, {
414
- disappearingMessagesInChat: false
342
+ event: {
343
+ isCanceled: false,
344
+ name: 'Reunião',
345
+ description: 'Alinhamento',
346
+ location: { name: 'Sala 3', address: 'Rua X, 100' },
347
+ startTime: Math.floor(Date.now() / 1000) + 3600,
348
+ endTime: Math.floor(Date.now() / 1000) + 7200,
349
+ }
415
350
  })
416
351
  ```
417
352
 
418
- ---
419
-
420
- ## 🎨 Mensagens Interativas (Botões)
421
-
422
- ### Botões Rápidos (Quick Reply)
423
-
424
- Envia botões de resposta rápida usando a sintaxe simplificada.
353
+ ### Enquete
425
354
 
426
355
  ```js
427
356
  await sock.sendMessage(jid, {
428
- text: 'Escolha uma opção:',
429
- footer: 'Sistema de Atendimento',
430
- buttons: [
431
- { buttonText: { displayText: '✅ Sim' }, buttonId: 'sim' },
432
- { buttonText: { displayText: '❌ Não' }, buttonId: 'nao' },
433
- { buttonText: { displayText: '❓ Talvez' }, buttonId: 'talvez' }
434
- ]
357
+ poll: {
358
+ name: 'Qual seu time?',
359
+ values: ['Flamengo', 'Corinthians', 'Palmeiras'],
360
+ selectableCount: 1 // 0 = múltipla escolha
361
+ }
435
362
  })
436
363
  ```
437
364
 
438
- ---
365
+ ### Invoice (nota fiscal)
439
366
 
440
- ### Lista
367
+ ```js
368
+ await sock.sendMessage(jid, {
369
+ image: buffer,
370
+ invoiceNote: 'Pagamento pedido #1234'
371
+ })
372
+ ```
441
373
 
442
- Envia uma lista interativa de opções (menu).
374
+ ### External Ad Reply
443
375
 
444
376
  ```js
445
377
  await sock.sendMessage(jid, {
446
- listMessage: {
447
- title: 'Menu Principal',
448
- text: 'Selecione uma opção abaixo:',
449
- footer: 'Powered by SystemZero',
450
- buttonText: 'Ver Opções',
451
- sections: [
452
- {
453
- title: 'Serviços',
454
- rows: [
455
- { title: 'Suporte', description: 'Falar com atendente', rowId: 'suporte' },
456
- { title: 'Financeiro', description: 'Ver cobranças', rowId: 'financeiro' }
457
- ]
458
- }
459
- ]
378
+ text: 'Confira!',
379
+ externalAdReply: {
380
+ title: 'System Zero',
381
+ body: 'Descrição do produto',
382
+ thumbnail: bufferImagem,
383
+ mediaType: 1,
384
+ sourceUrl: 'https://systemzone.store',
385
+ renderLargerThumbnail: true
460
386
  }
461
387
  })
462
388
  ```
463
389
 
464
- ---
465
-
466
- ### Botões Nativos (interactiveButtons)
467
-
468
- Botões nativos com suporte a imagem/vídeo no cabeçalho.
390
+ ### Mention All
469
391
 
470
392
  ```js
471
393
  await sock.sendMessage(jid, {
472
- interactiveButtons: [
473
- {
474
- name: 'quick_reply',
475
- buttonParamsJson: JSON.stringify({
476
- display_text: '📋 Ver Cardápio',
477
- id: 'cardapio'
478
- })
479
- },
480
- {
481
- name: 'cta_url',
482
- buttonParamsJson: JSON.stringify({
483
- display_text: '🌐 Acessar Site',
484
- url: 'https://meusite.com',
485
- merchant_url: 'https://meusite.com'
486
- })
487
- },
488
- {
489
- name: 'cta_call',
490
- buttonParamsJson: JSON.stringify({
491
- display_text: '📞 Ligar',
492
- phone_number: '+5511999999999'
493
- })
494
- }
495
- ],
496
- text: 'Olá! Como posso te ajudar?',
497
- footer: 'Atendimento 24h'
394
+ text: '👋 @all',
395
+ mentionAll: true
498
396
  })
499
397
  ```
500
398
 
501
- ---
502
-
503
- ### Pagamento Nativo
504
-
505
- Solicita um pagamento pelo WhatsApp Pay.
399
+ ### Convite de pagamento
506
400
 
507
401
  ```js
508
402
  await sock.sendMessage(jid, {
509
- interactiveButtons: [
510
- {
511
- name: 'review_and_pay',
512
- buttonParamsJson: JSON.stringify({
513
- currency: 'BRL',
514
- total_amount: { value: 5000, offset: 100 }, // R$ 50,00
515
- reference_id: 'PEDIDO-001',
516
- type: 'physical-goods',
517
- order: {
518
- status: 'pending',
519
- subtotal: { value: 5000, offset: 100 },
520
- order_type: 'ORDER',
521
- items: [{
522
- name: 'Produto X',
523
- amount: { value: 5000, offset: 100 },
524
- quantity: 1,
525
- sale_amount: { value: 5000, offset: 100 }
526
- }]
527
- }
528
- })
529
- }
530
- ],
531
- text: 'Seu pedido está pronto para pagamento!'
403
+ paymentInviteServiceType: 3
532
404
  })
533
405
  ```
534
406
 
535
- ---
536
-
537
- ### Produto
538
-
539
- Exibe um produto com imagem, preço e botões de ação.
407
+ ### Resultado de enquete (snapshot)
540
408
 
541
409
  ```js
542
410
  await sock.sendMessage(jid, {
543
- productMessage: {
544
- title: 'Tênis Nike Air Max',
545
- description: 'Conforto e estilo para o dia a dia.',
546
- thumbnail: { url: 'https://exemplo.com/tenis.jpg' },
547
- productId: 'PRODUTO-001',
548
- retailerId: 'LOJA-BR',
549
- priceAmount1000: 39900, // R$ 399,00
550
- currencyCode: 'BRL',
551
- url: 'https://minhaloja.com/produto',
552
- body: 'Aproveite a oferta!',
553
- footer: 'Frete grátis acima de R$ 200',
554
- buttons: [
555
- {
556
- name: 'quick_reply',
557
- buttonParamsJson: JSON.stringify({ display_text: '🛒 Comprar', id: 'comprar' })
558
- }
411
+ pollResult: {
412
+ name: 'Pergunta?',
413
+ pollType: 0, // 0 = poll, 1 = quiz
414
+ votes: [
415
+ { name: 'Opção A', voteCount: 12 },
416
+ { name: 'Opção B', voteCount: 7 },
559
417
  ]
560
418
  }
561
419
  })
@@ -563,530 +421,600 @@ await sock.sendMessage(jid, {
563
421
 
564
422
  ---
565
423
 
566
- ## 🤖 Funções Rich (Meta AI Style)
567
-
568
- Estas funções enviam mensagens no estilo do Meta AI com formatação especial.
424
+ ## 4. Botões e interativos
569
425
 
570
- ### Texto Rico
426
+ ### Estrutura base
571
427
 
572
428
  ```js
573
- await sock.sendRichText(jid, 'Esta é uma mensagem de texto rica! ✨')
429
+ const { generateWAMessageFromContent, proto } = require('@systemzero/baileys')
574
430
 
575
- // Com resposta (quoted)
576
- await sock.sendRichText(jid, 'Mensagem rica em resposta', mensagemOriginal)
577
- ```
578
-
579
- ---
580
-
581
- ### Código Rico
582
-
583
- Exibe um bloco de código com syntax highlighting.
431
+ const msg = generateWAMessageFromContent(jid, {
432
+ viewOnceMessage: {
433
+ message: {
434
+ interactiveMessage: proto.Message.InteractiveMessage.create({
435
+ header: { title: 'Título', hasMediaAttachment: false },
436
+ body: { text: 'Texto do corpo' },
437
+ footer: { text: 'Rodapé' },
438
+ nativeFlowMessage: {
439
+ buttons: [ /* tipos abaixo */ ]
440
+ }
441
+ })
442
+ }
443
+ }
444
+ }, { quoted: m })
584
445
 
585
- ```js
586
- await sock.sendRichCode(
587
- jid,
588
- 'Exemplo em JavaScript:', // Título (opcional)
589
- 'javascript', // Linguagem
590
- `function soma(a, b) {
591
- return a + b;
592
- }
593
- console.log(soma(2, 3));`
594
- )
446
+ await sock.relayMessage(jid, msg.message, { messageId: msg.key.id })
595
447
  ```
596
448
 
597
- ---
598
-
599
- ### Lista Rica
600
-
601
- Exibe uma lista de itens formatada.
449
+ ### Tipos de botão
602
450
 
603
451
  ```js
604
- await sock.sendRichList(
605
- jid,
606
- '📋 Lista de Tarefas:', // Título
607
- ['Estudar Node.js', 'Fazer deploy', 'Testar bot', 'Dormir']
608
- )
609
- ```
452
+ // Resposta rápida
453
+ { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: 'Confirmar', id: 'confirmar' }) }
610
454
 
611
- ---
455
+ // Link externo
456
+ { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: 'Abrir', url: 'https://systemzone.store' }) }
612
457
 
613
- ### Tabela Rica
458
+ // Copiar texto
459
+ { name: 'cta_copy', buttonParamsJson: JSON.stringify({ display_text: 'Copiar código', copy_code: 'PROMO2025' }) }
614
460
 
615
- Exibe uma tabela formatada (primeira linha é o cabeçalho).
461
+ // Ligar
462
+ { name: 'cta_call', buttonParamsJson: JSON.stringify({ display_text: 'Ligar', phone_number: '5511999999999' }) }
616
463
 
617
- ```js
618
- await sock.sendRichTable(
619
- jid,
620
- '📊 Relatório de Vendas', // Título
621
- [
622
- ['Produto', 'Qtd', 'Valor'], // Cabeçalho
623
- ['Camiseta', '10', 'R$ 300'],
624
- ['Calça', '5', 'R$ 500'],
625
- ['Tênis', '3', 'R$ 900']
626
- ],
627
- 'Total: R$ 1.700' // Rodapé (opcional)
628
- )
629
- ```
464
+ // Webview interno
465
+ { name: 'cta_webview', buttonParamsJson: JSON.stringify({ title: 'Painel', url: 'https://systemzone.store' }) }
630
466
 
631
- ---
467
+ // Lista dropdown com seções
468
+ {
469
+ name: 'single_select',
470
+ buttonParamsJson: JSON.stringify({
471
+ title: 'Escolher',
472
+ sections: [{
473
+ title: 'Categoria',
474
+ rows: [
475
+ { header: 'Op 1', title: 'Opção 1', description: 'Desc', id: 'op1' },
476
+ { header: 'Op 2', title: 'Opção 2', description: 'Desc', id: 'op2' },
477
+ ]
478
+ }]
479
+ })
480
+ }
481
+ ```
632
482
 
633
- ### Rich Completo
483
+ ### Header com imagem
634
484
 
635
- Combina texto, código, lista e tabela em uma única mensagem.
485
+ Upload da imagem antes de usar no header:
636
486
 
637
487
  ```js
638
- await sock.sendRichFull(jid, {
639
- title: '🚀 Relatório Completo',
640
- code: `const resultado = calcular()`,
641
- language: 'javascript',
642
- items: ['Item A', 'Item B', 'Item C'],
643
- table: [
644
- ['Campo', 'Valor'],
645
- ['Status', 'Ativo'],
646
- ['Versão', '1.0.3']
647
- ],
648
- footer: '© SystemZero Baileys'
488
+ const { generateWAMessage, generateMessageIDV2 } = require('@systemzero/baileys')
489
+
490
+ const uploaded = await generateWAMessage(jid, { image: buffer }, {
491
+ upload: sock.waUploadToServer,
492
+ userJid: sock.user.id,
493
+ messageId: generateMessageIDV2(sock.user.id),
649
494
  })
650
- ```
495
+ const img = uploaded.message?.imageMessage
651
496
 
652
- ---
497
+ // No header:
498
+ header: {
499
+ title: '',
500
+ hasMediaAttachment: true,
501
+ imageMessage: {
502
+ url: img.url,
503
+ mimetype: img.mimetype,
504
+ fileSha256: img.fileSha256,
505
+ fileLength: img.fileLength,
506
+ mediaKey: img.mediaKey,
507
+ fileEncSha256: img.fileEncSha256,
508
+ directPath: img.directPath,
509
+ mediaKeyTimestamp: img.mediaKeyTimestamp,
510
+ jpegThumbnail: img.jpegThumbnail,
511
+ }
512
+ }
513
+ ```
653
514
 
654
- ### Reels Ricos
515
+ ### Catálogo (product no header)
516
+
517
+ ```js
518
+ header: {
519
+ title: 'Produto',
520
+ hasMediaAttachment: true,
521
+ productMessage: proto.Message.ProductMessage.create({
522
+ product: proto.Message.ProductMessage.ProductSnapshot.create({
523
+ productImage: proto.Message.ImageMessage.create({ ...img }),
524
+ productId: 'ID-001',
525
+ title: 'Nome do Produto',
526
+ description: 'Descrição completa',
527
+ currencyCode: 'BRL',
528
+ priceAmount1000: 29990, // R$ 29,99
529
+ retailerId: 'minha-loja',
530
+ url: 'https://loja.com/produto',
531
+ productImageCount: 1,
532
+ }),
533
+ businessOwnerJid: sock.user.id
534
+ })
535
+ }
536
+ ```
655
537
 
656
- Envia uma mensagem no estilo de resultado de busca com reels/vídeos.
538
+ ### Carousel
657
539
 
658
540
  ```js
659
- await sock.sendRichReels(
660
- jid,
661
- 'Resultado da Busca', // Título
662
- 'Vídeos encontrados', // Header
663
- 'gatos fofinhos', // Query de busca
664
- [
541
+ await sock.sendMessage(jid, {
542
+ cards: [
543
+ {
544
+ image: buffer1,
545
+ caption: 'Texto do card 1',
546
+ title: 'Card 1',
547
+ nativeFlow: [
548
+ { text: 'Ver mais', id: 'card1' },
549
+ { text: 'Site', url: 'https://systemzone.store' }
550
+ ]
551
+ },
665
552
  {
666
- title: 'Gato dançando',
667
- url: 'https://video1.com',
668
- thumbnail: 'https://thumb1.com/img.jpg'
553
+ image: buffer2,
554
+ caption: 'Texto do card 2',
555
+ nativeFlow: [{ text: 'Clique', id: 'card2' }]
669
556
  }
670
- ]
671
- )
557
+ ],
558
+ footer: 'Rodapé'
559
+ })
672
560
  ```
673
561
 
674
- ---
675
-
676
- ### Perplexity IA
677
-
678
- Consulta a API Perplexity e envia a resposta no chat.
562
+ ### Template Buttons
679
563
 
680
564
  ```js
681
- await sock.sendPerplexity(
682
- jid,
683
- 'Qual a capital do Brasil?'
684
- )
685
-
686
- // Com opções (ex: responder a uma mensagem)
687
- await sock.sendPerplexity(
688
- jid,
689
- 'Explique inteligência artificial',
690
- { quoted: mensagemOriginal }
691
- )
565
+ await sock.sendMessage(jid, {
566
+ text: 'Escolha:',
567
+ templateButtons: [
568
+ { text: 'Resposta', id: 'res1' },
569
+ { text: 'Site', url: 'https://systemzone.store' },
570
+ { text: 'Ligar', call: '5511999999999' },
571
+ ]
572
+ })
692
573
  ```
693
574
 
694
- ---
695
-
696
- ## 📁 Tipos Especiais de Mensagem
697
-
698
- ### Álbum de Fotos/Vídeos
699
-
700
- Envia múltiplas fotos/vídeos como um álbum agrupado.
575
+ ### Sections (lista clássica)
701
576
 
702
577
  ```js
703
578
  await sock.sendMessage(jid, {
704
- albumMessage: [
705
- { image: { url: 'https://exemplo.com/foto1.jpg' }, caption: 'Foto 1' },
706
- { image: { url: 'https://exemplo.com/foto2.jpg' }, caption: 'Foto 2' },
707
- { video: { url: 'https://exemplo.com/clip.mp4' }, caption: 'Vídeo do evento' }
708
- ]
579
+ text: 'Selecione',
580
+ buttonText: 'Ver opções',
581
+ sections: [{
582
+ title: 'Categoria',
583
+ rows: [
584
+ { title: 'Item 1', description: 'Desc', id: 'item1' },
585
+ { title: 'Item 2', description: 'Desc', id: 'item2' },
586
+ ]
587
+ }]
709
588
  })
710
589
  ```
711
590
 
712
- ---
713
-
714
- ### Evento
715
-
716
- Cria um evento no grupo ou conversa.
591
+ ### Interactive como Template
717
592
 
718
593
  ```js
719
594
  await sock.sendMessage(jid, {
720
- eventMessage: {
721
- name: '🎉 Reunião de Equipe',
722
- description: 'Reunião semanal de alinhamento da equipe de desenvolvimento.',
723
- location: {
724
- degreesLatitude: -23.5505,
725
- degreesLongitude: -46.6333,
726
- name: 'Escritório Central, São Paulo'
727
- },
728
- joinLink: 'https://meet.google.com/abc-xyz',
729
- startTime: Date.now() + 86400000, // Amanhã
730
- endTime: Date.now() + 86400000 + 3600000, // +1 hora
731
- extraGuestsAllowed: true,
732
- isCanceled: false
733
- }
595
+ nativeFlow: [{ text: 'Clique', id: 'btn' }],
596
+ text: 'Mensagem',
597
+ interactiveAsTemplate: true
734
598
  })
735
599
  ```
736
600
 
737
- ---
738
-
739
- ### Resultado de Enquete
740
-
741
- Envia um snapshot de resultado de votação.
601
+ ### Botões com imagem no corpo (não no header)
742
602
 
743
603
  ```js
744
604
  await sock.sendMessage(jid, {
745
- pollResultMessage: {
746
- name: 'Qual sua linguagem favorita?',
747
- pollVotes: [
748
- { optionName: 'JavaScript', optionVoteCount: 42 },
749
- { optionName: 'Python', optionVoteCount: 35 },
750
- { optionName: 'TypeScript', optionVoteCount: 28 }
751
- ]
752
- }
605
+ image: buffer,
606
+ caption: 'Escolha:',
607
+ buttons: [
608
+ { text: 'Opção 1', id: 'op1' },
609
+ { text: 'Link', url: 'https://systemzone.store' },
610
+ ]
753
611
  })
754
612
  ```
755
613
 
756
- ---
757
-
758
- ### Story de Grupo
759
-
760
- Envia uma mensagem como story/status de grupo.
614
+ ### Áudio no rodapé de interativo
761
615
 
762
616
  ```js
763
617
  await sock.sendMessage(jid, {
764
- groupStatusMessage: {
765
- image: { url: 'https://exemplo.com/story.jpg' },
766
- caption: 'Nosso grupo é o melhor! 🔥'
767
- }
768
- })
769
-
770
- // Com vídeo
771
- await sock.sendMessage(jid, {
772
- groupStatusMessage: {
773
- video: { url: 'https://exemplo.com/story.mp4' },
774
- caption: 'Evento da semana'
775
- }
618
+ text: 'Ouça e escolha:',
619
+ nativeFlow: [{ text: 'Opção', id: 'op' }],
620
+ audioFooter: bufferAudio
776
621
  })
777
622
  ```
778
623
 
779
624
  ---
780
625
 
781
- ### Pagamento (requestPayment)
626
+ ## 5. Sticker Pack nativo
782
627
 
783
- Solicita um pagamento com nota ou sticker.
628
+ Envia um pack de figurinhas que aparece na aba de stickers do WhatsApp, igual a um pack real.
784
629
 
785
630
  ```js
786
631
  await sock.sendMessage(jid, {
787
- requestPaymentMessage: {
788
- amount: 15000, // R$ 150,00 (em centavos × 10)
789
- currency: 'BRL',
790
- from: '5511999999999@s.whatsapp.net',
791
- expiry: Math.floor(Date.now() / 1000) + 86400, // 24h
792
- note: 'Pagamento do serviço de bot 🤖'
793
- }
632
+ cover: { url: 'https://exemplo.com/capa.webp' },
633
+ stickers: [
634
+ { data: buffer1, emojis: ['😂'] },
635
+ { data: bufferAnimado, emojis: ['🔥', '💀'] },
636
+ { data: bufferPng, emojis: ['🐱'] }, // PNG converte automaticamente
637
+ ],
638
+ name: 'Nome do Pack',
639
+ publisher: 'Autor',
640
+ description: 'Descrição opcional'
794
641
  })
795
642
  ```
796
643
 
644
+ `cover` aceita `Buffer`, `{ url }` ou `{ stream }`. O mesmo vale para cada `sticker.data`.
645
+
646
+ Limites: máximo **60 figurinhas** por pack, cada uma com até **1MB**.
647
+
648
+ Requer `sharp` ou `@napi-rs/image` para conversão de PNG e geração de thumbnail. Sem eles, apenas WebP é aceito.
649
+
797
650
  ---
798
651
 
799
- ## 👥 Funções de Grupo
652
+ ## 6. Canais Newsletter
800
653
 
801
- ### Criar Grupo
654
+ ### Enviar texto
802
655
 
803
656
  ```js
804
- const grupo = await sock.groupCreate('Nome do Grupo', [
805
- '5511999999999@s.whatsapp.net',
806
- '5521888888888@s.whatsapp.net'
807
- ])
808
- console.log('Grupo criado:', grupo.id)
657
+ await sock.sendMessage('120363...@newsletter', { text: 'Novidade!' })
809
658
  ```
810
659
 
811
- ---
660
+ ### Enviar mídia
812
661
 
813
- ### Metadados do Grupo
662
+ `sendMessage` não passa pelo `encodeNewsletterMessage` corretamente para mídia. Use sempre `generateWAMessage` + `relayMessage`:
814
663
 
815
664
  ```js
816
- const info = await sock.groupMetadata('120363xxxxxxxx@g.us')
817
- console.log(info.subject) // Nome do grupo
818
- console.log(info.participants) // Lista de participantes
819
- console.log(info.desc) // Descrição
665
+ const { generateWAMessage, generateMessageIDV2 } = require('@systemzero/baileys')
666
+
667
+ const canalJid = '120363...@newsletter'
668
+
669
+ const fullMsg = await generateWAMessage(canalJid, {
670
+ image: buffer,
671
+ caption: 'Legenda'
672
+ }, {
673
+ upload: sock.waUploadToServer,
674
+ userJid: sock.user.id,
675
+ messageId: generateMessageIDV2(sock.user.id),
676
+ })
677
+
678
+ await sock.relayMessage(canalJid, fullMsg.message, {
679
+ messageId: fullMsg.key.id,
680
+ })
820
681
  ```
821
682
 
822
- ---
683
+ Funciona para `image`, `video`, `audio`, `sticker`, `document`.
823
684
 
824
- ### Adicionar / Remover / Promover / Rebaixar Participantes
685
+ ### Gerenciar canais
825
686
 
826
687
  ```js
827
- // Adicionar
828
- await sock.groupParticipantsUpdate(jid, ['5511999999999@s.whatsapp.net'], 'add')
688
+ // Criar
689
+ const canal = await sock.newsletterCreate('Nome do Canal', 'Descrição')
690
+
691
+ // Seguir / deixar
692
+ await sock.newsletterFollow(jid)
693
+ await sock.newsletterUnfollow(jid)
829
694
 
830
- // Remover
831
- await sock.groupParticipantsUpdate(jid, ['5511999999999@s.whatsapp.net'], 'remove')
695
+ // Silenciar
696
+ await sock.newsletterMute(jid)
697
+ await sock.newsletterUnmute(jid)
832
698
 
833
- // Tornar admin
834
- await sock.groupParticipantsUpdate(jid, ['5511999999999@s.whatsapp.net'], 'promote')
699
+ // Metadata
700
+ const meta = await sock.newsletterMetadata('jid', jid)
701
+ const meta = await sock.newsletterMetadata('invite', 'CODIGO')
835
702
 
836
- // Remover admin
837
- await sock.groupParticipantsUpdate(jid, ['5511999999999@s.whatsapp.net'], 'demote')
703
+ // Atualizar
704
+ await sock.newsletterUpdateName(jid, 'Novo Nome')
705
+ await sock.newsletterUpdateDescription(jid, 'Nova descrição')
706
+ await sock.newsletterUpdatePicture(jid, buffer)
707
+ await sock.newsletterRemovePicture(jid)
708
+
709
+ // Reagir a mensagem
710
+ await sock.newsletterReactMessage(jid, serverId, '❤️')
711
+
712
+ // Listar mensagens
713
+ const msgs = await sock.newsletterFetchMessages(jid, 30, 0, 0)
714
+
715
+ // Admin
716
+ const count = await sock.newsletterAdminCount(jid)
717
+ await sock.newsletterChangeOwner(jid, novoDonoJid)
718
+ await sock.newsletterDemote(jid, usuarioJid)
719
+ await sock.newsletterDelete(jid)
720
+
721
+ // Seguidores
722
+ const { subscribers } = await sock.newsletterSubscribers(jid)
838
723
  ```
839
724
 
840
725
  ---
841
726
 
842
- ### Atualizar Nome e Descrição
727
+ ## 7. Enquetes com decrypt
728
+
729
+ ### Criar enquete
843
730
 
844
731
  ```js
845
- await sock.groupUpdateSubject(jid, 'Novo Nome do Grupo ✨')
846
- await sock.groupUpdateDescription(jid, 'Nova descrição incrível do grupo!')
732
+ await sock.sendMessage(jid, {
733
+ poll: {
734
+ name: 'Pergunta?',
735
+ values: ['A', 'B', 'C'],
736
+ selectableCount: 1 // 0 = múltipla escolha
737
+ }
738
+ })
847
739
  ```
848
740
 
849
- ---
741
+ ### Receber e descriptografar votos
850
742
 
851
- ### Link de Convite
743
+ No `connect.js`, após `saveCreds`:
852
744
 
853
745
  ```js
854
- // Obter link
855
- const code = await sock.groupInviteCode(jid)
856
- console.log(`https://chat.whatsapp.com/${code}`)
746
+ const { getAggregateVotesInPollMessage } = require('@systemzero/baileys/lib/Utils/messages.js')
857
747
 
858
- // Revogar e gerar novo link
859
- await sock.groupRevokeInvite(jid)
748
+ sock.ev.on('messages.update', async (updates) => {
749
+ for (const { key, update } of updates) {
750
+ if (!update.pollUpdates) continue
751
+
752
+ const pollMsg = await store.loadMessage(key.remoteJid, key.id)
753
+ if (!pollMsg?.message) continue
860
754
 
861
- // Entrar por código
862
- await sock.groupAcceptInvite('CodigoAqui')
755
+ const result = getAggregateVotesInPollMessage({
756
+ message: pollMsg.message,
757
+ pollUpdates: update.pollUpdates,
758
+ })
863
759
 
864
- // Info do grupo pelo link
865
- const info = await sock.groupGetInviteInfo('CodigoAqui')
760
+ // [{ name: 'Opção A', voters: ['5511...@s.whatsapp.net'] }]
761
+ console.log(result)
762
+
763
+ if (!global.pollResults) global.pollResults = {}
764
+ global.pollResults[key.id] = { options: result, jid: key.remoteJid }
765
+ }
766
+ })
866
767
  ```
867
768
 
769
+ O `getMessage` precisa estar configurado no `makeWASocket` (veja seção 1).
770
+
868
771
  ---
869
772
 
870
- ### Configurações do Grupo
773
+ ## 8. AI Rich
871
774
 
872
- ```js
873
- // Apenas admins enviam mensagens
874
- await sock.groupSettingUpdate(jid, 'announcement')
775
+ Mensagens com formatação avançada: markdown, código, tabelas, hyperlinks clicáveis no texto.
875
776
 
876
- // Todos podem enviar
877
- await sock.groupSettingUpdate(jid, 'not_announcement')
777
+ ### Direto pelo socket
878
778
 
879
- // Apenas admins editam info
880
- await sock.groupSettingUpdate(jid, 'locked')
779
+ ```js
780
+ // Texto com hyperlink
781
+ await sock.sendRich(jid, [
782
+ sock.makeText('Acesse [nosso site](https://systemzone.store).')
783
+ ], quotedMsg)
881
784
 
882
- // Todos editam info
883
- await sock.groupSettingUpdate(jid, 'unlocked')
785
+ // Código
786
+ await sock.sendRich(jid, [
787
+ sock.makeCode('bash', 'npm i @systemzero/baileys')
788
+ ], null, ['RICH_RESPONSE_CODE'])
884
789
 
885
- // Modo de adição de membros
886
- await sock.groupMemberAddMode(jid, 'all_member_add') // Todos podem adicionar
887
- await sock.groupMemberAddMode(jid, 'admin_add') // Só admins
790
+ // Tabela
791
+ await sock.sendRich(jid, [
792
+ sock.makeTable([
793
+ ['Nome', 'Status'],
794
+ ['Botões', '✅'],
795
+ ['Canais', '✅'],
796
+ ])
797
+ ], null, ['RICH_RESPONSE_TABLE'])
888
798
 
889
- // Aprovação para entrar
890
- await sock.groupJoinApprovalMode(jid, 'on') // Ativar aprovação
891
- await sock.groupJoinApprovalMode(jid, 'off') // Desativar
892
- ```
799
+ // Lista
800
+ await sock.sendRich(jid, [
801
+ sock.makeList(['Item 1', 'Item 2', 'Item 3'])
802
+ ])
893
803
 
894
- ---
804
+ // Tudo junto
805
+ await sock.sendRich(jid, [
806
+ sock.makeText('# Título\nConteúdo com [link](https://systemzone.store)'),
807
+ sock.makeCode('javascript', 'const x = require("@systemzero/baileys")'),
808
+ sock.makeTable([['Col A', 'Col B'], ['val1', 'val2']]),
809
+ ], quotedMsg, ['RICH_RESPONSE_CODE', 'RICH_RESPONSE_TABLE'])
810
+ ```
895
811
 
896
- ### Sair do Grupo
812
+ ### Atalhos
897
813
 
898
814
  ```js
899
- await sock.groupLeave(jid)
815
+ await sock.sendRichText(jid, 'Texto com [link](https://systemzone.store)', quotedMsg)
816
+ await sock.sendRichCode(jid, 'Título', 'javascript', 'console.log("hi")', quotedMsg)
817
+ await sock.sendRichList(jid, 'Lista', ['A', 'B', 'C'], quotedMsg)
900
818
  ```
901
819
 
902
- ---
903
-
904
- ### Solicitações de Participação
820
+ ### Usando a classe AIRich
905
821
 
906
822
  ```js
907
- // Listar solicitações pendentes
908
- const solicitacoes = await sock.groupRequestParticipantsList(jid)
823
+ const { AIRich } = require('@systemzero/baileys/lib/MB.cjs')
909
824
 
910
- // Aprovar ou rejeitar
911
- await sock.groupRequestParticipantsUpdate(jid, ['5511999999999@s.whatsapp.net'], 'approve')
912
- await sock.groupRequestParticipantsUpdate(jid, ['5511999999999@s.whatsapp.net'], 'reject')
825
+ const msg = new AIRich(sock)
826
+ msg.addText('Texto com [link](https://systemzone.store)')
827
+ msg.addCode('javascript', 'const x = 1')
828
+ msg.addTable([['Col', 'Valor'], ['linha', 'dado']])
829
+ await msg.send(jid, { quoted: m })
913
830
  ```
914
831
 
915
832
  ---
916
833
 
917
- ## 💬 Funções de Chat
918
-
919
- ### Modificar Chat
834
+ ## 9. Grupos
920
835
 
921
836
  ```js
922
- // Arquivar conversa
923
- await sock.chatModify({ archive: true, lastMessages: [mensagem] }, jid)
837
+ // Criar
838
+ const grupo = await sock.groupCreate('Nome', ['5511...@s.whatsapp.net'])
924
839
 
925
- // Marcar como não lida
926
- await sock.chatModify({ markRead: false, lastMessages: [mensagem] }, jid)
840
+ // Participantes
841
+ await sock.groupParticipantsUpdate(jid, ['5511...@s.whatsapp.net'], 'add')
842
+ await sock.groupParticipantsUpdate(jid, ['5511...@s.whatsapp.net'], 'remove')
843
+ await sock.groupParticipantsUpdate(jid, ['5511...@s.whatsapp.net'], 'promote')
844
+ await sock.groupParticipantsUpdate(jid, ['5511...@s.whatsapp.net'], 'demote')
927
845
 
928
- // Mutar por 8 horas
929
- await sock.chatModify({ mute: 8 * 60 * 60 * 1000 }, jid)
846
+ // Sair
847
+ await sock.groupLeave(jid)
930
848
 
931
- // Desmutar
932
- await sock.chatModify({ mute: null }, jid)
849
+ // Nome e descrição
850
+ await sock.groupUpdateSubject(jid, 'Novo Nome')
851
+ await sock.groupUpdateDescription(jid, 'Nova descrição')
933
852
 
934
- // Fixar conversa
935
- await sock.chatModify({ pin: true }, jid)
853
+ // Convite
854
+ const code = await sock.groupInviteCode(jid)
855
+ await sock.groupRevokeInvite(jid)
856
+ await sock.groupAcceptInvite('CODIGO')
936
857
 
937
- // Limpar mensagens
938
- await sock.chatModify({ clear: { messages: [{ id: 'ID_MSG', fromMe: true }] } }, jid)
858
+ // Mensagens efêmeras (0 = desativar)
859
+ await sock.groupToggleEphemeral(jid, 86400)
939
860
 
940
- // Deletar conversa
941
- await sock.chatModify({ delete: true, lastMessages: [mensagem] }, jid)
861
+ // Metadata
862
+ const meta = await sock.groupMetadata(jid)
863
+ const grupos = await sock.groupFetchAllParticipating()
942
864
  ```
943
865
 
944
866
  ---
945
867
 
946
- ### Marcar como Lida
868
+ ## 10. Perfil e privacidade
947
869
 
948
870
  ```js
949
- const key = { remoteJid: jid, id: mensagem.key.id, participant: mensagem.key.participant }
950
- await sock.readMessages([key])
951
- ```
871
+ // Foto de perfil
872
+ const url = await sock.profilePictureUrl(jid, 'image')
873
+ await sock.updateProfilePicture(jid, buffer)
952
874
 
953
- ---
875
+ // Bio
876
+ await sock.updateProfileStatus('🤖 Bot ativo')
954
877
 
955
- ### Status e Perfil
878
+ // Verificar número
879
+ const [result] = await sock.onWhatsApp('5511999999999')
880
+ // { exists: true, jid: '5511...@s.whatsapp.net' }
956
881
 
957
- ```js
958
- // Ver foto de perfil
959
- const url = await sock.profilePictureUrl('5511999999999@s.whatsapp.net', 'image')
882
+ // Bloquear / desbloquear
883
+ await sock.updateBlockStatus(jid, 'block')
884
+ await sock.updateBlockStatus(jid, 'unblock')
960
885
 
961
- // Atualizar foto de perfil
962
- await sock.updateProfilePicture(jid, readFileSync('./nova_foto.jpg'))
886
+ // Presence
887
+ await sock.sendPresenceUpdate('composing', jid) // digitando
888
+ await sock.sendPresenceUpdate('recording', jid) // gravando
889
+ await sock.sendPresenceUpdate('available', jid) // online
890
+ await sock.sendPresenceUpdate('unavailable') // offline
891
+ await sock.presenceSubscribe(jid) // receber presence de contato
963
892
 
964
- // Remover foto de perfil
965
- await sock.removeProfilePicture(jid)
893
+ // Marcar como lido
894
+ await sock.readMessages([message.key])
966
895
 
967
- // Atualizar status (bio)
968
- await sock.updateProfileStatus('Desenvolvendo bots 🤖')
896
+ // Privacidade da foto
897
+ await sock.updateProfilePicturePrivacy('all') // 'all' | 'contacts' | 'none'
969
898
 
970
- // Atualizar nome
971
- await sock.updateProfileName('Meu Bot')
899
+ // Modificar chat
900
+ await sock.chatModify({ archive: true }, jid)
901
+ await sock.chatModify({ pin: true }, jid)
902
+ await sock.chatModify({ mute: 8 * 60 * 60 * 1000 }, jid)
903
+ await sock.chatModify({ star: { messages: [{ id, fromMe }], star: true } }, jid)
904
+ await sock.chatModify({ clear: { messages: [{ id, fromMe, timestamp }] } }, jid)
972
905
 
973
- // Ver status de outro usuário
974
- const status = await sock.fetchStatus('5511999999999@s.whatsapp.net')
906
+ // Desconectar
907
+ await sock.logout()
975
908
  ```
976
909
 
977
910
  ---
978
911
 
979
- ### Bloquear / Desbloquear
912
+ ## 11. Eventos do socket
980
913
 
981
914
  ```js
982
- await sock.updateBlockStatus('5511999999999@s.whatsapp.net', 'block')
983
- await sock.updateBlockStatus('5511999999999@s.whatsapp.net', 'unblock')
915
+ sock.ev.on('messages.upsert', ({ messages, type }) => {})
916
+ sock.ev.on('messages.update', (updates) => {})
917
+ sock.ev.on('messages.delete', (item) => {})
918
+ sock.ev.on('messages.reaction', (reactions) => {})
919
+ sock.ev.on('presence.update', ({ id, presences }) => {})
920
+ sock.ev.on('groups.update', (updates) => {})
921
+ sock.ev.on('group-participants.update', ({ id, participants, action }) => {})
922
+ sock.ev.on('contacts.update', (contacts) => {})
923
+ sock.ev.on('chats.update', (chats) => {})
924
+ sock.ev.on('connection.update', ({ connection, lastDisconnect, qr }) => {})
925
+ sock.ev.on('creds.update', saveCreds)
984
926
 
985
- // Ver lista de bloqueados
986
- const bloqueados = await sock.fetchBlocklist()
927
+ // Chamadas
928
+ sock.ev.on('call', (calls) => {
929
+ for (const call of calls) {
930
+ if (call.status === 'offer') {
931
+ sock.rejectCall(call.id, call.from)
932
+ }
933
+ }
934
+ })
987
935
  ```
988
936
 
989
937
  ---
990
938
 
991
- ### Contatos
939
+ ## 12. Utilitários
940
+
941
+ ### Download de mídia
992
942
 
993
943
  ```js
994
- // Adicionar ou editar contato
995
- await sock.addOrEditContact({
996
- jid: '5511999999999@s.whatsapp.net',
997
- notify: 'João Silva'
998
- })
944
+ const { downloadMediaMessage } = require('@systemzero/baileys')
999
945
 
1000
- // Remover contato
1001
- await sock.removeContact('5511999999999@s.whatsapp.net')
946
+ const buffer = await downloadMediaMessage(message, 'buffer', {})
947
+ const stream = await downloadMediaMessage(message, 'stream', {})
1002
948
  ```
1003
949
 
1004
- ---
1005
-
1006
- ## 🔒 Privacidade
950
+ ### Download manual por stream
1007
951
 
1008
952
  ```js
1009
- // Último visto: 'all' | 'contacts' | 'contact_blacklist' | 'none'
1010
- await sock.updateLastSeenPrivacy('contacts')
1011
-
1012
- // Online: 'all' | 'match_last_seen'
1013
- await sock.updateOnlinePrivacy('all')
1014
-
1015
- // Foto de perfil: 'all' | 'contacts' | 'contact_blacklist' | 'none'
1016
- await sock.updateProfilePicturePrivacy('contacts')
1017
-
1018
- // Status: 'all' | 'contacts' | 'contact_blacklist' | 'none'
1019
- await sock.updateStatusPrivacy('contacts')
1020
-
1021
- // Confirmação de leitura: 'all' | 'none'
1022
- await sock.updateReadReceiptsPrivacy('all')
953
+ const { downloadContentFromMessage } = require('@systemzero/baileys')
1023
954
 
1024
- // Adição em grupos: 'all' | 'contacts' | 'contact_blacklist' | 'none'
1025
- await sock.updateGroupsAddPrivacy('contacts')
1026
-
1027
- // Chamadas: 'all' | 'contacts' | 'contact_blacklist' | 'none'
1028
- await sock.updateCallPrivacy('contacts')
1029
-
1030
- // Preview de links: 'all' | 'none'
1031
- await sock.updateDisableLinkPreviewsPrivacy('none')
1032
-
1033
- // Modo de desaparecimento padrão
1034
- await sock.updateDefaultDisappearingMode(604800) // 7 dias
955
+ const stream = await downloadContentFromMessage(
956
+ { mediaKey, directPath, url },
957
+ 'image' // 'image' | 'video' | 'audio' | 'sticker' | 'document'
958
+ )
959
+ const chunks = []
960
+ for await (const chunk of stream) chunks.push(chunk)
961
+ const buffer = Buffer.concat(chunks)
1035
962
  ```
1036
963
 
1037
- ---
1038
-
1039
- ## 🏷️ Labels
964
+ ### Geração de mensagem manual
1040
965
 
1041
966
  ```js
1042
- // Criar/editar label
1043
- await sock.addLabel({ id: '1', name: 'Cliente VIP', color: 1 })
967
+ const {
968
+ generateWAMessage,
969
+ generateWAMessageFromContent,
970
+ generateMessageIDV2,
971
+ generateForwardMessageContent
972
+ } = require('@systemzero/baileys')
1044
973
 
1045
- // Label em chat
1046
- await sock.addChatLabel(jid, '1')
1047
- await sock.removeChatLabel(jid, '1')
974
+ // Com upload automático de mídia
975
+ const msg = await generateWAMessage(jid, { image: buffer }, {
976
+ upload: sock.waUploadToServer,
977
+ userJid: sock.user.id,
978
+ messageId: generateMessageIDV2(sock.user.id),
979
+ })
1048
980
 
1049
- // Label em mensagem
1050
- await sock.addMessageLabel(jid, msgId, '1')
1051
- await sock.removeMessageLabel(jid, msgId, '1')
981
+ // Sem upload (proto manual)
982
+ const msg = generateWAMessageFromContent(jid, { ... }, { quoted: m })
1052
983
 
1053
- // Favoritar mensagem
1054
- await sock.star(jid, [{ id: msgId, fromMe: true }], true)
984
+ // Enviar o proto
985
+ await sock.relayMessage(jid, msg.message, { messageId: msg.key.id })
1055
986
  ```
1056
987
 
1057
- ---
1058
-
1059
- ## 📡 Presença
988
+ ### Detectar dispositivo
1060
989
 
1061
990
  ```js
1062
- // Tipos: 'available' | 'unavailable' | 'composing' | 'recording' | 'paused'
1063
- await sock.sendPresenceUpdate('composing', jid) // "digitando..."
1064
- await sock.sendPresenceUpdate('recording', jid) // "gravando áudio..."
1065
- await sock.sendPresenceUpdate('available', jid) // Online
1066
- await sock.sendPresenceUpdate('unavailable', jid) // Offline
1067
-
1068
- // Inscrever-se na presença de alguém
1069
- await sock.presenceSubscribe(jid)
1070
-
1071
- // Ouvir updates de presença
1072
- sock.ev.on('presence.update', ({ id, presences }) => {
1073
- console.log(presences)
1074
- })
991
+ const { getDevice } = require('@systemzero/baileys')
992
+ const device = getDevice(message.key.id)
993
+ // 'android' | 'ios' | 'web' | 'unknown'
1075
994
  ```
1076
995
 
1077
- ---
996
+ ### JID utils
1078
997
 
1079
- ## 📌 Notas
998
+ ```js
999
+ const {
1000
+ jidNormalizedUser,
1001
+ isJidGroup,
1002
+ isJidNewsletter,
1003
+ jidEncode,
1004
+ jidDecode
1005
+ } = require('@systemzero/baileys')
1080
1006
 
1081
- - Todas as funções que enviam mensagens retornam o objeto `WAMessage` com a `key` da mensagem.
1082
- - O campo `key.id` pode ser usado para referenciar a mensagem em edições, deleções e fixações.
1083
- - Ao enviar mídia para grupos, certifique-se que o bot está participante do grupo.
1084
- - Funções Rich (`sendRich*`) requerem que o WhatsApp do destinatário seja uma versão recente.
1007
+ jidNormalizedUser('5511999999999@s.whatsapp.net')
1008
+ isJidGroup('120363...@g.us') // true
1009
+ isJidNewsletter('120363...@newsletter') // true
1010
+ ```
1085
1011
 
1086
1012
  ---
1087
1013
 
1088
1014
  <div align="center">
1089
1015
 
1090
- **@systemzero/baileys v1.0.3** · Feito com ❤️ por [blackhzx](https://t.me/blackhzx)
1016
+ **@systemzero/baileys v1.0.5**
1017
+
1018
+ Desenvolvido por [Josué </>](https://t.me/blackhzx) · [Canal WhatsApp](https://whatsapp.com/channel/0029VaqUb9aGk1FxqeKKOd2i) · [systemzone.store](https://systemzone.store)
1091
1019
 
1092
- </div>
1020
+ </div>