Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(engine): baileys group management (list/info/create/participants/leave/subject/description/invite)
rmyndharis6df74c3f1fa3
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 592537393..64c38b203 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -19,6 +19,17 @@ class FakeSock extends EventEmitter {public sendMessage = jest.fn();public onWhatsApp = jest.fn();public sendPresenceUpdate = jest.fn().mockResolvedValue(undefined);+ public groupFetchAllParticipating = jest.fn();+ public groupMetadata = jest.fn();+ public groupCreate = jest.fn();+ public groupParticipantsUpdate = jest.fn().mockResolvedValue(undefined);+ public groupLeave = jest.fn().mockResolvedValue(undefined);+ public groupUpdateSubject = jest.fn().mockResolvedValue(undefined);+ public groupUpdateDescription = jest.fn().mockResolvedValue(undefined);+ public groupInviteCode = jest.fn();+ public groupRevokeInvite = jest.fn();+ public profilePictureUrl = jest.fn();+ public updateBlockStatus = jest.fn().mockResolvedValue(undefined);fire(event: string, arg: unknown): void {this.emitter.emit(event, arg);}@@ -149,9 +160,8 @@ describe('BaileysAdapter lifecycle & status', () => {});describe('BaileysAdapter capability gating', () => {- it('throws EngineNotSupportedError for store-backed methods (e.g. getGroups, getChats)', async () => {+ it('throws EngineNotSupportedError for store-backed methods (e.g. getChats)', async () => {const adapter = newAdapter();- await expect(adapter.getGroups()).rejects.toBeInstanceOf(EngineNotSupportedError);await expect(adapter.getChats()).rejects.toBeInstanceOf(EngineNotSupportedError);});});@@ -522,3 +532,85 @@ describe('BaileysAdapter store-backed ops', () => {expect(fakeStore.clearSession).toHaveBeenCalledWith('sess-1');});});++describe('BaileysAdapter group management', () => {+ const META = {+ id: '[email protected]',+ subject: 'G',+ participants: [{ id: '[email protected]', admin: 'superadmin' }],+ };++ beforeEach(() => {+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ jest.clearAllMocks();+ });++ const ready = async (): Promise<BaileysAdapter> => {+ const adapter = newAdapter();+ await adapter.initialize({});+ fakeSock.fire('connection.update', { connection: 'open' });+ return adapter;+ };++ it('getGroups maps groupFetchAllParticipating', async () => {+ fakeSock.groupFetchAllParticipating.mockResolvedValue({ '[email protected]': META });+ const adapter = await ready();+ const groups = await adapter.getGroups();+ expect(groups).toEqual([+ { id: '[email protected]', name: 'G', participantsCount: 1, isAdmin: true, linkedParentJID: null },+ ]);+ });++ it('getGroupInfo maps groupMetadata, and returns null when it rejects', async () => {+ fakeSock.groupMetadata.mockResolvedValueOnce(META);+ const adapter = await ready();+ expect((await adapter.getGroupInfo('[email protected]'))?.id).toBe('[email protected]');+ fakeSock.groupMetadata.mockRejectedValueOnce(new Error('not a group'));+ expect(await adapter.getGroupInfo('[email protected]')).toBeNull();+ });++ it('createGroup returns the mapped new group', async () => {+ fakeSock.groupCreate.mockResolvedValue(META);+ const adapter = await ready();+ const g = await adapter.createGroup('G', ['[email protected]']);+ expect(fakeSock.groupCreate).toHaveBeenCalledWith('G', ['[email protected]']);+ expect(g.id).toBe('[email protected]');+ });++ it.each([+ ['addParticipants', 'add'],+ ['removeParticipants', 'remove'],+ ['promoteParticipants', 'promote'],+ ['demoteParticipants', 'demote'],+ ])('%s calls groupParticipantsUpdate with %s', async (method, action) => {+ const adapter = await ready();+ await (adapter as unknown as Record<string, (g: string, p: string[]) => Promise<void>>)[method]('[email protected]', [+ '[email protected]',+ ]);+ expect(fakeSock.groupParticipantsUpdate).toHaveBeenCalledWith('[email protected]', ['[email protected]'], action);+ });++ it('leaveGroup / setGroupSubject / setGroupDescription delegate to the socket', async () => {+ const adapter = await ready();+ await adapter.leaveGroup('[email protected]');+ expect(fakeSock.groupLeave).toHaveBeenCalledWith('[email protected]');+ await adapter.setGroupSubject('[email protected]', 'New');+ expect(fakeSock.groupUpdateSubject).toHaveBeenCalledWith('[email protected]', 'New');+ await adapter.setGroupDescription('[email protected]', 'Desc');+ expect(fakeSock.groupUpdateDescription).toHaveBeenCalledWith('[email protected]', 'Desc');+ });++ it('getGroupInviteCode / revokeGroupInviteCode return the code', async () => {+ fakeSock.groupInviteCode.mockResolvedValue('ABC123');+ fakeSock.groupRevokeInvite.mockResolvedValue('NEW456');+ const adapter = await ready();+ expect(await adapter.getGroupInviteCode('[email protected]')).toBe('ABC123');+ expect(await adapter.revokeGroupInviteCode('[email protected]')).toBe('NEW456');+ });++ it('group ops reject with EngineNotReadyError before connect', async () => {+ const adapter = newAdapter();+ await adapter.initialize({});+ await expect(adapter.getGroups()).rejects.toBeInstanceOf(EngineNotReadyError);+ });+});diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex f90d01d0d..86b639b9d 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -7,6 +7,7 @@ import makeWASocket, {} from '@whiskeysockets/baileys';import type { AnyMessageContent, MiscMessageGenerationOptions, WAMessage, WASocket } from '@whiskeysockets/baileys';import { buildIncomingMessageFromBaileys, mapBaileysStatus } from './baileys-message-mapper';+import { mapBaileysGroup, mapBaileysGroupInfo } from './baileys-group-mapper';import type { ILogger } from '@whiskeysockets/baileys/lib/Utils/logger.js';import {ChatState,@@ -335,56 +336,90 @@ export class BaileysAdapter implements IWhatsAppEngine {await this.sock!.sendMessage(chatId, { delete: target.key });}- // ----- Gated: not supported by this minimal slice (no store) ------ /* eslint-disable @typescript-eslint/no-unused-vars */+ // ----- Groups ------ getMessageReactions(_chatId: string, _messageId: string): Promise<MessageReaction[]> {- return this.unsupported('getMessageReactions');+ async getGroups(): Promise<Group[]> {+ this.ensureReady();+ const all = await this.sock!.groupFetchAllParticipating();+ const self = this.normalizedSelfJid();+ return Object.values(all).map(metadata => mapBaileysGroup(metadata, self));}- getContacts(): Promise<Contact[]> {- return this.unsupported('getContacts');++ async getGroupInfo(groupId: string): Promise<GroupInfo | null> {+ this.ensureReady();+ try {+ const metadata = await this.sock!.groupMetadata(groupId);+ return mapBaileysGroupInfo(metadata);+ } catch {+ return null; // not a group / not found+ }}- getContactById(_contactId: string): Promise<Contact | null> {- return this.unsupported('getContactById');++ async createGroup(name: string, participants: string[]): Promise<Group> {+ this.ensureReady();+ const metadata = await this.sock!.groupCreate(name, participants);+ return mapBaileysGroup(metadata, this.normalizedSelfJid());}- resolveContactPhone(_contactId: string): Promise<string | null> {- return this.unsupported('resolveContactPhone');++ async addParticipants(groupId: string, participants: string[]): Promise<void> {+ this.ensureReady();+ await this.sock!.groupParticipantsUpdate(groupId, participants, 'add');}- getGroups(): Promise<Group[]> {- return this.unsupported('getGroups');++ async removeParticipants(groupId: string, participants: string[]): Promise<void> {+ this.ensureReady();+ await this.sock!.groupParticipantsUpdate(groupId, participants, 'remove');}- getGroupInfo(_groupId: string): Promise<GroupInfo | null> {- return this.unsupported('getGroupInfo');++ async promoteParticipants(groupId: string, participants: string[]): Promise<void> {+ this.ensureReady();+ await this.sock!.groupParticipantsUpdate(groupId, participants, 'promote');}- createGroup(_name: string, _participants: string[]): Promise<Group> {- return this.unsupported('createGroup');++ async demoteParticipants(groupId: string, participants: string[]): Promise<void> {+ this.ensureReady();+ await this.sock!.groupParticipantsUpdate(groupId, participants, 'demote');}- addParticipants(_groupId: string, _participants: string[]): Promise<void> {- return this.unsupported('addParticipants');++ async leaveGroup(groupId: string): Promise<void> {+ this.ensureReady();+ await this.sock!.groupLeave(groupId);}- removeParticipants(_groupId: string, _participants: string[]): Promise<void> {- return this.unsupported('removeParticipants');++ async setGroupSubject(groupId: string, subject: string): Promise<void> {+ this.ensureReady();+ await this.sock!.groupUpdateSubject(groupId, subject);}- promoteParticipants(_groupId: string, _participants: string[]): Promise<void> {- return this.unsupported('promoteParticipants');++ async setGroupDescription(groupId: string, description: string): Promise<void> {+ this.ensureReady();+ await this.sock!.groupUpdateDescription(groupId, description);}- demoteParticipants(_groupId: string, _participants: string[]): Promise<void> {- return this.unsupported('demoteParticipants');++ async getGroupInviteCode(groupId: string): Promise<string> {+ this.ensureReady();+ return (await this.sock!.groupInviteCode(groupId)) ?? '';}- leaveGroup(_groupId: string): Promise<void> {- return this.unsupported('leaveGroup');++ async revokeGroupInviteCode(groupId: string): Promise<string> {+ this.ensureReady();+ return (await this.sock!.groupRevokeInvite(groupId)) ?? '';}- setGroupSubject(_groupId: string, _subject: string): Promise<void> {- return this.unsupported('setGroupSubject');++ // ----- Gated: not supported by this minimal slice (no store) -----+ /* eslint-disable @typescript-eslint/no-unused-vars */++ getMessageReactions(_chatId: string, _messageId: string): Promise<MessageReaction[]> {+ return this.unsupported('getMessageReactions');}- setGroupDescription(_groupId: string, _description: string): Promise<void> {- return this.unsupported('setGroupDescription');+ getContacts(): Promise<Contact[]> {+ return this.unsupported('getContacts');}- getGroupInviteCode(_groupId: string): Promise<string> {- return this.unsupported('getGroupInviteCode');+ getContactById(_contactId: string): Promise<Contact | null> {+ return this.unsupported('getContactById');}- revokeGroupInviteCode(_groupId: string): Promise<string> {- return this.unsupported('revokeGroupInviteCode');+ resolveContactPhone(_contactId: string): Promise<string | null> {+ return this.unsupported('resolveContactPhone');}getChatHistory(_chatId: string, _limit?: number, _includeMedia?: boolean): Promise<IncomingMessage[]> {return this.unsupported('getChatHistory');