feat(bot): add group sync upsert

This commit is contained in:
yiekheng 2026-05-09 16:21:01 +08:00
parent c2ee793ae6
commit f8bd20184f

View File

@ -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 };
}