DB-backed workspace + LangGraph agent
This commit is contained in:
163
Frontend/server/api/telegram/webhook.post.ts
Normal file
163
Frontend/server/api/telegram/webhook.post.ts
Normal file
@@ -0,0 +1,163 @@
|
||||
import { readBody, getQuery, getHeader } from "h3";
|
||||
import { prisma } from "../../utils/prisma";
|
||||
|
||||
function teamIdFromWebhook(event: any) {
|
||||
const q = getQuery(event);
|
||||
const fromQuery = typeof q.teamId === "string" ? q.teamId : null;
|
||||
return fromQuery || process.env.TELEGRAM_DEFAULT_TEAM_ID || "demo-team";
|
||||
}
|
||||
|
||||
function assertSecret(event: any) {
|
||||
const expected = process.env.TELEGRAM_WEBHOOK_SECRET;
|
||||
if (!expected) return;
|
||||
|
||||
const got = getHeader(event, "x-telegram-bot-api-secret-token");
|
||||
if (!got || got !== expected) {
|
||||
throw createError({ statusCode: 401, statusMessage: "invalid telegram secret token" });
|
||||
}
|
||||
}
|
||||
|
||||
function displayNameFromTelegram(obj: any) {
|
||||
const first = obj?.first_name || "";
|
||||
const last = obj?.last_name || "";
|
||||
const u = obj?.username ? `@${obj.username}` : "";
|
||||
const full = `${first} ${last}`.trim();
|
||||
return (full || u || "Telegram user").trim();
|
||||
}
|
||||
|
||||
async function upsertBusinessConnection(teamId: string, bc: any) {
|
||||
if (!bc?.id) return;
|
||||
const businessConnectionId = String(bc.id);
|
||||
|
||||
await prisma.telegramBusinessConnection.upsert({
|
||||
where: { teamId_businessConnectionId: { teamId, businessConnectionId } },
|
||||
update: {
|
||||
isEnabled: typeof bc.is_enabled === "boolean" ? bc.is_enabled : undefined,
|
||||
canReply: typeof bc.can_reply === "boolean" ? bc.can_reply : undefined,
|
||||
rawJson: bc,
|
||||
},
|
||||
create: {
|
||||
teamId,
|
||||
businessConnectionId,
|
||||
isEnabled: typeof bc.is_enabled === "boolean" ? bc.is_enabled : null,
|
||||
canReply: typeof bc.can_reply === "boolean" ? bc.can_reply : null,
|
||||
rawJson: bc,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureContactForTelegramChat(teamId: string, externalChatId: string, tgUser: any) {
|
||||
const existing = await prisma.omniContactIdentity.findUnique({
|
||||
where: { teamId_channel_externalId: { teamId, channel: "TELEGRAM", externalId: externalChatId } },
|
||||
include: { contact: true },
|
||||
});
|
||||
if (existing) return existing.contact;
|
||||
|
||||
const contact = await prisma.contact.create({
|
||||
data: {
|
||||
teamId,
|
||||
name: displayNameFromTelegram(tgUser),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.omniContactIdentity.create({
|
||||
data: {
|
||||
teamId,
|
||||
contactId: contact.id,
|
||||
channel: "TELEGRAM",
|
||||
externalId: externalChatId,
|
||||
},
|
||||
});
|
||||
|
||||
return contact;
|
||||
}
|
||||
|
||||
async function ensureThread(input: {
|
||||
teamId: string;
|
||||
contactId: string;
|
||||
externalChatId: string;
|
||||
businessConnectionId?: string | null;
|
||||
title?: string | null;
|
||||
}) {
|
||||
return prisma.omniThread.upsert({
|
||||
where: {
|
||||
teamId_channel_externalChatId_businessConnectionId: {
|
||||
teamId: input.teamId,
|
||||
channel: "TELEGRAM",
|
||||
externalChatId: input.externalChatId,
|
||||
businessConnectionId: input.businessConnectionId ?? null,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
contactId: input.contactId,
|
||||
title: input.title ?? undefined,
|
||||
},
|
||||
create: {
|
||||
teamId: input.teamId,
|
||||
contactId: input.contactId,
|
||||
channel: "TELEGRAM",
|
||||
externalChatId: input.externalChatId,
|
||||
businessConnectionId: input.businessConnectionId ?? null,
|
||||
title: input.title ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
assertSecret(event);
|
||||
const teamId = teamIdFromWebhook(event);
|
||||
|
||||
const update = (await readBody<any>(event)) || {};
|
||||
|
||||
// business_connection updates (user connected/disconnected bot)
|
||||
if (update.business_connection) {
|
||||
await upsertBusinessConnection(teamId, update.business_connection);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
const msg = update.business_message || update.edited_business_message;
|
||||
if (!msg) return { ok: true };
|
||||
|
||||
const businessConnectionId = msg.business_connection_id ? String(msg.business_connection_id) : null;
|
||||
const chatId = msg.chat?.id != null ? String(msg.chat.id) : null;
|
||||
const providerMessageId = msg.message_id != null ? String(msg.message_id) : null;
|
||||
|
||||
if (!chatId || !providerMessageId) return { ok: true };
|
||||
|
||||
const text = typeof msg.text === "string" ? msg.text : typeof msg.caption === "string" ? msg.caption : "";
|
||||
const occurredAt = msg.date ? new Date(Number(msg.date) * 1000) : new Date();
|
||||
|
||||
const contact = await ensureContactForTelegramChat(teamId, chatId, msg.from || msg.chat);
|
||||
const thread = await ensureThread({
|
||||
teamId,
|
||||
contactId: contact.id,
|
||||
externalChatId: chatId,
|
||||
businessConnectionId,
|
||||
title: msg.chat?.title ? String(msg.chat.title) : null,
|
||||
});
|
||||
|
||||
// Dedupe on (threadId, providerMessageId). If duplicate, ignore.
|
||||
try {
|
||||
await prisma.omniMessage.create({
|
||||
data: {
|
||||
teamId,
|
||||
contactId: contact.id,
|
||||
threadId: thread.id,
|
||||
direction: "IN",
|
||||
channel: "TELEGRAM",
|
||||
status: "DELIVERED",
|
||||
text: text || "",
|
||||
providerMessageId,
|
||||
providerUpdateId: update.update_id != null ? String(update.update_id) : null,
|
||||
rawJson: update,
|
||||
occurredAt,
|
||||
},
|
||||
});
|
||||
} catch (e: any) {
|
||||
// Prisma unique constraint violation => duplicate delivery
|
||||
if (e?.code !== "P2002") throw e;
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user