@hdriel/whatsapp-socket 1.0.6 → 1.2.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.
- package/README.md +11 -8
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +186 -8
- package/dist/index.d.ts +186 -8
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ReadStream } from 'node:fs';
|
|
2
2
|
import { Readable } from 'stream';
|
|
3
|
-
import {
|
|
3
|
+
import { WAMessage, MessageUpsertType, WASocket, UserFacingSocketConfig, GroupMetadata } from '@fadzzzslebew/baileys';
|
|
4
4
|
import { StringValue } from 'ms';
|
|
5
5
|
import { Logger } from 'stack-trace-logger';
|
|
6
6
|
|
|
@@ -26,7 +26,6 @@ type WhatsappSocketBaseProps = ({
|
|
|
26
26
|
customPairingCode?: string;
|
|
27
27
|
};
|
|
28
28
|
declare class WhatsappSocketBase {
|
|
29
|
-
protected socket: null | WASocket;
|
|
30
29
|
protected readonly fileAuthStateDirectoryPath?: string;
|
|
31
30
|
protected readonly mongoURL?: string;
|
|
32
31
|
protected readonly mongoCollection: string;
|
|
@@ -62,10 +61,17 @@ declare class WhatsappSocketBase {
|
|
|
62
61
|
[key: string]: any;
|
|
63
62
|
}): Promise<string>;
|
|
64
63
|
static randomPairingCode(pattern: string, length?: number): string;
|
|
65
|
-
|
|
64
|
+
private static instances;
|
|
65
|
+
static getInstance(props: WhatsappSocketBaseProps): WASocket;
|
|
66
|
+
static clearInstance(key?: string): void;
|
|
67
|
+
constructor(props: WhatsappSocketBaseProps);
|
|
66
68
|
private getLatestWhatsAppVersion;
|
|
67
69
|
private getAuthCollection;
|
|
68
70
|
private authenticate;
|
|
71
|
+
static buildSocketKey(props: Partial<WhatsappSocketBaseProps>): string;
|
|
72
|
+
get socketKey(): string;
|
|
73
|
+
get socket(): WASocket | null;
|
|
74
|
+
set socket(sock: WASocket | null);
|
|
69
75
|
startConnection({ options, connectionAttempts, onOpen, onClose, onQR, onConnectionStatusChange, pairingPhone: _pairingPhone, debug: _debug, }?: {
|
|
70
76
|
options?: UserFacingSocketConfig;
|
|
71
77
|
debug?: boolean;
|
|
@@ -99,7 +105,18 @@ type ButtonPhone = {
|
|
|
99
105
|
tel: string;
|
|
100
106
|
};
|
|
101
107
|
type CallToActionButtons = Array<ButtonURL | ButtonCopy | ButtonPhone>;
|
|
102
|
-
|
|
108
|
+
type GroupMessageOptions = {
|
|
109
|
+
mentions?: string[];
|
|
110
|
+
replyToMessageId?: string;
|
|
111
|
+
};
|
|
112
|
+
type CreateGroupOptions = {
|
|
113
|
+
name: string;
|
|
114
|
+
participants?: string[];
|
|
115
|
+
description?: string;
|
|
116
|
+
};
|
|
117
|
+
type GroupSettingsType = 'announcement' | 'not_announcement' | 'locked' | 'unlocked';
|
|
118
|
+
|
|
119
|
+
declare class WhatsappSocketPrivateMessages extends WhatsappSocketBase {
|
|
103
120
|
constructor(props: WhatsappSocketBaseProps);
|
|
104
121
|
sendTextMessage(to: string, text: string, replyToMessageId?: string): Promise<any>;
|
|
105
122
|
sendButtonsMessage(to: string, { subtitle, title, buttons }: {
|
|
@@ -117,7 +134,7 @@ declare class WhatsappSocketMessages extends WhatsappSocketBase {
|
|
|
117
134
|
}): Promise<any>;
|
|
118
135
|
}
|
|
119
136
|
|
|
120
|
-
declare class
|
|
137
|
+
declare class WhatsappSocketPrivateStream extends WhatsappSocketPrivateMessages {
|
|
121
138
|
constructor(props: WhatsappSocketBaseProps);
|
|
122
139
|
protected sendFileFromStream(to: string, stream: Readable | Buffer, options: {
|
|
123
140
|
filename: string;
|
|
@@ -166,7 +183,7 @@ declare class WhatsappSocketStream extends WhatsappSocketMessages {
|
|
|
166
183
|
}): Promise<any>;
|
|
167
184
|
}
|
|
168
185
|
|
|
169
|
-
declare class
|
|
186
|
+
declare class WhatsappSocketPrivateFiles extends WhatsappSocketPrivateStream {
|
|
170
187
|
constructor(props: WhatsappSocketBaseProps);
|
|
171
188
|
sendImageMessage(to: string, imageSrc: string | Buffer<any> | ReadStream, { caption, filename }?: {
|
|
172
189
|
caption?: string;
|
|
@@ -205,8 +222,169 @@ declare class WhatsappSocketFiles extends WhatsappSocketStream {
|
|
|
205
222
|
}): Promise<void>;
|
|
206
223
|
}
|
|
207
224
|
|
|
208
|
-
declare class
|
|
225
|
+
declare class WhatsappSocketGroups extends WhatsappSocketBase {
|
|
226
|
+
/**
|
|
227
|
+
* פורמט Group ID לתבנית WhatsApp
|
|
228
|
+
* Format Group ID to WhatsApp pattern
|
|
229
|
+
* Group IDs end with @g.us instead of @s.whatsapp.net
|
|
230
|
+
*/
|
|
231
|
+
static formatGroupId(groupId: string): string;
|
|
232
|
+
/**
|
|
233
|
+
* בדיקה האם מדובר ב-Group ID או Phone Number
|
|
234
|
+
* Check if this is a group ID or phone number
|
|
235
|
+
*/
|
|
236
|
+
static isGroupId(jid: string): boolean;
|
|
237
|
+
constructor(props: WhatsappSocketBaseProps);
|
|
238
|
+
/**
|
|
239
|
+
* Create a new WhatsApp group
|
|
240
|
+
*/
|
|
241
|
+
createGroup({ name, participants, description }: CreateGroupOptions): Promise<any>;
|
|
242
|
+
/**
|
|
243
|
+
* Update group name (subject)
|
|
244
|
+
*/
|
|
245
|
+
updateGroupName(groupId: string, newName: string): Promise<any>;
|
|
246
|
+
/**
|
|
247
|
+
* Update group description
|
|
248
|
+
*/
|
|
249
|
+
updateGroupDescription(groupId: string, description: string): Promise<any>;
|
|
250
|
+
/**
|
|
251
|
+
* Update group settings (who can send messages, edit info, etc.)
|
|
252
|
+
*/
|
|
253
|
+
updateGroupSettings(groupId: string, setting: GroupSettingsType): Promise<any>;
|
|
254
|
+
/**
|
|
255
|
+
* Add participants to group
|
|
256
|
+
*/
|
|
257
|
+
addParticipants(groupId: string, participants: string[]): Promise<any>;
|
|
258
|
+
/**
|
|
259
|
+
* Remove participants from group
|
|
260
|
+
*/
|
|
261
|
+
removeParticipants(groupId: string, participants: string[]): Promise<any>;
|
|
262
|
+
/**
|
|
263
|
+
* Promote participant to admin
|
|
264
|
+
*/
|
|
265
|
+
promoteToAdmin(groupId: string, participants: string[]): Promise<any>;
|
|
266
|
+
/**
|
|
267
|
+
* הורדת משתתף ממנהל
|
|
268
|
+
* Demote participant from admin
|
|
269
|
+
*/
|
|
270
|
+
demoteFromAdmin(groupId: string, participants: string[]): Promise<any>;
|
|
271
|
+
/**
|
|
272
|
+
* Leave a group
|
|
273
|
+
*/
|
|
274
|
+
leaveGroup(groupId: string): Promise<any>;
|
|
275
|
+
/**
|
|
276
|
+
* Get group metadata
|
|
277
|
+
*/
|
|
278
|
+
getGroupMetadata(groupId: string): Promise<GroupMetadata | undefined>;
|
|
279
|
+
/**
|
|
280
|
+
* Get all groups
|
|
281
|
+
*/
|
|
282
|
+
getAllGroups(): Promise<GroupMetadata[]>;
|
|
283
|
+
/**
|
|
284
|
+
* Get group invite code
|
|
285
|
+
*/
|
|
286
|
+
getGroupInviteCode(groupId: string): Promise<string | undefined>;
|
|
287
|
+
/**
|
|
288
|
+
* Revoke group invite code (creates new one)
|
|
289
|
+
*/
|
|
290
|
+
revokeGroupInviteCode(groupId: string): Promise<string | undefined>;
|
|
291
|
+
/**
|
|
292
|
+
* Join group using invite code
|
|
293
|
+
*/
|
|
294
|
+
joinGroupViaInvite(inviteCode: string): Promise<string | undefined>;
|
|
295
|
+
/**
|
|
296
|
+
* Get group info from invite code
|
|
297
|
+
*/
|
|
298
|
+
getGroupInfoFromInvite(inviteCode: string): Promise<any>;
|
|
299
|
+
/**
|
|
300
|
+
* Update group profile picture
|
|
301
|
+
*/
|
|
302
|
+
updateGroupProfilePicture(groupId: string, imageBuffer: Buffer): Promise<any>;
|
|
303
|
+
/**
|
|
304
|
+
* Remove group profile picture
|
|
305
|
+
*/
|
|
306
|
+
removeGroupProfilePicture(groupId: string): Promise<any>;
|
|
307
|
+
/**
|
|
308
|
+
* Get group profile picture URL
|
|
309
|
+
*/
|
|
310
|
+
getGroupProfilePicture(groupId: string, highRes?: boolean): Promise<string | undefined>;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
declare class WhatsappSocketGroupMessages extends WhatsappSocketGroups {
|
|
314
|
+
constructor(props: WhatsappSocketBaseProps);
|
|
315
|
+
/**
|
|
316
|
+
* Send text message to group
|
|
317
|
+
*/
|
|
318
|
+
sendTextMessage(groupId: string, text: string, options?: GroupMessageOptions): Promise<any>;
|
|
319
|
+
/**
|
|
320
|
+
* Send buttons message to group
|
|
321
|
+
*/
|
|
322
|
+
sendButtonsMessage(groupId: string, { title, subtitle, buttons, }: {
|
|
323
|
+
title: string;
|
|
324
|
+
subtitle?: string;
|
|
325
|
+
buttons: CallToActionButtons;
|
|
326
|
+
}): Promise<any>;
|
|
327
|
+
/**
|
|
328
|
+
* Send reply buttons message to group
|
|
329
|
+
*/
|
|
330
|
+
sendReplyButtonsMessage(groupId: string, { title, subtitle, buttons, mentions, }: {
|
|
331
|
+
title: string;
|
|
332
|
+
subtitle?: string;
|
|
333
|
+
buttons: Array<string | {
|
|
334
|
+
id: number | string;
|
|
335
|
+
label: string;
|
|
336
|
+
}>;
|
|
337
|
+
mentions?: string[];
|
|
338
|
+
}): Promise<any>;
|
|
339
|
+
/**
|
|
340
|
+
* Send image to group
|
|
341
|
+
*/
|
|
342
|
+
sendImageMessage(groupId: string, imageBuffer: Buffer, // todo: handle also stream and string url
|
|
343
|
+
{ caption, mentions }?: GroupMessageOptions & {
|
|
344
|
+
caption?: string;
|
|
345
|
+
}): Promise<any>;
|
|
346
|
+
/**
|
|
347
|
+
* Send video to group
|
|
348
|
+
*/
|
|
349
|
+
sendVideoMessage(groupId: string, videoBuffer: Buffer, // todo: handle also stream and string url
|
|
350
|
+
caption?: string, options?: GroupMessageOptions): Promise<any>;
|
|
351
|
+
/**
|
|
352
|
+
* Send audio to group
|
|
353
|
+
*/
|
|
354
|
+
sendAudioMessage(groupId: string, audioBuffer: Buffer, // todo: handle also stream and string url
|
|
355
|
+
options?: {
|
|
356
|
+
ptt?: boolean;
|
|
357
|
+
mentions?: string[];
|
|
358
|
+
}): Promise<any>;
|
|
359
|
+
/**
|
|
360
|
+
* Send document to group
|
|
361
|
+
*/
|
|
362
|
+
sendDocumentMessage(groupId: string, documentBuffer: Buffer, // todo: handle also stream and string url
|
|
363
|
+
fileName: string, mimeType?: string, options?: GroupMessageOptions): Promise<any>;
|
|
364
|
+
/**
|
|
365
|
+
* Send location to group
|
|
366
|
+
*/
|
|
367
|
+
sendLocationMessage(groupId: string, latitude: number, longitude: number, name?: string, address?: string): Promise<any>;
|
|
368
|
+
/**
|
|
369
|
+
* Send message mentioning all group participants
|
|
370
|
+
*/
|
|
371
|
+
sendMentionAll(groupId: string, text: string): Promise<any>;
|
|
372
|
+
/**
|
|
373
|
+
* Send reaction to a message in group
|
|
374
|
+
*/
|
|
375
|
+
sendReactionMessage(groupId: string, messageId: string, emoji: string): Promise<any>;
|
|
376
|
+
/**
|
|
377
|
+
* Delete a message in group (only works for own messages)
|
|
378
|
+
*/
|
|
379
|
+
deleteGroupMessage(groupId: string, messageId: string): Promise<any>;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
declare class WhatsappSocket extends WhatsappSocketPrivateFiles {
|
|
383
|
+
constructor(props: WhatsappSocketBaseProps);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
declare class WhatsappSocketGroup extends WhatsappSocketGroupMessages {
|
|
209
387
|
constructor(props: WhatsappSocketBaseProps);
|
|
210
388
|
}
|
|
211
389
|
|
|
212
|
-
export { WhatsappSocket };
|
|
390
|
+
export { WhatsappSocket, WhatsappSocketGroup };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ReadStream } from 'node:fs';
|
|
2
2
|
import { Readable } from 'stream';
|
|
3
|
-
import {
|
|
3
|
+
import { WAMessage, MessageUpsertType, WASocket, UserFacingSocketConfig, GroupMetadata } from '@fadzzzslebew/baileys';
|
|
4
4
|
import { StringValue } from 'ms';
|
|
5
5
|
import { Logger } from 'stack-trace-logger';
|
|
6
6
|
|
|
@@ -26,7 +26,6 @@ type WhatsappSocketBaseProps = ({
|
|
|
26
26
|
customPairingCode?: string;
|
|
27
27
|
};
|
|
28
28
|
declare class WhatsappSocketBase {
|
|
29
|
-
protected socket: null | WASocket;
|
|
30
29
|
protected readonly fileAuthStateDirectoryPath?: string;
|
|
31
30
|
protected readonly mongoURL?: string;
|
|
32
31
|
protected readonly mongoCollection: string;
|
|
@@ -62,10 +61,17 @@ declare class WhatsappSocketBase {
|
|
|
62
61
|
[key: string]: any;
|
|
63
62
|
}): Promise<string>;
|
|
64
63
|
static randomPairingCode(pattern: string, length?: number): string;
|
|
65
|
-
|
|
64
|
+
private static instances;
|
|
65
|
+
static getInstance(props: WhatsappSocketBaseProps): WASocket;
|
|
66
|
+
static clearInstance(key?: string): void;
|
|
67
|
+
constructor(props: WhatsappSocketBaseProps);
|
|
66
68
|
private getLatestWhatsAppVersion;
|
|
67
69
|
private getAuthCollection;
|
|
68
70
|
private authenticate;
|
|
71
|
+
static buildSocketKey(props: Partial<WhatsappSocketBaseProps>): string;
|
|
72
|
+
get socketKey(): string;
|
|
73
|
+
get socket(): WASocket | null;
|
|
74
|
+
set socket(sock: WASocket | null);
|
|
69
75
|
startConnection({ options, connectionAttempts, onOpen, onClose, onQR, onConnectionStatusChange, pairingPhone: _pairingPhone, debug: _debug, }?: {
|
|
70
76
|
options?: UserFacingSocketConfig;
|
|
71
77
|
debug?: boolean;
|
|
@@ -99,7 +105,18 @@ type ButtonPhone = {
|
|
|
99
105
|
tel: string;
|
|
100
106
|
};
|
|
101
107
|
type CallToActionButtons = Array<ButtonURL | ButtonCopy | ButtonPhone>;
|
|
102
|
-
|
|
108
|
+
type GroupMessageOptions = {
|
|
109
|
+
mentions?: string[];
|
|
110
|
+
replyToMessageId?: string;
|
|
111
|
+
};
|
|
112
|
+
type CreateGroupOptions = {
|
|
113
|
+
name: string;
|
|
114
|
+
participants?: string[];
|
|
115
|
+
description?: string;
|
|
116
|
+
};
|
|
117
|
+
type GroupSettingsType = 'announcement' | 'not_announcement' | 'locked' | 'unlocked';
|
|
118
|
+
|
|
119
|
+
declare class WhatsappSocketPrivateMessages extends WhatsappSocketBase {
|
|
103
120
|
constructor(props: WhatsappSocketBaseProps);
|
|
104
121
|
sendTextMessage(to: string, text: string, replyToMessageId?: string): Promise<any>;
|
|
105
122
|
sendButtonsMessage(to: string, { subtitle, title, buttons }: {
|
|
@@ -117,7 +134,7 @@ declare class WhatsappSocketMessages extends WhatsappSocketBase {
|
|
|
117
134
|
}): Promise<any>;
|
|
118
135
|
}
|
|
119
136
|
|
|
120
|
-
declare class
|
|
137
|
+
declare class WhatsappSocketPrivateStream extends WhatsappSocketPrivateMessages {
|
|
121
138
|
constructor(props: WhatsappSocketBaseProps);
|
|
122
139
|
protected sendFileFromStream(to: string, stream: Readable | Buffer, options: {
|
|
123
140
|
filename: string;
|
|
@@ -166,7 +183,7 @@ declare class WhatsappSocketStream extends WhatsappSocketMessages {
|
|
|
166
183
|
}): Promise<any>;
|
|
167
184
|
}
|
|
168
185
|
|
|
169
|
-
declare class
|
|
186
|
+
declare class WhatsappSocketPrivateFiles extends WhatsappSocketPrivateStream {
|
|
170
187
|
constructor(props: WhatsappSocketBaseProps);
|
|
171
188
|
sendImageMessage(to: string, imageSrc: string | Buffer<any> | ReadStream, { caption, filename }?: {
|
|
172
189
|
caption?: string;
|
|
@@ -205,8 +222,169 @@ declare class WhatsappSocketFiles extends WhatsappSocketStream {
|
|
|
205
222
|
}): Promise<void>;
|
|
206
223
|
}
|
|
207
224
|
|
|
208
|
-
declare class
|
|
225
|
+
declare class WhatsappSocketGroups extends WhatsappSocketBase {
|
|
226
|
+
/**
|
|
227
|
+
* פורמט Group ID לתבנית WhatsApp
|
|
228
|
+
* Format Group ID to WhatsApp pattern
|
|
229
|
+
* Group IDs end with @g.us instead of @s.whatsapp.net
|
|
230
|
+
*/
|
|
231
|
+
static formatGroupId(groupId: string): string;
|
|
232
|
+
/**
|
|
233
|
+
* בדיקה האם מדובר ב-Group ID או Phone Number
|
|
234
|
+
* Check if this is a group ID or phone number
|
|
235
|
+
*/
|
|
236
|
+
static isGroupId(jid: string): boolean;
|
|
237
|
+
constructor(props: WhatsappSocketBaseProps);
|
|
238
|
+
/**
|
|
239
|
+
* Create a new WhatsApp group
|
|
240
|
+
*/
|
|
241
|
+
createGroup({ name, participants, description }: CreateGroupOptions): Promise<any>;
|
|
242
|
+
/**
|
|
243
|
+
* Update group name (subject)
|
|
244
|
+
*/
|
|
245
|
+
updateGroupName(groupId: string, newName: string): Promise<any>;
|
|
246
|
+
/**
|
|
247
|
+
* Update group description
|
|
248
|
+
*/
|
|
249
|
+
updateGroupDescription(groupId: string, description: string): Promise<any>;
|
|
250
|
+
/**
|
|
251
|
+
* Update group settings (who can send messages, edit info, etc.)
|
|
252
|
+
*/
|
|
253
|
+
updateGroupSettings(groupId: string, setting: GroupSettingsType): Promise<any>;
|
|
254
|
+
/**
|
|
255
|
+
* Add participants to group
|
|
256
|
+
*/
|
|
257
|
+
addParticipants(groupId: string, participants: string[]): Promise<any>;
|
|
258
|
+
/**
|
|
259
|
+
* Remove participants from group
|
|
260
|
+
*/
|
|
261
|
+
removeParticipants(groupId: string, participants: string[]): Promise<any>;
|
|
262
|
+
/**
|
|
263
|
+
* Promote participant to admin
|
|
264
|
+
*/
|
|
265
|
+
promoteToAdmin(groupId: string, participants: string[]): Promise<any>;
|
|
266
|
+
/**
|
|
267
|
+
* הורדת משתתף ממנהל
|
|
268
|
+
* Demote participant from admin
|
|
269
|
+
*/
|
|
270
|
+
demoteFromAdmin(groupId: string, participants: string[]): Promise<any>;
|
|
271
|
+
/**
|
|
272
|
+
* Leave a group
|
|
273
|
+
*/
|
|
274
|
+
leaveGroup(groupId: string): Promise<any>;
|
|
275
|
+
/**
|
|
276
|
+
* Get group metadata
|
|
277
|
+
*/
|
|
278
|
+
getGroupMetadata(groupId: string): Promise<GroupMetadata | undefined>;
|
|
279
|
+
/**
|
|
280
|
+
* Get all groups
|
|
281
|
+
*/
|
|
282
|
+
getAllGroups(): Promise<GroupMetadata[]>;
|
|
283
|
+
/**
|
|
284
|
+
* Get group invite code
|
|
285
|
+
*/
|
|
286
|
+
getGroupInviteCode(groupId: string): Promise<string | undefined>;
|
|
287
|
+
/**
|
|
288
|
+
* Revoke group invite code (creates new one)
|
|
289
|
+
*/
|
|
290
|
+
revokeGroupInviteCode(groupId: string): Promise<string | undefined>;
|
|
291
|
+
/**
|
|
292
|
+
* Join group using invite code
|
|
293
|
+
*/
|
|
294
|
+
joinGroupViaInvite(inviteCode: string): Promise<string | undefined>;
|
|
295
|
+
/**
|
|
296
|
+
* Get group info from invite code
|
|
297
|
+
*/
|
|
298
|
+
getGroupInfoFromInvite(inviteCode: string): Promise<any>;
|
|
299
|
+
/**
|
|
300
|
+
* Update group profile picture
|
|
301
|
+
*/
|
|
302
|
+
updateGroupProfilePicture(groupId: string, imageBuffer: Buffer): Promise<any>;
|
|
303
|
+
/**
|
|
304
|
+
* Remove group profile picture
|
|
305
|
+
*/
|
|
306
|
+
removeGroupProfilePicture(groupId: string): Promise<any>;
|
|
307
|
+
/**
|
|
308
|
+
* Get group profile picture URL
|
|
309
|
+
*/
|
|
310
|
+
getGroupProfilePicture(groupId: string, highRes?: boolean): Promise<string | undefined>;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
declare class WhatsappSocketGroupMessages extends WhatsappSocketGroups {
|
|
314
|
+
constructor(props: WhatsappSocketBaseProps);
|
|
315
|
+
/**
|
|
316
|
+
* Send text message to group
|
|
317
|
+
*/
|
|
318
|
+
sendTextMessage(groupId: string, text: string, options?: GroupMessageOptions): Promise<any>;
|
|
319
|
+
/**
|
|
320
|
+
* Send buttons message to group
|
|
321
|
+
*/
|
|
322
|
+
sendButtonsMessage(groupId: string, { title, subtitle, buttons, }: {
|
|
323
|
+
title: string;
|
|
324
|
+
subtitle?: string;
|
|
325
|
+
buttons: CallToActionButtons;
|
|
326
|
+
}): Promise<any>;
|
|
327
|
+
/**
|
|
328
|
+
* Send reply buttons message to group
|
|
329
|
+
*/
|
|
330
|
+
sendReplyButtonsMessage(groupId: string, { title, subtitle, buttons, mentions, }: {
|
|
331
|
+
title: string;
|
|
332
|
+
subtitle?: string;
|
|
333
|
+
buttons: Array<string | {
|
|
334
|
+
id: number | string;
|
|
335
|
+
label: string;
|
|
336
|
+
}>;
|
|
337
|
+
mentions?: string[];
|
|
338
|
+
}): Promise<any>;
|
|
339
|
+
/**
|
|
340
|
+
* Send image to group
|
|
341
|
+
*/
|
|
342
|
+
sendImageMessage(groupId: string, imageBuffer: Buffer, // todo: handle also stream and string url
|
|
343
|
+
{ caption, mentions }?: GroupMessageOptions & {
|
|
344
|
+
caption?: string;
|
|
345
|
+
}): Promise<any>;
|
|
346
|
+
/**
|
|
347
|
+
* Send video to group
|
|
348
|
+
*/
|
|
349
|
+
sendVideoMessage(groupId: string, videoBuffer: Buffer, // todo: handle also stream and string url
|
|
350
|
+
caption?: string, options?: GroupMessageOptions): Promise<any>;
|
|
351
|
+
/**
|
|
352
|
+
* Send audio to group
|
|
353
|
+
*/
|
|
354
|
+
sendAudioMessage(groupId: string, audioBuffer: Buffer, // todo: handle also stream and string url
|
|
355
|
+
options?: {
|
|
356
|
+
ptt?: boolean;
|
|
357
|
+
mentions?: string[];
|
|
358
|
+
}): Promise<any>;
|
|
359
|
+
/**
|
|
360
|
+
* Send document to group
|
|
361
|
+
*/
|
|
362
|
+
sendDocumentMessage(groupId: string, documentBuffer: Buffer, // todo: handle also stream and string url
|
|
363
|
+
fileName: string, mimeType?: string, options?: GroupMessageOptions): Promise<any>;
|
|
364
|
+
/**
|
|
365
|
+
* Send location to group
|
|
366
|
+
*/
|
|
367
|
+
sendLocationMessage(groupId: string, latitude: number, longitude: number, name?: string, address?: string): Promise<any>;
|
|
368
|
+
/**
|
|
369
|
+
* Send message mentioning all group participants
|
|
370
|
+
*/
|
|
371
|
+
sendMentionAll(groupId: string, text: string): Promise<any>;
|
|
372
|
+
/**
|
|
373
|
+
* Send reaction to a message in group
|
|
374
|
+
*/
|
|
375
|
+
sendReactionMessage(groupId: string, messageId: string, emoji: string): Promise<any>;
|
|
376
|
+
/**
|
|
377
|
+
* Delete a message in group (only works for own messages)
|
|
378
|
+
*/
|
|
379
|
+
deleteGroupMessage(groupId: string, messageId: string): Promise<any>;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
declare class WhatsappSocket extends WhatsappSocketPrivateFiles {
|
|
383
|
+
constructor(props: WhatsappSocketBaseProps);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
declare class WhatsappSocketGroup extends WhatsappSocketGroupMessages {
|
|
209
387
|
constructor(props: WhatsappSocketBaseProps);
|
|
210
388
|
}
|
|
211
389
|
|
|
212
|
-
export { WhatsappSocket };
|
|
390
|
+
export { WhatsappSocket, WhatsappSocketGroup };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import ae,{ReadStream}from'fs';import ne,{generateWAMessageFromContent,WAProto,useMultiFileAuthState,makeCacheableSignalKeyStore,DisconnectReason,initAuthCreds}from'@fadzzzslebew/baileys';import F from'ms';import q from'qrcode';import {MongoClient}from'mongodb';import ce from'pino';import {parseStream,parseBuffer}from'music-metadata';import {basename}from'path';var D={replacer:(o,e)=>Buffer.isBuffer(e)||e instanceof Uint8Array||e?.type==="Buffer"?{type:"Buffer",data:Buffer.from(e?.data||e).toString("base64")}:e,reviver:(o,e)=>{if(typeof e=="object"&&e&&(e.buffer===true||e.type==="Buffer")){let t=e.data||e.value;return typeof t=="string"?Buffer.from(t,"base64"):Buffer.from(t||[])}return e}},z=async o=>{let e=(s,a)=>{let i={$set:{...JSON.parse(JSON.stringify(s,D.replacer))}};return o.updateOne({_id:a},i,{upsert:true})},t=async s=>{try{let a=JSON.stringify(await o.findOne({_id:s}));return JSON.parse(a,D.reviver)}catch{return null}},n=async s=>{try{await o.deleteOne({_id:s});}catch{}},r=await t("creds")||initAuthCreds();return {state:{creds:r,keys:{get:async(s,a)=>{let c={};return await Promise.all(a.map(async i=>{let g=await t(`${s}-${i}`);s==="app-state-sync-key"&&g&&(g=WAProto.Message.AppStateSyncKeyData.fromObject(g)),c[i]=g;})),c},set:async s=>{let a=[];for(let c of Object.keys(s))for(let i of Object.keys(s[c])){let g=s[c][i],u=`${c}-${i}`;a.push(g?e(g,u):n(u));}await Promise.all(a);}}},saveCreds:()=>e(r,"creds")}},O=z;var U=o=>F(o)/1e3;async function f(o){let t=await(await fetch(o)).arrayBuffer();return Buffer.from(t)}async function ee(o,e){try{let t=await parseStream(o,{mimeType:e||"audio/mpeg"});return Math.floor(t.format.duration||0)}catch(t){throw console.error("Error parsing stream:",t),t}finally{o.destroyed||o.destroy();}}async function te(o,e){try{let t=await parseBuffer(o,e||"audio/mpeg").catch(()=>null);return t?Math.floor(t.format.duration||0):0}catch(t){throw console.error("Error parsing buffer:",t),t}}async function E(o,e){return o instanceof ReadStream?ee(o,e):te(o,e)}async function j(o){let e=[];for await(let t of o)e.push(t);return Buffer.concat(e)}function L(o){if(o.path){let e=o.path.toString();return basename(e)}}var M=o=>new Promise(e=>setTimeout(e,F(o))),H={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",bmp:"image/bmp",svg:"image/svg+xml",mp4:"video/mp4",avi:"video/x-msvideo",mov:"video/quicktime",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",opus:"audio/opus",aac:"audio/aac",m4a:"audio/mp4",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed"};var Q=ce({level:"silent"}),w=class o{socket;fileAuthStateDirectoryPath;mongoURL;mongoCollection="whatsapp-auth";logger;debug;printQRInTerminal;pairingPhone;customPairingCode;appName;onPreConnectionSendMessageFailed;onOpen;onClose;onQR;onConnectionStatusChange;onReceiveMessages;static DEFAULT_COUNTRY_CODE="972";static CONNECTION_TIMEOUT="2s";static formatPhoneNumber(e,t=o.DEFAULT_COUNTRY_CODE){if(e.endsWith("@s.whatsapp.net"))return e;let n=e.replace(/[^0-9]/g,"");return n.startsWith("05")&&(n=n.substring(1)),n.startsWith(t)||(n=t+n),n}static formatPhoneNumberToWhatsappPattern(e,t=o.DEFAULT_COUNTRY_CODE){if(e.endsWith("@s.whatsapp.net"))return e;let n=o.formatPhoneNumber(e,t);return n=`${n}@s.whatsapp.net`,n}static getWhatsappPhoneLink({phone:e,message:t,countryCode:n=o.DEFAULT_COUNTRY_CODE}){let r=this.formatPhoneNumber(e,n),s=t?`?text=${encodeURI(t)}`:"";return `https://wa.me/${r}${s}`}static async qrToImage(e,t={}){return q.toDataURL(e,{errorCorrectionLevel:"H",width:400,margin:2,...t})}static async qrToTerminalString(e,t={}){return q.toString(e,{type:"terminal",small:true,...t})}static randomPairingCode(e,t=8){if(!e.includes("[")&&e.length===t)return e;let n="",r=[],s=c=>{let i=[];for(let g=0;g<c.length;g++)if(c[g+1]==="-"&&c[g+2]){let u=c.charCodeAt(g),d=c.charCodeAt(g+2);for(let m=u;m<=d;m++)i.push(String.fromCharCode(m));g+=2;}else i.push(c[g]);return i};for(let c=0;c<e.length&&n.length<t;c++){let i=e[c];if(i==="["){let g=e.indexOf("]",c),u=e.slice(c+1,g);r=s(u),c=g;}else n+=i;}for(;n.length<t&&r.length;)n+=r[Math.floor(Math.random()*r.length)];let a=n.toUpperCase();return a.padEnd(t,a)}constructor({fileAuthStateDirectoryPath:e,mongoURL:t,mongoCollection:n="whatsapp-auth",logger:r,onOpen:s,onClose:a,onQR:c,onReceiveMessages:i,onConnectionStatusChange:g,debug:u,printQRInTerminal:d,pairingPhone:m,customPairingCode:R,onPreConnectionSendMessageFailed:b,appName:W}){this.appName=W,this.mongoURL=t,this.fileAuthStateDirectoryPath=e,this.mongoCollection=n,this.logger=r,this.debug=u,this.printQRInTerminal=d,this.pairingPhone=m,this.customPairingCode=R,this.socket=null,this.onPreConnectionSendMessageFailed=b,this.onConnectionStatusChange=g,this.onReceiveMessages=i,this.onOpen=s,this.onClose=a,this.onQR=c;}async getLatestWhatsAppVersion(){try{let e=["https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json","https://raw.githubusercontent.com/whiskeysockets/baileys/master/src/Defaults/baileys-version.json"];for(let t of e)try{let n=await fetch(t);if(n.ok)return (await n.json()).version}catch{continue}return console.log("Could not fetch version, using fallback"),[2,3e3,1015901307]}catch(e){return console.error("Error fetching version:",e),[2,3e3,1015901307]}}async getAuthCollection(){if(!this.mongoURL)return [];let e=new MongoClient(this.mongoURL);return await e.connect(),[e.db().collection(this.mongoCollection),e]}async authenticate(){if(!this.mongoURL&&!this.fileAuthStateDirectoryPath)throw new Error("fileAuthStateDirectoryPath/MongoURL is missing");if(!this.mongoURL){let{saveCreds:s,state:a}=await useMultiFileAuthState(this.fileAuthStateDirectoryPath);return {auth:a,saveCreds:s}}let[e]=await this.getAuthCollection(),{state:t,saveCreds:n}=await O(e);return {auth:{creds:t.creds,keys:makeCacheableSignalKeyStore(t.keys,Q)},saveCreds:n}}async startConnection({options:e,connectionAttempts:t=3,onOpen:n=this.onOpen,onClose:r=this.onClose,onQR:s=this.onQR,onConnectionStatusChange:a=this.onConnectionStatusChange,pairingPhone:c,debug:i}={}){let g=c??this.pairingPhone,{saveCreds:u,auth:d}=await this.authenticate(),m=i===void 0?this.debug:i,R=await this.getLatestWhatsAppVersion(),b=async()=>new Promise(x=>{let y=ne({version:R,logger:Q,browser:[this.appName||"baileys","1.0.0",""],syncFullHistory:false,shouldSyncHistoryMessage:()=>false,shouldIgnoreJid:h=>h.includes("@newsletter"),...e,printQRInTerminal:false,auth:d});y.ev.on("connection.update",async h=>{let{connection:S,lastDisconnect:N,qr:T}=h;if(T){if(m&&this.logger?.info("WHATSAPP","QR Code received",{qr:T}),this.printQRInTerminal){let J=await o.qrToTerminalString(T,{small:true}).catch(()=>null);console.log(J);}this.customPairingCode?o.randomPairingCode(this.customPairingCode):void 0;let P=g?o.formatPhoneNumber(g):null,C=P?await y.requestPairingCode(P):null;m&&this.printQRInTerminal&&this.logger?.info("WHATSAPP","QR Pairing Code",{code:C,pairingPhone:P}),await s?.(T,C);}switch(S){case "connecting":{m&&this.logger?.debug("WHATSAPP","Connecting..."),a?.("connecting");break}case "open":{m&&this.logger?.info("WHATSAPP","Connection opened successfully!"),this.socket=y,await n?.(),a?.("open"),x(this.socket);break}case "close":{let I=t-- >0&&N?.error?.output?.statusCode!==DisconnectReason.loggedOut,P=N?.error?.output?.statusCode,C=N?.error?.message;m&&this.logger?.info("WHATSAPP","Connection closed",{statusCode:P,errorMessage:C,shouldReconnect:I}),I&&t?(m&&this.logger?.info("WHATSAPP","Reconnecting..."),await M(o.CONNECTION_TIMEOUT),x(b())):(m&&this.logger?.warn("WHATSAPP","Logged out, clearing auth state"),await r?.(),this.socket=null,x(this.socket)),a?.("close");break}}}),y.ev.on("creds.update",u),this.onReceiveMessages&&typeof this.onReceiveMessages=="function"&&y.ev.on("messages.upsert",async({messages:h,type:S})=>{this.logger?.info("WHATSAPP","Received messages",{type:S,totalMessages:h.length}),this.onReceiveMessages?.(h,S);});}),W=await b();return await M(o.CONNECTION_TIMEOUT),W}async ensureSocketConnected(){return this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection().catch(e=>(this.onPreConnectionSendMessageFailed?.(e),null))),this.socket}async closeConnection(){this.socket&&(this.debug&&this.logger?.info("WHATSAPP","Closing connection"),this.socket.end(void 0),this.socket=null);}async clearAuthState(){if(await this.closeConnection(),this.mongoURL){let[e,t]=await this.getAuthCollection();this.debug&&this.logger?.info("WHATSAPP","Deleting auth state, required to scanning QR again"),await e?.deleteMany({}),await t?.close();}else this.fileAuthStateDirectoryPath&&ae.rmSync(this.fileAuthStateDirectoryPath,{recursive:true,force:true});}async resetConnection({pairingPhone:e,autoConnect:t=true}={}){await this.clearAuthState(),t&&(await M(o.CONNECTION_TIMEOUT),await this.startConnection({pairingPhone:e}));}isConnected(){return this.socket!==null&&this.socket.user!==void 0}};var B=class o extends w{constructor(e){super(e);}async sendTextMessage(e,t,n){await this.ensureSocketConnected();let r=o.formatPhoneNumberToWhatsappPattern(e),s={...n&&{quoted:{key:{id:n}}}};return this.socket?.sendMessage(r,{text:t},s)}async sendButtonsMessage(e,{subtitle:t,title:n,buttons:r}){if(!n||!r.length)throw new Error("sendButtonsMessage: No title or buttons required field found.");await this.ensureSocketConnected();let s=o.formatPhoneNumberToWhatsappPattern(e),a=r?.map(i=>{let g={display_text:i.label},u;switch(true){case !!i.url:u="cta_url",g.url=i.url;break;case !!i.copy:u="cta_copy",g.copy_code=i.copy;break;case !!i.tel:u="cta_call",g.phone_number=i.tel;break;case !!i.email:u="cta_email",g.email=i.email;break;case !!(i.reminderOn||i.reminderDate):u="cta_reminder";let{reminderOn:d,reminderDate:m}=i;g.reminder_name=i.reminderName,g.reminder_timestamp=m?Math.floor(+new Date(m)/1e3):Math.floor(Date.now()/1e3)+U(d??"0s");break;default:u="";break}return {name:u,buttonParamsJson:JSON.stringify(g)}}).filter(i=>i.name),c=generateWAMessageFromContent(s,{viewOnceMessage:{message:{interactiveMessage:WAProto.Message.InteractiveMessage.create({...n&&{body:WAProto.Message.InteractiveMessage.Body.create({text:n})},...t&&{footer:WAProto.Message.InteractiveMessage.Footer.create({text:t})},...!!a?.length&&{nativeFlowMessage:WAProto.Message.InteractiveMessage.NativeFlowMessage.create({buttons:a})}})}}},{userJid:s});return this.debug&&this.logger?.debug("WHATSAPP","send buttons message",{jid:s,footer:t,body:n,buttons:a}),this.socket?.relayMessage(s,c.message,{messageId:c.key.id})}async sendReplyButtonsMessage(e,{title:t,subtitle:n,buttons:r}){if(!t||!r.length)throw new Error("sendReplyButtonsMessage: No title or buttons required field found.");await this.ensureSocketConnected();let s=o.formatPhoneNumberToWhatsappPattern(e),a=r.filter(c=>c).map((c,i)=>typeof c=="string"?{buttonId:`id-${i}`,buttonText:{displayText:c},type:1}:{buttonId:`${c.id}`,buttonText:{displayText:c.label},type:1});return this.debug&&this.logger?.debug("WHATSAPP","send reply buttons message",{jid:s,text:t,footer:n,buttons:a}),this.socket?.sendMessage(s,{text:t,...n&&{footer:n},buttons:a})}};var v=class o extends B{constructor(e){super(e);}async sendFileFromStream(e,t,n){await this.ensureSocketConnected();let r=o.formatPhoneNumberToWhatsappPattern(e),s=t instanceof Buffer?t:await this.streamToBuffer(t),a=n.mimetype||this.getMimetypeFromFilename(n.filename),c=await this.createFileMessage(s,a,n),i={...n.replyToMessageId&&{quoted:{key:{id:n.replyToMessageId}}}};return this.socket?.sendMessage(r,c,i)}async streamToBuffer(e){return new Promise((t,n)=>{let r=[];e.on("data",s=>r.push(Buffer.from(s))),e.on("error",s=>n(s)),e.on("end",()=>t(Buffer.concat(r)));})}getMimetypeFromFilename(e){let t=e.split(".").pop()?.toLowerCase();return H[t||""]||"application/octet-stream"}async createFileMessage(e,t,n){let[r]=t.split("/");switch(r){case "image":return {image:e,caption:n.caption,mimetype:t,fileName:n.filename};case "video":return {video:e,caption:n.caption,mimetype:t,fileName:n.filename,gifPlayback:n.gifPlayback||false,jpegThumbnail:n.jpegThumbnail,...n.seconds&&{seconds:n.seconds}};case "audio":return n.ptt?{audio:e,mimetype:"audio/ogg; codecs=opus",ptt:true,...n.seconds&&{seconds:n.seconds}}:{audio:e,mimetype:t,fileName:n.filename,...n.seconds&&{seconds:n.seconds}};default:return {document:e,mimetype:t,fileName:n.filename,caption:n.caption,jpegThumbnail:n.jpegThumbnail}}}async sendImage(e,t,n={}){return this.sendFileFromStream(e,t,{filename:n.filename||"image.jpg",caption:n.caption,replyToMessageId:n.replyToMessageId})}async sendVideo(e,t,n={}){return this.sendFileFromStream(e,t,{filename:n.filename||"video.mp4",caption:n.caption,gifPlayback:n.gifPlayback,replyToMessageId:n.replyToMessageId,jpegThumbnail:n.jpegThumbnail})}async sendAudio(e,t,n={}){return this.sendFileFromStream(e,t,{filename:n.filename||"audio.mp3",mimetype:n.ptt?"audio/ogg; codecs=opus":"",ptt:n.ptt,seconds:n.seconds,replyToMessageId:n.replyToMessageId})}async sendDocument(e,t,n){return this.sendFileFromStream(e,t,{filename:n.filename,mimetype:n.mimetype,caption:n.caption,replyToMessageId:n.replyToMessageId,jpegThumbnail:n.jpegThumbnail})}async sendVoiceNote(e,t,n={}){return this.sendAudio(e,t,{ptt:true,seconds:n.seconds,replyToMessageId:n.replyToMessageId})}async sendSticker(e,t,n={}){await this.ensureSocketConnected();let r=o.formatPhoneNumberToWhatsappPattern(e),s=t instanceof Buffer?t:await this.streamToBuffer(t),a={...n.replyToMessageId&&{quoted:{key:{id:n.replyToMessageId}}}};return this.socket?.sendMessage(r,{sticker:s},a)}};var A=class o extends v{constructor(e){super(e);}async sendImageMessage(e,t,{caption:n="",filename:r}={}){await this.ensureSocketConnected();let s=o.formatPhoneNumberToWhatsappPattern(e),a=typeof t=="string"?await f(t):t;return this.debug&&this.logger?.debug("WHATSAPP","send image message",{jid:s,caption:n,filename:r}),await this.sendImage(s,a,{caption:n,...r&&{filename:r}})}async sendVideoMessage(e,t,{caption:n="",filename:r,sendAsGifPlayback:s=false}={}){await this.ensureSocketConnected();let a=o.formatPhoneNumberToWhatsappPattern(e),c=typeof t=="string"?await f(t):t;return this.debug&&this.logger?.debug("WHATSAPP","send video message",{jid:a,caption:n,filename:r,gifPlayback:s}),await this.sendVideo(a,c,{caption:n,gifPlayback:s,...r&&{filename:r}})}async sendFileMessage(e,t,{caption:n="",mimetype:r="application/vnd.openxmlformats-officedocument.wordprocessingml.document",replyToMessageId:s,jpegThumbnailSrc:a,filename:c}={}){await this.ensureSocketConnected();let i=o.formatPhoneNumberToWhatsappPattern(e),g=typeof t=="string"?await f(t):t,u;typeof a=="string"?u=await f(a):a instanceof ReadStream?u=await j(a):u=a;let d="mu-document";if(t instanceof ReadStream){let m=L(t);m&&(d=m);}else typeof t=="string"&&(d=basename(t));return this.debug&&this.logger?.debug("WHATSAPP","send file message",{jid:i,caption:n,mimetype:r,filename:d,replyToMessageId:s,includeJpegThumbnail:!!u}),await this.sendDocument(i,g,{caption:n,mimetype:r,filename:d,replyToMessageId:s,jpegThumbnail:u})}async sendAudioMessage(e,t,{filename:n,replyToMessageId:r,mimetype:s,seconds:a}={}){await this.ensureSocketConnected();let c=o.formatPhoneNumberToWhatsappPattern(e),i=typeof t=="string"?await f(t):t,g=a||await E(i,s).catch(()=>0);return this.debug&&this.logger?.debug("WHATSAPP","send audio message",{jid:c,mimetype:s,filename:n,seconds:g,replyToMessageId:r}),await this.sendAudio(c,i,{...n&&{filename:n},...s&&{mimetype:s},...g&&{seconds:g},...r&&{replyToMessageId:r}})}async sendStickerMessage(e,t,{replyToMessageId:n}={}){await this.ensureSocketConnected();let r=o.formatPhoneNumberToWhatsappPattern(e),s=typeof t=="string"?await f(t):t;this.debug&&this.logger?.debug("WHATSAPP","send sticker message",{jid:r,replyToMessageId:n}),await this.sendSticker(r,s,{replyToMessageId:n});}};var _=class extends A{constructor(e){super(e);}};
|
|
2
|
-
export{
|
|
1
|
+
import ge,{ReadStream}from'fs';import ae,{generateWAMessageFromContent,WAProto,useMultiFileAuthState,makeCacheableSignalKeyStore,DisconnectReason,initAuthCreds}from'@fadzzzslebew/baileys';import U from'ms';import V from'qrcode';import {MongoClient}from'mongodb';import pe from'pino';import {parseStream,parseBuffer}from'music-metadata';import {basename}from'path';var E={replacer:(o,e)=>Buffer.isBuffer(e)||e instanceof Uint8Array||e?.type==="Buffer"?{type:"Buffer",data:Buffer.from(e?.data||e).toString("base64")}:e,reviver:(o,e)=>{if(typeof e=="object"&&e&&(e.buffer===true||e.type==="Buffer")){let t=e.data||e.value;return typeof t=="string"?Buffer.from(t,"base64"):Buffer.from(t||[])}return e}},_=async o=>{let e=(n,a)=>{let i={$set:{...JSON.parse(JSON.stringify(n,E.replacer))}};return o.updateOne({_id:a},i,{upsert:true})},t=async n=>{try{let a=JSON.stringify(await o.findOne({_id:n}));return JSON.parse(a,E.reviver)}catch{return null}},r=async n=>{try{await o.deleteOne({_id:n});}catch{}},s=await t("creds")||initAuthCreds();return {state:{creds:s,keys:{get:async(n,a)=>{let u={};return await Promise.all(a.map(async i=>{let c=await t(`${n}-${i}`);n==="app-state-sync-key"&&c&&(c=WAProto.Message.AppStateSyncKeyData.fromObject(c)),u[i]=c;})),u},set:async n=>{let a=[];for(let u of Object.keys(n))for(let i of Object.keys(n[u])){let c=n[u][i],g=`${u}-${i}`;a.push(c?e(c,g):r(g));}await Promise.all(a);}}},saveCreds:()=>e(s,"creds")}},F=_;var H=o=>U(o)/1e3;async function l(o){let t=await(await fetch(o)).arrayBuffer();return Buffer.from(t)}async function se(o,e){try{let t=await parseStream(o,{mimeType:e||"audio/mpeg"});return Math.floor(t.format.duration||0)}catch(t){throw console.error("Error parsing stream:",t),t}finally{o.destroyed||o.destroy();}}async function ne(o,e){try{let t=await parseBuffer(o,e||"audio/mpeg").catch(()=>null);return t?Math.floor(t.format.duration||0):0}catch(t){throw console.error("Error parsing buffer:",t),t}}async function q(o,e){return o instanceof ReadStream?se(o,e):ne(o,e)}async function L(o){let e=[];for await(let t of o)e.push(t);return Buffer.concat(e)}function j(o){if(o.path){let e=o.path.toString();return basename(e)}}var T=o=>new Promise(e=>setTimeout(e,U(o))),J={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",bmp:"image/bmp",svg:"image/svg+xml",mp4:"video/mp4",avi:"video/x-msvideo",mov:"video/quicktime",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",opus:"audio/opus",aac:"audio/aac",m4a:"audio/mp4",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed"};var Q=pe({level:"silent"}),y=class o{fileAuthStateDirectoryPath;mongoURL;mongoCollection="whatsapp-auth";logger;debug;printQRInTerminal;pairingPhone;customPairingCode;appName;onPreConnectionSendMessageFailed;onOpen;onClose;onQR;onConnectionStatusChange;onReceiveMessages;static DEFAULT_COUNTRY_CODE="972";static CONNECTION_TIMEOUT="2s";static formatPhoneNumber(e,t=o.DEFAULT_COUNTRY_CODE){if(e.endsWith("@s.whatsapp.net"))return e;let r=e.replace(/[^0-9]/g,"");return r.startsWith("05")&&(r=r.substring(1)),r.startsWith(t)||(r=t+r),r}static formatPhoneNumberToWhatsappPattern(e,t=o.DEFAULT_COUNTRY_CODE){if(e.endsWith("@s.whatsapp.net"))return e;let r=o.formatPhoneNumber(e,t);return r=`${r}@s.whatsapp.net`,r.replace(/:\d+@/,"@")}static getWhatsappPhoneLink({phone:e,message:t,countryCode:r=o.DEFAULT_COUNTRY_CODE}){let s=this.formatPhoneNumber(e,r),n=t?`?text=${encodeURI(t)}`:"";return `https://wa.me/${s}${n}`}static async qrToImage(e,t={}){return V.toDataURL(e,{errorCorrectionLevel:"H",width:400,margin:2,...t})}static async qrToTerminalString(e,t={}){return V.toString(e,{type:"terminal",small:true,...t})}static randomPairingCode(e,t=8){if(!e.includes("[")&&e.length===t)return e;let r="",s=[],n=u=>{let i=[];for(let c=0;c<u.length;c++)if(u[c+1]==="-"&&u[c+2]){let g=u.charCodeAt(c),p=u.charCodeAt(c+2);for(let d=g;d<=p;d++)i.push(String.fromCharCode(d));c+=2;}else i.push(u[c]);return i};for(let u=0;u<e.length&&r.length<t;u++){let i=e[u];if(i==="["){let c=e.indexOf("]",u),g=e.slice(u+1,c);s=n(g),u=c;}else r+=i;}for(;r.length<t&&s.length;)r+=s[Math.floor(Math.random()*s.length)];let a=r.toUpperCase();return a.padEnd(t,a)}static instances=new Map;static getInstance(e){let t=o.buildSocketKey(e);return o.instances.has(t)||new o(e),o.instances.get(t)}static clearInstance(e){e?o.instances.delete(e):o.instances.clear();}constructor(e){let{fileAuthStateDirectoryPath:t,mongoURL:r,mongoCollection:s="whatsapp-auth",logger:n,onOpen:a,onClose:u,onQR:i,onReceiveMessages:c,onConnectionStatusChange:g,debug:p,printQRInTerminal:d,pairingPhone:D,customPairingCode:w,onPreConnectionSendMessageFailed:x,appName:P}=e;this.appName=P,this.mongoURL=r,this.fileAuthStateDirectoryPath=t,this.mongoCollection=s,this.logger=n,this.debug=p,this.printQRInTerminal=d,this.pairingPhone=D,this.customPairingCode=w,this.onPreConnectionSendMessageFailed=x,this.onConnectionStatusChange=g,this.onReceiveMessages=c,this.onOpen=a,this.onClose=u,this.onQR=i,o.instances.has(this.socketKey)&&(this.socket=o.instances.get(this.socketKey));}async getLatestWhatsAppVersion(){try{let e=["https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json","https://raw.githubusercontent.com/whiskeysockets/baileys/master/src/Defaults/baileys-version.json"];for(let t of e)try{let r=await fetch(t);if(r.ok)return (await r.json()).version}catch{continue}return console.log("Could not fetch version, using fallback"),[2,3e3,1015901307]}catch(e){return console.error("Error fetching version:",e),[2,3e3,1015901307]}}async getAuthCollection(){if(!this.mongoURL)return [];let e=new MongoClient(this.mongoURL);return await e.connect(),[e.db().collection(this.mongoCollection),e]}async authenticate(){if(!this.mongoURL&&!this.fileAuthStateDirectoryPath)throw new Error("fileAuthStateDirectoryPath/MongoURL is missing");if(!this.mongoURL){let{saveCreds:n,state:a}=await useMultiFileAuthState(this.fileAuthStateDirectoryPath);return {auth:a,saveCreds:n}}let[e]=await this.getAuthCollection(),{state:t,saveCreds:r}=await F(e);return {auth:{creds:t.creds,keys:makeCacheableSignalKeyStore(t.keys,Q)},saveCreds:r}}static buildSocketKey(e){return e.appName||e.pairingPhone||e.mongoCollection||e.fileAuthStateDirectoryPath||"default"}get socketKey(){return this.appName||this.pairingPhone||this.mongoCollection||this.fileAuthStateDirectoryPath||"default"}get socket(){return o.instances.get(this.socketKey)??null}set socket(e){o.instances.set(this.socketKey,e);}async startConnection({options:e,connectionAttempts:t=3,onOpen:r=this.onOpen,onClose:s=this.onClose,onQR:n=this.onQR,onConnectionStatusChange:a=this.onConnectionStatusChange,pairingPhone:u,debug:i}={}){let c=u??this.pairingPhone,{saveCreds:g,auth:p}=await this.authenticate(),d=i===void 0?this.debug:i,D=await this.getLatestWhatsAppVersion(),w=async()=>new Promise(P=>{let b=ae({version:D,logger:Q,browser:[this.appName||"baileys","1.0.0",""],syncFullHistory:true,shouldIgnoreJid:h=>h.includes("@newsletter"),...e,printQRInTerminal:false,auth:p});b.ev.on("connection.update",async h=>{let{connection:k,lastDisconnect:N,qr:M}=h;if(M){if(d&&this.logger?.info("WHATSAPP","QR Code received",{qr:M}),this.printQRInTerminal){let Y=await o.qrToTerminalString(M,{small:true}).catch(()=>null);console.log(Y);}this.customPairingCode?o.randomPairingCode(this.customPairingCode):void 0;let S=c?o.formatPhoneNumber(c):null,A=S?await b.requestPairingCode(S):null;d&&this.printQRInTerminal&&this.logger?.info("WHATSAPP","QR Pairing Code",{code:A,pairingPhone:S}),await n?.(M,A);}switch(k){case "connecting":{d&&this.logger?.debug("WHATSAPP","Connecting..."),a?.("connecting");break}case "open":{d&&this.logger?.info("WHATSAPP","Connection opened successfully!"),this.socket=b,await r?.(),a?.("open"),P(this.socket);break}case "close":{let O=t-- >0&&N?.error?.output?.statusCode!==DisconnectReason.loggedOut,S=N?.error?.output?.statusCode,A=N?.error?.message;d&&this.logger?.info("WHATSAPP","Connection closed",{statusCode:S,errorMessage:A,shouldReconnect:O}),O&&t?(d&&this.logger?.info("WHATSAPP","Reconnecting..."),await T(o.CONNECTION_TIMEOUT),P(w())):(d&&this.logger?.warn("WHATSAPP","Logged out, clearing auth state"),await s?.(),this.socket=null,P(this.socket)),a?.("close");break}}}),b.ev.on("creds.update",g),this.onReceiveMessages&&typeof this.onReceiveMessages=="function"&&b.ev.on("messages.upsert",async({messages:h,type:k})=>{this.logger?.info("WHATSAPP","Received messages",{type:k,totalMessages:h.length}),this.onReceiveMessages?.(h,k);});}),x=await w();return await T(o.CONNECTION_TIMEOUT),x}async ensureSocketConnected(){return this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection().catch(e=>(this.onPreConnectionSendMessageFailed?.(e),null))),this.socket}async closeConnection(){this.socket&&(this.debug&&this.logger?.info("WHATSAPP","Closing connection"),this.socket.end(void 0),this.socket=null);}async clearAuthState(){if(await this.closeConnection(),this.mongoURL){let[e,t]=await this.getAuthCollection();this.debug&&this.logger?.info("WHATSAPP","Deleting auth state, required to scanning QR again"),await e?.deleteMany({}),await t?.close();}else this.fileAuthStateDirectoryPath&&ge.rmSync(this.fileAuthStateDirectoryPath,{recursive:true,force:true});}async resetConnection({pairingPhone:e,autoConnect:t=true}={}){await this.clearAuthState(),t&&(await T(o.CONNECTION_TIMEOUT),await this.startConnection({pairingPhone:e}));}isConnected(){return !!this.socket?.user}};var I=class o extends y{constructor(e){super(e);}async sendTextMessage(e,t,r){await this.ensureSocketConnected();let s=o.formatPhoneNumberToWhatsappPattern(e),n={...r&&{quoted:{key:{id:r}}}};return this.socket?.sendMessage(s,{text:t},n)}async sendButtonsMessage(e,{subtitle:t,title:r,buttons:s}){if(!r||!s.length)throw new Error("sendButtonsMessage: No title or buttons required field found.");await this.ensureSocketConnected();let n=o.formatPhoneNumberToWhatsappPattern(e),a=s?.map(i=>{let c={display_text:i.label},g;switch(true){case !!i.url:g="cta_url",c.url=i.url;break;case !!i.copy:g="cta_copy",c.copy_code=i.copy;break;case !!i.tel:g="cta_call",c.phone_number=i.tel;break;case !!i.email:g="cta_email",c.email=i.email;break;case !!(i.reminderOn||i.reminderDate):g="cta_reminder";let{reminderOn:p,reminderDate:d}=i;c.reminder_name=i.reminderName,c.reminder_timestamp=d?Math.floor(+new Date(d)/1e3):Math.floor(Date.now()/1e3)+H(p??"0s");break;default:g="";break}return {name:g,buttonParamsJson:JSON.stringify(c)}}).filter(i=>i.name),u=generateWAMessageFromContent(n,{viewOnceMessage:{message:{interactiveMessage:WAProto.Message.InteractiveMessage.create({...r&&{body:WAProto.Message.InteractiveMessage.Body.create({text:r})},...t&&{footer:WAProto.Message.InteractiveMessage.Footer.create({text:t})},...!!a?.length&&{nativeFlowMessage:WAProto.Message.InteractiveMessage.NativeFlowMessage.create({buttons:a})}})}}},{userJid:n});return this.debug&&this.logger?.debug("WHATSAPP","send buttons message",{jid:n,footer:t,body:r,buttons:a}),this.socket?.relayMessage(n,u.message,{messageId:u.key.id})}async sendReplyButtonsMessage(e,{title:t,subtitle:r,buttons:s}){if(!t||!s.length)throw new Error("sendReplyButtonsMessage: No title or buttons required field found.");await this.ensureSocketConnected();let n=o.formatPhoneNumberToWhatsappPattern(e),a=s.filter(u=>u).map((u,i)=>typeof u=="string"?{buttonId:`id-${i}`,buttonText:{displayText:u},type:1}:{buttonId:`${u.id}`,buttonText:{displayText:u.label},type:1});return this.debug&&this.logger?.debug("WHATSAPP","send reply buttons message",{jid:n,text:t,footer:r,buttons:a}),this.socket?.sendMessage(n,{text:t,...r&&{footer:r},buttons:a})}};var v=class o extends I{constructor(e){super(e);}async sendFileFromStream(e,t,r){await this.ensureSocketConnected();let s=o.formatPhoneNumberToWhatsappPattern(e),n=t instanceof Buffer?t:await this.streamToBuffer(t),a=r.mimetype||this.getMimetypeFromFilename(r.filename),u=await this.createFileMessage(n,a,r),i={...r.replyToMessageId&&{quoted:{key:{id:r.replyToMessageId}}}};return this.socket?.sendMessage(s,u,i)}async streamToBuffer(e){return new Promise((t,r)=>{let s=[];e.on("data",n=>s.push(Buffer.from(n))),e.on("error",n=>r(n)),e.on("end",()=>t(Buffer.concat(s)));})}getMimetypeFromFilename(e){let t=e.split(".").pop()?.toLowerCase();return J[t||""]||"application/octet-stream"}async createFileMessage(e,t,r){let[s]=t.split("/");switch(s){case "image":return {image:e,caption:r.caption,mimetype:t,fileName:r.filename};case "video":return {video:e,caption:r.caption,mimetype:t,fileName:r.filename,gifPlayback:r.gifPlayback||false,jpegThumbnail:r.jpegThumbnail,...r.seconds&&{seconds:r.seconds}};case "audio":return r.ptt?{audio:e,mimetype:"audio/ogg; codecs=opus",ptt:true,...r.seconds&&{seconds:r.seconds}}:{audio:e,mimetype:t,fileName:r.filename,...r.seconds&&{seconds:r.seconds}};default:return {document:e,mimetype:t,fileName:r.filename,caption:r.caption,jpegThumbnail:r.jpegThumbnail}}}async sendImage(e,t,r={}){return this.sendFileFromStream(e,t,{filename:r.filename||"image.jpg",caption:r.caption,replyToMessageId:r.replyToMessageId})}async sendVideo(e,t,r={}){return this.sendFileFromStream(e,t,{filename:r.filename||"video.mp4",caption:r.caption,gifPlayback:r.gifPlayback,replyToMessageId:r.replyToMessageId,jpegThumbnail:r.jpegThumbnail})}async sendAudio(e,t,r={}){return this.sendFileFromStream(e,t,{filename:r.filename||"audio.mp3",mimetype:r.ptt?"audio/ogg; codecs=opus":"",ptt:r.ptt,seconds:r.seconds,replyToMessageId:r.replyToMessageId})}async sendDocument(e,t,r){return this.sendFileFromStream(e,t,{filename:r.filename,mimetype:r.mimetype,caption:r.caption,replyToMessageId:r.replyToMessageId,jpegThumbnail:r.jpegThumbnail})}async sendVoiceNote(e,t,r={}){return this.sendAudio(e,t,{ptt:true,seconds:r.seconds,replyToMessageId:r.replyToMessageId})}async sendSticker(e,t,r={}){await this.ensureSocketConnected();let s=o.formatPhoneNumberToWhatsappPattern(e),n=t instanceof Buffer?t:await this.streamToBuffer(t),a={...r.replyToMessageId&&{quoted:{key:{id:r.replyToMessageId}}}};return this.socket?.sendMessage(s,{sticker:n},a)}};var G=class o extends v{constructor(e){super(e);}async sendImageMessage(e,t,{caption:r="",filename:s}={}){await this.ensureSocketConnected();let n=o.formatPhoneNumberToWhatsappPattern(e),a=typeof t=="string"?await l(t):t;return this.debug&&this.logger?.debug("WHATSAPP","send image message",{jid:n,caption:r,filename:s}),await this.sendImage(n,a,{caption:r,...s&&{filename:s}})}async sendVideoMessage(e,t,{caption:r="",filename:s,sendAsGifPlayback:n=false}={}){await this.ensureSocketConnected();let a=o.formatPhoneNumberToWhatsappPattern(e),u=typeof t=="string"?await l(t):t;return this.debug&&this.logger?.debug("WHATSAPP","send video message",{jid:a,caption:r,filename:s,gifPlayback:n}),await this.sendVideo(a,u,{caption:r,gifPlayback:n,...s&&{filename:s}})}async sendFileMessage(e,t,{caption:r="",mimetype:s="application/vnd.openxmlformats-officedocument.wordprocessingml.document",replyToMessageId:n,jpegThumbnailSrc:a,filename:u}={}){await this.ensureSocketConnected();let i=o.formatPhoneNumberToWhatsappPattern(e),c=typeof t=="string"?await l(t):t,g;typeof a=="string"?g=await l(a):a instanceof ReadStream?g=await L(a):g=a;let p="mu-document";if(t instanceof ReadStream){let d=j(t);d&&(p=d);}else typeof t=="string"&&(p=basename(t));return this.debug&&this.logger?.debug("WHATSAPP","send file message",{jid:i,caption:r,mimetype:s,filename:p,replyToMessageId:n,includeJpegThumbnail:!!g}),await this.sendDocument(i,c,{caption:r,mimetype:s,filename:p,replyToMessageId:n,jpegThumbnail:g})}async sendAudioMessage(e,t,{filename:r,replyToMessageId:s,mimetype:n,seconds:a}={}){await this.ensureSocketConnected();let u=o.formatPhoneNumberToWhatsappPattern(e),i=typeof t=="string"?await l(t):t,c=a||await q(i,n).catch(()=>0);return this.debug&&this.logger?.debug("WHATSAPP","send audio message",{jid:u,mimetype:n,filename:r,seconds:c,replyToMessageId:s}),await this.sendAudio(u,i,{...r&&{filename:r},...n&&{mimetype:n},...c&&{seconds:c},...s&&{replyToMessageId:s}})}async sendStickerMessage(e,t,{replyToMessageId:r}={}){await this.ensureSocketConnected();let s=o.formatPhoneNumberToWhatsappPattern(e),n=typeof t=="string"?await l(t):t;this.debug&&this.logger?.debug("WHATSAPP","send sticker message",{jid:s,replyToMessageId:r}),await this.sendSticker(s,n,{replyToMessageId:r});}};var K=class extends G{constructor(e){super(e);}};var W=class o extends y{static formatGroupId(e){return e.endsWith("@g.us")?e:`${e.replace(/@s\.whatsapp\.net|@g\.us/g,"")}@g.us`}static isGroupId(e){return e.endsWith("@g.us")}constructor(e){super(e);}async createGroup({name:e,participants:t,description:r}){if(!e)throw new Error("createGroup: Group name is required.");await this.ensureSocketConnected();let s=(t??[]).map(a=>o.formatPhoneNumberToWhatsappPattern(a));if(s.length===0){let a=this.socket?.user?.id;if(!a)throw new Error("createGroup: Could not get bot user ID. Make sure socket is connected.");let u=o.formatPhoneNumberToWhatsappPattern(a);s.push(u),this.debug&&this.logger?.debug("WHATSAPP","No participants provided, creating group with self only",{selfJid:a});}this.debug&&this.logger?.debug("WHATSAPP","Creating group",{name:e,participantsCount:s.length});let n=await this.socket?.groupCreate(e,s);if(r&&n?.id){let a=o.formatGroupId(n.id);await this.updateGroupDescription(a,r);}return n}async updateGroupName(e,t){if(!e||!t)throw new Error("updateGroupName: Group ID and new name are required.");await this.ensureSocketConnected();let r=o.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Updating group name",{groupId:r,newName:t}),this.socket?.groupUpdateSubject(r,t)}async updateGroupDescription(e,t){if(!e)throw new Error("updateGroupDescription: Group ID is required.");await this.ensureSocketConnected();let r=o.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Updating group description",{groupId:r}),this.socket?.groupUpdateDescription(r,t||"")}async updateGroupSettings(e,t){if(!e||!t)throw new Error("updateGroupSettings: Group ID and setting are required.");await this.ensureSocketConnected();let r=o.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Updating group settings",{groupId:r,setting:t}),this.socket?.groupSettingUpdate(r,t)}async addParticipants(e,t){if(!e)throw new Error("addParticipants: Group ID is required.");if(t?.length)return;await this.ensureSocketConnected();let r=o.formatGroupId(e),s=t.map(n=>o.formatPhoneNumberToWhatsappPattern(n));return this.debug&&this.logger?.debug("WHATSAPP","Adding participants to group",{groupId:r,participantsCount:s.length}),this.socket?.groupParticipantsUpdate(r,s,"add")}async removeParticipants(e,t){if(!e)throw new Error("removeParticipants: Group ID is required.");if(!t?.length)return;await this.ensureSocketConnected();let r=o.formatGroupId(e),s=t.map(n=>o.formatPhoneNumberToWhatsappPattern(n));return this.debug&&this.logger?.debug("WHATSAPP","Removing participants from group",{groupId:r,participantsCount:s.length}),this.socket?.groupParticipantsUpdate(r,s,"remove")}async promoteToAdmin(e,t){if(!e)throw new Error("promoteToAdmin: Group ID is required.");if(!t?.length)return;await this.ensureSocketConnected();let r=o.formatGroupId(e),s=t.map(n=>o.formatPhoneNumberToWhatsappPattern(n));return this.debug&&this.logger?.debug("WHATSAPP","Promoting participants to admin",{groupId:r,participantsCount:s.length}),this.socket?.groupParticipantsUpdate(r,s,"promote")}async demoteFromAdmin(e,t){if(!e)throw new Error("demoteFromAdmin: Group ID is required.");if(!t?.length)return;await this.ensureSocketConnected();let r=o.formatGroupId(e),s=t.map(n=>o.formatPhoneNumberToWhatsappPattern(n));return this.debug&&this.logger?.debug("WHATSAPP","Demoting participants from admin",{groupId:r,participantsCount:s.length}),this.socket?.groupParticipantsUpdate(r,s,"demote")}async leaveGroup(e){if(!e)throw new Error("leaveGroup: Group ID is required.");await this.ensureSocketConnected();let t=o.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Leaving group",{groupId:t}),this.socket?.groupLeave(t)}async getGroupMetadata(e){if(!e)throw new Error("getGroupMetadata: Group ID is required.");await this.ensureSocketConnected();let t=o.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Fetching group metadata",{groupId:t}),this.socket?.groupMetadata(t)}async getAllGroups(){await this.ensureSocketConnected(),this.debug&&this.logger?.debug("WHATSAPP","Fetching all groups");let e=await this.socket?.groupFetchAllParticipating();return e?Object.values(e):[]}async getGroupInviteCode(e){if(!e)throw new Error("getGroupInviteCode: Group ID is required.");await this.ensureSocketConnected();let t=o.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Fetching group invite code",{groupId:t}),this.socket?.groupInviteCode(t)}async revokeGroupInviteCode(e){if(!e)throw new Error("revokeGroupInviteCode: Group ID is required.");await this.ensureSocketConnected();let t=o.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Revoking group invite code",{groupId:t}),this.socket?.groupRevokeInvite(t)}async joinGroupViaInvite(e){if(!e)throw new Error("joinGroupViaInvite: Invite code is required.");return await this.ensureSocketConnected(),this.debug&&this.logger?.debug("WHATSAPP","Joining group via invite",{inviteCode:e}),this.socket?.groupAcceptInvite(e)}async getGroupInfoFromInvite(e){if(!e)throw new Error("getGroupInfoFromInvite: Invite code is required.");return await this.ensureSocketConnected(),this.debug&&this.logger?.debug("WHATSAPP","Fetching group info from invite",{inviteCode:e}),this.socket?.groupGetInviteInfo(e)}async updateGroupProfilePicture(e,t){if(!e||!t)throw new Error("updateGroupProfilePicture: Group ID and image buffer are required.");await this.ensureSocketConnected();let r=o.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Updating group profile picture",{groupId:r}),this.socket?.updateProfilePicture(r,t)}async removeGroupProfilePicture(e){if(!e)throw new Error("removeGroupProfilePicture: Group ID is required.");await this.ensureSocketConnected();let t=o.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Removing group profile picture",{groupId:t}),this.socket?.removeProfilePicture(t)}async getGroupProfilePicture(e,t=false){if(!e)throw new Error("getGroupProfilePicture: Group ID is required.");await this.ensureSocketConnected();let r=o.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Fetching group profile picture",{groupId:r,highRes:t}),this.socket?.profilePictureUrl(r,t?"image":"preview")}};var R=class o extends W{constructor(e){super(e);}async sendTextMessage(e,t,r){if(!e||!t)throw new Error("sendTextMessage: Group ID and text are required.");await this.ensureSocketConnected();let s=o.formatGroupId(e),n={};return r?.replyToMessageId&&(n.quoted={key:{id:r.replyToMessageId}}),this.debug&&this.logger?.debug("WHATSAPP","Sending text message to group",{groupId:s,textLength:t.length,hasMentions:!!r?.mentions?.length}),this.socket?.sendMessage(s,{text:t},n)}async sendButtonsMessage(e,{title:t,subtitle:r,buttons:s}){if(!e||!t||!s?.length)throw new Error("sendButtonsMessage: Group ID, title, and buttons are required.");await this.ensureSocketConnected();let n=o.formatGroupId(e),a=s?.map(i=>{let c={display_text:i.label},g;switch(true){case !!i.url:g="cta_url",c.url=i.url;break;case !!i.copy:g="cta_copy",c.copy_code=i.copy;break;case !!i.tel:g="cta_call",c.phone_number=i.tel;break;default:g="";break}return {name:g,buttonParamsJson:JSON.stringify(c)}}).filter(i=>i.name),u=generateWAMessageFromContent(n,{viewOnceMessage:{message:{interactiveMessage:WAProto.Message.InteractiveMessage.create({body:WAProto.Message.InteractiveMessage.Body.create({text:t}),...r&&{footer:WAProto.Message.InteractiveMessage.Footer.create({text:r})},nativeFlowMessage:WAProto.Message.InteractiveMessage.NativeFlowMessage.create({buttons:a})})}}},{userJid:n});return this.debug&&this.logger?.debug("WHATSAPP","Sending buttons message to group",{groupId:n,title:t,buttonsCount:a.length}),this.socket?.relayMessage(n,u.message,{messageId:u.key.id})}async sendReplyButtonsMessage(e,{title:t,subtitle:r,buttons:s,mentions:n}){if(!e||!t||!s?.length)throw new Error("sendReplyButtonsMessage: Group ID, title, and buttons are required.");await this.ensureSocketConnected();let a=o.formatGroupId(e),u=s.filter(c=>c).map((c,g)=>typeof c=="string"?{buttonId:`id-${g}`,buttonText:{displayText:c},type:1}:{buttonId:`${c.id}`,buttonText:{displayText:c.label},type:1}),i={text:t,buttons:u,...r&&{footer:r}};return n?.length&&(i.mentions=n.map(c=>o.formatPhoneNumberToWhatsappPattern(c))),this.debug&&this.logger?.debug("WHATSAPP","Sending reply buttons message to group",{groupId:a,title:t,buttonsCount:u.length}),this.socket?.sendMessage(a,i)}async sendImageMessage(e,t,{caption:r,mentions:s}={}){if(!e||!t)throw new Error("sendImage: Group ID and image buffer are required.");await this.ensureSocketConnected();let n=o.formatGroupId(e),a={image:t,...r&&{caption:r}};return s?.length&&(a.mentions=s.map(u=>o.formatPhoneNumberToWhatsappPattern(u))),this.debug&&this.logger?.debug("WHATSAPP","Sending image to group",{groupId:n,hasCaption:!!r}),this.socket?.sendMessage(n,a)}async sendVideoMessage(e,t,r,s){if(!e||!t)throw new Error("sendVideo: Group ID and video buffer are required.");await this.ensureSocketConnected();let n=o.formatGroupId(e),a={video:t,...r&&{caption:r}};return s?.mentions?.length&&(a.mentions=s.mentions.map(u=>o.formatPhoneNumberToWhatsappPattern(u))),this.debug&&this.logger?.debug("WHATSAPP","Sending video to group",{groupId:n,hasCaption:!!r}),this.socket?.sendMessage(n,a)}async sendAudioMessage(e,t,r){if(!e||!t)throw new Error("sendAudio: Group ID and audio buffer are required.");await this.ensureSocketConnected();let s=o.formatGroupId(e),n={audio:t,ptt:r?.ptt??false};return r?.mentions?.length&&(n.mentions=r.mentions.map(a=>o.formatPhoneNumberToWhatsappPattern(a))),this.debug&&this.logger?.debug("WHATSAPP","Sending audio to group",{groupId:s,isPTT:n.ptt}),this.socket?.sendMessage(s,n)}async sendDocumentMessage(e,t,r,s,n){if(!e||!t||!r)throw new Error("sendDocument: Group ID, document buffer, and fileName are required.");await this.ensureSocketConnected();let a=o.formatGroupId(e),u={document:t,fileName:r,...s&&{mimetype:s}};return n?.mentions?.length&&(u.mentions=n.mentions.map(i=>o.formatPhoneNumberToWhatsappPattern(i))),this.debug&&this.logger?.debug("WHATSAPP","Sending document to group",{groupId:a,fileName:r}),this.socket?.sendMessage(a,u)}async sendLocationMessage(e,t,r,s,n){if(!e||t===void 0||r===void 0)throw new Error("sendLocation: Group ID, latitude, and longitude are required.");await this.ensureSocketConnected();let a=o.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Sending location to group",{groupId:a,latitude:t,longitude:r}),this.socket?.sendMessage(a,{location:{degreesLatitude:t,degreesLongitude:r,...s&&{name:s},...n&&{address:n}}})}async sendMentionAll(e,t){if(!e||!t)throw new Error("sendMentionAll: Group ID and text are required.");await this.ensureSocketConnected();let r=o.formatGroupId(e),s=await this.getGroupMetadata(r);if(!s)throw new Error("Could not fetch group metadata");let n=s.participants.map(a=>a.id);return this.debug&&this.logger?.debug("WHATSAPP","Sending mention all message to group",{groupId:r,participantsCount:n.length}),this.socket?.sendMessage(r,{text:t,mentions:n})}async sendReactionMessage(e,t,r){if(!e||!t||!r)throw new Error("sendReaction: Group ID, message ID, and emoji are required.");await this.ensureSocketConnected();let s=o.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Sending reaction to group message",{groupId:s,messageId:t,emoji:r}),this.socket?.sendMessage(s,{react:{text:r,key:{id:t,remoteJid:s}}})}async deleteGroupMessage(e,t){if(!e||!t)throw new Error("deleteGroupMessage: Group ID and message ID are required.");await this.ensureSocketConnected();let r=o.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Deleting message in group",{groupId:r,messageId:t}),this.socket?.sendMessage(r,{delete:{id:t,remoteJid:r,fromMe:true}})}};var z=class extends R{constructor(e){super(e);}};
|
|
2
|
+
export{K as WhatsappSocket,z as WhatsappSocketGroup};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|