import type { JobsOptions } from "bullmq"; import { prisma } from "../utils/prisma"; import { telegramApiBase, requireTelegramBotToken } from "../utils/telegram"; import { enqueueOutboundDelivery, startOutboundDeliveryWorker } from "./outboundDelivery"; type TelegramSendJob = { omniMessageId: string; }; function asObject(value: unknown): Record { if (!value || typeof value !== "object" || Array.isArray(value)) return {}; return value as Record; } function readNestedString(obj: Record, path: string[]): string { let current: unknown = obj; for (const segment of path) { if (!current || typeof current !== "object" || Array.isArray(current)) return ""; current = (current as Record)[segment]; } return typeof current === "string" ? current.trim() : ""; } export async function enqueueTelegramSend(input: TelegramSendJob, opts?: JobsOptions) { const msg = await prisma.omniMessage.findUnique({ where: { id: input.omniMessageId }, include: { thread: true }, }); if (!msg) throw new Error(`omni message not found: ${input.omniMessageId}`); if (msg.channel !== "TELEGRAM" || msg.direction !== "OUT") { throw new Error(`Invalid omni message for telegram send: ${msg.id}`); } const raw = asObject(msg.rawJson); const text = readNestedString(raw, ["normalized", "text"]) || readNestedString(raw, ["payloadNormalized", "text"]) || msg.text; if (!text) { throw new Error(`Omni message has empty text payload: ${msg.id}`); } const token = requireTelegramBotToken(); const endpoint = `${telegramApiBase()}/bot${token}/sendMessage`; const payload = { chat_id: msg.thread.externalChatId, text, ...(msg.thread.businessConnectionId ? { business_connection_id: msg.thread.businessConnectionId } : {}), }; return enqueueOutboundDelivery( { omniMessageId: msg.id, endpoint, method: "POST", payload, provider: "telegram_business", channel: "TELEGRAM", }, opts, ); } export function startTelegramSendWorker() { return startOutboundDeliveryWorker(); }