@hdriel/whatsapp-socket 1.2.0 → 1.2.1
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/dist/decs-u-xMMNZ4.d.cts +136 -0
- package/dist/decs-u-xMMNZ4.d.ts +136 -0
- package/dist/group.cjs +3 -0
- package/dist/group.cjs.map +1 -0
- package/dist/group.d.cts +168 -0
- package/dist/group.d.ts +168 -0
- package/dist/group.js +3 -0
- package/dist/group.js.map +1 -0
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -390
- package/dist/index.d.ts +8 -390
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/private.cjs +3 -0
- package/dist/private.cjs.map +1 -0
- package/dist/private.d.cts +131 -0
- package/dist/private.d.ts +131 -0
- package/dist/private.js +3 -0
- package/dist/private.js.map +1 -0
- package/package.json +17 -5
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { WAMessage, MessageUpsertType, WASocket, UserFacingSocketConfig } from '@fadzzzslebew/baileys';
|
|
2
|
+
import { StringValue } from 'ms';
|
|
3
|
+
import { Logger } from 'stack-trace-logger';
|
|
4
|
+
|
|
5
|
+
type WhatsappSocketBaseProps = ({
|
|
6
|
+
mongoURL: string;
|
|
7
|
+
fileAuthStateDirectoryPath?: string | undefined;
|
|
8
|
+
} | {
|
|
9
|
+
mongoURL?: string | undefined;
|
|
10
|
+
fileAuthStateDirectoryPath: string;
|
|
11
|
+
}) & {
|
|
12
|
+
appName?: string;
|
|
13
|
+
logger?: Logger;
|
|
14
|
+
mongoCollection?: string;
|
|
15
|
+
onOpen?: () => Promise<void> | void;
|
|
16
|
+
onClose?: () => Promise<void> | void;
|
|
17
|
+
onConnectionStatusChange?: (connectionStatus: 'connecting' | 'close' | 'open') => Promise<void> | void;
|
|
18
|
+
onReceiveMessages?: (messages: WAMessage[], type: MessageUpsertType) => Promise<void> | void;
|
|
19
|
+
onPreConnectionSendMessageFailed?: (error: Error | string) => Promise<void> | void;
|
|
20
|
+
onQR?: (qr: string, code?: string | null) => Promise<void> | void;
|
|
21
|
+
debug?: boolean;
|
|
22
|
+
printQRInTerminal?: boolean;
|
|
23
|
+
pairingPhone?: string;
|
|
24
|
+
customPairingCode?: string;
|
|
25
|
+
};
|
|
26
|
+
declare class WhatsappSocketBase {
|
|
27
|
+
protected readonly fileAuthStateDirectoryPath?: string;
|
|
28
|
+
protected readonly mongoURL?: string;
|
|
29
|
+
protected readonly mongoCollection: string;
|
|
30
|
+
protected readonly logger?: Logger;
|
|
31
|
+
protected readonly debug?: boolean;
|
|
32
|
+
protected readonly printQRInTerminal?: boolean;
|
|
33
|
+
protected readonly pairingPhone?: string;
|
|
34
|
+
protected readonly customPairingCode?: string;
|
|
35
|
+
protected readonly appName?: string;
|
|
36
|
+
private readonly onPreConnectionSendMessageFailed?;
|
|
37
|
+
private onOpen?;
|
|
38
|
+
private onClose?;
|
|
39
|
+
private onQR?;
|
|
40
|
+
private onConnectionStatusChange?;
|
|
41
|
+
private readonly onReceiveMessages?;
|
|
42
|
+
static DEFAULT_COUNTRY_CODE: string;
|
|
43
|
+
static CONNECTION_TIMEOUT: StringValue;
|
|
44
|
+
static formatPhoneNumber(phone: string, countryCode?: string): string;
|
|
45
|
+
static formatPhoneNumberToWhatsappPattern(phone: string, countryCode?: string): string;
|
|
46
|
+
static getWhatsappPhoneLink({ phone, message, countryCode, }: {
|
|
47
|
+
phone: string;
|
|
48
|
+
countryCode?: string;
|
|
49
|
+
message?: string;
|
|
50
|
+
}): string;
|
|
51
|
+
static qrToImage(qr: string, options?: {
|
|
52
|
+
errorCorrectionLevel?: 'H' | 'L' | 'M';
|
|
53
|
+
width?: number;
|
|
54
|
+
margin?: number;
|
|
55
|
+
[key: string]: any;
|
|
56
|
+
}): Promise<string>;
|
|
57
|
+
static qrToTerminalString(qr: string, options?: {
|
|
58
|
+
small?: boolean;
|
|
59
|
+
[key: string]: any;
|
|
60
|
+
}): Promise<string>;
|
|
61
|
+
static randomPairingCode(pattern: string, length?: number): string;
|
|
62
|
+
private static instances;
|
|
63
|
+
static getInstance(props: WhatsappSocketBaseProps): WASocket;
|
|
64
|
+
static clearInstance(key?: string): void;
|
|
65
|
+
constructor(props: WhatsappSocketBaseProps);
|
|
66
|
+
private getLatestWhatsAppVersion;
|
|
67
|
+
private getAuthCollection;
|
|
68
|
+
private authenticate;
|
|
69
|
+
static buildSocketKey(props: Partial<WhatsappSocketBaseProps>): string;
|
|
70
|
+
get socketKey(): string;
|
|
71
|
+
get socket(): WASocket | null;
|
|
72
|
+
set socket(sock: WASocket | null);
|
|
73
|
+
startConnection({ options, connectionAttempts, onOpen, onClose, onQR, onConnectionStatusChange, pairingPhone: _pairingPhone, debug: _debug, }?: {
|
|
74
|
+
options?: UserFacingSocketConfig;
|
|
75
|
+
debug?: boolean;
|
|
76
|
+
pairingPhone?: string;
|
|
77
|
+
connectionAttempts?: number;
|
|
78
|
+
onOpen?: () => Promise<void> | void;
|
|
79
|
+
onClose?: () => Promise<void> | void;
|
|
80
|
+
onQR?: (qr: string, code?: string | null) => Promise<void> | void;
|
|
81
|
+
onConnectionStatusChange?: (status: 'open' | 'close' | 'connecting') => Promise<void> | void;
|
|
82
|
+
}): Promise<WASocket | null>;
|
|
83
|
+
ensureSocketConnected(): Promise<WASocket | null>;
|
|
84
|
+
closeConnection(): Promise<void>;
|
|
85
|
+
clearAuthState(): Promise<void>;
|
|
86
|
+
resetConnection({ pairingPhone, autoConnect }?: {
|
|
87
|
+
pairingPhone?: string;
|
|
88
|
+
autoConnect?: boolean;
|
|
89
|
+
}): Promise<void>;
|
|
90
|
+
isConnected(): boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Delete a message for everyone (if within time limit) or just for yourself
|
|
93
|
+
* @param messageId - The message ID to delete
|
|
94
|
+
* @param chatJid - The chat JID (phone number in WhatsApp format)
|
|
95
|
+
* @param deleteForEveryone - If true, deletes for everyone (only works if you sent the message and within ~48h)
|
|
96
|
+
* @returns Promise with the result
|
|
97
|
+
*/
|
|
98
|
+
deleteMessage(messageId: string, chatJid: string, deleteForEveryone?: true): Promise<any>;
|
|
99
|
+
/**
|
|
100
|
+
* Delete multiple messages at once
|
|
101
|
+
* @param messages - Array of {messageId, chatJid} objects
|
|
102
|
+
* @param deleteForEveryone - If true, deletes for everyone
|
|
103
|
+
* @returns Promise with array of results
|
|
104
|
+
*/
|
|
105
|
+
deleteMessages(messages: Array<{
|
|
106
|
+
messageId: string;
|
|
107
|
+
chatJid: string;
|
|
108
|
+
}>, deleteForEveryone?: true): Promise<any[]>;
|
|
109
|
+
loadRecentMessages(chatJid: string, messageId: string): Promise<WAMessage | null>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
type ButtonURL = {
|
|
113
|
+
label: string;
|
|
114
|
+
url: string;
|
|
115
|
+
};
|
|
116
|
+
type ButtonCopy = {
|
|
117
|
+
label: string;
|
|
118
|
+
copy: string;
|
|
119
|
+
};
|
|
120
|
+
type ButtonPhone = {
|
|
121
|
+
label: string;
|
|
122
|
+
tel: string;
|
|
123
|
+
};
|
|
124
|
+
type CallToActionButtons = Array<ButtonURL | ButtonCopy | ButtonPhone>;
|
|
125
|
+
type GroupMessageOptions = {
|
|
126
|
+
mentions?: string[];
|
|
127
|
+
replyToMessageId?: string;
|
|
128
|
+
};
|
|
129
|
+
type CreateGroupOptions = {
|
|
130
|
+
name: string;
|
|
131
|
+
participants?: string[];
|
|
132
|
+
description?: string;
|
|
133
|
+
};
|
|
134
|
+
type GroupSettingsType = 'announcement' | 'not_announcement' | 'locked' | 'unlocked';
|
|
135
|
+
|
|
136
|
+
export { type CallToActionButtons as C, type GroupSettingsType as G, WhatsappSocketBase as W, type WhatsappSocketBaseProps as a, type CreateGroupOptions as b, type GroupMessageOptions as c };
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { WAMessage, MessageUpsertType, WASocket, UserFacingSocketConfig } from '@fadzzzslebew/baileys';
|
|
2
|
+
import { StringValue } from 'ms';
|
|
3
|
+
import { Logger } from 'stack-trace-logger';
|
|
4
|
+
|
|
5
|
+
type WhatsappSocketBaseProps = ({
|
|
6
|
+
mongoURL: string;
|
|
7
|
+
fileAuthStateDirectoryPath?: string | undefined;
|
|
8
|
+
} | {
|
|
9
|
+
mongoURL?: string | undefined;
|
|
10
|
+
fileAuthStateDirectoryPath: string;
|
|
11
|
+
}) & {
|
|
12
|
+
appName?: string;
|
|
13
|
+
logger?: Logger;
|
|
14
|
+
mongoCollection?: string;
|
|
15
|
+
onOpen?: () => Promise<void> | void;
|
|
16
|
+
onClose?: () => Promise<void> | void;
|
|
17
|
+
onConnectionStatusChange?: (connectionStatus: 'connecting' | 'close' | 'open') => Promise<void> | void;
|
|
18
|
+
onReceiveMessages?: (messages: WAMessage[], type: MessageUpsertType) => Promise<void> | void;
|
|
19
|
+
onPreConnectionSendMessageFailed?: (error: Error | string) => Promise<void> | void;
|
|
20
|
+
onQR?: (qr: string, code?: string | null) => Promise<void> | void;
|
|
21
|
+
debug?: boolean;
|
|
22
|
+
printQRInTerminal?: boolean;
|
|
23
|
+
pairingPhone?: string;
|
|
24
|
+
customPairingCode?: string;
|
|
25
|
+
};
|
|
26
|
+
declare class WhatsappSocketBase {
|
|
27
|
+
protected readonly fileAuthStateDirectoryPath?: string;
|
|
28
|
+
protected readonly mongoURL?: string;
|
|
29
|
+
protected readonly mongoCollection: string;
|
|
30
|
+
protected readonly logger?: Logger;
|
|
31
|
+
protected readonly debug?: boolean;
|
|
32
|
+
protected readonly printQRInTerminal?: boolean;
|
|
33
|
+
protected readonly pairingPhone?: string;
|
|
34
|
+
protected readonly customPairingCode?: string;
|
|
35
|
+
protected readonly appName?: string;
|
|
36
|
+
private readonly onPreConnectionSendMessageFailed?;
|
|
37
|
+
private onOpen?;
|
|
38
|
+
private onClose?;
|
|
39
|
+
private onQR?;
|
|
40
|
+
private onConnectionStatusChange?;
|
|
41
|
+
private readonly onReceiveMessages?;
|
|
42
|
+
static DEFAULT_COUNTRY_CODE: string;
|
|
43
|
+
static CONNECTION_TIMEOUT: StringValue;
|
|
44
|
+
static formatPhoneNumber(phone: string, countryCode?: string): string;
|
|
45
|
+
static formatPhoneNumberToWhatsappPattern(phone: string, countryCode?: string): string;
|
|
46
|
+
static getWhatsappPhoneLink({ phone, message, countryCode, }: {
|
|
47
|
+
phone: string;
|
|
48
|
+
countryCode?: string;
|
|
49
|
+
message?: string;
|
|
50
|
+
}): string;
|
|
51
|
+
static qrToImage(qr: string, options?: {
|
|
52
|
+
errorCorrectionLevel?: 'H' | 'L' | 'M';
|
|
53
|
+
width?: number;
|
|
54
|
+
margin?: number;
|
|
55
|
+
[key: string]: any;
|
|
56
|
+
}): Promise<string>;
|
|
57
|
+
static qrToTerminalString(qr: string, options?: {
|
|
58
|
+
small?: boolean;
|
|
59
|
+
[key: string]: any;
|
|
60
|
+
}): Promise<string>;
|
|
61
|
+
static randomPairingCode(pattern: string, length?: number): string;
|
|
62
|
+
private static instances;
|
|
63
|
+
static getInstance(props: WhatsappSocketBaseProps): WASocket;
|
|
64
|
+
static clearInstance(key?: string): void;
|
|
65
|
+
constructor(props: WhatsappSocketBaseProps);
|
|
66
|
+
private getLatestWhatsAppVersion;
|
|
67
|
+
private getAuthCollection;
|
|
68
|
+
private authenticate;
|
|
69
|
+
static buildSocketKey(props: Partial<WhatsappSocketBaseProps>): string;
|
|
70
|
+
get socketKey(): string;
|
|
71
|
+
get socket(): WASocket | null;
|
|
72
|
+
set socket(sock: WASocket | null);
|
|
73
|
+
startConnection({ options, connectionAttempts, onOpen, onClose, onQR, onConnectionStatusChange, pairingPhone: _pairingPhone, debug: _debug, }?: {
|
|
74
|
+
options?: UserFacingSocketConfig;
|
|
75
|
+
debug?: boolean;
|
|
76
|
+
pairingPhone?: string;
|
|
77
|
+
connectionAttempts?: number;
|
|
78
|
+
onOpen?: () => Promise<void> | void;
|
|
79
|
+
onClose?: () => Promise<void> | void;
|
|
80
|
+
onQR?: (qr: string, code?: string | null) => Promise<void> | void;
|
|
81
|
+
onConnectionStatusChange?: (status: 'open' | 'close' | 'connecting') => Promise<void> | void;
|
|
82
|
+
}): Promise<WASocket | null>;
|
|
83
|
+
ensureSocketConnected(): Promise<WASocket | null>;
|
|
84
|
+
closeConnection(): Promise<void>;
|
|
85
|
+
clearAuthState(): Promise<void>;
|
|
86
|
+
resetConnection({ pairingPhone, autoConnect }?: {
|
|
87
|
+
pairingPhone?: string;
|
|
88
|
+
autoConnect?: boolean;
|
|
89
|
+
}): Promise<void>;
|
|
90
|
+
isConnected(): boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Delete a message for everyone (if within time limit) or just for yourself
|
|
93
|
+
* @param messageId - The message ID to delete
|
|
94
|
+
* @param chatJid - The chat JID (phone number in WhatsApp format)
|
|
95
|
+
* @param deleteForEveryone - If true, deletes for everyone (only works if you sent the message and within ~48h)
|
|
96
|
+
* @returns Promise with the result
|
|
97
|
+
*/
|
|
98
|
+
deleteMessage(messageId: string, chatJid: string, deleteForEveryone?: true): Promise<any>;
|
|
99
|
+
/**
|
|
100
|
+
* Delete multiple messages at once
|
|
101
|
+
* @param messages - Array of {messageId, chatJid} objects
|
|
102
|
+
* @param deleteForEveryone - If true, deletes for everyone
|
|
103
|
+
* @returns Promise with array of results
|
|
104
|
+
*/
|
|
105
|
+
deleteMessages(messages: Array<{
|
|
106
|
+
messageId: string;
|
|
107
|
+
chatJid: string;
|
|
108
|
+
}>, deleteForEveryone?: true): Promise<any[]>;
|
|
109
|
+
loadRecentMessages(chatJid: string, messageId: string): Promise<WAMessage | null>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
type ButtonURL = {
|
|
113
|
+
label: string;
|
|
114
|
+
url: string;
|
|
115
|
+
};
|
|
116
|
+
type ButtonCopy = {
|
|
117
|
+
label: string;
|
|
118
|
+
copy: string;
|
|
119
|
+
};
|
|
120
|
+
type ButtonPhone = {
|
|
121
|
+
label: string;
|
|
122
|
+
tel: string;
|
|
123
|
+
};
|
|
124
|
+
type CallToActionButtons = Array<ButtonURL | ButtonCopy | ButtonPhone>;
|
|
125
|
+
type GroupMessageOptions = {
|
|
126
|
+
mentions?: string[];
|
|
127
|
+
replyToMessageId?: string;
|
|
128
|
+
};
|
|
129
|
+
type CreateGroupOptions = {
|
|
130
|
+
name: string;
|
|
131
|
+
participants?: string[];
|
|
132
|
+
description?: string;
|
|
133
|
+
};
|
|
134
|
+
type GroupSettingsType = 'announcement' | 'not_announcement' | 'locked' | 'unlocked';
|
|
135
|
+
|
|
136
|
+
export { type CallToActionButtons as C, type GroupSettingsType as G, WhatsappSocketBase as W, type WhatsappSocketBaseProps as a, type CreateGroupOptions as b, type GroupMessageOptions as c };
|
package/dist/group.cjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var q=require('@fadzzzslebew/baileys'),L=require('ms'),j=require('fs'),E=require('qrcode'),mongodb=require('mongodb'),$=require('pino');require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var q__default=/*#__PURE__*/_interopDefault(q);var L__default=/*#__PURE__*/_interopDefault(L);var j__default=/*#__PURE__*/_interopDefault(j);var E__default=/*#__PURE__*/_interopDefault(E);var $__default=/*#__PURE__*/_interopDefault($);var D={replacer:(s,e)=>Buffer.isBuffer(e)||e instanceof Uint8Array||e?.type==="Buffer"?{type:"Buffer",data:Buffer.from(e?.data||e).toString("base64")}:e,reviver:(s,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}},H=async s=>{let e=(n,i)=>{let c={$set:{...JSON.parse(JSON.stringify(n,D.replacer))}};return s.updateOne({_id:i},c,{upsert:true})},t=async n=>{try{let i=JSON.stringify(await s.findOne({_id:n}));return JSON.parse(i,D.reviver)}catch{return null}},r=async n=>{try{await s.deleteOne({_id:n});}catch{}},o=await t("creds")||q.initAuthCreds();return {state:{creds:o,keys:{get:async(n,i)=>{let a={};return await Promise.all(i.map(async c=>{let u=await t(`${n}-${c}`);n==="app-state-sync-key"&&u&&(u=q.WAProto.Message.AppStateSyncKeyData.fromObject(u)),a[c]=u;})),a},set:async n=>{let i=[];for(let a of Object.keys(n))for(let c of Object.keys(n[a])){let u=n[a][c],g=`${a}-${c}`;i.push(u?e(u,g):r(g));}await Promise.all(i);}}},saveCreds:()=>e(o,"creds")}},R=H;var y=s=>new Promise(e=>setTimeout(e,typeof s=="number"?s:L__default.default(s)));var O=$__default.default({level:"silent"}),k=class s{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=s.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=s.DEFAULT_COUNTRY_CODE){if(e.endsWith("@s.whatsapp.net"))return e;let r=s.formatPhoneNumber(e,t);return r=`${r}@s.whatsapp.net`,r.replace(/:\d+@/,"@")}static getWhatsappPhoneLink({phone:e,message:t,countryCode:r=s.DEFAULT_COUNTRY_CODE}){let o=this.formatPhoneNumber(e,r),n=t?`?text=${encodeURI(t)}`:"";return `https://wa.me/${o}${n}`}static async qrToImage(e,t={}){return E__default.default.toDataURL(e,{errorCorrectionLevel:"H",width:400,margin:2,...t})}static async qrToTerminalString(e,t={}){return E__default.default.toString(e,{type:"terminal",small:true,...t})}static randomPairingCode(e,t=8){if(!e.includes("[")&&e.length===t)return e;let r="",o=[],n=a=>{let c=[];for(let u=0;u<a.length;u++)if(a[u+1]==="-"&&a[u+2]){let g=a.charCodeAt(u),m=a.charCodeAt(u+2);for(let p=g;p<=m;p++)c.push(String.fromCharCode(p));u+=2;}else c.push(a[u]);return c};for(let a=0;a<e.length&&r.length<t;a++){let c=e[a];if(c==="["){let u=e.indexOf("]",a),g=e.slice(a+1,u);o=n(g),a=u;}else r+=c;}for(;r.length<t&&o.length;)r+=o[Math.floor(Math.random()*o.length)];let i=r.toUpperCase();return i.padEnd(t,i)}static instances=new Map;static getInstance(e){let t=s.buildSocketKey(e);return s.instances.has(t)||new s(e),s.instances.get(t)}static clearInstance(e){e?s.instances.delete(e):s.instances.clear();}constructor(e){let{fileAuthStateDirectoryPath:t,mongoURL:r,mongoCollection:o="whatsapp-auth",logger:n,onOpen:i,onClose:a,onQR:c,onReceiveMessages:u,onConnectionStatusChange:g,debug:m,printQRInTerminal:p,pairingPhone:M,customPairingCode:S,onPreConnectionSendMessageFailed:I,appName:l}=e;this.appName=l,this.mongoURL=r,this.fileAuthStateDirectoryPath=t,this.mongoCollection=o,this.logger=n,this.debug=m,this.printQRInTerminal=p,this.pairingPhone=M,this.customPairingCode=S,this.onPreConnectionSendMessageFailed=I,this.onConnectionStatusChange=g,this.onReceiveMessages=u,this.onOpen=i,this.onClose=a,this.onQR=c,s.instances.has(this.socketKey)&&(this.socket=s.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 mongodb.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:i}=await q.useMultiFileAuthState(this.fileAuthStateDirectoryPath);return {auth:i,saveCreds:n}}let[e]=await this.getAuthCollection(),{state:t,saveCreds:r}=await R(e);return {auth:{creds:t.creds,keys:q.makeCacheableSignalKeyStore(t.keys,O)},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 s.instances.get(this.socketKey)??null}set socket(e){s.instances.set(this.socketKey,e);}async startConnection({options:e,connectionAttempts:t=3,onOpen:r=this.onOpen,onClose:o=this.onClose,onQR:n=this.onQR,onConnectionStatusChange:i=this.onConnectionStatusChange,pairingPhone:a,debug:c}={}){let u=a??this.pairingPhone,{saveCreds:g,auth:m}=await this.authenticate(),p=c===void 0?this.debug:c,M=await this.getLatestWhatsAppVersion(),S=async()=>new Promise(l=>{let f=q__default.default({version:M,logger:O,browser:[this.appName||"baileys","1.0.0",""],syncFullHistory:true,shouldIgnoreJid:d=>d.includes("@newsletter"),...e,printQRInTerminal:false,auth:m});f.ev.on("connection.update",async d=>{let{connection:w,lastDisconnect:T,qr:b}=d;if(b){if(p&&this.logger?.info("WHATSAPP","QR Code received",{qr:b}),this.printQRInTerminal){let x=await s.qrToTerminalString(b,{small:true}).catch(()=>null);console.log(x);}this.customPairingCode?s.randomPairingCode(this.customPairingCode):void 0;let P=u?s.formatPhoneNumber(u):null,A=P?await f.requestPairingCode(P):null;p&&this.printQRInTerminal&&this.logger?.info("WHATSAPP","QR Pairing Code",{code:A,pairingPhone:P}),await n?.(b,A);}switch(w){case "connecting":{p&&this.logger?.debug("WHATSAPP","Connecting..."),i?.("connecting");break}case "open":{p&&this.logger?.info("WHATSAPP","Connection opened successfully!"),this.socket=f,await r?.(),i?.("open"),l(this.socket);break}case "close":{let W=t-- >0&&T?.error?.output?.statusCode!==q.DisconnectReason.loggedOut,P=T?.error?.output?.statusCode,A=T?.error?.message;p&&this.logger?.info("WHATSAPP","Connection closed",{statusCode:P,errorMessage:A,shouldReconnect:W}),W&&t?(p&&this.logger?.info("WHATSAPP","Reconnecting..."),await y(s.CONNECTION_TIMEOUT),l(S())):(p&&this.logger?.warn("WHATSAPP","Logged out, clearing auth state"),await o?.(),this.socket=null,l(this.socket)),i?.("close");break}}}),f.ev.on("creds.update",g),this.onReceiveMessages&&typeof this.onReceiveMessages=="function"&&f.ev.on("messages.upsert",async({messages:d,type:w})=>{this.logger?.info("WHATSAPP","Received messages",{type:w,totalMessages:d.length}),this.onReceiveMessages?.(d,w);});}),I=await S();return await y(s.CONNECTION_TIMEOUT),I}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&&j__default.default.rmSync(this.fileAuthStateDirectoryPath,{recursive:true,force:true});}async resetConnection({pairingPhone:e,autoConnect:t=true}={}){await this.clearAuthState(),t&&(await y(s.CONNECTION_TIMEOUT),await this.startConnection({pairingPhone:e}));}isConnected(){return !!this.socket?.user}async deleteMessage(e,t,r=true){if(await this.ensureSocketConnected(),!this.socket)throw new Error("Socket not connected");let o=s.formatPhoneNumberToWhatsappPattern(t);try{if(r){let n=await this.socket.sendMessage(o,{delete:{remoteJid:o,fromMe:!0,id:e,participant:void 0}});return this.debug&&this.logger?.info("WHATSAPP","Message deleted for everyone",{messageId:e,chatJid:o}),n}else throw this.debug&&this.logger?.warn("WHATSAPP","Delete for me is not supported via API",{messageId:e,chatJid:o,reason:["Delete for me only (clear message locally)",`Note: This doesn't work via API - WhatsApp doesn't support "delete for me" via Baileys`,"We can only revoke messages (delete for everyone)"].join(`
|
|
2
|
+
`)}),new Error("Delete for me is not supported via WhatsApp API. Use deleteForEveryone=true to revoke the message.")}catch(n){throw this.debug&&this.logger?.error("WHATSAPP","Failed to delete message",{messageId:e,chatJid:o,error:n.message}),n}}async deleteMessages(e,t=true){await this.ensureSocketConnected();let r=[];for(let{messageId:o,chatJid:n}of e)try{let i=await this.deleteMessage(o,n,t);r.push({success:!0,messageId:o,result:i}),await y("500ms");}catch(i){r.push({success:false,messageId:o,error:i.message});}return r}async loadRecentMessages(e,t){await this.ensureSocketConnected();let r=s.formatPhoneNumberToWhatsappPattern(e);try{return await this.socket?.waitForMessage(t,3e3)||null}catch(o){return this.debug&&this.logger?.error("WHATSAPP","Failed to load message history",{chatJid:r,error:o.message}),null}}};var C=class s extends k{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 o=(t??[]).map(i=>s.formatPhoneNumberToWhatsappPattern(i));if(o.length===0){let i=this.socket?.user?.id;if(!i)throw new Error("createGroup: Could not get bot user ID. Make sure socket is connected.");let a=s.formatPhoneNumberToWhatsappPattern(i);o.push(a),this.debug&&this.logger?.debug("WHATSAPP","No participants provided, creating group with self only",{selfJid:i});}this.debug&&this.logger?.debug("WHATSAPP","Creating group",{name:e,description:r,participants:o});let n=await this.socket?.groupCreate(e,o);if(r&&n?.id){let i=s.formatGroupId(n.id);await this.updateGroupDescription(i,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=s.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=s.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=s.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Updating group settings",{groupId:r,setting:t}),this.socket?.groupSettingUpdate(r,t)}async updateGroupParticipants(e,t,r){if(!e)throw new Error("addParticipants: Group ID is required.");let o=[].concat(t).filter(a=>a);if(o?.length)return;await this.ensureSocketConnected();let n=s.formatGroupId(e),i=o.map(a=>s.formatPhoneNumberToWhatsappPattern(a));return this.debug&&this.logger?.debug("WHATSAPP",`${r} participants to group`,{groupId:n,participantsCount:i.length}),this.socket?.groupParticipantsUpdate(n,i,r)}async addParticipants(e,t){return this.updateGroupParticipants(e,t,"add")}async removeParticipants(e,t){return this.updateGroupParticipants(e,t,"remove")}async promoteToAdmin(e,t){return this.updateGroupParticipants(e,t,"promote")}async demoteFromAdmin(e,t){return this.updateGroupParticipants(e,t,"demote")}async leaveGroup(e){if(!e)throw new Error("leaveGroup: Group ID is required.");await this.ensureSocketConnected();let t=s.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=s.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=s.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=s.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=s.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=s.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=s.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 G=class s extends C{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 o=s.formatGroupId(e),n={};return r?.replyToMessageId&&(n.quoted={key:{id:r.replyToMessageId}}),this.debug&&this.logger?.debug("WHATSAPP","Sending text message to group",{groupId:o,textLength:t.length,hasMentions:!!r?.mentions?.length}),this.socket?.sendMessage(o,{text:t},n)}async sendButtonsMessage(e,{title:t,subtitle:r,buttons:o}){if(!e||!t||!o?.length)throw new Error("sendButtonsMessage: Group ID, title, and buttons are required.");await this.ensureSocketConnected();let n=s.formatGroupId(e),i=o?.map(c=>{let u={display_text:c.label},g;switch(true){case !!c.url:g="cta_url",u.url=c.url;break;case !!c.copy:g="cta_copy",u.copy_code=c.copy;break;case !!c.tel:g="cta_call",u.phone_number=c.tel;break;default:g="";break}return {name:g,buttonParamsJson:JSON.stringify(u)}}).filter(c=>c.name),a=q.generateWAMessageFromContent(n,{viewOnceMessage:{message:{interactiveMessage:q.WAProto.Message.InteractiveMessage.create({body:q.WAProto.Message.InteractiveMessage.Body.create({text:t}),...r&&{footer:q.WAProto.Message.InteractiveMessage.Footer.create({text:r})},nativeFlowMessage:q.WAProto.Message.InteractiveMessage.NativeFlowMessage.create({buttons:i})})}}},{userJid:n});return this.debug&&this.logger?.debug("WHATSAPP","Sending buttons message to group",{groupId:n,title:t,buttonsCount:i.length}),this.socket?.relayMessage(n,a.message,{messageId:a.key.id})}async sendReplyButtonsMessage(e,{title:t,subtitle:r,buttons:o,mentions:n}){if(!e||!t||!o?.length)throw new Error("sendReplyButtonsMessage: Group ID, title, and buttons are required.");await this.ensureSocketConnected();let i=s.formatGroupId(e),a=o.filter(u=>u).map((u,g)=>typeof u=="string"?{buttonId:`id-${g}`,buttonText:{displayText:u},type:1}:{buttonId:`${u.id}`,buttonText:{displayText:u.label},type:1}),c={text:t,buttons:a,...r&&{footer:r}};return n?.length&&(c.mentions=n.map(u=>s.formatPhoneNumberToWhatsappPattern(u))),this.debug&&this.logger?.debug("WHATSAPP","Sending reply buttons message to group",{groupId:i,title:t,buttonsCount:a.length}),this.socket?.sendMessage(i,c)}async sendImageMessage(e,t,{caption:r,mentions:o}={}){if(!e||!t)throw new Error("sendImage: Group ID and image buffer are required.");await this.ensureSocketConnected();let n=s.formatGroupId(e),i={image:t,...r&&{caption:r}};return o?.length&&(i.mentions=o.map(a=>s.formatPhoneNumberToWhatsappPattern(a))),this.debug&&this.logger?.debug("WHATSAPP","Sending image to group",{groupId:n,hasCaption:!!r}),this.socket?.sendMessage(n,i)}async sendVideoMessage(e,t,r,o){if(!e||!t)throw new Error("sendVideo: Group ID and video buffer are required.");await this.ensureSocketConnected();let n=s.formatGroupId(e),i={video:t,...r&&{caption:r}};return o?.mentions?.length&&(i.mentions=o.mentions.map(a=>s.formatPhoneNumberToWhatsappPattern(a))),this.debug&&this.logger?.debug("WHATSAPP","Sending video to group",{groupId:n,hasCaption:!!r}),this.socket?.sendMessage(n,i)}async sendAudioMessage(e,t,r){if(!e||!t)throw new Error("sendAudio: Group ID and audio buffer are required.");await this.ensureSocketConnected();let o=s.formatGroupId(e),n={audio:t,ptt:r?.ptt??false};return r?.mentions?.length&&(n.mentions=r.mentions.map(i=>s.formatPhoneNumberToWhatsappPattern(i))),this.debug&&this.logger?.debug("WHATSAPP","Sending audio to group",{groupId:o,isPTT:n.ptt}),this.socket?.sendMessage(o,n)}async sendDocumentMessage(e,t,r,o,n){if(!e||!t||!r)throw new Error("sendDocument: Group ID, document buffer, and fileName are required.");await this.ensureSocketConnected();let i=s.formatGroupId(e),a={document:t,fileName:r,...o&&{mimetype:o}};return n?.mentions?.length&&(a.mentions=n.mentions.map(c=>s.formatPhoneNumberToWhatsappPattern(c))),this.debug&&this.logger?.debug("WHATSAPP","Sending document to group",{groupId:i,fileName:r}),this.socket?.sendMessage(i,a)}async sendLocationMessage(e,t,r,o,n){if(!e||t===void 0||r===void 0)throw new Error("sendLocation: Group ID, latitude, and longitude are required.");await this.ensureSocketConnected();let i=s.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Sending location to group",{groupId:i,latitude:t,longitude:r}),this.socket?.sendMessage(i,{location:{degreesLatitude:t,degreesLongitude:r,...o&&{name:o},...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=s.formatGroupId(e),o=await this.getGroupMetadata(r);if(!o)throw new Error("Could not fetch group metadata");let n=o.participants.map(i=>i.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 o=s.formatGroupId(e);return this.debug&&this.logger?.debug("WHATSAPP","Sending reaction to group message",{groupId:o,messageId:t,emoji:r}),this.socket?.sendMessage(o,{react:{text:r,key:{id:t,remoteJid:o}}})}async deleteGroupMessage(e,t){if(!e||!t)throw new Error("deleteGroupMessage: Group ID and message ID are required.");await this.ensureSocketConnected();let r=s.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 B=class extends G{constructor(e){super(e);}};exports.WhatsappSocketGroup=B;//# sourceMappingURL=group.cjs.map
|
|
3
|
+
//# sourceMappingURL=group.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mongoAuthState.ts","../src/helpers.ts","../src/whatsappSocket.base.ts","../src/whatsappSocket.group.management.ts","../src/whatsappSocket.group.messages.ts","../src/whatsappSocket.group.client.ts"],"names":["BufferJSON","_k","value","_","val","useMongoDBAuthState","collection","writeData","data","id","update","readData","removeData","creds","initAuthCreds","type","ids","proto","tasks","category","key","mongoAuthState_default","sleep","timeout","resolve","ms","pinoLogger","P","WhatsappSocketBase","_WhatsappSocketBase","phone","countryCode","strNumber","message","formattedPhone","messageQuery","qr","options","QRCode","pattern","length","result","pool","buildPool","block","chars","i","start","end","c","char","upperCaseResult","props","instanceKey","fileAuthStateDirectoryPath","mongoURL","mongoCollection","logger","onOpen","onClose","onQR","onReceiveMessages","onConnectionStatusChange","debug","printQRInTerminal","pairingPhone","customPairingCode","onPreConnectionSendMessageFailed","appName","sources","url","response","error","mongoClient","MongoClient","saveCreds","state","useMultiFileAuthState","makeCacheableSignalKeyStore","sock","connectionAttempts","_pairingPhone","_debug","auth","version","connect","makeWASocket","jid","connection","lastDisconnect","qrcode","pairing","code","shouldReconnect","DisconnectReason","statusCode","errorMessage","messages","socket","fs","autoConnect","messageId","chatJid","deleteForEveryone","results","WhatsappSocketGroups","_WhatsappSocketGroups","groupId","name","participants","description","formattedParticipants","selfJid","pId","formattedGroupId","newName","setting","participant","action","v","groups","inviteCode","imageBuffer","highRes","WhatsappSocketGroupMessages","_WhatsappSocketGroupMessages","text","messageOptions","title","subtitle","buttons","buttonsValue","btn","buttonParamsJson","msg","generateWAMessageFromContent","mentions","index","caption","videoBuffer","audioBuffer","documentBuffer","fileName","mimeType","latitude","longitude","address","groupMetadata","p","emoji","WhatsappSocketGroup"],"mappings":"idAOA,IAAMA,CAAAA,CAAa,CACf,QAAA,CAAU,CAACC,EAAYC,CAAAA,GACf,MAAA,CAAO,QAAA,CAASA,CAAK,CAAA,EAAKA,CAAAA,YAAiB,YAAcA,CAAAA,EAAO,IAAA,GAAS,SAClE,CACH,IAAA,CAAM,SACN,IAAA,CAAM,MAAA,CAAO,IAAA,CAAKA,CAAAA,EAAO,IAAA,EAAQA,CAAK,EAAE,QAAA,CAAS,QAAQ,CAC7D,CAAA,CAEGA,CAAAA,CAGX,QAAS,CAACC,CAAAA,CAAWD,CAAAA,GAAe,CAChC,GAAI,OAAOA,GAAU,QAAA,EAAcA,CAAAA,GAAUA,EAAM,MAAA,GAAW,IAAA,EAAQA,EAAM,IAAA,GAAS,QAAA,CAAA,CAAW,CAC5F,IAAME,CAAAA,CAAMF,CAAAA,CAAM,MAAQA,CAAAA,CAAM,KAAA,CAChC,OAAO,OAAOE,CAAAA,EAAQ,SAAW,MAAA,CAAO,IAAA,CAAKA,CAAAA,CAAK,QAAQ,CAAA,CAAI,MAAA,CAAO,KAAKA,CAAAA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AAI,IAAA,CAAK,KAAA,EACL,IAAA,CAAK,MAAA,EAAQ,KAAA,CAAM,UAAA,CAAY,2BAAA,CAA6B,CACxD,OAAA,CAASO,CAAAA,CACT,SAAA,CAAAb,CACJ,CAAC,CAAA,CAGE,IAAA,CAAK,MAAA,EAAQ,WAAA,CAAYa,CAAAA,CAAkB,CAC9C,MAAA,CAAQ,CACJ,EAAA,CAAIb,CAAAA,CACJ,SAAA,CAAWa,CAAAA,CACX,MAAA,CAAQ,IACZ,CACJ,CAAC,CACL,CACJ,CAAA,CCxcO,IAAMoC,CAAAA,CAAN,cAAkC1B,CAA4B,CACjE,WAAA,CAAYxE,CAAAA,CAAyC,CACjD,KAAA,CAAMA,CAAK,EACf,CACJ","file":"group.cjs","sourcesContent":["import {\n type AuthenticationCreds,\n type SignalDataTypeMap,\n initAuthCreds,\n WAProto as proto,\n} from '@fadzzzslebew/baileys';\n\nconst BufferJSON = {\n replacer: (_k: string, value: any) => {\n if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {\n return {\n type: 'Buffer',\n data: Buffer.from(value?.data || value).toString('base64'),\n };\n }\n return value;\n },\n\n reviver: (_: string, value: any) => {\n if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {\n const val = value.data || value.value;\n return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);\n }\n return value;\n },\n};\n\nconst useMongoDBAuthState = async (collection: any) => {\n const writeData = (data: any, id: string) => {\n const informationToStore = JSON.parse(JSON.stringify(data, BufferJSON.replacer));\n const update = { $set: { ...informationToStore } };\n return collection.updateOne({ _id: id }, update, { upsert: true });\n };\n\n const readData = async (id: string) => {\n try {\n const data = JSON.stringify(await collection.findOne({ _id: id }));\n return JSON.parse(data, BufferJSON.reviver);\n } catch (error) {\n return null;\n }\n };\n\n const removeData = async (id: string) => {\n try {\n await collection.deleteOne({ _id: id });\n } catch (_a) {}\n };\n\n const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();\n\n return {\n state: {\n creds,\n keys: {\n get: async (type: keyof SignalDataTypeMap, ids: string[]) => {\n const data: { [id: string]: any } = {};\n await Promise.all(\n ids.map(async (id) => {\n let value = await readData(`${type}-${id}`);\n if (type === 'app-state-sync-key' && value) {\n value = proto.Message.AppStateSyncKeyData.fromObject(value);\n }\n data[id] = value;\n })\n );\n return data;\n },\n set: async (data: any) => {\n const tasks: Promise<any>[] = [];\n for (const category of Object.keys(data)) {\n for (const id of Object.keys(data[category])) {\n const value = data[category][id];\n const key = `${category}-${id}`;\n tasks.push(value ? writeData(value, key) : removeData(key));\n }\n }\n await Promise.all(tasks);\n },\n },\n },\n saveCreds: () => {\n return writeData(creds, 'creds');\n },\n };\n};\n\nexport default useMongoDBAuthState;\n","import { basename } from 'node:path';\nimport { ReadStream } from 'node:fs';\nimport ms, { type StringValue } from 'ms';\n// NOTE: Hidden for Dynamic Import for ESM-only Packages\n// import { parseBuffer, parseStream } from 'music-metadata';\n\nexport const getTotalSeconds = (msValue: StringValue) => {\n const value = ms(msValue);\n return value / 1000;\n};\n\nexport async function getUrlBuffer(url: string) {\n const response = await fetch(url);\n const arrayBuffer = await response.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n return buffer;\n}\n\nasync function getDurationFromStream(stream: ReadStream, mimeType?: string): Promise<number> {\n try {\n const { parseStream } = await import('music-metadata');\n const metadata = await parseStream(stream, { mimeType: mimeType || 'audio/mpeg' });\n return Math.floor(metadata.format.duration || 0);\n } catch (error) {\n console.error('Error parsing stream:', error);\n throw error;\n } finally {\n if (!stream.destroyed) {\n stream.destroy();\n }\n }\n}\n\nasync function getDurationFromBuffer(buffer: Buffer, mimeType?: string): Promise<number> {\n try {\n const { parseBuffer } = await import('music-metadata');\n const metadata = await parseBuffer(buffer, mimeType || 'audio/mpeg').catch(() => null);\n return metadata ? Math.floor(metadata.format.duration || 0) : 0;\n } catch (error) {\n console.error('Error parsing buffer:', error);\n throw error;\n }\n}\n\nexport async function getAudioFileDuration(audioFile: ReadStream | Buffer, mimeType?: string): Promise<number> {\n if (audioFile instanceof ReadStream) {\n return getDurationFromStream(audioFile, mimeType);\n } else {\n return getDurationFromBuffer(audioFile, mimeType);\n }\n}\n\nexport async function streamToBuffer(stream: ReadStream): Promise<Buffer> {\n const chunks: Buffer[] = [];\n\n for await (const chunk of stream) {\n chunks.push(chunk);\n }\n\n return Buffer.concat(chunks);\n}\n\nexport function getFilenameFromStream(stream: ReadStream): string | undefined {\n if (stream.path) {\n const pathStr = stream.path.toString();\n return basename(pathStr);\n }\n return undefined;\n}\n\nexport const sleep = (timeout: StringValue | number) => {\n return new Promise((resolve) => setTimeout(resolve, typeof timeout === 'number' ? timeout : ms(timeout)));\n};\n\nexport const MIME_TYPES: { [key: string]: string } = {\n // Images\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n bmp: 'image/bmp',\n svg: 'image/svg+xml',\n\n // Videos\n mp4: 'video/mp4',\n avi: 'video/x-msvideo',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n webm: 'video/webm',\n\n // Audio\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n opus: 'audio/opus',\n aac: 'audio/aac',\n m4a: 'audio/mp4',\n\n // Documents\n pdf: 'application/pdf',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n txt: 'text/plain',\n zip: 'application/zip',\n rar: 'application/x-rar-compressed',\n '7z': 'application/x-7z-compressed',\n};\n","// Baileys links\n// https://whiskeysockets.github.io/docs/tutorial-basics/sending-messages\n// https://github.com/WhiskeySockets/Baileys\n// https://github.com/ndalu-id/baileys-api\n// https://whiskeysockets.github.io/Baileys/\n// alternatives:\n// https://www.npmjs.com/package/mudslide\n// https://www.npmjs.com/package/whatsapp-web.js\n// https://www.npmjs.com/package/wbm\nimport {\n default as makeWASocket,\n DisconnectReason,\n makeCacheableSignalKeyStore,\n type MessageUpsertType,\n type UserFacingSocketConfig,\n type WAMessage,\n type WASocket,\n useMultiFileAuthState,\n type AuthenticationState,\n} from '@fadzzzslebew/baileys';\nimport { type StringValue } from 'ms';\nimport type { Logger as MyLogger } from 'stack-trace-logger';\nimport fs from 'node:fs';\nimport QRCode from 'qrcode';\nimport { type Collection, type Document as MongoDocument, MongoClient } from 'mongodb';\nimport P from 'pino';\nimport type { Boom } from '@hapi/boom';\nimport useMongoDBAuthState from './mongoAuthState';\nimport { sleep } from './helpers';\n\nconst pinoLogger: any = P({ level: 'silent' });\n\nexport type WhatsappSocketBaseProps = (\n | { mongoURL: string; fileAuthStateDirectoryPath?: string | undefined }\n | { mongoURL?: string | undefined; fileAuthStateDirectoryPath: string }\n) & {\n appName?: string;\n logger?: MyLogger;\n mongoCollection?: string;\n onOpen?: () => Promise<void> | void;\n onClose?: () => Promise<void> | void;\n onConnectionStatusChange?: (connectionStatus: 'connecting' | 'close' | 'open') => Promise<void> | void;\n onReceiveMessages?: (messages: WAMessage[], type: MessageUpsertType) => Promise<void> | void;\n onPreConnectionSendMessageFailed?: (error: Error | string) => Promise<void> | void;\n onQR?: (qr: string, code?: string | null) => Promise<void> | void;\n debug?: boolean;\n printQRInTerminal?: boolean;\n pairingPhone?: string;\n customPairingCode?: string;\n};\n\nexport class WhatsappSocketBase {\n protected readonly fileAuthStateDirectoryPath?: string;\n protected readonly mongoURL?: string;\n protected readonly mongoCollection: string = 'whatsapp-auth';\n protected readonly logger?: MyLogger;\n protected readonly debug?: boolean;\n protected readonly printQRInTerminal?: boolean;\n protected readonly pairingPhone?: string;\n protected readonly customPairingCode?: string;\n protected readonly appName?: string;\n private readonly onPreConnectionSendMessageFailed?: (error: Error | string) => Promise<void> | void;\n private onOpen?: () => Promise<void> | void;\n private onClose?: () => Promise<void> | void;\n private onQR?: (qr: string, code?: string | null) => Promise<void> | void;\n private onConnectionStatusChange?: (connectionStatus: 'open' | 'close' | 'connecting') => Promise<void> | void;\n private readonly onReceiveMessages?: (messages: WAMessage[], type: MessageUpsertType) => Promise<void> | void;\n static DEFAULT_COUNTRY_CODE: string = '972';\n static CONNECTION_TIMEOUT: StringValue = '2s';\n\n static formatPhoneNumber(phone: string, countryCode: string = WhatsappSocketBase.DEFAULT_COUNTRY_CODE): string {\n if (phone.endsWith('@s.whatsapp.net')) return phone;\n\n let strNumber = phone.replace(/[^0-9]/g, '');\n if (strNumber.startsWith('05')) strNumber = strNumber.substring(1);\n if (!strNumber.startsWith(countryCode)) strNumber = countryCode + strNumber;\n\n return strNumber; // formatted Number should look like: '+972 051-333-4444' to: '972513334444'\n }\n\n static formatPhoneNumberToWhatsappPattern(\n phone: string,\n countryCode: string = WhatsappSocketBase.DEFAULT_COUNTRY_CODE\n ): string {\n if (phone.endsWith('@s.whatsapp.net')) return phone;\n\n let strNumber = WhatsappSocketBase.formatPhoneNumber(phone, countryCode);\n strNumber = `${strNumber}@s.whatsapp.net`; // formatted Number should look like: '972513334444@s.whatsapp.net'\n return strNumber.replace(/:\\d+@/, '@'); // remove the sessionId\n }\n\n static getWhatsappPhoneLink({\n phone,\n message,\n countryCode = WhatsappSocketBase.DEFAULT_COUNTRY_CODE,\n }: {\n phone: string;\n countryCode?: string;\n message?: string;\n }) {\n const formattedPhone = this.formatPhoneNumber(phone, countryCode);\n const messageQuery = message ? `?text=${encodeURI(message)}` : '';\n return `https://wa.me/${formattedPhone}${messageQuery}`;\n }\n\n static async qrToImage(\n qr: string,\n options: {\n errorCorrectionLevel?: 'H' | 'L' | 'M';\n width?: number;\n margin?: number;\n [key: string]: any;\n } = {}\n ) {\n return QRCode.toDataURL(qr, {\n errorCorrectionLevel: 'H', // Changed to 'H' (High) for better reliability\n width: 400, // Increased size for better scanning\n margin: 2, // Ensure adequate margin\n ...options,\n });\n }\n\n static async qrToTerminalString(qr: string, options: { small?: boolean; [key: string]: any } = {}) {\n return QRCode.toString(qr, { type: 'terminal', small: true, ...options });\n }\n\n // only 8 alphanumeric (no more or less), patterns [a-z0-8] | aaaa[0-8] xxzzvvcc [zaq0-8]\n static randomPairingCode(pattern: string, length = 8) {\n // no randomness needed\n if (!pattern.includes('[') && pattern.length === length) {\n return pattern;\n }\n\n let result = '';\n let pool: string[] = [];\n\n const buildPool = (block: string) => {\n const chars: string[] = [];\n\n for (let i = 0; i < block.length; i++) {\n if (block[i + 1] === '-' && block[i + 2]) {\n const start = block.charCodeAt(i);\n const end = block.charCodeAt(i + 2);\n\n for (let c = start; c <= end; c++) {\n chars.push(String.fromCharCode(c));\n }\n\n i += 2;\n } else {\n chars.push(block[i]);\n }\n }\n\n return chars;\n };\n\n for (let i = 0; i < pattern.length && result.length < length; i++) {\n const char = pattern[i];\n\n if (char === '[') {\n const end = pattern.indexOf(']', i);\n const block = pattern.slice(i + 1, end);\n\n pool = buildPool(block);\n i = end;\n } else {\n result += char;\n }\n }\n\n // fill remaining from pool\n while (result.length < length && pool.length) {\n result += pool[Math.floor(Math.random() * pool.length)];\n }\n\n const upperCaseResult = result.toUpperCase();\n return upperCaseResult.padEnd(length, upperCaseResult);\n }\n\n private static instances: Map<string, WASocket | null> = new Map();\n\n static getInstance(props: WhatsappSocketBaseProps): WASocket {\n const instanceKey = WhatsappSocketBase.buildSocketKey(props);\n if (!WhatsappSocketBase.instances.has(instanceKey)) {\n new WhatsappSocketBase(props);\n }\n\n return WhatsappSocketBase.instances.get(instanceKey)!;\n }\n\n static clearInstance(key?: string): void {\n if (key) {\n WhatsappSocketBase.instances.delete(key);\n } else {\n WhatsappSocketBase.instances.clear();\n }\n }\n\n constructor(props: WhatsappSocketBaseProps) {\n const {\n fileAuthStateDirectoryPath,\n mongoURL,\n mongoCollection = 'whatsapp-auth',\n logger,\n onOpen,\n onClose,\n onQR,\n onReceiveMessages,\n onConnectionStatusChange,\n debug,\n printQRInTerminal,\n pairingPhone,\n customPairingCode,\n onPreConnectionSendMessageFailed,\n appName,\n } = props;\n\n this.appName = appName;\n this.mongoURL = mongoURL;\n this.fileAuthStateDirectoryPath = fileAuthStateDirectoryPath;\n this.mongoCollection = mongoCollection;\n this.logger = logger;\n this.debug = debug;\n this.printQRInTerminal = printQRInTerminal;\n this.pairingPhone = pairingPhone;\n this.customPairingCode = customPairingCode;\n this.onPreConnectionSendMessageFailed = onPreConnectionSendMessageFailed;\n this.onConnectionStatusChange = onConnectionStatusChange;\n this.onReceiveMessages = onReceiveMessages;\n this.onOpen = onOpen;\n this.onClose = onClose;\n this.onQR = onQR;\n\n if (WhatsappSocketBase.instances.has(this.socketKey)) {\n this.socket = WhatsappSocketBase.instances.get(this.socketKey)!;\n // instance.logger?.debug('WHATSAPP', 'RETURN SINGLETON INSTANCE!');\n }\n }\n\n private async getLatestWhatsAppVersion(): Promise<[number, number, number]> {\n try {\n // Try multiple sources\n const sources = [\n 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json',\n 'https://raw.githubusercontent.com/whiskeysockets/baileys/master/src/Defaults/baileys-version.json',\n ];\n\n for (const url of sources) {\n try {\n const response = await fetch(url);\n if (response.ok) {\n const data = (await response.json()) as { version: [number, number, number] };\n return data.version as [number, number, number];\n }\n } catch (err) {\n continue;\n }\n }\n\n // Fallback to a known working version\n console.log('Could not fetch version, using fallback');\n return [2, 3000, 1015901307]; // Recent version as of late 2024\n } catch (error) {\n console.error('Error fetching version:', error);\n return [2, 3000, 1015901307]; // Fallback\n }\n }\n\n private async getAuthCollection(): Promise<[] | [Collection<MongoDocument>, MongoClient]> {\n if (!this.mongoURL) return [];\n\n const mongoClient = new MongoClient(this.mongoURL);\n await mongoClient.connect();\n const collection = mongoClient.db().collection(this.mongoCollection);\n\n return [collection, mongoClient];\n }\n\n private async authenticate(): Promise<{ auth: AuthenticationState; saveCreds: any }> {\n if (!this.mongoURL && !this.fileAuthStateDirectoryPath) {\n throw new Error('fileAuthStateDirectoryPath/MongoURL is missing');\n }\n if (!this.mongoURL) {\n const { saveCreds, state } = await useMultiFileAuthState(this.fileAuthStateDirectoryPath as string);\n return { auth: state, saveCreds };\n }\n\n const [collection] = await this.getAuthCollection();\n\n const { state, saveCreds } = await useMongoDBAuthState(collection);\n const auth = {\n creds: state.creds,\n keys: makeCacheableSignalKeyStore(state.keys, pinoLogger as any),\n } as AuthenticationState;\n\n return { auth, saveCreds };\n }\n\n static buildSocketKey(props: Partial<WhatsappSocketBaseProps>) {\n return (\n props.appName ||\n props.pairingPhone ||\n props.mongoCollection ||\n props.fileAuthStateDirectoryPath ||\n 'default'\n );\n }\n\n get socketKey(): string {\n return (\n this.appName || this.pairingPhone || this.mongoCollection || this.fileAuthStateDirectoryPath || 'default'\n );\n }\n\n get socket(): WASocket | null {\n return WhatsappSocketBase.instances.get(this.socketKey) ?? null;\n }\n\n set socket(sock: WASocket | null) {\n WhatsappSocketBase.instances.set(this.socketKey, sock);\n }\n\n async startConnection({\n options,\n connectionAttempts = 3,\n onOpen = this.onOpen,\n onClose = this.onClose,\n onQR = this.onQR,\n onConnectionStatusChange = this.onConnectionStatusChange,\n pairingPhone: _pairingPhone,\n debug: _debug,\n }: {\n options?: UserFacingSocketConfig;\n debug?: boolean;\n pairingPhone?: string;\n connectionAttempts?: number;\n onOpen?: () => Promise<void> | void;\n onClose?: () => Promise<void> | void;\n onQR?: (qr: string, code?: string | null) => Promise<void> | void;\n onConnectionStatusChange?: (status: 'open' | 'close' | 'connecting') => Promise<void> | void;\n } = {}): Promise<WASocket | null> {\n const pairingPhone = _pairingPhone ?? this.pairingPhone;\n const { saveCreds, auth } = await this.authenticate();\n const debug = _debug === undefined ? this.debug : _debug;\n\n // Fetch latest Baileys version for better compatibility\n const version = await this.getLatestWhatsAppVersion();\n\n const connect = async (): Promise<WASocket | null> => {\n return new Promise((resolve) => {\n const sock = makeWASocket({\n version: version,\n logger: pinoLogger,\n browser: [this.appName || 'baileys', '1.0.0', ''], // ['Ubuntu', 'Chrome', '20.0.04'],\n syncFullHistory: true, // Don't sync full history on first connect\n // shouldSyncHistoryMessage: () => false,\n shouldIgnoreJid: (jid) => jid.includes('@newsletter'), // Ignore newsletter\n ...options,\n printQRInTerminal: false,\n ...{ auth },\n });\n\n // CRITICAL: Handle connection updates properly\n sock.ev.on('connection.update', async (update) => {\n const { connection, lastDisconnect, qr } = update;\n\n if (qr) {\n if (debug) this.logger?.info('WHATSAPP', 'QR Code received', { qr });\n if (this.printQRInTerminal) {\n const qrcode = await WhatsappSocketBase.qrToTerminalString(qr, { small: true }).catch(\n () => null\n );\n console.log(qrcode);\n }\n\n // @ts-ignore\n const pair = this.customPairingCode\n ? WhatsappSocketBase.randomPairingCode(this.customPairingCode)\n : undefined;\n\n const pairing = pairingPhone ? WhatsappSocketBase.formatPhoneNumber(pairingPhone) : null;\n const code = pairing ? await sock.requestPairingCode(pairing) : null;\n\n if (debug && this.printQRInTerminal) {\n this.logger?.info('WHATSAPP', 'QR Pairing Code', { code, pairingPhone: pairing });\n }\n await onQR?.(qr, code);\n }\n\n switch (connection) {\n case 'connecting': {\n if (debug) this.logger?.debug('WHATSAPP', 'Connecting...');\n onConnectionStatusChange?.('connecting');\n break;\n }\n\n case 'open': {\n if (debug) this.logger?.info('WHATSAPP', 'Connection opened successfully!');\n this.socket = sock;\n await onOpen?.();\n onConnectionStatusChange?.('open');\n resolve(this.socket);\n break;\n }\n\n case 'close': {\n const shouldReconnect =\n connectionAttempts-- > 0 &&\n (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut;\n\n const statusCode = (lastDisconnect?.error as Boom)?.output?.statusCode;\n const errorMessage = lastDisconnect?.error?.message;\n\n if (debug) {\n this.logger?.info('WHATSAPP', 'Connection closed', {\n statusCode,\n errorMessage,\n shouldReconnect,\n });\n }\n\n // IMPORTANT: Error code 515 (Stream Errored) after QR scan is NORMAL\n // The connection must restart after pairing - this is expected behavior\n if (shouldReconnect && connectionAttempts) {\n if (debug) this.logger?.info('WHATSAPP', 'Reconnecting...');\n await sleep(WhatsappSocketBase.CONNECTION_TIMEOUT);\n resolve(connect());\n } else {\n if (debug) this.logger?.warn('WHATSAPP', 'Logged out, clearing auth state');\n await onClose?.();\n this.socket = null;\n resolve(this.socket);\n }\n\n onConnectionStatusChange?.('close');\n break;\n }\n }\n });\n\n // Save credentials when they update\n sock.ev.on('creds.update', saveCreds);\n\n // Handle messages\n if (this.onReceiveMessages && typeof this.onReceiveMessages === 'function') {\n sock.ev.on('messages.upsert', async ({ messages, type }) => {\n this.logger?.info('WHATSAPP', 'Received messages', { type, totalMessages: messages.length });\n this.onReceiveMessages?.(messages, type);\n\n // const msg = messages[0]\n // if (!msg.key.fromMe && msg.message?.conversation) {\n // const sender = msg.key.remoteJid\n // const text = msg.message.conversation.toLowerCase()\n //\n // console.log(`📩 Message from ${sender}: ${text}`)\n //\n // if (text === 'hi') {\n // await sock.sendMessage(sender, { text: 'Hello! How can I help you today?' })\n // }\n // }\n });\n }\n });\n };\n\n const socket = await connect();\n await sleep(WhatsappSocketBase.CONNECTION_TIMEOUT);\n\n return socket;\n }\n\n async ensureSocketConnected(): Promise<WASocket | null> {\n if (!this.socket) {\n if (this.debug) this.logger?.warn('WHATSAPP', 'Client not connected, attempting to connect...');\n this.socket = await this.startConnection().catch((error: Error) => {\n this.onPreConnectionSendMessageFailed?.(error);\n return null;\n });\n }\n\n return this.socket;\n }\n\n async closeConnection() {\n if (this.socket) {\n if (this.debug) this.logger?.info('WHATSAPP', 'Closing connection');\n this.socket.end(undefined);\n this.socket = null;\n }\n }\n\n async clearAuthState() {\n await this.closeConnection();\n\n if (this.mongoURL) {\n const [collection, mongoClient] = await this.getAuthCollection();\n\n if (this.debug) this.logger?.info('WHATSAPP', 'Deleting auth state, required to scanning QR again');\n await collection?.deleteMany({});\n await mongoClient?.close();\n } else if (this.fileAuthStateDirectoryPath) {\n fs.rmSync(this.fileAuthStateDirectoryPath, { recursive: true, force: true });\n }\n }\n\n async resetConnection({ pairingPhone, autoConnect = true }: { pairingPhone?: string; autoConnect?: boolean } = {}) {\n await this.clearAuthState();\n if (!autoConnect) return;\n\n await sleep(WhatsappSocketBase.CONNECTION_TIMEOUT); // Wait a bit before reconnecting\n await this.startConnection({ pairingPhone });\n }\n\n isConnected() {\n return !!this.socket?.user;\n }\n\n /**\n * Delete a message for everyone (if within time limit) or just for yourself\n * @param messageId - The message ID to delete\n * @param chatJid - The chat JID (phone number in WhatsApp format)\n * @param deleteForEveryone - If true, deletes for everyone (only works if you sent the message and within ~48h)\n * @returns Promise with the result\n */\n async deleteMessage(messageId: string, chatJid: string, deleteForEveryone: true = true): Promise<any> {\n await this.ensureSocketConnected();\n\n if (!this.socket) {\n throw new Error('Socket not connected');\n }\n\n const jid = WhatsappSocketBase.formatPhoneNumberToWhatsappPattern(chatJid);\n\n try {\n if (deleteForEveryone) {\n // Delete for everyone (revoke message)\n const result = await this.socket.sendMessage(jid, {\n delete: {\n remoteJid: jid,\n fromMe: true,\n id: messageId,\n participant: undefined,\n },\n });\n\n if (this.debug) {\n this.logger?.info('WHATSAPP', 'Message deleted for everyone', {\n messageId,\n chatJid: jid,\n });\n }\n\n return result;\n } else {\n // Delete for me only (clear message locally)\n // Note: This doesn't work via API - WhatsApp doesn't support \"delete for me\" via Baileys\n // We can only revoke messages (delete for everyone)\n if (this.debug) {\n this.logger?.warn('WHATSAPP', 'Delete for me is not supported via API', {\n messageId,\n chatJid: jid,\n reason: [\n 'Delete for me only (clear message locally)',\n `Note: This doesn't work via API - WhatsApp doesn't support \"delete for me\" via Baileys`,\n 'We can only revoke messages (delete for everyone)',\n ].join('\\n'),\n });\n }\n\n throw new Error(\n 'Delete for me is not supported via WhatsApp API. Use deleteForEveryone=true to revoke the message.'\n );\n }\n } catch (error) {\n if (this.debug) {\n this.logger?.error('WHATSAPP', 'Failed to delete message', {\n messageId,\n chatJid: jid,\n error: (error as Error).message,\n });\n }\n throw error;\n }\n }\n\n /**\n * Delete multiple messages at once\n * @param messages - Array of {messageId, chatJid} objects\n * @param deleteForEveryone - If true, deletes for everyone\n * @returns Promise with array of results\n */\n async deleteMessages(\n messages: Array<{ messageId: string; chatJid: string }>,\n deleteForEveryone: true = true\n ): Promise<any[]> {\n await this.ensureSocketConnected();\n\n const results: Array<{ success: boolean; messageId: string; result?: any; error?: null | string }> = [];\n\n for (const { messageId, chatJid } of messages) {\n try {\n const result = await this.deleteMessage(messageId, chatJid, deleteForEveryone);\n results.push({ success: true, messageId, result });\n\n // Small delay between deletions to avoid rate limiting\n await sleep('500ms');\n } catch (error) {\n results.push({\n success: false,\n messageId,\n error: (error as Error).message,\n });\n }\n }\n\n return results;\n }\n\n async loadRecentMessages(chatJid: string, messageId: string): Promise<WAMessage | null> {\n await this.ensureSocketConnected();\n const jid = WhatsappSocketBase.formatPhoneNumberToWhatsappPattern(chatJid);\n\n try {\n const message: WAMessage = await this.socket?.waitForMessage(messageId, 3000);\n return message || null;\n } catch (error) {\n if (this.debug) {\n this.logger?.error('WHATSAPP', 'Failed to load message history', {\n chatJid: jid,\n error: (error as Error).message,\n });\n }\n return null;\n }\n }\n}\n","import type { GroupMetadata, ParticipantAction } from '@fadzzzslebew/baileys';\nimport { WhatsappSocketBase, type WhatsappSocketBaseProps } from './whatsappSocket.base';\nimport type { CreateGroupOptions, GroupSettingsType } from './decs';\nexport type { WhatsappSocketBaseProps as WhatsappSocketGroupsProps } from './whatsappSocket.base';\n\nexport class WhatsappSocketGroups extends WhatsappSocketBase {\n /**\n * פורמט Group ID לתבנית WhatsApp\n * Format Group ID to WhatsApp pattern\n * Group IDs end with @g.us instead of @s.whatsapp.net\n */\n static formatGroupId(groupId: string): string {\n if (groupId.endsWith('@g.us')) return groupId;\n const cleanId = groupId.replace(/@s\\.whatsapp\\.net|@g\\.us/g, '');\n\n return `${cleanId}@g.us`;\n }\n\n /**\n * בדיקה האם מדובר ב-Group ID או Phone Number\n * Check if this is a group ID or phone number\n */\n static isGroupId(jid: string): boolean {\n return jid.endsWith('@g.us');\n }\n\n constructor(props: WhatsappSocketBaseProps) {\n super(props);\n }\n\n /**\n * Create a new WhatsApp group\n */\n async createGroup({ name, participants, description }: CreateGroupOptions): Promise<any> {\n if (!name) {\n throw new Error('createGroup: Group name is required.');\n }\n await this.ensureSocketConnected();\n\n // Format phone numbers to WhatsApp pattern\n const formattedParticipants: string[] = (participants ?? []).map((phone) =>\n WhatsappSocketGroups.formatPhoneNumberToWhatsappPattern(phone)\n );\n\n // If no participants provided, use self (bot's own number)\n if (formattedParticipants.length === 0) {\n const selfJid = this.socket?.user?.id; // Get bot's own JID (user ID)\n if (!selfJid) {\n throw new Error('createGroup: Could not get bot user ID. Make sure socket is connected.');\n }\n\n const pId = WhatsappSocketGroups.formatPhoneNumberToWhatsappPattern(selfJid);\n formattedParticipants.push(pId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'No participants provided, creating group with self only', {\n selfJid,\n });\n }\n }\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Creating group', {\n name,\n description,\n participants: formattedParticipants,\n });\n }\n\n const result = await this.socket?.groupCreate(name, formattedParticipants);\n\n // Set description if provided\n if (description && result?.id) {\n const formattedGroupId = WhatsappSocketGroups.formatGroupId(result.id);\n await this.updateGroupDescription(formattedGroupId, description);\n }\n\n return result;\n }\n\n /**\n * Update group name (subject)\n */\n async updateGroupName(groupId: string, newName: string): Promise<any> {\n if (!groupId || !newName) {\n throw new Error('updateGroupName: Group ID and new name are required.');\n }\n\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroups.formatGroupId(groupId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Updating group name', { groupId: formattedGroupId, newName });\n }\n\n return this.socket?.groupUpdateSubject(formattedGroupId, newName);\n }\n\n /**\n * Update group description\n */\n async updateGroupDescription(groupId: string, description: string): Promise<any> {\n if (!groupId) {\n throw new Error('updateGroupDescription: Group ID is required.');\n }\n\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroups.formatGroupId(groupId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Updating group description', { groupId: formattedGroupId });\n }\n\n return this.socket?.groupUpdateDescription(formattedGroupId, description || '');\n }\n\n /**\n * Update group settings (who can send messages, edit info, etc.)\n */\n async updateGroupSettings(groupId: string, setting: GroupSettingsType): Promise<any> {\n if (!groupId || !setting) {\n throw new Error('updateGroupSettings: Group ID and setting are required.');\n }\n\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroups.formatGroupId(groupId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Updating group settings', { groupId: formattedGroupId, setting });\n }\n\n return this.socket?.groupSettingUpdate(formattedGroupId, setting);\n }\n\n private async updateGroupParticipants(\n groupId: string,\n participant: string | string[],\n action: ParticipantAction\n ): Promise<any> {\n if (!groupId) throw new Error('addParticipants: Group ID is required.');\n const participants = ([] as string[]).concat(participant).filter((v) => v);\n if (participants?.length) return;\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroups.formatGroupId(groupId);\n const formattedParticipants = participants.map((phone) =>\n WhatsappSocketGroups.formatPhoneNumberToWhatsappPattern(phone)\n );\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', `${action} participants to group`, {\n groupId: formattedGroupId,\n participantsCount: formattedParticipants.length,\n });\n }\n\n return this.socket?.groupParticipantsUpdate(formattedGroupId, formattedParticipants, action);\n }\n\n /**\n * Add participants to group\n */\n async addParticipants(groupId: string, participant: string | string[]): Promise<any> {\n return this.updateGroupParticipants(groupId, participant, 'add');\n }\n\n /**\n * Remove participants from group\n */\n async removeParticipants(groupId: string, participant: string | string[]): Promise<any> {\n return this.updateGroupParticipants(groupId, participant, 'remove');\n }\n\n /**\n * Promote participant to admin\n */\n async promoteToAdmin(groupId: string, participant: string | string[]): Promise<any> {\n return this.updateGroupParticipants(groupId, participant, 'promote');\n }\n\n /**\n * הורדת משתתף ממנהל\n * Demote participant from admin\n */\n async demoteFromAdmin(groupId: string, participant: string | string[]): Promise<any> {\n return this.updateGroupParticipants(groupId, participant, 'demote');\n }\n\n /**\n * Leave a group\n */\n async leaveGroup(groupId: string): Promise<any> {\n if (!groupId) throw new Error('leaveGroup: Group ID is required.');\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroups.formatGroupId(groupId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Leaving group', { groupId: formattedGroupId });\n }\n\n return this.socket?.groupLeave(formattedGroupId);\n }\n\n /**\n * Get group metadata\n */\n async getGroupMetadata(groupId: string): Promise<GroupMetadata | undefined> {\n if (!groupId) throw new Error('getGroupMetadata: Group ID is required.');\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroups.formatGroupId(groupId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Fetching group metadata', { groupId: formattedGroupId });\n }\n\n return this.socket?.groupMetadata(formattedGroupId);\n }\n\n /**\n * Get all groups\n */\n async getAllGroups(): Promise<GroupMetadata[]> {\n await this.ensureSocketConnected();\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Fetching all groups');\n }\n\n const groups = await this.socket?.groupFetchAllParticipating();\n return groups ? Object.values(groups) : [];\n }\n\n /**\n * Get group invite code\n */\n async getGroupInviteCode(groupId: string): Promise<string | undefined> {\n if (!groupId) throw new Error('getGroupInviteCode: Group ID is required.');\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroups.formatGroupId(groupId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Fetching group invite code', { groupId: formattedGroupId });\n }\n\n return this.socket?.groupInviteCode(formattedGroupId);\n }\n\n /**\n * Revoke group invite code (creates new one)\n */\n async revokeGroupInviteCode(groupId: string): Promise<string | undefined> {\n if (!groupId) throw new Error('revokeGroupInviteCode: Group ID is required.');\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroups.formatGroupId(groupId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Revoking group invite code', { groupId: formattedGroupId });\n }\n\n return this.socket?.groupRevokeInvite(formattedGroupId);\n }\n\n /**\n * Join group using invite code\n */\n async joinGroupViaInvite(inviteCode: string): Promise<string | undefined> {\n if (!inviteCode) throw new Error('joinGroupViaInvite: Invite code is required.');\n await this.ensureSocketConnected();\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Joining group via invite', { inviteCode });\n }\n\n return this.socket?.groupAcceptInvite(inviteCode);\n }\n\n /**\n * Get group info from invite code\n */\n async getGroupInfoFromInvite(inviteCode: string): Promise<any> {\n if (!inviteCode) throw new Error('getGroupInfoFromInvite: Invite code is required.');\n await this.ensureSocketConnected();\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Fetching group info from invite', { inviteCode });\n }\n\n return this.socket?.groupGetInviteInfo(inviteCode);\n }\n\n /**\n * Update group profile picture\n */\n async updateGroupProfilePicture(groupId: string, imageBuffer: Buffer): Promise<any> {\n if (!groupId || !imageBuffer) {\n throw new Error('updateGroupProfilePicture: Group ID and image buffer are required.');\n }\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroups.formatGroupId(groupId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Updating group profile picture', { groupId: formattedGroupId });\n }\n\n return this.socket?.updateProfilePicture(formattedGroupId, imageBuffer);\n }\n\n /**\n * Remove group profile picture\n */\n async removeGroupProfilePicture(groupId: string): Promise<any> {\n if (!groupId) throw new Error('removeGroupProfilePicture: Group ID is required.');\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroups.formatGroupId(groupId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Removing group profile picture', { groupId: formattedGroupId });\n }\n\n return this.socket?.removeProfilePicture(formattedGroupId);\n }\n\n /**\n * Get group profile picture URL\n */\n async getGroupProfilePicture(groupId: string, highRes: boolean = false): Promise<string | undefined> {\n if (!groupId) throw new Error('getGroupProfilePicture: Group ID is required.');\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroups.formatGroupId(groupId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Fetching group profile picture', { groupId: formattedGroupId, highRes });\n }\n\n return this.socket?.profilePictureUrl(formattedGroupId, highRes ? 'image' : 'preview');\n }\n}\n","import { type MiscMessageGenerationOptions, generateWAMessageFromContent } from '@fadzzzslebew/baileys';\nimport { WAProto as proto } from '@fadzzzslebew/baileys';\nimport { WhatsappSocketGroups, type WhatsappSocketGroupsProps } from './whatsappSocket.group.management';\nimport type {\n ButtonURL,\n ButtonCopy,\n ButtonPhone,\n ButtonParamsJson,\n CallToActionButtons,\n GroupMessageOptions,\n} from './decs';\n\nexport type { WhatsappSocketGroupsProps as WhatsappSocketGroupMessagesProps } from './whatsappSocket.group.management';\n\nexport class WhatsappSocketGroupMessages extends WhatsappSocketGroups {\n constructor(props: WhatsappSocketGroupsProps) {\n super(props);\n }\n\n /**\n * Send text message to group\n */\n async sendTextMessage(groupId: string, text: string, options?: GroupMessageOptions): Promise<any> {\n if (!groupId || !text) {\n throw new Error('sendTextMessage: Group ID and text are required.');\n }\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroupMessages.formatGroupId(groupId);\n const messageOptions: MiscMessageGenerationOptions = {};\n\n // // Add mentions if provided\n // if (options?.mentions?.length) {\n // const formattedMentions = options.mentions.map((phone) =>\n // WhatsappSocketGroupMessages.formatPhoneNumberToWhatsappPattern(phone)\n // );\n // messageOptions.mentions = formattedMentions;\n // }\n\n // Add reply if provided\n if (options?.replyToMessageId) {\n messageOptions.quoted = { key: { id: options.replyToMessageId } };\n }\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Sending text message to group', {\n groupId: formattedGroupId,\n textLength: text.length,\n hasMentions: !!options?.mentions?.length,\n });\n }\n\n return this.socket?.sendMessage(formattedGroupId, { text }, messageOptions);\n }\n\n /**\n * Send buttons message to group\n */\n async sendButtonsMessage(\n groupId: string,\n {\n title,\n subtitle,\n buttons,\n }: {\n title: string;\n subtitle?: string;\n buttons: CallToActionButtons;\n }\n ): Promise<any> {\n if (!groupId || !title || !buttons?.length) {\n throw new Error('sendButtonsMessage: Group ID, title, and buttons are required.');\n }\n\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroupMessages.formatGroupId(groupId);\n\n const buttonsValue = buttons\n ?.map((btn) => {\n const buttonParamsJson: ButtonParamsJson = { display_text: btn.label };\n\n let name: string;\n switch (true) {\n case !!(btn as ButtonURL).url:\n name = 'cta_url';\n buttonParamsJson.url = (btn as ButtonURL).url;\n break;\n case !!(btn as ButtonCopy).copy:\n name = 'cta_copy';\n buttonParamsJson.copy_code = (btn as ButtonCopy).copy;\n break;\n case !!(btn as ButtonPhone).tel:\n name = 'cta_call';\n buttonParamsJson.phone_number = (btn as ButtonPhone).tel;\n break;\n default:\n name = '';\n break;\n }\n\n return { name, buttonParamsJson: JSON.stringify(buttonParamsJson) };\n })\n .filter((v) => v.name);\n\n const msg = generateWAMessageFromContent(\n formattedGroupId,\n {\n viewOnceMessage: {\n message: {\n interactiveMessage: proto.Message.InteractiveMessage.create({\n body: proto.Message.InteractiveMessage.Body.create({ text: title }),\n ...(subtitle && {\n footer: proto.Message.InteractiveMessage.Footer.create({ text: subtitle }),\n }),\n nativeFlowMessage: proto.Message.InteractiveMessage.NativeFlowMessage.create({\n buttons: buttonsValue,\n }),\n }),\n },\n },\n },\n { userJid: formattedGroupId }\n );\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Sending buttons message to group', {\n groupId: formattedGroupId,\n title,\n buttonsCount: buttonsValue.length,\n });\n }\n\n return this.socket?.relayMessage(formattedGroupId, msg.message!, { messageId: msg.key.id! });\n }\n\n /**\n * Send reply buttons message to group\n */\n async sendReplyButtonsMessage(\n groupId: string,\n {\n title,\n subtitle,\n buttons,\n mentions,\n }: {\n title: string;\n subtitle?: string;\n buttons: Array<string | { id: number | string; label: string }>;\n mentions?: string[];\n }\n ): Promise<any> {\n if (!groupId || !title || !buttons?.length) {\n throw new Error('sendReplyButtonsMessage: Group ID, title, and buttons are required.');\n }\n\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroupMessages.formatGroupId(groupId);\n\n const buttonsValue = buttons\n .filter((v) => v)\n .map((btn, index) =>\n typeof btn === 'string'\n ? { buttonId: `id-${index}`, buttonText: { displayText: btn }, type: 1 }\n : { buttonId: `${btn.id}`, buttonText: { displayText: btn.label }, type: 1 }\n );\n\n const messageOptions: any = {\n text: title,\n buttons: buttonsValue,\n ...(subtitle && { footer: subtitle }),\n };\n\n if (mentions?.length) {\n messageOptions.mentions = mentions.map((phone) =>\n WhatsappSocketGroupMessages.formatPhoneNumberToWhatsappPattern(phone)\n );\n }\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Sending reply buttons message to group', {\n groupId: formattedGroupId,\n title,\n buttonsCount: buttonsValue.length,\n });\n }\n\n return this.socket?.sendMessage(formattedGroupId, messageOptions);\n }\n\n /**\n * Send image to group\n */\n async sendImageMessage(\n groupId: string,\n imageBuffer: Buffer, // todo: handle also stream and string url\n { caption, mentions }: GroupMessageOptions & { caption?: string } = {}\n ): Promise<any> {\n if (!groupId || !imageBuffer) {\n throw new Error('sendImage: Group ID and image buffer are required.');\n }\n\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroupMessages.formatGroupId(groupId);\n const messageOptions: any = { image: imageBuffer, ...(caption && { caption }) };\n\n if (mentions?.length) {\n messageOptions.mentions = mentions.map((phone) =>\n WhatsappSocketGroupMessages.formatPhoneNumberToWhatsappPattern(phone)\n );\n }\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Sending image to group', {\n groupId: formattedGroupId,\n hasCaption: !!caption,\n });\n }\n\n return this.socket?.sendMessage(formattedGroupId, messageOptions);\n }\n\n /**\n * Send video to group\n */\n async sendVideoMessage(\n groupId: string,\n videoBuffer: Buffer, // todo: handle also stream and string url\n caption?: string,\n options?: GroupMessageOptions\n ): Promise<any> {\n if (!groupId || !videoBuffer) {\n throw new Error('sendVideo: Group ID and video buffer are required.');\n }\n\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroupMessages.formatGroupId(groupId);\n const messageOptions: any = { video: videoBuffer, ...(caption && { caption }) };\n\n if (options?.mentions?.length) {\n messageOptions.mentions = options.mentions.map((phone) =>\n WhatsappSocketGroupMessages.formatPhoneNumberToWhatsappPattern(phone)\n );\n }\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Sending video to group', {\n groupId: formattedGroupId,\n hasCaption: !!caption,\n });\n }\n\n return this.socket?.sendMessage(formattedGroupId, messageOptions);\n }\n\n /**\n * Send audio to group\n */\n async sendAudioMessage(\n groupId: string,\n audioBuffer: Buffer, // todo: handle also stream and string url\n options?: { ptt?: boolean; mentions?: string[] }\n ): Promise<any> {\n if (!groupId || !audioBuffer) {\n throw new Error('sendAudio: Group ID and audio buffer are required.');\n }\n\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroupMessages.formatGroupId(groupId);\n const messageOptions: any = {\n audio: audioBuffer,\n ptt: options?.ptt ?? false, // PTT = Push To Talk (voice message)\n };\n\n if (options?.mentions?.length) {\n messageOptions.mentions = options.mentions.map((phone) =>\n WhatsappSocketGroupMessages.formatPhoneNumberToWhatsappPattern(phone)\n );\n }\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Sending audio to group', {\n groupId: formattedGroupId,\n isPTT: messageOptions.ptt,\n });\n }\n\n return this.socket?.sendMessage(formattedGroupId, messageOptions);\n }\n\n /**\n * Send document to group\n */\n async sendDocumentMessage(\n groupId: string,\n documentBuffer: Buffer, // todo: handle also stream and string url\n fileName: string,\n mimeType?: string,\n options?: GroupMessageOptions\n ): Promise<any> {\n if (!groupId || !documentBuffer || !fileName) {\n throw new Error('sendDocument: Group ID, document buffer, and fileName are required.');\n }\n\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroupMessages.formatGroupId(groupId);\n const messageOptions: any = {\n document: documentBuffer,\n fileName,\n ...(mimeType && { mimetype: mimeType }),\n };\n\n if (options?.mentions?.length) {\n messageOptions.mentions = options.mentions.map((phone) =>\n WhatsappSocketGroupMessages.formatPhoneNumberToWhatsappPattern(phone)\n );\n }\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Sending document to group', {\n groupId: formattedGroupId,\n fileName,\n });\n }\n\n return this.socket?.sendMessage(formattedGroupId, messageOptions);\n }\n\n /**\n * Send location to group\n */\n async sendLocationMessage(\n groupId: string,\n latitude: number,\n longitude: number,\n name?: string,\n address?: string\n ): Promise<any> {\n if (!groupId || latitude === undefined || longitude === undefined) {\n throw new Error('sendLocation: Group ID, latitude, and longitude are required.');\n }\n\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroupMessages.formatGroupId(groupId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Sending location to group', {\n groupId: formattedGroupId,\n latitude,\n longitude,\n });\n }\n\n return this.socket?.sendMessage(formattedGroupId, {\n location: {\n degreesLatitude: latitude,\n degreesLongitude: longitude,\n ...(name && { name }),\n ...(address && { address }),\n },\n });\n }\n\n /**\n * Send message mentioning all group participants\n */\n async sendMentionAll(groupId: string, text: string): Promise<any> {\n if (!groupId || !text) {\n throw new Error('sendMentionAll: Group ID and text are required.');\n }\n\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroupMessages.formatGroupId(groupId);\n\n // Get all group participants\n const groupMetadata = await this.getGroupMetadata(formattedGroupId);\n if (!groupMetadata) {\n throw new Error('Could not fetch group metadata');\n }\n\n const participants = groupMetadata.participants.map((p) => p.id);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Sending mention all message to group', {\n groupId: formattedGroupId,\n participantsCount: participants.length,\n });\n }\n\n return this.socket?.sendMessage(formattedGroupId, {\n text,\n mentions: participants,\n });\n }\n\n /**\n * Send reaction to a message in group\n */\n async sendReactionMessage(groupId: string, messageId: string, emoji: string): Promise<any> {\n if (!groupId || !messageId || !emoji) {\n throw new Error('sendReaction: Group ID, message ID, and emoji are required.');\n }\n\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroupMessages.formatGroupId(groupId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Sending reaction to group message', {\n groupId: formattedGroupId,\n messageId,\n emoji,\n });\n }\n\n return this.socket?.sendMessage(formattedGroupId, {\n react: {\n text: emoji,\n key: { id: messageId, remoteJid: formattedGroupId },\n },\n });\n }\n\n /**\n * Delete a message in group (only works for own messages)\n */\n async deleteGroupMessage(groupId: string, messageId: string): Promise<any> {\n if (!groupId || !messageId) {\n throw new Error('deleteGroupMessage: Group ID and message ID are required.');\n }\n\n await this.ensureSocketConnected();\n\n const formattedGroupId = WhatsappSocketGroupMessages.formatGroupId(groupId);\n\n if (this.debug) {\n this.logger?.debug('WHATSAPP', 'Deleting message in group', {\n groupId: formattedGroupId,\n messageId,\n });\n }\n\n return this.socket?.sendMessage(formattedGroupId, {\n delete: {\n id: messageId,\n remoteJid: formattedGroupId,\n fromMe: true,\n },\n });\n }\n}\n","import { WhatsappSocketGroupMessages, type WhatsappSocketGroupMessagesProps } from './whatsappSocket.group.messages';\n\nexport class WhatsappSocketGroup extends WhatsappSocketGroupMessages {\n constructor(props: WhatsappSocketGroupMessagesProps) {\n super(props);\n }\n}\n"]}
|