skailan-conversations
Version:
Servicio de conversaciones y mensajería para Skailan
142 lines • 5.69 kB
JavaScript
import { ProcessTelegramWebhook } from "../../app/use-cases/ProcessTelegramWebhook";
import { ConversationPrismaRepository } from "../../infra/database/prisma/ConversationPrismaRepository";
import { ChannelPrismaRepository } from "../../infra/database/prisma/ChannelPrismaRepository";
import { MessagePrismaRepository } from "../../infra/database/prisma/MessagePrismaRepository";
import { StartConversation } from "../../app/use-cases/StartConversation";
import { CreateMessage } from "../../app/use-cases/CreateMessage";
import { PrismaClient } from "@prisma/client";
export class TelegramWebhookController {
processTelegramWebhook;
startConversation;
createMessage;
constructor() {
// Inicializar use cases con repositorios
const prisma = new PrismaClient();
const conversationRepository = new ConversationPrismaRepository(prisma);
const channelRepository = new ChannelPrismaRepository(prisma);
const messageRepository = new MessagePrismaRepository(prisma);
this.startConversation = new StartConversation(conversationRepository, channelRepository);
this.createMessage = new CreateMessage(messageRepository, conversationRepository);
this.processTelegramWebhook = new ProcessTelegramWebhook(conversationRepository, channelRepository, messageRepository, this.startConversation, this.createMessage);
}
/**
* Maneja las actualizaciones de webhook de Telegram
*/
async handleWebhook(req, res) {
try {
const update = req.body;
const organizationId = req.organization?.id;
if (!organizationId) {
res.status(400).json({ error: "Organization ID not found" });
return;
}
// Obtener el canal de Telegram para esta organización
const channelRepository = new ChannelPrismaRepository(new PrismaClient());
const channels = await channelRepository.findAll(organizationId);
const telegramChannel = channels.find(channel => channel.type === 'telegram');
if (!telegramChannel) {
res.status(400).json({ error: "Telegram channel not found for this organization" });
return;
}
// Procesar la actualización de Telegram
await this.processTelegramWebhook.execute({
update,
organizationId,
channelId: telegramChannel.id,
});
res.json({
success: true,
message: "Webhook processed successfully",
});
}
catch (error) {
console.error("❌ Error procesando webhook de Telegram:", error);
res.status(500).json({
success: false,
error: "Internal server error",
});
}
}
/**
* Verifica el webhook de Telegram
*/
async verifyWebhook(req, res) {
try {
const { mode, token, challenge } = req.query;
if (mode === "subscribe" &&
token === process.env.TELEGRAM_WEBHOOK_VERIFY_TOKEN) {
res.status(200).send(challenge);
}
else {
res.status(403).json({ error: "Invalid verification token" });
}
}
catch (error) {
console.error("❌ Error verificando webhook:", error);
res.status(500).json({ error: "Internal server error" });
}
}
/**
* Obtiene información del bot
*/
async getBotInfo(req, res) {
try {
const organizationId = req.organization?.id;
if (!organizationId) {
res.status(400).json({ error: "Organization ID not found" });
return;
}
// Aquí deberías obtener la información del bot desde la base de datos
// Por ahora retornamos información básica
res.json({
success: true,
data: {
botName: "Skailan Bot",
username: process.env.TELEGRAM_BOT_USERNAME,
webhookUrl: process.env.TELEGRAM_WEBHOOK_URL,
isActive: true,
},
});
}
catch (error) {
console.error("❌ Error obteniendo información del bot:", error);
res.status(500).json({ error: "Internal server error" });
}
}
/**
* Configura el webhook de Telegram
*/
async setWebhook(req, res) {
try {
const { url } = req.body;
const organizationId = req.organization?.id;
if (!organizationId) {
res.status(400).json({ error: "Organization ID not found" });
return;
}
if (!url) {
res.status(400).json({ error: "Webhook URL is required" });
return;
}
// Aquí deberías configurar el webhook en Telegram
// Por ahora solo validamos la URL
try {
new URL(url);
}
catch {
res.status(400).json({ error: "Invalid webhook URL" });
return;
}
res.json({
success: true,
message: "Webhook configured successfully",
data: { webhookUrl: url },
});
}
catch (error) {
console.error("❌ Error configurando webhook:", error);
res.status(500).json({ error: "Internal server error" });
}
}
}
//# sourceMappingURL=telegramWebhookController.js.map