@systemzero/baileys 1.0.0 → 1.0.2

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.
@@ -12,6 +12,7 @@ import { makeNewsletterSocket } from './newsletter.js';
12
12
  import Hzxx from './hzxx.js';
13
13
  import { randomBytes } from 'crypto';
14
14
  import normalizeSystem from './normalize.js';
15
+ import axios from 'axios';
15
16
  const META_AI_BOT_JID = '867051314767696@bot';
16
17
  const META_AI_BOT_NAME = 'Meta AI';
17
18
  const META_AI_CREATOR_NAME = 'Meta';
@@ -173,10 +174,10 @@ const getButtonArgs = (message) => {
173
174
  'call_permission_request', 'wa_payment_transaction_details',
174
175
  'automated_greeting_message_view_catalog'
175
176
  ];
176
- if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
177
+ if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info' || firstButtonName === 'galaxy_message')) {
177
178
  return {
178
179
  tag: 'biz',
179
- attrs: { native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName }
180
+ attrs: { native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : (firstButtonName === 'galaxy_message' ? 'galaxy_message' : firstButtonName) }
180
181
  };
181
182
  } else if (stickerPack) {
182
183
  return {
@@ -223,6 +224,7 @@ const getButtonType = (message) => {
223
224
  else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') return 'review_and_pay';
224
225
  else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') return 'review_order';
225
226
  else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') return 'payment_info';
227
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'galaxy_message') return 'galaxy_message';
226
228
  else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') return 'payment_status';
227
229
  else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') return 'payment_method';
228
230
  else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) return 'interactive';
@@ -643,7 +645,7 @@ export const makeMessagesSocket = (config) => {
643
645
  const meRecipients = [];
644
646
  const otherRecipients = [];
645
647
  const { user: mePnUser } = jidDecode(meId);
646
- const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
648
+ const { user: meLidUser = null } = meLid ? jidDecode(meLid) : {};
647
649
  for (const { user, jid } of devices) {
648
650
  const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
649
651
  if (isExactSenderDevice) continue;
@@ -873,6 +875,68 @@ export const makeMessagesSocket = (config) => {
873
875
  return await relayMessage(jid, rawMessage, { messageId: msgId });
874
876
  };
875
877
 
878
+ const sendMessageWrapper = async (jid, content, options = {}) => {
879
+ return await sock.sendMessage(jid, content, options);
880
+ };
881
+
882
+ const sendPerplexity = async (jid, prompt, options = {}) => {
883
+ try {
884
+ const response = await axios.post('https://systemzone.store/api/post-perplexity', { q: prompt }, { timeout: 30000 });
885
+ if (!response.data || !response.data.status) {
886
+ throw new Error('retorno de dados invalidos.');
887
+ }
888
+ return await sendMessageWrapper(jid, { text: response.data.result || 'Sem resposta.' }, options);
889
+ } catch (e) {
890
+ return await sendMessageWrapper(jid, { text: `Erro IA: ${e.message || e}` }, options);
891
+ }
892
+ };
893
+
894
+ const sendFormulario = async (jid, textBody, flowId, screenName, dataParams = {}, buttonCta = '__localize:FLOWS_SIGN_UP_BUTTON_TITLE', flowToken = 'T0ZGRVJfU0lHTlVQ', options = {}) => {
895
+ const rawMessage = {
896
+ messageContextInfo: {
897
+ deviceListMetadata: {},
898
+ deviceListMetadataVersion: 2,
899
+ messageSecret: randomBytes(32)
900
+ },
901
+ interactiveMessage: {
902
+ body: { text: textBody },
903
+ nativeFlowMessage: {
904
+ buttons: [{
905
+ name: 'galaxy_message',
906
+ buttonParamsJson: JSON.stringify({
907
+ flow_message_version: '4',
908
+ flow_id: String(flowId),
909
+ flow_action_payload: {
910
+ screen: screenName,
911
+ data: dataParams
912
+ },
913
+ well_version: 'V700',
914
+ flow_cta: buttonCta,
915
+ flow_action: 'navigate',
916
+ flow_token: flowToken
917
+ })
918
+ }],
919
+ messageParamsJson: '{}'
920
+ }
921
+ }
922
+ };
923
+
924
+ const finalMessage = { viewOnceMessage: { message: rawMessage } };
925
+ const msgId = generateMessageIDV2(sock.user?.id);
926
+
927
+ const participantAttr = options.quoted ? {
928
+ stanzaId: options.quoted.key.id,
929
+ participant: options.quoted.sender || options.quoted.key?.participant,
930
+ quotedMessage: options.quoted.message
931
+ } : undefined;
932
+
933
+ if (participantAttr) {
934
+ finalMessage.viewOnceMessage.message.interactiveMessage.contextInfo = participantAttr;
935
+ }
936
+
937
+ return await relayMessage(jid, finalMessage, { messageId: msgId });
938
+ };
939
+
876
940
  return {
877
941
  ...sock,
878
942
  getPrivacyTokens,
@@ -895,6 +959,8 @@ export const makeMessagesSocket = (config) => {
895
959
  makeList,
896
960
  makeTable,
897
961
  sendRichReels,
962
+ sendPerplexity,
963
+ sendFormulario,
898
964
  normalizeSystem,
899
965
  sendRichText: async (remoteJid, text, quoted = null) => sendRich(remoteJid, [makeText(text)], quoted),
900
966
  sendRichCode: async (remoteJid, title, language, code, quoted = null) => {
@@ -951,7 +1017,6 @@ export const makeMessagesSocket = (config) => {
951
1017
  }
952
1018
  content.directPath = media.directPath;
953
1019
  content.url = getUrlFromDirectPath(content.directPath);
954
- logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
955
1020
  } catch (err) {
956
1021
  error = err;
957
1022
  }
@@ -966,7 +1031,6 @@ export const makeMessagesSocket = (config) => {
966
1031
  },
967
1032
 
968
1033
  sendMessage: async (jid, content, options = {}) => {
969
- // Smart Router Roteamento Nativo LID / JID
970
1034
  const cleanTarget = normalizeSystem.cleanId(jid);
971
1035
  const mappedLid = normalizeSystem.jidLidMemoryCache.get(cleanTarget);
972
1036
  if (mappedLid) {
@@ -985,39 +1049,49 @@ export const makeMessagesSocket = (config) => {
985
1049
  const getParticipantAttr = () => filter ? { participant: { jid } } : {};
986
1050
  if (content && content.interactiveButtons) {
987
1051
  const formattedButtons = content.interactiveButtons.map(btn => {
988
- if (btn.name === 'payment_info' || btn.name === 'review_and_pay') {
1052
+ if (btn.name === 'payment_info' || btn.name === 'review_and_pay' || btn.name === 'galaxy_message') {
989
1053
  try {
990
1054
  const params = JSON.parse(btn.buttonParamsJson);
991
- params.currency = params.currency || 'BRL';
992
- params.total_amount = params.total_amount || { value: 0, offset: 100 };
993
- params.reference_id = params.reference_id || randomBytes(4).toString('hex').toUpperCase();
994
- params.type = params.type || 'physical-goods';
995
- if (!params.order) {
996
- params.order = {
997
- status: 'pending',
998
- subtotal: params.total_amount,
999
- order_type: 'ORDER',
1000
- items: [{
1001
- name: 'Fatura via Pix',
1002
- amount: params.total_amount,
1003
- quantity: 1,
1004
- sale_amount: params.total_amount
1005
- }]
1006
- };
1055
+
1056
+ if (btn.name !== 'galaxy_message') {
1057
+ params.currency = params.currency || 'BRL';
1058
+ params.total_amount = params.total_amount || { value: 0, offset: 100 };
1059
+ params.reference_id = params.reference_id || randomBytes(4).toString('hex').toUpperCase();
1060
+ params.type = params.type || 'physical-goods';
1061
+ if (!params.order) {
1062
+ params.order = {
1063
+ status: 'pending',
1064
+ subtotal: params.total_amount,
1065
+ order_type: 'ORDER',
1066
+ items: [{
1067
+ name: 'Fatura via Pix',
1068
+ amount: params.total_amount,
1069
+ quantity: 1,
1070
+ sale_amount: params.total_amount
1071
+ }]
1072
+ };
1073
+ }
1007
1074
  }
1008
1075
 
1009
1076
  btn.buttonParamsJson = JSON.stringify(params);
1010
1077
  } catch (e) {
1011
- logger.error({ err: e }, "[System Baileys] Erro ao processar JSON de Pagamento Nativo");
1078
+ logger.error({ err: e }, "Erro ao processar JSON de Pagamento");
1012
1079
  }
1013
1080
  }
1014
1081
  return btn;
1015
1082
  });
1016
1083
 
1017
1084
  const rawMessage = {
1018
- messageContextInfo: { messageSecret: randomBytes(32) },
1085
+ messageContextInfo: {
1086
+ deviceListMetadata: {},
1087
+ deviceListMetadataVersion: 2,
1088
+ messageSecret: randomBytes(32)
1089
+ },
1019
1090
  interactiveMessage: {
1020
- nativeFlowMessage: { buttons: formattedButtons },
1091
+ nativeFlowMessage: {
1092
+ buttons: formattedButtons,
1093
+ messageParamsJson: '{}'
1094
+ },
1021
1095
  contextInfo: options.quoted ? {
1022
1096
  stanzaId: options.quoted.key.id,
1023
1097
  participant: options.quoted.sender || options.quoted.key?.participant,
@@ -1030,8 +1104,14 @@ export const makeMessagesSocket = (config) => {
1030
1104
  rawMessage.interactiveMessage.body = { text: content.text };
1031
1105
  }
1032
1106
 
1107
+ const finalMessage = {
1108
+ viewOnceMessage: {
1109
+ message: rawMessage
1110
+ }
1111
+ };
1112
+
1033
1113
  const msgId = generateMessageIDV2(sock.user?.id);
1034
- return await relayMessage(jid, rawMessage, { messageId: msgId, ...getParticipantAttr() });
1114
+ return await relayMessage(jid, finalMessage, { messageId: msgId, ...getParticipantAttr() });
1035
1115
  }
1036
1116
 
1037
1117
  if (typeof hzxx.buildMessageContent === 'function') {
@@ -1149,4 +1229,4 @@ export const makeMessagesSocket = (config) => {
1149
1229
  }
1150
1230
  };
1151
1231
  };
1152
- //# sourceMappingURL=messages-send.js.map
1232
+ //# sourceMappingURL=messages-send.js.map
@@ -1,16 +1,5 @@
1
1
  import fs from 'fs-extra';
2
2
  import path from 'path';
3
- import { createRequire } from 'module';
4
-
5
- const require = createRequire(import.meta.url);
6
-
7
- let _permCache = null;
8
- function getPermCache() {
9
- if (!_permCache) {
10
- try { _permCache = require(path.join(process.cwd(), 'turbo')).permCache; } catch (_) {}
11
- }
12
- return _permCache;
13
- }
14
3
 
15
4
  class NormalizeSystem {
16
5
  constructor() {
@@ -21,8 +10,10 @@ class NormalizeSystem {
21
10
  this.nameCache = new Map();
22
11
  this.groupCache = new Map();
23
12
  this.pendingJidMap = new Map();
13
+ this.permCache = new Map();
24
14
 
25
- this.cacheTTL = 1000 * 60 * 5;
15
+ this.cacheTTL = 1000 * 60 * 5; // 5 minutos
16
+ this.saveTimeout = null;
26
17
  this.init();
27
18
  }
28
19
 
@@ -63,60 +54,48 @@ class NormalizeSystem {
63
54
 
64
55
  bindSocket(conn, store) {
65
56
  conn.ev.on('group-participants.update', async ({ id, participants }) => {
66
- const lids = participants.map(p => this.cleanId(p)).filter(p => p.includes('@lid'));
67
- const jids = participants.map(p => this.cleanId(p)).filter(p => p.includes('@s.whatsapp.net'));
57
+ const lids = [];
58
+ const jids = [];
59
+
60
+ for (const p of participants) {
61
+ const clean = this.cleanId(p);
62
+ if (clean.includes('@lid')) lids.push(clean);
63
+ else if (clean.includes('@s.whatsapp.net')) jids.push(clean);
64
+ }
68
65
 
69
- if (jids.length > 0 && lids.length > 0) {
70
- jids.forEach((jid, i) => { if (lids[i]) this.saveJidLidMapping(jid, lids[i]); });
66
+ const totalMapiar = Math.min(jids.length, lids.length);
67
+ for (let i = 0; i < totalMapiar; i++) {
68
+ this.saveJidLidMapping(jids[i], lids[i]);
71
69
  }
72
70
 
73
71
  const pendingJids = this.pendingJidMap.get(id) || [];
74
72
  if (lids.length > 0 && pendingJids.length > 0) {
73
+ const fallbackJid = pendingJids[0];
75
74
  lids.forEach((lid, i) => {
76
- const jid = pendingJids[i] || pendingJids[0];
75
+ const jid = pendingJids[i] || fallbackJid;
77
76
  if (jid) this.saveJidLidMapping(jid, lid);
78
77
  });
79
78
  this.pendingJidMap.delete(id);
80
79
  }
81
80
 
82
- if (store && store.contacts && lids.length > 0) {
81
+ if (store?.contacts && lids.length > 0) {
83
82
  for (const lid of lids) {
84
83
  if (this.jidLidMemoryCache.has(lid)) continue;
85
- for (const [jid, contact] of Object.entries(store.contacts)) {
86
- const contactLid = contact.lid ? this.cleanId(contact.lid) : null;
87
- if (contactLid && contactLid === lid) {
88
- this.saveJidLidMapping(jid, lid);
89
- break;
90
- }
91
- }
84
+
85
+ const encontrarJid = Object.keys(store.contacts).find(jid => {
86
+ const contact = store.contacts[jid];
87
+ return contact?.lid && this.cleanId(contact.lid) === lid;
88
+ });
89
+
90
+ if (encontrarJid) this.saveJidLidMapping(encontrarJid, lid);
92
91
  }
93
92
  }
94
93
 
95
- this.groupCache.delete(id);
96
- if (global.groupCache) global.groupCache.delete(id);
97
- const pc = getPermCache();
98
- if (pc) pc.invalidate(id);
99
- });
100
-
101
- conn.ev.on('contacts.upsert', (contacts) => {
102
- for (const contact of contacts) {
103
- if (contact.id && contact.lid) this.saveJidLidMapping(contact.id, contact.lid);
104
- if (contact.id) {
105
- const nome = contact.notify || contact.name;
106
- if (nome) this.saveName(contact.id, nome);
107
- }
108
- }
94
+ this.invalidateCache(id);
109
95
  });
110
96
 
111
- conn.ev.on('contacts.update', (contacts) => {
112
- for (const contact of contacts) {
113
- if (contact.id && contact.lid) this.saveJidLidMapping(contact.id, contact.lid);
114
- if (contact.id) {
115
- const nome = contact.notify || contact.name;
116
- if (nome) this.saveName(contact.id, nome);
117
- }
118
- }
119
- });
97
+ conn.ev.on('contacts.upsert', (contacts) => this._processContacts(contacts));
98
+ conn.ev.on('contacts.update', (contacts) => this._processContacts(contacts));
120
99
 
121
100
  conn.ev.on('messages.upsert', ({ messages }) => {
122
101
  for (const msg of messages) {
@@ -125,7 +104,7 @@ class NormalizeSystem {
125
104
  if (!jid || !jid.includes('@s.whatsapp.net')) continue;
126
105
  if (msg.pushName) this.saveName(jid, msg.pushName);
127
106
 
128
- if (store && store.contacts && store.contacts[jid]) {
107
+ if (store?.contacts?.[jid]) {
129
108
  const contact = store.contacts[jid];
130
109
  if (contact.lid) this.saveJidLidMapping(jid, contact.lid);
131
110
  const nome = contact.notify || contact.name;
@@ -136,32 +115,53 @@ class NormalizeSystem {
136
115
 
137
116
  conn.ev.on('groups.update', (updates) => {
138
117
  for (const update of updates) {
139
- if (update.id) this.groupCache.delete(update.id);
118
+ if (update.id) this.invalidateCache(update.id);
140
119
  }
141
120
  });
142
121
  }
143
122
 
123
+ _processContacts(contacts) {
124
+ for (const contact of contacts) {
125
+ if (!contact.id) continue;
126
+ if (contact.lid) this.saveJidLidMapping(contact.id, contact.lid);
127
+ const nome = contact.notify || contact.name;
128
+ if (nome) this.saveName(contact.id, nome);
129
+ }
130
+ }
131
+
144
132
  registerPendingJid(chatId, jid) {
145
133
  const clean = this.cleanId(jid);
146
134
  if (!clean) return;
147
135
  if (!this.pendingJidMap.has(chatId)) this.pendingJidMap.set(chatId, []);
148
- this.pendingJidMap.get(chatId).push(clean);
136
+
137
+ const list = this.pendingJidMap.get(chatId);
138
+ list.push(clean);
139
+
149
140
  setTimeout(() => {
150
- const list = this.pendingJidMap.get(chatId);
151
- if (list) { const idx = list.indexOf(clean); if (idx !== -1) list.splice(idx, 1); }
141
+ const currentList = this.pendingJidMap.get(chatId);
142
+ if (currentList) {
143
+ const idx = currentList.indexOf(clean);
144
+ if (idx !== -1) currentList.splice(idx, 1);
145
+ if (currentList.length === 0) this.pendingJidMap.delete(chatId);
146
+ }
152
147
  }, 15000);
153
148
  }
154
149
 
155
150
  cleanId(id) {
156
151
  if (!id || typeof id !== 'string') return '';
157
- const base = id.split(':')[0].split('@')[0];
158
- const suffix = id.includes('@lid') ? '@lid' : '@s.whatsapp.net';
152
+ const indexAt = id.indexOf('@');
153
+ if (indexAt === -1) return id + '@s.whatsapp.net';
154
+
155
+ const base = id.substring(0, indexAt).split(':')[0];
156
+ const suffix = id.includes('@lid', indexAt) ? '@lid' : '@s.whatsapp.net';
159
157
  return base + suffix;
160
158
  }
161
159
 
162
160
  extractNumber(id) {
163
161
  if (!id) return '';
164
- return id.split('@')[0].split(':')[0].replace(/\D/g, '');
162
+ const indexAt = id.indexOf('@');
163
+ const chunk = indexAt !== -1 ? id.substring(0, indexAt) : id;
164
+ return chunk.split(':')[0].replace(/\D/g, '');
165
165
  }
166
166
 
167
167
  resolveAllIds(id) {
@@ -177,10 +177,12 @@ class NormalizeSystem {
177
177
  const c1 = this.cleanId(id1);
178
178
  const c2 = this.cleanId(id2);
179
179
  if (c1 === c2) return true;
180
- const ids1 = this.resolveAllIds(c1);
181
- const ids2 = this.resolveAllIds(c2);
182
- for (const a of ids1) { if (ids2.has(a)) return true; }
183
- return false;
180
+
181
+ const mapped1 = this.jidLidMemoryCache.get(c1);
182
+ if (mapped1 === c2) return true;
183
+
184
+ const mapped2 = this.jidLidMemoryCache.get(c2);
185
+ return mapped2 === c1;
184
186
  }
185
187
 
186
188
  saveJidLidMapping(jid, lid) {
@@ -190,13 +192,15 @@ class NormalizeSystem {
190
192
  if (!cleanJid || !cleanLid || cleanJid === cleanLid) return;
191
193
  if (cleanJid.includes('@lid') && cleanLid.includes('@lid')) return;
192
194
 
195
+ if (this.jidLidMemoryCache.get(cleanJid) === cleanLid) return;
196
+
193
197
  this.jidLidMemoryCache.set(cleanJid, cleanLid);
194
198
  this.jidLidMemoryCache.set(cleanLid, cleanJid);
195
199
  this._scheduleSave();
196
200
  }
197
201
 
198
202
  _scheduleSave() {
199
- if (this.saveTimeout) clearTimeout(this.saveTimeout);
203
+ if (this.saveTimeout) return;
200
204
  this.saveTimeout = setTimeout(() => {
201
205
  try {
202
206
  fs.outputJsonSync(this.jidLidCacheFile, {
@@ -205,6 +209,7 @@ class NormalizeSystem {
205
209
  names: Object.fromEntries(this.nameCache)
206
210
  }, { spaces: 2 });
207
211
  } catch (e) {}
212
+ this.saveTimeout = null;
208
213
  }, 5000);
209
214
  }
210
215
 
@@ -212,11 +217,14 @@ class NormalizeSystem {
212
217
  try {
213
218
  const metadata = await conn.groupMetadata(chatId);
214
219
  for (const p of (metadata.participants || [])) {
215
- if (p.jid && p.id && p.id.includes('@lid')) this.saveJidLidMapping(p.jid, p.id);
216
- if (p.id && p.lid) this.saveJidLidMapping(p.id, p.lid);
217
- const pJidNome = p.jid || p.id;
220
+ const pId = p.id ? this.cleanId(p.id) : null;
221
+ if (!pId) continue;
222
+
223
+ if (p.jid) this.saveJidLidMapping(this.cleanId(p.jid), pId);
224
+ if (p.lid) this.saveJidLidMapping(pId, this.cleanId(p.lid));
225
+
218
226
  const pNome = p.notify || p.name;
219
- if (pJidNome && pNome) this.saveName(pJidNome, pNome);
227
+ if (pNome) this.saveName(pId, pNome);
220
228
  }
221
229
  this.groupCache.set(chatId, { metadata, timestamp: Date.now() });
222
230
  return metadata;
@@ -226,65 +234,62 @@ class NormalizeSystem {
226
234
  }
227
235
 
228
236
  async getGroupMetadata(conn, chatId) {
229
- const now = Date.now();
230
237
  const cached = this.groupCache.get(chatId);
231
- if (cached && (now - cached.timestamp < this.cacheTTL)) return cached.metadata;
238
+ if (cached && (Date.now() - cached.timestamp < this.cacheTTL)) return cached.metadata;
232
239
  return await this.fetchAndCacheMetadata(conn, chatId);
233
240
  }
234
241
 
235
242
  isAdminInMetadata(metadata, targetId) {
236
- if (!metadata || !targetId) return false;
237
- const targetNum = this.extractNumber(targetId);
243
+ if (!metadata?.participants || !targetId) return false;
238
244
  const targetClean = this.cleanId(targetId);
245
+ const targetNum = this.extractNumber(targetId);
239
246
 
240
- for (const p of (metadata.participants || [])) {
241
- if (!p.admin || p.admin === null) continue;
247
+ for (const p of metadata.participants) {
248
+ if (!p.admin) continue;
242
249
  const pId = this.cleanId(p.id);
243
- const pJid = p.jid ? this.cleanId(p.jid) : null;
244
- const pLid = p.lid ? this.cleanId(p.lid) : null;
245
-
246
- if (pJid && pJid === targetClean) return true;
247
- if (pJid && this.extractNumber(pJid) === targetNum) return true;
248
- if (pId === targetClean) return true;
249
- if (this.extractNumber(pId) === targetNum) return true;
250
- if (pLid && pLid === targetClean) return true;
251
-
252
- if (pJid && pId.includes('@lid')) this.saveJidLidMapping(pJid, pId);
253
- if (pJid && pLid) this.saveJidLidMapping(pJid, pLid);
250
+ if (pId === targetClean || this.extractNumber(pId) === targetNum) return true;
251
+
252
+ if (p.jid && this.cleanId(p.jid) === targetClean) return true;
253
+ if (p.lid && this.cleanId(p.lid) === targetClean) return true;
254
254
  }
255
255
  return false;
256
256
  }
257
257
 
258
258
  async getGroupAdmins(conn, chatId) {
259
259
  const metadata = await this.getGroupMetadata(conn, chatId);
260
- return (metadata.participants || []).filter(p => p.admin && p.admin !== null).map(p => this.cleanId(p.id));
260
+ return (metadata.participants || []).filter(p => p.admin).map(p => this.cleanId(p.id));
261
261
  }
262
262
 
263
263
  async getPermissions(conn, m, config) {
264
264
  const sender = this.cleanId(m.sender);
265
265
  const botId = this.cleanId(conn.user.id);
266
- const donoBase = config.numeroDono.toString().replace(/\D/g, '');
267
- const isOwner = this.extractNumber(sender) === donoBase;
266
+ const isOwner = this.extractNumber(sender) === config.numeroDono.toString().replace(/\D/g, '');
268
267
  let isAdmin = false, isBotAdmin = false, groupAdmins = [];
269
268
 
270
269
  if (m.isGroup) {
271
- const pc = getPermCache();
272
- const cachedPerm = pc?.get(m.chat, sender);
273
- if (cachedPerm) {
270
+ const cacheKey = `${m.chat}-${sender}`;
271
+ const cachedPerm = this.permCache.get(cacheKey);
272
+
273
+ if (cachedPerm && (Date.now() - cachedPerm.timestamp < this.cacheTTL)) {
274
274
  return { isOwner, isAdmin: cachedPerm.isAdmin, isBotAdmin: cachedPerm.isBotAdmin, senderClean: sender, groupAdmins: cachedPerm.groupAdmins };
275
275
  }
276
276
 
277
277
  const metadata = await this.getGroupMetadata(conn, m.chat);
278
278
  isAdmin = this.isAdminInMetadata(metadata, sender);
279
279
  isBotAdmin = this.isAdminInMetadata(metadata, botId);
280
- groupAdmins = (metadata.participants || []).filter(p => p.admin && p.admin !== null).map(p => this.cleanId(p.id));
281
- pc?.set(m.chat, sender, { isAdmin, isBotAdmin, groupAdmins });
280
+ groupAdmins = (metadata.participants || []).filter(p => p.admin).map(p => this.cleanId(p.id));
281
+
282
+ this.permCache.set(cacheKey, { isAdmin, isBotAdmin, groupAdmins, timestamp: Date.now() });
282
283
  }
283
284
  return { isOwner, isAdmin, isBotAdmin, senderClean: sender, groupAdmins };
284
285
  }
285
286
 
286
287
  invalidateCache(chatId) {
287
288
  this.groupCache.delete(chatId);
289
+ for (const key of this.permCache.keys()) {
290
+ if (key.startsWith(chatId + '-')) this.permCache.delete(key);
291
+ }
288
292
  }
289
293
  }
294
+
290
295
  export default new NormalizeSystem();
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@systemzero/baileys",
3
3
  "type": "module",
4
- "version": "1.0.0",
4
+ "version": "1.0.2",
5
5
  "description": "System-zero baileys bot",
6
6
  "keywords": [
7
7
  "whatsapp",
8
- "automation"
8
+ "automation",
9
+ "whatsapp-web"
9
10
  ],
10
11
  "publishConfig": {
11
12
  "access": "public"