@areumtecnologia/baileys 1.0.0

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.
@@ -0,0 +1,8 @@
1
+ {
2
+ "folders": [
3
+ {
4
+ "path": "."
5
+ }
6
+ ],
7
+ "settings": {}
8
+ }
package/desktop.ini ADDED
Binary file
Binary file
@@ -0,0 +1,94 @@
1
+
2
+ /**
3
+ * Manipula operações relacionadas a grupos.
4
+ *
5
+ * @copyright Áreum Tecnologia
6
+ * @author Áreum Tecnologia
7
+ * @class GroupHandler
8
+ * @param {import('../client').default} client - A instância principal do cliente.
9
+ *
10
+ * @method getMetadata Obtém os metadados de um grupo.
11
+ * @param {string} groupId - O ID do grupo.
12
+ * @returns {Promise<Object>} Metadados do grupo.
13
+ *
14
+ * @method create Cria um novo grupo.
15
+ * @param {string} subject - Nome do grupo.
16
+ * @param {string[]} participantsJids - Lista de JIDs dos participantes.
17
+ * @returns {Promise<Object>} Dados do grupo criado.
18
+ *
19
+ * @method leave Deixa um grupo.
20
+ * @param {string} groupId - O ID do grupo.
21
+ * @returns {Promise<Object>} Resultado da operação.
22
+ *
23
+ * @method updateName Atualiza o nome de um grupo.
24
+ * @param {string} groupId - O ID do grupo.
25
+ * @param {string} newName - Novo nome do grupo.
26
+ * @returns {Promise<Object>} Resultado da operação.
27
+ *
28
+ * @method updateDescription Atualiza a descrição de um grupo.
29
+ * @param {string} groupId - O ID do grupo.
30
+ * @param {string} newDescription - Nova descrição do grupo.
31
+ * @returns {Promise<Object>} Resultado da operação.
32
+ *
33
+ * @method updateParticipants Modifica a lista de participantes de um grupo.
34
+ * @param {string} groupId - O ID do grupo.
35
+ * @param {string[]} participantsJids - Lista de JIDs dos participantes.
36
+ * @param {'add'|'remove'} action - Ação a ser realizada.
37
+ * @returns {Promise<Object>} Resultado da operação.
38
+ *
39
+ * @method getInviteCode Obtém o código de convite de um grupo.
40
+ * @param {string} groupId - O ID do grupo.
41
+ * @returns {Promise<string>} Código de convite do grupo.
42
+ */
43
+ class GroupHandler {
44
+ /**
45
+ * @param {import('../client').default} client - A instância principal do cliente.
46
+ */
47
+ constructor(client) {
48
+ this.client = client;
49
+ }
50
+
51
+ /** Obtém os metadados de um grupo. */
52
+ async getMetadata(groupId) {
53
+ this.client._validateConnection();
54
+ return this.client.sock.groupMetadata(groupId);
55
+ }
56
+
57
+ /** Cria um novo grupo. */
58
+ async create(subject, participantsJids) {
59
+ this.client._validateConnection();
60
+ return this.client.sock.groupCreate(subject, participantsJids);
61
+ }
62
+
63
+ /** Deixa um grupo. */
64
+ async leave(groupId) {
65
+ this.client._validateConnection();
66
+ return this.client.sock.groupLeave(groupId);
67
+ }
68
+
69
+ /** Atualiza o nome de um grupo. */
70
+ async updateName(groupId, newName) {
71
+ this.client._validateConnection();
72
+ return this.client.sock.groupUpdateSubject(groupId, newName);
73
+ }
74
+
75
+ /** Atualiza a descrição de um grupo. */
76
+ async updateDescription(groupId, newDescription) {
77
+ this.client._validateConnection();
78
+ return this.client.sock.groupUpdateDescription(groupId, newDescription);
79
+ }
80
+
81
+ /** Modifica a lista de participantes de um grupo. */
82
+ async updateParticipants(groupId, participantsJids, action) {
83
+ this.client._validateConnection();
84
+ return this.client.sock.groupParticipantsUpdate(groupId, participantsJids, action);
85
+ }
86
+
87
+ /** Obtém o código de convite de um grupo. */
88
+ async getInviteCode(groupId) {
89
+ this.client._validateConnection();
90
+ return this.client.sock.groupInviteCode(groupId);
91
+ }
92
+ }
93
+
94
+ module.exports = GroupHandler;
@@ -0,0 +1,285 @@
1
+
2
+ /**
3
+ * @copyright Áreum Tecnologia
4
+ * @author Áreum Tecnologia
5
+ * @license Proprietary
6
+ *
7
+ * Manipula o envio e recebimento de mensagens via WhatsApp utilizando Baileys.
8
+ * Fornece métodos para envio de texto, mídia, localização, contatos, enquetes, ações de mensagem e interatividade.
9
+ *
10
+ * @class MessageHandler
11
+ * @classdesc Classe central para manipulação de mensagens no WhatsApp.
12
+ *
13
+ * @property {import('../client').default} client - Instância principal do cliente Baileys.
14
+ *
15
+ * @example
16
+ * const MessageHandler = require('./handlers/messages');
17
+ * const handler = new MessageHandler(client);
18
+ * await handler.sendTextMessage('5511999999999@s.whatsapp.net', 'Olá!');
19
+ */
20
+ // const { sendButtons, sendInteractiveMessage } = require('baileys_helper');
21
+ const { Utils, MessageNormalizer } = require('../utils');
22
+
23
+ class MessageHandler {
24
+ /**
25
+ * @param {import('../../../client').default} client - A instância principal do cliente.
26
+ */
27
+ constructor(client) {
28
+ this.client = client;
29
+ }
30
+
31
+ /**
32
+ * Método central de envio de mensagens. Realiza a normalização do JID antes do envio.
33
+ * @private
34
+ */
35
+ async sendMessage(jid, content, options = {}) {
36
+ this.client._validateConnection();
37
+ const verifiedJid = await this.client.users.isOnWhatsApp(jid);
38
+ if (verifiedJid && verifiedJid.exists) {
39
+ const msg = await this.client.sock.sendMessage(verifiedJid.jid, content, options);
40
+ const nmsg = await MessageNormalizer.normalize(msg, this.client);
41
+ return nmsg;
42
+ }
43
+ else {
44
+ if (verifiedJid) {
45
+ return verifiedJid;
46
+ }
47
+ // Se verifiedJid e undefined ou null cria objeto padrao
48
+ return { error: { exists: false, message: "WA_NUMBER_NOT_FOUNDED" } };
49
+ }
50
+ }
51
+
52
+ // =================================================================================================
53
+ // MÉTODOS DE ENVIO BÁSICOS
54
+ // =================================================================================================
55
+
56
+ /** Envia uma mensagem de texto. */
57
+ async sendTextMessage(jid, text, options = {}) {
58
+ return this.sendMessage(jid, { text }, options);
59
+ }
60
+
61
+ /** Responde a uma mensagem específica. */
62
+ async reply(originalMessage, content) {
63
+ const jid = originalMessage.key.remoteJid;
64
+ // Não é necessário normalizar o JID aqui, pois ele vem de uma mensagem existente.
65
+ return this.client.sock.sendMessage(jid, content, { quoted: originalMessage });
66
+ }
67
+
68
+ // =================================================================================================
69
+ // MÉTODOS DE ENVIO DE MÍDIA
70
+ // =================================================================================================
71
+
72
+ /** Envia uma imagem. */
73
+ async sendImage(jid, media, caption = '', options = {}) {
74
+ const content = {
75
+ image: typeof media === 'string' ? { url: media } : media,
76
+ caption,
77
+ viewOnce: !!options.viewOnce // Adiciona o modificador de visualização única
78
+ };
79
+ return this.sendMessage(jid, content, options);
80
+ }
81
+
82
+ /** Envia um vídeo. */
83
+ async sendVideo(jid, media, caption = '', options = {}) {
84
+ const content = {
85
+ video: typeof media === 'string' ? { url: media } : media,
86
+ caption,
87
+ viewOnce: !!options.viewOnce // Adiciona o modificador de visualização única
88
+ };
89
+ return this.sendMessage(jid, content, options);
90
+ }
91
+
92
+ /** Envia um áudio (como mensagem de voz). */
93
+ async sendAudio(jid, media, ptt = true, options = {}) {
94
+ const content = {
95
+ audio: typeof media === 'string' ? { url: media } : media,
96
+ ptt
97
+ };
98
+ return this.sendMessage(jid, content, options);
99
+ }
100
+
101
+ /** Envia um documento. */
102
+ async sendDocument(jid, media, mimetype, fileName = 'file', options = {}) {
103
+ const content = {
104
+ document: typeof media === 'string' ? { url: media } : media,
105
+ mimetype,
106
+ fileName
107
+ };
108
+ return this.sendMessage(jid, content, options);
109
+ }
110
+
111
+ // =================================================================================================
112
+ // NOVOS MÉTODOS DE MENSAGENS ESTRUTURADAS
113
+ // =================================================================================================
114
+
115
+ /** Envia uma localização. */
116
+ async sendLocation(jid, latitude, longitude, name = '', address = '') {
117
+ const content = {
118
+ location: {
119
+ degreesLatitude: latitude,
120
+ degreesLongitude: longitude,
121
+ name: name,
122
+ address: address
123
+ }
124
+ };
125
+ return this.sendMessage(jid, content);
126
+ }
127
+
128
+ /**
129
+ * Envia um ou mais contatos.
130
+ * @param {string} jid - O JID do destinatário.
131
+ * @param {Array<object>} contacts - Um array de contatos.
132
+ * @param {string} contacts[].fullName - O nome completo do contato.
133
+ * @param {string} contacts[].waid - O número de telefone no formato internacional (ex: 5511999999999).
134
+ * @param {string} [contacts[].organization] - A organização do contato (opcional).
135
+ */
136
+ async sendContacts(jid, contacts) {
137
+ const vcards = contacts.map(c => ({
138
+ displayName: c.fullName,
139
+ vcard: `BEGIN:VCARD\nVERSION:3.0\nFN:${c.fullName}\n${c.organization ? `ORG:${c.organization};\n` : ''}TEL;type=CELL;type=VOICE;waid=${c.waid}:+${c.waid.replace(/ /g, '')}\nEND:VCARD`
140
+ }));
141
+
142
+ const content = {
143
+ contacts: {
144
+ contacts: vcards
145
+ }
146
+ };
147
+ return this.sendMessage(jid, content);
148
+ }
149
+
150
+ /**
151
+ * Envia uma enquete (poll).
152
+ * @param {string} jid - O JID do destinatário.
153
+ * @param {string} pollName - A pergunta da enquete.
154
+ * @param {string[]} pollValues - Um array com as opções da enquete.
155
+ * @param {object} [options={}] - Opções adicionais.
156
+ * @param {number} [options.selectableCount=1] - Quantas opções podem ser selecionadas. 1 para escolha única, 0 para múltipla escolha.
157
+ */
158
+ async sendPoll(jid, pollName, pollValues, options = {}) {
159
+ const content = {
160
+ poll: {
161
+ name: pollName,
162
+ values: pollValues,
163
+ selectableCount: options.selectableCount === 0 ? 0 : 1
164
+ }
165
+ };
166
+ return this.sendMessage(jid, content);
167
+ }
168
+
169
+ /**
170
+ * Envia uma mensagem de link (preview).
171
+ * @param {string} jid - O JID do destinatário.
172
+ * @param {string} url - O link a ser enviado.
173
+ * @param {string} [caption=''] - Texto opcional para acompanhar o link.
174
+ * @param {object} [options={}] - Opções adicionais.
175
+ */
176
+ async sendLink(jid, url, options = {}) {
177
+
178
+ return this.sendMessage(jid, { text: url }, options);
179
+ }
180
+
181
+ // =================================================================================================
182
+ // MÉTODOS DE AÇÕES DE MENSAGEM
183
+ // =================================================================================================
184
+
185
+ /** Encaminha uma mensagem para um JID. */
186
+ async forwardMessage(jid, messageToForward) {
187
+ const content = {
188
+ forward: messageToForward
189
+ };
190
+ return this.sendMessage(jid, content);
191
+ }
192
+
193
+ /** Edita o conteúdo de uma mensagem enviada anteriormente pelo bot. */
194
+ async editMessage(originalMessageKey, newText) {
195
+ const jid = originalMessageKey.remoteJid;
196
+ const content = {
197
+ text: newText,
198
+ edit: originalMessageKey
199
+ };
200
+ // Não precisa normalizar, pois o JID vem de uma mensagem existente.
201
+ return this.client.sock.sendMessage(jid, content);
202
+ }
203
+
204
+ /** Reage a uma mensagem com um emoji. */
205
+ async react(messageKey, emoji) {
206
+ const reaction = { react: { text: emoji, key: messageKey } };
207
+ return this.sendMessage(messageKey.remoteJid, reaction);
208
+ }
209
+
210
+ /** Apaga uma mensagem (enviada pelo bot). */
211
+ async delete(messageKey) {
212
+ return this.sendMessage(messageKey.remoteJid, { delete: messageKey });
213
+ }
214
+
215
+ // =================================================================================================
216
+ // MÉTODOS INTERATIVOS E OUTROS
217
+ // =================================================================================================
218
+ /** Envia acoes */
219
+ async sendTyping(jid) {
220
+ try {
221
+ this.client._validateConnection();
222
+ const verifiedJid = await this.client.users.isOnWhatsApp(jid);
223
+ if (verifiedJid && verifiedJid.exists) {
224
+
225
+ await this.client.sock.presenceSubscribe(jid)
226
+ await this.client.sock.sendPresenceUpdate('available', jid)
227
+ await Utils.delay(500);
228
+
229
+ await this.client.sock.sendPresenceUpdate('composing', jid)
230
+ await Utils.delay(5000)
231
+
232
+ return await this.client.sock.sendPresenceUpdate('paused', jid)
233
+ }
234
+ else {
235
+ return verifiedJid;
236
+ }
237
+
238
+ } catch (error) {
239
+ throw error;
240
+ }
241
+ }
242
+ /** Marca mensagens como lidas. */
243
+ async read(messageKey) {
244
+ this.client._validateConnection();
245
+ return this.client.sock.readMessages([messageKey]);
246
+ }
247
+
248
+ async sendInteractiveMessage(jid, interactiveMessage, more) {
249
+ const verifiedJid = await this.client.users.isOnWhatsApp(jid);
250
+ if (verifiedJid && verifiedJid.exists) {
251
+ return await sendInteractiveMessage(this.client.sock, verifiedJid.jid, interactiveMessage, more);
252
+ }
253
+ else {
254
+ return verifiedJid;
255
+ }
256
+ }
257
+
258
+ /** Envia uma mensagem com botões interativos. */
259
+ async sendButtons(jid, messageButton) {
260
+ const verifiedJid = await this.client.users.isOnWhatsApp(jid);
261
+ if (verifiedJid && verifiedJid.exists) {
262
+ return await sendButtons(this.client.sock, verifiedJid.jid, messageButton);
263
+ }
264
+ else {
265
+ return verifiedJid;
266
+ }
267
+ }
268
+
269
+ /** Faz o download de mídia de uma mensagem. */
270
+ async download(message) {
271
+ this.client._validateConnection();
272
+ const type = Object.keys(message.message)[0];
273
+ const messageContent = message.message[type];
274
+ if (!messageContent.url) throw new Error('Mensagem não contém mídia para download.');
275
+
276
+ const stream = await this.client.downloadContentFromMessage(messageContent, type.replace('Message', ''));
277
+ let buffer = Buffer.from([]);
278
+ for await (const chunk of stream) {
279
+ buffer = Buffer.concat([buffer, chunk]);
280
+ }
281
+ return buffer;
282
+ }
283
+ }
284
+
285
+ module.exports = MessageHandler;
@@ -0,0 +1,9 @@
1
+ class PresenceStatus {
2
+ static COMPOSING = 'composing'; // digitando...
3
+ static RECORDING = 'recording'; // gravando áudio...
4
+ static PAUSED = 'paused'; // parou de digitar/gravar
5
+ static AVAILABLE = 'available'; // online
6
+ static UNAVAILABLE = 'unavailable'; // offline
7
+ }
8
+
9
+ module.exports = PresenceStatus;
@@ -0,0 +1,94 @@
1
+
2
+ /**
3
+ * @copyright Áreum Tecnologia
4
+ * @file Gerenciador de operações de usuário para o cliente WhatsApp.
5
+ * @module UserHandler
6
+ *
7
+ * @description
8
+ * Esta classe fornece métodos para manipulação de usuários, incluindo obtenção de status,
9
+ * foto de perfil, verificação de existência no WhatsApp, atualização de perfil, bloqueio/desbloqueio,
10
+ * e envio de atualizações de presença.
11
+ *
12
+ * @author Áreum Tecnologia
13
+ */
14
+ const PresenceStatus = require('./presence-status');
15
+
16
+ class UserHandler {
17
+ /**
18
+ * @param {import('../../../client').default} client - A instância principal do cliente.
19
+ */
20
+ constructor(client) {
21
+ this.client = client;
22
+ }
23
+
24
+ async getStatus(id) {
25
+ const myStatus = await this.client.sock.fetchStatus(id);
26
+ return myStatus;
27
+ }
28
+
29
+ async getMyStatus() {
30
+ const { id } = this.client.sock.user;
31
+ const myStatus = await this.getStatus(id);
32
+ return myStatus;
33
+ }
34
+
35
+ /** Obtém a URL da foto de perfil de um usuário ou grupo. */
36
+ async getProfilePicture(jid) {
37
+ this.client._validateConnection();
38
+ return this.client.sock.profilePictureUrl(jid, 'image');
39
+ }
40
+
41
+ /** Verifica se um número está no WhatsApp. Inclusive retorna ID verdadeira para numeros brasileiros com 9 digitos */
42
+ async isOnWhatsApp(numbers) {
43
+ this.client._validateConnection();
44
+
45
+ // Se for apenas 1 número
46
+ if (!Array.isArray(numbers)) {
47
+ const [result] = await this.client.sock.onWhatsApp(numbers);
48
+ return result;
49
+ }
50
+
51
+ // Se for lista de números
52
+ const results = await this.client.sock.onWhatsApp(...numbers);
53
+ return results;
54
+ }
55
+
56
+ /** Atualiza o nome do perfil do bot. */
57
+ async updateProfileName(newName) {
58
+ this.client._validateConnection();
59
+ return this.client.sock.updateProfileName(newName);
60
+ }
61
+
62
+ /** Atualiza o recado/status do perfil do bot. */
63
+ async updateProfileStatus(newStatus) {
64
+ this.client._validateConnection();
65
+ return this.client.sock.updateProfileStatus(newStatus);
66
+ }
67
+
68
+ /** Bloqueia um usuário. */
69
+ async block(jid) {
70
+ this.client._validateConnection();
71
+ return this.client.sock.updateBlockStatus(jid, 'block');
72
+ }
73
+
74
+ /** Desbloqueia um usuário. */
75
+ async unblock(jid) {
76
+ this.client._validateConnection();
77
+ return this.client.sock.updateBlockStatus(jid, 'unblock');
78
+ }
79
+
80
+ /** Obtém a lista de contatos bloqueados. */
81
+ async getBlocklist() {
82
+ this.client._validateConnection();
83
+ return this.client.sock.fetchBlocklist();
84
+ }
85
+
86
+ /** Envia uma atualização de presença. Use PresenceStatus */
87
+
88
+ async sendPresence(jid, presenceStatus) {
89
+ this.client._validateConnection();
90
+ await this.client.sock.sendPresenceUpdate(presenceStatus, jid);
91
+ }
92
+ }
93
+
94
+ module.exports = { UserHandler, PresenceStatus };