From f8bd20184fa6e9f9e8ba4f8fb7b67af133961050 Mon Sep 17 00:00:00 2001 From: yiekheng Date: Sat, 9 May 2026 16:21:01 +0800 Subject: [PATCH] feat(bot): add group sync upsert --- apps/bot/src/whatsapp/group-sync.ts | 42 +++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 apps/bot/src/whatsapp/group-sync.ts diff --git a/apps/bot/src/whatsapp/group-sync.ts b/apps/bot/src/whatsapp/group-sync.ts new file mode 100644 index 0000000..00afcd2 --- /dev/null +++ b/apps/bot/src/whatsapp/group-sync.ts @@ -0,0 +1,42 @@ +import { sql } from "drizzle-orm"; +import type { WASocket } from "@whiskeysockets/baileys"; +import { whatsappGroups } from "@cmbot/db"; +import { db } from "../db.js"; +import { logger } from "../logger.js"; + +export async function syncGroupsForAccount( + accountId: string, + socket: WASocket, +): Promise<{ synced: number }> { + const meta = await socket.groupFetchAllParticipating(); + const entries = Object.values(meta); + + if (entries.length === 0) { + logger.info({ accountId }, "group-sync: no groups"); + return { synced: 0 }; + } + + const rows = entries.map((g) => ({ + accountId, + waGroupJid: g.id, + name: g.subject ?? "(no subject)", + participantCount: g.participants?.length ?? 0, + isArchived: false, + lastSyncedAt: new Date(), + })); + + await db + .insert(whatsappGroups) + .values(rows) + .onConflictDoUpdate({ + target: [whatsappGroups.accountId, whatsappGroups.waGroupJid], + set: { + name: sql`excluded.name`, + participantCount: sql`excluded.participant_count`, + lastSyncedAt: sql`excluded.last_synced_at`, + }, + }); + + logger.info({ accountId, count: rows.length }, "group-sync: synced"); + return { synced: rows.length }; +}