ai-md-baileys 1.0.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ const major = parseInt(process.versions.node.split('.')[0], 10);
2
+
3
+ if (major < 20) {
4
+ console.error(
5
+ `\n❌ This package requires Node.js 20+ to run reliably.\n` +
6
+ ` You are using Node.js ${process.versions.node}.\n` +
7
+ ` Please upgrade to Node.js 20+ to proceed.\n`
8
+ );
9
+ process.exit(1);
10
+ }
@@ -0,0 +1,432 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import { WAMessageStubType } from '../Types/index.js';
3
+ import { generateMessageID, generateMessageIDV2, unixTimestampSeconds } from '../Utils/index.js';
4
+ import logger from '../Utils/logger.js';
5
+ import { getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString, jidEncode, jidNormalizedUser } from '../WABinary/index.js';
6
+ import { makeBusinessSocket } from './business.js';
7
+ export const makeCommunitiesSocket = (config) => {
8
+ const sock = makeBusinessSocket(config);
9
+ const { authState, ev, query, upsertMessage } = sock;
10
+ const communityQuery = async (jid, type, content) => query({
11
+ tag: 'iq',
12
+ attrs: {
13
+ type,
14
+ xmlns: 'w:g2',
15
+ to: jid
16
+ },
17
+ content
18
+ });
19
+ const communityMetadata = async (jid) => {
20
+ const result = await communityQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }]);
21
+ return extractCommunityMetadata(result);
22
+ };
23
+ const communityFetchAllParticipating = async () => {
24
+ const result = await query({
25
+ tag: 'iq',
26
+ attrs: {
27
+ to: '@g.us',
28
+ xmlns: 'w:g2',
29
+ type: 'get'
30
+ },
31
+ content: [
32
+ {
33
+ tag: 'participating',
34
+ attrs: {},
35
+ content: [
36
+ { tag: 'participants', attrs: {} },
37
+ { tag: 'description', attrs: {} }
38
+ ]
39
+ }
40
+ ]
41
+ });
42
+ const data = {};
43
+ const communitiesChild = getBinaryNodeChild(result, 'communities');
44
+ if (communitiesChild) {
45
+ const communities = getBinaryNodeChildren(communitiesChild, 'community');
46
+ for (const communityNode of communities) {
47
+ const meta = extractCommunityMetadata({
48
+ tag: 'result',
49
+ attrs: {},
50
+ content: [communityNode]
51
+ });
52
+ data[meta.id] = meta;
53
+ }
54
+ }
55
+ sock.ev.emit('groups.update', Object.values(data));
56
+ return data;
57
+ };
58
+ async function parseGroupResult(node) {
59
+ logger.info({ node }, 'parseGroupResult');
60
+ const groupNode = getBinaryNodeChild(node, 'group');
61
+ if (groupNode) {
62
+ try {
63
+ logger.info({ groupNode }, 'groupNode');
64
+ const metadata = await sock.groupMetadata(`${groupNode.attrs.id}@g.us`);
65
+ return metadata ? metadata : Optional.empty();
66
+ }
67
+ catch (error) {
68
+ console.error('Error parsing group metadata:', error);
69
+ return Optional.empty();
70
+ }
71
+ }
72
+ return Optional.empty();
73
+ }
74
+ const Optional = {
75
+ empty: () => null,
76
+ of: (value) => (value !== null ? { value } : null)
77
+ };
78
+ sock.ws.on('CB:ib,,dirty', async (node) => {
79
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
80
+ if (attrs.type !== 'communities') {
81
+ return;
82
+ }
83
+ await communityFetchAllParticipating();
84
+ await sock.cleanDirtyBits('groups');
85
+ });
86
+ return {
87
+ ...sock,
88
+ communityQuery,
89
+ communityMetadata,
90
+ communityCreate: async (subject, body) => {
91
+ const descriptionId = generateMessageID().substring(0, 12);
92
+ const result = await communityQuery('@g.us', 'set', [
93
+ {
94
+ tag: 'create',
95
+ attrs: { subject },
96
+ content: [
97
+ {
98
+ tag: 'description',
99
+ attrs: { id: descriptionId },
100
+ content: [
101
+ {
102
+ tag: 'body',
103
+ attrs: {},
104
+ content: Buffer.from(body || '', 'utf-8')
105
+ }
106
+ ]
107
+ },
108
+ {
109
+ tag: 'parent',
110
+ attrs: { default_membership_approval_mode: 'request_required' }
111
+ },
112
+ {
113
+ tag: 'allow_non_admin_sub_group_creation',
114
+ attrs: {}
115
+ },
116
+ {
117
+ tag: 'create_general_chat',
118
+ attrs: {}
119
+ }
120
+ ]
121
+ }
122
+ ]);
123
+ return await parseGroupResult(result);
124
+ },
125
+ communityCreateGroup: async (subject, participants, parentCommunityJid) => {
126
+ const key = generateMessageIDV2();
127
+ const result = await communityQuery('@g.us', 'set', [
128
+ {
129
+ tag: 'create',
130
+ attrs: {
131
+ subject,
132
+ key
133
+ },
134
+ content: [
135
+ ...participants.map(jid => ({
136
+ tag: 'participant',
137
+ attrs: { jid }
138
+ })),
139
+ { tag: 'linked_parent', attrs: { jid: parentCommunityJid } }
140
+ ]
141
+ }
142
+ ]);
143
+ return await parseGroupResult(result);
144
+ },
145
+ communityLeave: async (id) => {
146
+ await communityQuery('@g.us', 'set', [
147
+ {
148
+ tag: 'leave',
149
+ attrs: {},
150
+ content: [{ tag: 'community', attrs: { id } }]
151
+ }
152
+ ]);
153
+ },
154
+ communityUpdateSubject: async (jid, subject) => {
155
+ await communityQuery(jid, 'set', [
156
+ {
157
+ tag: 'subject',
158
+ attrs: {},
159
+ content: Buffer.from(subject, 'utf-8')
160
+ }
161
+ ]);
162
+ },
163
+ communityLinkGroup: async (groupJid, parentCommunityJid) => {
164
+ await communityQuery(parentCommunityJid, 'set', [
165
+ {
166
+ tag: 'links',
167
+ attrs: {},
168
+ content: [
169
+ {
170
+ tag: 'link',
171
+ attrs: { link_type: 'sub_group' },
172
+ content: [{ tag: 'group', attrs: { jid: groupJid } }]
173
+ }
174
+ ]
175
+ }
176
+ ]);
177
+ },
178
+ communityUnlinkGroup: async (groupJid, parentCommunityJid) => {
179
+ await communityQuery(parentCommunityJid, 'set', [
180
+ {
181
+ tag: 'unlink',
182
+ attrs: { unlink_type: 'sub_group' },
183
+ content: [{ tag: 'group', attrs: { jid: groupJid } }]
184
+ }
185
+ ]);
186
+ },
187
+ communityFetchLinkedGroups: async (jid) => {
188
+ let communityJid = jid;
189
+ let isCommunity = false;
190
+ // Try to determine if it is a subgroup or a community
191
+ const metadata = await sock.groupMetadata(jid);
192
+ if (metadata.linkedParent) {
193
+ // It is a subgroup, get the community jid
194
+ communityJid = metadata.linkedParent;
195
+ }
196
+ else {
197
+ // It is a community
198
+ isCommunity = true;
199
+ }
200
+ // Fetch all subgroups of the community
201
+ const result = await communityQuery(communityJid, 'get', [{ tag: 'sub_groups', attrs: {} }]);
202
+ const linkedGroupsData = [];
203
+ const subGroupsNode = getBinaryNodeChild(result, 'sub_groups');
204
+ if (subGroupsNode) {
205
+ const groupNodes = getBinaryNodeChildren(subGroupsNode, 'group');
206
+ for (const groupNode of groupNodes) {
207
+ linkedGroupsData.push({
208
+ id: groupNode.attrs.id ? jidEncode(groupNode.attrs.id, 'g.us') : undefined,
209
+ subject: groupNode.attrs.subject || '',
210
+ creation: groupNode.attrs.creation ? Number(groupNode.attrs.creation) : undefined,
211
+ owner: groupNode.attrs.creator ? jidNormalizedUser(groupNode.attrs.creator) : undefined,
212
+ size: groupNode.attrs.size ? Number(groupNode.attrs.size) : undefined
213
+ });
214
+ }
215
+ }
216
+ return {
217
+ communityJid,
218
+ isCommunity,
219
+ linkedGroups: linkedGroupsData
220
+ };
221
+ },
222
+ communityRequestParticipantsList: async (jid) => {
223
+ const result = await communityQuery(jid, 'get', [
224
+ {
225
+ tag: 'membership_approval_requests',
226
+ attrs: {}
227
+ }
228
+ ]);
229
+ const node = getBinaryNodeChild(result, 'membership_approval_requests');
230
+ const participants = getBinaryNodeChildren(node, 'membership_approval_request');
231
+ return participants.map(v => v.attrs);
232
+ },
233
+ communityRequestParticipantsUpdate: async (jid, participants, action) => {
234
+ const result = await communityQuery(jid, 'set', [
235
+ {
236
+ tag: 'membership_requests_action',
237
+ attrs: {},
238
+ content: [
239
+ {
240
+ tag: action,
241
+ attrs: {},
242
+ content: participants.map(jid => ({
243
+ tag: 'participant',
244
+ attrs: { jid }
245
+ }))
246
+ }
247
+ ]
248
+ }
249
+ ]);
250
+ const node = getBinaryNodeChild(result, 'membership_requests_action');
251
+ const nodeAction = getBinaryNodeChild(node, action);
252
+ const participantsAffected = getBinaryNodeChildren(nodeAction, 'participant');
253
+ return participantsAffected.map(p => {
254
+ return { status: p.attrs.error || '200', jid: p.attrs.jid };
255
+ });
256
+ },
257
+ communityParticipantsUpdate: async (jid, participants, action) => {
258
+ const result = await communityQuery(jid, 'set', [
259
+ {
260
+ tag: action,
261
+ attrs: action === 'remove' ? { linked_groups: 'true' } : {},
262
+ content: participants.map(jid => ({
263
+ tag: 'participant',
264
+ attrs: { jid }
265
+ }))
266
+ }
267
+ ]);
268
+ const node = getBinaryNodeChild(result, action);
269
+ const participantsAffected = getBinaryNodeChildren(node, 'participant');
270
+ return participantsAffected.map(p => {
271
+ return { status: p.attrs.error || '200', jid: p.attrs.jid, content: p };
272
+ });
273
+ },
274
+ communityUpdateDescription: async (jid, description) => {
275
+ const metadata = await communityMetadata(jid);
276
+ const prev = metadata.descId ?? null;
277
+ await communityQuery(jid, 'set', [
278
+ {
279
+ tag: 'description',
280
+ attrs: {
281
+ ...(description ? { id: generateMessageID() } : { delete: 'true' }),
282
+ ...(prev ? { prev } : {})
283
+ },
284
+ content: description ? [{ tag: 'body', attrs: {}, content: Buffer.from(description, 'utf-8') }] : undefined
285
+ }
286
+ ]);
287
+ },
288
+ communityInviteCode: async (jid) => {
289
+ const result = await communityQuery(jid, 'get', [{ tag: 'invite', attrs: {} }]);
290
+ const inviteNode = getBinaryNodeChild(result, 'invite');
291
+ return inviteNode?.attrs.code;
292
+ },
293
+ communityRevokeInvite: async (jid) => {
294
+ const result = await communityQuery(jid, 'set', [{ tag: 'invite', attrs: {} }]);
295
+ const inviteNode = getBinaryNodeChild(result, 'invite');
296
+ return inviteNode?.attrs.code;
297
+ },
298
+ communityAcceptInvite: async (code) => {
299
+ const results = await communityQuery('@g.us', 'set', [{ tag: 'invite', attrs: { code } }]);
300
+ const result = getBinaryNodeChild(results, 'community');
301
+ return result?.attrs.jid;
302
+ },
303
+ /**
304
+ * revoke a v4 invite for someone
305
+ * @param communityJid community jid
306
+ * @param invitedJid jid of person you invited
307
+ * @returns true if successful
308
+ */
309
+ communityRevokeInviteV4: async (communityJid, invitedJid) => {
310
+ const result = await communityQuery(communityJid, 'set', [
311
+ { tag: 'revoke', attrs: {}, content: [{ tag: 'participant', attrs: { jid: invitedJid } }] }
312
+ ]);
313
+ return !!result;
314
+ },
315
+ /**
316
+ * accept a CommunityInviteMessage
317
+ * @param key the key of the invite message, or optionally only provide the jid of the person who sent the invite
318
+ * @param inviteMessage the message to accept
319
+ */
320
+ communityAcceptInviteV4: ev.createBufferedFunction(async (key, inviteMessage) => {
321
+ key = typeof key === 'string' ? { remoteJid: key } : key;
322
+ const results = await communityQuery(inviteMessage.groupJid, 'set', [
323
+ {
324
+ tag: 'accept',
325
+ attrs: {
326
+ code: inviteMessage.inviteCode,
327
+ expiration: inviteMessage.inviteExpiration.toString(),
328
+ admin: key.remoteJid
329
+ }
330
+ }
331
+ ]);
332
+ // if we have the full message key
333
+ // update the invite message to be expired
334
+ if (key.id) {
335
+ // create new invite message that is expired
336
+ inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage);
337
+ inviteMessage.inviteExpiration = 0;
338
+ inviteMessage.inviteCode = '';
339
+ ev.emit('messages.update', [
340
+ {
341
+ key,
342
+ update: {
343
+ message: {
344
+ groupInviteMessage: inviteMessage
345
+ }
346
+ }
347
+ }
348
+ ]);
349
+ }
350
+ // generate the community add message
351
+ await upsertMessage({
352
+ key: {
353
+ remoteJid: inviteMessage.groupJid,
354
+ id: generateMessageIDV2(sock.user?.id),
355
+ fromMe: false,
356
+ participant: key.remoteJid // TODO: investigate if this makes any sense at all
357
+ },
358
+ messageStubType: WAMessageStubType.GROUP_PARTICIPANT_ADD,
359
+ messageStubParameters: [JSON.stringify(authState.creds.me)],
360
+ participant: key.remoteJid,
361
+ messageTimestamp: unixTimestampSeconds()
362
+ }, 'notify');
363
+ return results.attrs.from;
364
+ }),
365
+ communityGetInviteInfo: async (code) => {
366
+ const results = await communityQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }]);
367
+ return extractCommunityMetadata(results);
368
+ },
369
+ communityToggleEphemeral: async (jid, ephemeralExpiration) => {
370
+ const content = ephemeralExpiration
371
+ ? { tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } }
372
+ : { tag: 'not_ephemeral', attrs: {} };
373
+ await communityQuery(jid, 'set', [content]);
374
+ },
375
+ communitySettingUpdate: async (jid, setting) => {
376
+ await communityQuery(jid, 'set', [{ tag: setting, attrs: {} }]);
377
+ },
378
+ communityMemberAddMode: async (jid, mode) => {
379
+ await communityQuery(jid, 'set', [{ tag: 'member_add_mode', attrs: {}, content: mode }]);
380
+ },
381
+ communityJoinApprovalMode: async (jid, mode) => {
382
+ await communityQuery(jid, 'set', [
383
+ { tag: 'membership_approval_mode', attrs: {}, content: [{ tag: 'community_join', attrs: { state: mode } }] }
384
+ ]);
385
+ },
386
+ communityFetchAllParticipating
387
+ };
388
+ };
389
+ export const extractCommunityMetadata = (result) => {
390
+ const community = getBinaryNodeChild(result, 'community');
391
+ const descChild = getBinaryNodeChild(community, 'description');
392
+ let desc;
393
+ let descId;
394
+ if (descChild) {
395
+ desc = getBinaryNodeChildString(descChild, 'body');
396
+ descId = descChild.attrs.id;
397
+ }
398
+ const communityId = community.attrs.id?.includes('@')
399
+ ? community.attrs.id
400
+ : jidEncode(community.attrs.id || '', 'g.us');
401
+ const eph = getBinaryNodeChild(community, 'ephemeral')?.attrs.expiration;
402
+ const memberAddMode = getBinaryNodeChildString(community, 'member_add_mode') === 'all_member_add';
403
+ const metadata = {
404
+ id: communityId,
405
+ subject: community.attrs.subject || '',
406
+ subjectOwner: community.attrs.s_o,
407
+ subjectTime: Number(community.attrs.s_t || 0),
408
+ size: getBinaryNodeChildren(community, 'participant').length,
409
+ creation: Number(community.attrs.creation || 0),
410
+ owner: community.attrs.creator ? jidNormalizedUser(community.attrs.creator) : undefined,
411
+ desc,
412
+ descId,
413
+ linkedParent: getBinaryNodeChild(community, 'linked_parent')?.attrs.jid || undefined,
414
+ restrict: !!getBinaryNodeChild(community, 'locked'),
415
+ announce: !!getBinaryNodeChild(community, 'announcement'),
416
+ isCommunity: !!getBinaryNodeChild(community, 'parent'),
417
+ isCommunityAnnounce: !!getBinaryNodeChild(community, 'default_sub_community'),
418
+ joinApprovalMode: !!getBinaryNodeChild(community, 'membership_approval_mode'),
419
+ memberAddMode,
420
+ participants: getBinaryNodeChildren(community, 'participant').map(({ attrs }) => {
421
+ return {
422
+ // TODO: IMPLEMENT THE PN/LID FIELDS HERE!!
423
+ id: attrs.jid,
424
+ admin: (attrs.type || null)
425
+ };
426
+ }),
427
+ ephemeralDuration: eph ? +eph : undefined,
428
+ addressingMode: getBinaryNodeChildString(community, 'addressing_mode')
429
+ };
430
+ return metadata;
431
+ };
432
+ //# sourceMappingURL=communities.js.map