// npm install @shtab/sdk; run with Node.js 24: node bot.ts // Set SHTAB_API_BASE_URL to point the SDK at a local API when testing. import { createServer } from "node:http"; import { ShtabClient } from "@shtab/sdk"; import { parseDelivery, PayloadError, SignatureError, WebhookRouter } from "@shtab/sdk/webhooks"; function required(name: string): string { const value = process.env[name]; if (!value) throw new Error("Set " + name); return value; } const client = new ShtabClient(required("SHTAB_TOKEN"), { tokenType: "bot", baseUrl: process.env.SHTAB_API_BASE_URL || undefined, }); const secret = required("SHTAB_WEBHOOK_SECRET"); const teamId = required("SHTAB_TEAM_ID"); const router = new WebhookRouter(); router.on("messenger.message.created", async (event) => { const message = event.body; if (!message || message.text.trim().toLowerCase() !== "ping") return; await client.botsChatsMessagesRepliesCreate({ path: { team_id: teamId, chat_id: String(message.chat_id), message_id: String(message.thread_root_id ?? message.id), }, body: { text: "pong", client_message_id: event.event_id }, }); }); createServer(async (req, res) => { if (req.method !== "POST") { res.writeHead(405, { Allow: "POST" }).end(); return; } try { const chunks: Buffer[] = []; let size = 0; for await (const chunk of req) { size += chunk.length; if (size > 8 * 1024 * 1024) { res.writeHead(413).end(); return; } chunks.push(chunk); } const signature = req.headers["x-shtab-signature"]; const delivery = await parseDelivery(Buffer.concat(chunks), typeof signature === "string" ? signature : "", secret); await router.dispatch(delivery); res.writeHead(204).end(); } catch (error) { res.writeHead(error instanceof SignatureError ? 401 : error instanceof PayloadError ? 400 : 503).end(); } }).listen(Number(process.env.PORT ?? 8080), "127.0.0.1");