telegram and whatsapp channel integrations, validate bot tokens before saving

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-27 08:53:01 +00:00
co-authored by Claude Opus 4.6
parent bc4c20929c
commit b698e3d962
15 changed files with 2571 additions and 40 deletions
+12 -2
View File
@@ -8,6 +8,8 @@ import { migrateSettingsToResources } from './migrate-resources';
import { generateResourceSkill } from './api/pi/pi-bridge';
import { initQueue } from './queue';
import { startDiscordBotIfConfigured } from './channels/discord/bot';
import { startTelegramBotIfConfigured } from './channels/telegram/bot';
import { startWhatsAppBotIfConfigured } from './channels/whatsapp/bot';
mkdirSync(DATA_PATH, { recursive: true });
@@ -59,11 +61,19 @@ async function installPi(): Promise<boolean> {
await migrateSettingsToResources();
generateResourceSkill(DATA_PATH);
await initQueue().catch(err => {
await initQueue().catch((err) => {
console.error('[bootstrap] Failed to initialize queue:', err);
});
await startDiscordBotIfConfigured().catch(err => {
await startDiscordBotIfConfigured().catch((err) => {
console.error('[channels] Failed to start Discord bot:', err);
});
await startTelegramBotIfConfigured().catch((err) => {
console.error('[channels] Failed to start Telegram bot:', err);
});
await startWhatsAppBotIfConfigured().catch((err) => {
console.error('[channels] Failed to start WhatsApp bot:', err);
});
})();
+7 -1
View File
@@ -1,6 +1,12 @@
import type { ChannelProvider } from './types';
import { upsertUserIntegration } from 'officerdb';
const configKeyMap: Record<ChannelProvider, string> = {
discord: 'discordId',
telegram: 'telegramId',
whatsapp: 'whatsappId',
};
type PairingEntry = {
userId: number;
email: string;
@@ -71,7 +77,7 @@ export async function consumePairingCode(code: string, channelUserId: string): P
await upsertUserIntegration({
userId: entry.userId,
provider: entry.provider,
config: { discordId: channelUserId },
config: { [configKeyMap[entry.provider]]: channelUserId },
});
return { userId: entry.userId, email: entry.email, provider: entry.provider };
+270 -12
View File
@@ -1,11 +1,16 @@
import { createRouter } from '@@/create-router';
import {
getServerIntegration,
upsertServerIntegration,
getUserIntegration,
deleteUserIntegration,
} from 'officerdb';
import { getServerIntegration, upsertServerIntegration, getUserIntegration, deleteUserIntegration } from 'officerdb';
import { startDiscordBot, stopDiscordBot, isDiscordBotRunning, getDiscordBotUsername } from './discord/bot';
import { startTelegramBot, stopTelegramBot, isTelegramBotRunning, getTelegramBotUsername } from './telegram/bot';
import {
startWhatsAppBot,
stopWhatsAppBot,
isWhatsAppBotRunning,
getWhatsAppBotPhone,
getWhatsAppQR,
subscribeQR,
disconnectWhatsApp,
} from './whatsapp/bot';
import { generatePairingCode } from './pairing';
export const channelsRouter = createRouter();
@@ -52,27 +57,36 @@ channelsRouter.put('/discord/config', async (ctx) => {
if (serverInvite !== undefined) newConfig.serverInvite = serverInvite;
if (botHandle !== undefined) newConfig.botHandle = botHandle;
await upsertServerIntegration('discord', newConfig, enabled ?? existing?.enabled ?? true);
// Restart bot if running or if we have a token and it's enabled
const shouldRun = enabled ?? existing?.enabled ?? true;
const token = (botToken ?? existingConfig.botToken) as string | undefined;
if (token && shouldRun) {
// If a new token is provided, validate it by starting the bot before saving
if (botToken && shouldRun) {
try {
await startDiscordBot(botToken);
} catch (err) {
console.error('[channels] Discord bot token validation failed:', err);
return ctx.json({ error: 'Invalid bot token — connection failed' }, 400);
}
}
await upsertServerIntegration('discord', newConfig, shouldRun);
// Start/restart with existing token (already validated on initial save)
if (!botToken && token && shouldRun) {
try {
await startDiscordBot(token);
} catch (err) {
console.error('[channels] Failed to start Discord bot:', err);
return ctx.json({ success: true, botStarted: false, error: String(err) });
}
return ctx.json({ success: true, botStarted: true });
}
if (!shouldRun) {
await stopDiscordBot();
}
return ctx.json({ success: true, botStarted: false });
return ctx.json({ success: true, botStarted: token && shouldRun });
});
channelsRouter.get('/discord/status', async (ctx) => {
@@ -114,3 +128,247 @@ channelsRouter.delete('/discord/connection', async (ctx) => {
const deleted = await deleteUserIntegration(user.id, 'discord');
return ctx.json({ success: deleted });
});
// ── Admin: Telegram config ──
channelsRouter.get('/telegram/config', async (ctx) => {
const user = ctx.get('user');
if (user.role !== 'Super Admin') return ctx.json({ error: 'Forbidden' }, 403);
const integration = await getServerIntegration('telegram');
if (!integration) return ctx.json({ configured: false });
const config = integration.config as Record<string, unknown>;
const botToken = config.botToken as string | undefined;
return ctx.json({
configured: !!botToken,
enabled: integration.enabled,
botToken: botToken ? `${botToken.slice(0, 8)}...${botToken.slice(-4)}` : null,
serverInvite: (config.serverInvite as string) ?? null,
botHandle: (config.botHandle as string) ?? null,
});
});
channelsRouter.put('/telegram/config', async (ctx) => {
const user = ctx.get('user');
if (user.role !== 'Super Admin') return ctx.json({ error: 'Forbidden' }, 403);
const body = ctx.get('body') as Record<string, unknown>;
const botToken = body.botToken as string | undefined;
const enabled = body.enabled as boolean | undefined;
const serverInvite = body.serverInvite as string | undefined;
const botHandle = body.botHandle as string | undefined;
if (!botToken && enabled === undefined && serverInvite === undefined && botHandle === undefined) {
return ctx.json({ error: 'At least one field required' }, 400);
}
const existing = await getServerIntegration('telegram');
const existingConfig = (existing?.config ?? {}) as Record<string, unknown>;
const newConfig = { ...existingConfig };
if (botToken) newConfig.botToken = botToken;
if (serverInvite !== undefined) newConfig.serverInvite = serverInvite;
if (botHandle !== undefined) newConfig.botHandle = botHandle;
const shouldRun = enabled ?? existing?.enabled ?? true;
const token = (botToken ?? existingConfig.botToken) as string | undefined;
// If a new token is provided, validate it by starting the bot before saving
if (botToken && shouldRun) {
try {
await startTelegramBot(botToken);
} catch (err) {
console.error('[channels] Telegram bot token validation failed:', err);
return ctx.json({ error: 'Invalid bot token — connection failed' }, 400);
}
}
await upsertServerIntegration('telegram', newConfig, shouldRun);
// Start/restart with existing token (already validated on initial save)
if (!botToken && token && shouldRun) {
try {
await startTelegramBot(token);
} catch (err) {
console.error('[channels] Failed to start Telegram bot:', err);
return ctx.json({ success: true, botStarted: false, error: String(err) });
}
}
if (!shouldRun) {
await stopTelegramBot();
}
return ctx.json({ success: true, botStarted: token && shouldRun });
});
channelsRouter.get('/telegram/status', async (ctx) => {
const integration = await getServerIntegration('telegram');
const config = (integration?.config ?? {}) as Record<string, unknown>;
return ctx.json({
configured: !!config.botToken,
enabled: integration?.enabled ?? false,
running: isTelegramBotRunning(),
botUsername: getTelegramBotUsername(),
serverInvite: (config.serverInvite as string) ?? null,
botHandle: (config.botHandle as string) ?? null,
});
});
// ── User: Telegram pairing ──
channelsRouter.post('/telegram/pair', async (ctx) => {
const user = ctx.get('user');
const code = generatePairingCode(user.id, user.email, 'telegram');
return ctx.json({ code, expiresIn: 600 });
});
channelsRouter.get('/telegram/connection', async (ctx) => {
const user = ctx.get('user');
const integration = await getUserIntegration(user.id, 'telegram');
if (!integration) return ctx.json({ linked: false });
const config = integration.config as Record<string, unknown>;
return ctx.json({
linked: true,
telegramId: config.telegramId,
});
});
channelsRouter.delete('/telegram/connection', async (ctx) => {
const user = ctx.get('user');
const deleted = await deleteUserIntegration(user.id, 'telegram');
return ctx.json({ success: deleted });
});
// ── Admin: WhatsApp config ──
channelsRouter.get('/whatsapp/config', async (ctx) => {
const user = ctx.get('user');
if (user.role !== 'Super Admin') return ctx.json({ error: 'Forbidden' }, 403);
const integration = await getServerIntegration('whatsapp');
return ctx.json({
configured: integration?.enabled ?? false,
enabled: integration?.enabled ?? false,
running: isWhatsAppBotRunning(),
phone: getWhatsAppBotPhone(),
});
});
channelsRouter.put('/whatsapp/config', async (ctx) => {
const user = ctx.get('user');
if (user.role !== 'Super Admin') return ctx.json({ error: 'Forbidden' }, 403);
const body = ctx.get('body') as Record<string, unknown>;
const enabled = body.enabled as boolean | undefined;
if (enabled === true) {
await upsertServerIntegration('whatsapp', {}, true);
try {
await startWhatsAppBot();
} catch (err) {
console.error('[channels] Failed to start WhatsApp bot:', err);
return ctx.json({ success: true, botStarted: false, error: String(err) });
}
return ctx.json({ success: true, botStarted: true });
}
if (enabled === false) {
await disconnectWhatsApp();
return ctx.json({ success: true, botStarted: false });
}
return ctx.json({ error: 'enabled field required' }, 400);
});
channelsRouter.get('/whatsapp/status', async (ctx) => {
const integration = await getServerIntegration('whatsapp');
return ctx.json({
configured: integration?.enabled ?? false,
enabled: integration?.enabled ?? false,
running: isWhatsAppBotRunning(),
phone: getWhatsAppBotPhone(),
});
});
channelsRouter.get('/whatsapp/qr', async (ctx) => {
const user = ctx.get('user');
if (user.role !== 'Super Admin') return ctx.json({ error: 'Forbidden' }, 403);
// SSE stream for QR code updates
return new Response(
new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
const sendEvent = (data: Record<string, unknown>) => {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
};
// Send current QR if available
const currentQR = getWhatsAppQR();
if (currentQR) {
sendEvent({ type: 'qr', qr: currentQR });
} else if (isWhatsAppBotRunning()) {
sendEvent({ type: 'authenticated', phone: getWhatsAppBotPhone() });
} else {
sendEvent({ type: 'waiting' });
}
const unsubscribe = subscribeQR((qr, event) => {
if (event === 'qr' && qr) {
sendEvent({ type: 'qr', qr });
} else if (event === 'authenticated') {
sendEvent({ type: 'authenticated', phone: getWhatsAppBotPhone() });
} else if (event === 'disconnected') {
sendEvent({ type: 'disconnected' });
}
});
// Clean up when client disconnects
ctx.req.raw.signal.addEventListener('abort', () => {
unsubscribe();
controller.close();
});
},
}),
{
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
},
);
});
// ── User: WhatsApp pairing ──
channelsRouter.post('/whatsapp/pair', async (ctx) => {
const user = ctx.get('user');
const code = generatePairingCode(user.id, user.email, 'whatsapp');
return ctx.json({ code, expiresIn: 600 });
});
channelsRouter.get('/whatsapp/connection', async (ctx) => {
const user = ctx.get('user');
const integration = await getUserIntegration(user.id, 'whatsapp');
if (!integration) return ctx.json({ linked: false });
const config = integration.config as Record<string, unknown>;
return ctx.json({
linked: true,
whatsappId: config.whatsappId,
});
});
channelsRouter.delete('/whatsapp/connection', async (ctx) => {
const user = ctx.get('user');
const deleted = await deleteUserIntegration(user.id, 'whatsapp');
return ctx.json({ success: deleted });
});
+56
View File
@@ -0,0 +1,56 @@
import TelegramBot from 'node-telegram-bot-api';
import { getServerIntegration } from 'officerdb';
import { handleTelegramMessage } from './handler';
let bot: TelegramBot | null = null;
let cachedUsername: string | null = null;
export async function startTelegramBot(token: string): Promise<void> {
if (bot) {
await stopTelegramBot();
}
bot = new TelegramBot(token, { polling: true });
bot.on('message', (msg) => {
handleTelegramMessage(msg).catch((err) => {
console.error('[telegram] Unhandled error in message handler:', err);
});
});
const me = await bot.getMe();
cachedUsername = me.username ?? null;
console.log(`[telegram] Bot logged in as @${cachedUsername}`);
}
export async function stopTelegramBot(): Promise<void> {
if (bot) {
await bot.stopPolling();
bot = null;
cachedUsername = null;
console.log('[telegram] Bot stopped');
}
}
export function isTelegramBotRunning(): boolean {
return bot !== null && bot.isPolling();
}
export function getTelegramBotUsername(): string | null {
return cachedUsername;
}
export function getTelegramBot(): TelegramBot | null {
return bot;
}
export async function startTelegramBotIfConfigured(): Promise<void> {
const integration = await getServerIntegration('telegram');
if (!integration?.enabled) return;
const config = integration.config as Record<string, unknown>;
const botToken = config.botToken as string | undefined;
if (!botToken) return;
await startTelegramBot(botToken);
}
+51
View File
@@ -0,0 +1,51 @@
const MAX_LENGTH = 4096;
export function chunkMessage(text: string): string[] {
if (text.length <= MAX_LENGTH) return [text];
const chunks: string[] = [];
const paragraphs = text.split('\n\n');
let current = '';
for (const paragraph of paragraphs) {
if (paragraph.length > MAX_LENGTH) {
// Flush current chunk
if (current) {
chunks.push(current.trim());
current = '';
}
// Split long paragraph on newlines
const lines = paragraph.split('\n');
for (const line of lines) {
if (line.length > MAX_LENGTH) {
// Flush current
if (current) {
chunks.push(current.trim());
current = '';
}
// Hard-split long line
for (let i = 0; i < line.length; i += MAX_LENGTH) {
chunks.push(line.slice(i, i + MAX_LENGTH));
}
} else if (current.length + 1 + line.length > MAX_LENGTH) {
chunks.push(current.trim());
current = line;
} else {
current += (current ? '\n' : '') + line;
}
}
} else if (current.length + 2 + paragraph.length > MAX_LENGTH) {
chunks.push(current.trim());
current = paragraph;
} else {
current += (current ? '\n\n' : '') + paragraph;
}
}
if (current.trim()) {
chunks.push(current.trim());
}
return chunks;
}
+288
View File
@@ -0,0 +1,288 @@
import type TelegramBot from 'node-telegram-bot-api';
import { findUserByIntegrationConfig, readConfigValue } from 'officerdb';
import { sendAndAwait, getSessionModel, setSessionModel } from '../send-and-await';
import { consumePairingCode } from '../pairing';
import { chunkMessage } from './chunker';
import { getTelegramBot } from './bot';
import { listPiModels } from '@@/api/pi/list-models';
import { enqueue } from '@@/queue/engine';
import { readJob } from '@@/queue/storage';
import { openEmailDb } from '@@/api/email/email-db';
import type { ModelInfo } from '@@/api/pi/types';
const PAIRING_CODE_PATTERN = /^[A-Z0-9]{6}$/;
const TYPING_INTERVAL_MS = 5_000;
type SendFn = (text: string) => Promise<unknown>;
type AccessPolicy = { allowedModels: string[] };
const ACCESS_POLICY_KEY = 'pi-access-policy';
async function getVisibleModels(): Promise<ModelInfo[]> {
const allModels = await listPiModels();
const policy = await readConfigValue<AccessPolicy>(ACCESS_POLICY_KEY, { allowedModels: [] });
const allowed = policy.allowedModels;
if (allowed.length === 0) return allModels;
const allowedSet = new Set(allowed);
const allowedProviderSet = new Set(allowed.map((key) => key.split(':')[0]));
return allModels.filter((m) => {
const key = `${m.provider}:${m.id}`;
const isExplicitlyAllowed = allowedSet.has(key);
const isFromNewProvider = !allowedProviderSet.has(m.provider);
return isExplicitlyAllowed || isFromNewProvider;
});
}
type CommandContext = {
content: string;
send: SendFn;
userId: number;
email: string;
telegramId: string;
};
async function handleEmailSync(ctx: CommandContext): Promise<void> {
const { send, email } = ctx;
let countBefore = 0;
try {
const db = openEmailDb(email);
const row = db.query('SELECT COUNT(*) as count FROM emails WHERE deleted = 0').get() as { count: number };
countBefore = row.count;
db.close();
} catch {
// DB might not exist yet
}
await send('Syncing emails...');
const job = await enqueue({ lane: 'google-api', type: 'gmail-sync', userId: email });
const poll = async (): Promise<'completed' | 'failed' | 'cancelled'> => {
for (let i = 0; i < 120; i++) {
await new Promise((r) => setTimeout(r, 3000));
const current = await readJob(job.id);
if (!current) return 'failed';
if (current.status === 'completed' || current.status === 'failed' || current.status === 'cancelled') {
return current.status;
}
}
return 'failed';
};
const status = await poll();
if (status !== 'completed') {
await send('Email sync failed. Check the queue dashboard for details.');
return;
}
try {
const db = openEmailDb(email);
const row = db.query('SELECT COUNT(*) as count FROM emails WHERE deleted = 0').get() as { count: number };
const countAfter = row.count;
const newCount = countAfter - countBefore;
if (newCount <= 0) {
db.close();
await send('Sync complete — no new emails.');
return;
}
const newest = db
.query('SELECT from_name, from_address, subject FROM emails WHERE deleted = 0 ORDER BY date DESC LIMIT ?')
.all(Math.min(newCount, 20)) as Array<{ from_name: string | null; from_address: string; subject: string }>;
db.close();
const lines = newest.map((e) => {
const sender = e.from_name || e.from_address;
return `- *${sender}*: ${e.subject}`;
});
let text = `Sync complete — *${newCount}* new email${newCount !== 1 ? 's' : ''}`;
if (newCount > 20) text += ` (showing latest 20)`;
text += `:\n\n${lines.join('\n')}`;
const chunks = chunkMessage(text);
for (const chunk of chunks) {
await send(chunk);
}
} catch (err) {
await send(`Sync complete but failed to read results: ${err instanceof Error ? err.message : String(err)}`);
}
}
async function handleCommand(ctx: CommandContext): Promise<boolean> {
const { content, send, telegramId } = ctx;
const lower = content.toLowerCase();
const helpSections: Record<string, string> = {
models:
'*Models:*\n' +
'`!model` — show current model\n' +
'`!model <id>` — switch model\n' +
'`!models` — list available models',
email: '*Email:*\n' + '`!email sync` — sync Gmail and show new emails',
};
if (lower === '!help' || lower.startsWith('!help ')) {
const topic = content.slice('!help'.length).trim().toLowerCase();
if (topic && topic in helpSections) {
await send(helpSections[topic]!);
return true;
}
if (topic) {
await send(
`Unknown topic: \`${topic}\`\nAvailable: ${Object.keys(helpSections)
.map((k) => `\`${k}\``)
.join(', ')}`,
);
return true;
}
const full = Object.values(helpSections).join('\n\n');
await send(full + '\n\n`!help <topic>` — show commands for a topic');
return true;
}
if (lower === '!models') {
const models = await getVisibleModels();
if (models.length === 0) {
await send('No models available.');
return true;
}
const current = getSessionModel('telegram', telegramId);
const grouped = new Map<string, string[]>();
for (const m of models) {
const list = grouped.get(m.provider) ?? [];
list.push(m.id === current ? `*${m.id}* (current)` : m.id);
grouped.set(m.provider, list);
}
let text = '*Available models:*\n';
for (const [provider, ids] of grouped) {
text += `\n_${provider}_\n${ids.map((id) => ` ${id}`).join('\n')}\n`;
}
text += '\nUse `!model <id>` to switch.';
await send(text);
return true;
}
if (lower === '!model') {
const current = getSessionModel('telegram', telegramId);
await send(
current
? `Current model: *${current}*`
: 'No active session yet — the default model will be used on your next message.',
);
return true;
}
if (lower.startsWith('!model ')) {
const requested = content.slice('!model '.length).trim();
if (!requested) {
const current = getSessionModel('telegram', telegramId);
await send(current ? `Current model: *${current}*` : 'No active session yet.');
return true;
}
const models = await getVisibleModels();
const match = models.find((m) => m.id === requested || m.name === requested);
if (!match) {
await send(`Model not found: \`${requested}\`\nUse \`!models\` to see available models.`);
return true;
}
setSessionModel('telegram', telegramId, match.id);
await send(`Model switched to *${match.id}*. The new model will be used on your next message.`);
return true;
}
if (lower === '!email sync') {
await handleEmailSync(ctx);
return true;
}
return false;
}
export async function handleTelegramMessage(msg: TelegramBot.Message): Promise<void> {
const bot = getTelegramBot();
if (!bot) return;
// Ignore non-private chats, bot messages, non-text
if (msg.chat.type !== 'private') return;
if (msg.from?.is_bot) return;
if (!msg.text) return;
const chatId = msg.chat.id;
const telegramId = String(msg.from!.id);
const content = msg.text.trim();
if (!content) return;
const send: SendFn = (text: string) => bot.sendMessage(chatId, text);
// Look up linked Officer user
const linked = await findUserByIntegrationConfig('telegram', 'telegramId', telegramId);
if (!linked) {
if (PAIRING_CODE_PATTERN.test(content.toUpperCase())) {
const result = await consumePairingCode(content.toUpperCase(), telegramId);
if (result) {
await send('Account linked! You can now chat with me.');
return;
}
await send('Invalid or expired pairing code. Please generate a new one from Officer Settings.');
return;
}
await send(
"I don't recognize your Telegram account. To link it:\n" +
'1. Go to Officer Settings → Integrations → Telegram\n' +
'2. Click "Link Telegram" to get a pairing code\n' +
'3. Send the 6-character code to me here',
);
return;
}
// Handle commands
if (content.startsWith('!')) {
const handled = await handleCommand({
content,
send,
userId: linked.user.id,
email: linked.user.email,
telegramId,
});
if (handled) return;
}
// Typing indicator
const sendTyping = () => {
bot.sendChatAction(chatId, 'typing').catch(() => {});
};
const typingInterval = setInterval(sendTyping, TYPING_INTERVAL_MS);
sendTyping();
try {
const result = await sendAndAwait({
userId: linked.user.id,
email: linked.user.email,
username: linked.user.username ?? linked.user.email.split('@')[0]!,
prompt: content,
context: 'telegram',
contextId: telegramId,
});
clearInterval(typingInterval);
const signature = `\`${result.model}\`\n`;
const chunks = chunkMessage(result.text);
for (let i = 0; i < chunks.length; i++) {
await send(i === 0 ? signature + chunks[i]! : chunks[i]!);
}
} catch (err) {
clearInterval(typingInterval);
console.error('[telegram] Error handling message:', err);
await send('Sorry, something went wrong processing your message.').catch(() => {});
}
}
+122
View File
@@ -0,0 +1,122 @@
import { join } from 'path';
import { Client, LocalAuth } from 'whatsapp-web.js';
import { getServerIntegration, upsertServerIntegration } from 'officerdb';
import { DATA_PATH } from '@@/data-path';
import { handleWhatsAppMessage } from './handler';
let client: Client | null = null;
let currentQR: string | null = null;
let clientReady = false;
type QRListener = (qr: string | null, event: 'qr' | 'authenticated' | 'disconnected') => void;
const qrListeners = new Set<QRListener>();
export async function startWhatsAppBot(): Promise<void> {
if (client) {
await stopWhatsAppBot();
}
clientReady = false;
currentQR = null;
client = new Client({
authStrategy: new LocalAuth({ dataPath: join(DATA_PATH, '.wwebjs_auth') }),
puppeteer: {
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
},
});
client.on('qr', (qr) => {
currentQR = qr;
for (const listener of qrListeners) {
listener(qr, 'qr');
}
console.log('[whatsapp] QR code received — scan with your phone');
});
client.on('ready', () => {
clientReady = true;
currentQR = null;
for (const listener of qrListeners) {
listener(null, 'authenticated');
}
const phone = client?.info?.wid?.user ?? 'unknown';
console.log(`[whatsapp] Bot ready — phone: ${phone}`);
});
client.on('authenticated', () => {
console.log('[whatsapp] Authenticated');
});
client.on('auth_failure', (msg) => {
console.error('[whatsapp] Auth failure:', msg);
});
client.on('disconnected', (reason) => {
clientReady = false;
currentQR = null;
for (const listener of qrListeners) {
listener(null, 'disconnected');
}
console.log('[whatsapp] Disconnected:', reason);
});
client.on('message', (msg) => {
handleWhatsAppMessage(msg).catch((err) => {
console.error('[whatsapp] Unhandled error in message handler:', err);
});
});
await client.initialize();
}
export async function stopWhatsAppBot(): Promise<void> {
if (client) {
try {
await client.destroy();
} catch {
// May fail if not connected
}
client = null;
clientReady = false;
currentQR = null;
console.log('[whatsapp] Bot stopped');
}
}
export function isWhatsAppBotRunning(): boolean {
return client !== null && clientReady;
}
export function getWhatsAppBotPhone(): string | null {
if (!client || !clientReady) return null;
return client.info?.wid?.user ?? null;
}
export function getWhatsAppQR(): string | null {
return currentQR;
}
export function subscribeQR(listener: QRListener): () => void {
qrListeners.add(listener);
return () => {
qrListeners.delete(listener);
};
}
export function getWhatsAppClient(): Client | null {
return client;
}
export async function startWhatsAppBotIfConfigured(): Promise<void> {
const integration = await getServerIntegration('whatsapp');
if (!integration?.enabled) return;
await startWhatsAppBot();
}
export async function disconnectWhatsApp(): Promise<void> {
await stopWhatsAppBot();
await upsertServerIntegration('whatsapp', {}, false);
}
+292
View File
@@ -0,0 +1,292 @@
import type { Message as WAMessage } from 'whatsapp-web.js';
import { findUserByIntegrationConfig, readConfigValue } from 'officerdb';
import { sendAndAwait, getSessionModel, setSessionModel } from '../send-and-await';
import { consumePairingCode } from '../pairing';
import { getWhatsAppClient } from './bot';
import { listPiModels } from '@@/api/pi/list-models';
import { enqueue } from '@@/queue/engine';
import { readJob } from '@@/queue/storage';
import { openEmailDb } from '@@/api/email/email-db';
import type { ModelInfo } from '@@/api/pi/types';
const PAIRING_CODE_PATTERN = /^[A-Z0-9]{6}$/;
const TYPING_INTERVAL_MS = 5_000;
type SendFn = (text: string) => Promise<unknown>;
type AccessPolicy = { allowedModels: string[] };
const ACCESS_POLICY_KEY = 'pi-access-policy';
function extractPhone(waId: string): string {
// WhatsApp ID format: 5511999999999@c.us → 5511999999999
return waId.split('@')[0]!;
}
async function getVisibleModels(): Promise<ModelInfo[]> {
const allModels = await listPiModels();
const policy = await readConfigValue<AccessPolicy>(ACCESS_POLICY_KEY, { allowedModels: [] });
const allowed = policy.allowedModels;
if (allowed.length === 0) return allModels;
const allowedSet = new Set(allowed);
const allowedProviderSet = new Set(allowed.map((key) => key.split(':')[0]));
return allModels.filter((m) => {
const key = `${m.provider}:${m.id}`;
const isExplicitlyAllowed = allowedSet.has(key);
const isFromNewProvider = !allowedProviderSet.has(m.provider);
return isExplicitlyAllowed || isFromNewProvider;
});
}
type CommandContext = {
content: string;
send: SendFn;
userId: number;
email: string;
whatsappId: string;
};
async function handleEmailSync(ctx: CommandContext): Promise<void> {
const { send, email } = ctx;
let countBefore = 0;
try {
const db = openEmailDb(email);
const row = db.query('SELECT COUNT(*) as count FROM emails WHERE deleted = 0').get() as { count: number };
countBefore = row.count;
db.close();
} catch {
// DB might not exist yet
}
await send('Syncing emails...');
const job = await enqueue({ lane: 'google-api', type: 'gmail-sync', userId: email });
const poll = async (): Promise<'completed' | 'failed' | 'cancelled'> => {
for (let i = 0; i < 120; i++) {
await new Promise((r) => setTimeout(r, 3000));
const current = await readJob(job.id);
if (!current) return 'failed';
if (current.status === 'completed' || current.status === 'failed' || current.status === 'cancelled') {
return current.status;
}
}
return 'failed';
};
const status = await poll();
if (status !== 'completed') {
await send('Email sync failed. Check the queue dashboard for details.');
return;
}
try {
const db = openEmailDb(email);
const row = db.query('SELECT COUNT(*) as count FROM emails WHERE deleted = 0').get() as { count: number };
const countAfter = row.count;
const newCount = countAfter - countBefore;
if (newCount <= 0) {
db.close();
await send('Sync complete — no new emails.');
return;
}
const newest = db
.query('SELECT from_name, from_address, subject FROM emails WHERE deleted = 0 ORDER BY date DESC LIMIT ?')
.all(Math.min(newCount, 20)) as Array<{ from_name: string | null; from_address: string; subject: string }>;
db.close();
const lines = newest.map((e) => {
const sender = e.from_name || e.from_address;
return `- *${sender}*: ${e.subject}`;
});
let text = `Sync complete — *${newCount}* new email${newCount !== 1 ? 's' : ''}`;
if (newCount > 20) text += ` (showing latest 20)`;
text += `:\n\n${lines.join('\n')}`;
await send(text);
} catch (err) {
await send(`Sync complete but failed to read results: ${err instanceof Error ? err.message : String(err)}`);
}
}
async function handleCommand(ctx: CommandContext): Promise<boolean> {
const { content, send, whatsappId } = ctx;
const lower = content.toLowerCase();
const helpSections: Record<string, string> = {
models:
'*Models:*\n' +
'`!model` — show current model\n' +
'`!model <id>` — switch model\n' +
'`!models` — list available models',
email: '*Email:*\n' + '`!email sync` — sync Gmail and show new emails',
};
if (lower === '!help' || lower.startsWith('!help ')) {
const topic = content.slice('!help'.length).trim().toLowerCase();
if (topic && topic in helpSections) {
await send(helpSections[topic]!);
return true;
}
if (topic) {
await send(
`Unknown topic: \`${topic}\`\nAvailable: ${Object.keys(helpSections)
.map((k) => `\`${k}\``)
.join(', ')}`,
);
return true;
}
const full = Object.values(helpSections).join('\n\n');
await send(full + '\n\n`!help <topic>` — show commands for a topic');
return true;
}
if (lower === '!models') {
const models = await getVisibleModels();
if (models.length === 0) {
await send('No models available.');
return true;
}
const current = getSessionModel('whatsapp', whatsappId);
const grouped = new Map<string, string[]>();
for (const m of models) {
const list = grouped.get(m.provider) ?? [];
list.push(m.id === current ? `*${m.id}* (current)` : m.id);
grouped.set(m.provider, list);
}
let text = '*Available models:*\n';
for (const [provider, ids] of grouped) {
text += `\n_${provider}_\n${ids.map((id) => ` ${id}`).join('\n')}\n`;
}
text += '\nUse `!model <id>` to switch.';
await send(text);
return true;
}
if (lower === '!model') {
const current = getSessionModel('whatsapp', whatsappId);
await send(
current
? `Current model: *${current}*`
: 'No active session yet — the default model will be used on your next message.',
);
return true;
}
if (lower.startsWith('!model ')) {
const requested = content.slice('!model '.length).trim();
if (!requested) {
const current = getSessionModel('whatsapp', whatsappId);
await send(current ? `Current model: *${current}*` : 'No active session yet.');
return true;
}
const models = await getVisibleModels();
const match = models.find((m) => m.id === requested || m.name === requested);
if (!match) {
await send(`Model not found: \`${requested}\`\nUse \`!models\` to see available models.`);
return true;
}
setSessionModel('whatsapp', whatsappId, match.id);
await send(`Model switched to *${match.id}*. The new model will be used on your next message.`);
return true;
}
if (lower === '!email sync') {
await handleEmailSync(ctx);
return true;
}
return false;
}
export async function handleWhatsAppMessage(msg: WAMessage): Promise<void> {
const waClient = getWhatsAppClient();
if (!waClient) return;
// Ignore group chats, status broadcasts, own messages
if (msg.from.endsWith('@g.us')) return;
if (msg.from === 'status@broadcast') return;
if (msg.fromMe) return;
if (!msg.body) return;
const phone = extractPhone(msg.from);
const content = msg.body.trim();
if (!content) return;
const send: SendFn = (text: string) => waClient.sendMessage(msg.from, text);
// Look up linked Officer user
const linked = await findUserByIntegrationConfig('whatsapp', 'whatsappId', phone);
if (!linked) {
if (PAIRING_CODE_PATTERN.test(content.toUpperCase())) {
const result = await consumePairingCode(content.toUpperCase(), phone);
if (result) {
await send('Account linked! You can now chat with me.');
return;
}
await send('Invalid or expired pairing code. Please generate a new one from Officer Settings.');
return;
}
await send(
"I don't recognize your WhatsApp number. To link it:\n" +
'1. Go to Officer Settings → Integrations → WhatsApp\n' +
'2. Click "Link WhatsApp" to get a pairing code\n' +
'3. Send the 6-character code to me here',
);
return;
}
// Handle commands
if (content.startsWith('!')) {
const handled = await handleCommand({
content,
send,
userId: linked.user.id,
email: linked.user.email,
whatsappId: phone,
});
if (handled) return;
}
// Typing indicator
const sendTyping = async () => {
try {
const chat = await msg.getChat();
await chat.sendStateTyping();
} catch {
// ignore
}
};
const typingInterval = setInterval(sendTyping, TYPING_INTERVAL_MS);
sendTyping();
try {
const result = await sendAndAwait({
userId: linked.user.id,
email: linked.user.email,
username: linked.user.username ?? linked.user.email.split('@')[0]!,
prompt: content,
context: 'whatsapp',
contextId: phone,
});
clearInterval(typingInterval);
// WhatsApp has 65k char limit — no chunking needed
const signature = `\`${result.model}\`\n`;
await send(signature + result.text);
} catch (err) {
clearInterval(typingInterval);
console.error('[whatsapp] Error handling message:', err);
await send('Sorry, something went wrong processing your message.').catch(() => {});
}
}