Files
wallabicher/web/backend/routes/telegram.js
Omar Sánchez Pizarro 81bf0675ed mongodb
Signed-off-by: Omar Sánchez Pizarro <omar.sanchez@pistacero.net>
2026-01-20 03:21:50 +01:00

110 lines
3.8 KiB
JavaScript

import express from 'express';
import { basicAuthMiddleware } from '../middlewares/auth.js';
import { getTelegramConfig, setTelegramConfig } from '../services/mongodb.js';
const router = express.Router();
// Obtener configuración de Telegram del usuario autenticado
router.get('/config', basicAuthMiddleware, async (req, res) => {
try {
const username = req.user.username;
const config = await getTelegramConfig(username);
if (!config) {
return res.json({
token: '',
channel: '',
enable_polling: false
});
}
res.json(config);
} catch (error) {
console.error('Error obteniendo configuración de Telegram:', error);
res.status(500).json({ error: error.message });
}
});
// Guardar configuración de Telegram del usuario autenticado
router.put('/config', basicAuthMiddleware, async (req, res) => {
try {
const username = req.user.username;
const { token, channel, enable_polling } = req.body;
if (!token || !channel) {
return res.status(400).json({ error: 'Token y channel son requeridos' });
}
await setTelegramConfig(username, {
token,
channel,
enable_polling: enable_polling || false
});
res.json({ success: true });
} catch (error) {
console.error('Error guardando configuración de Telegram:', error);
res.status(500).json({ error: error.message });
}
});
// Obtener threads/topics de Telegram
router.get('/threads', basicAuthMiddleware, async (req, res) => {
try {
const username = req.user.username;
const config = await getTelegramConfig(username);
if (!config || !config.token || !config.channel) {
return res.status(400).json({ error: 'Token o canal de Telegram no configurados' });
}
const token = config.token;
const channel = config.channel;
// Convertir el canal a chat_id si es necesario
let chatId = channel;
if (channel.startsWith('@')) {
// Para canales con @, necesitamos obtener el chat_id primero
const getChatUrl = `https://api.telegram.org/bot${token}/getChat?chat_id=${encodeURIComponent(channel)}`;
const chatResponse = await fetch(getChatUrl);
const chatData = await chatResponse.json();
if (!chatData.ok) {
return res.status(400).json({ error: `Error obteniendo chat: ${chatData.description || 'Chat no encontrado'}` });
}
chatId = chatData.result.id;
}
// Intentar obtener forum topics
const forumTopicsUrl = `https://api.telegram.org/bot${token}/getForumTopics?chat_id=${chatId}&limit=100`;
const topicsResponse = await fetch(forumTopicsUrl);
const topicsData = await topicsResponse.json();
if (topicsData.ok && topicsData.result?.topics) {
const threads = topicsData.result.topics.map(topic => ({
id: topic.message_thread_id,
name: topic.name || `Thread ${topic.message_thread_id}`,
icon_color: topic.icon_color,
icon_custom_emoji_id: topic.icon_custom_emoji_id,
}));
return res.json({ threads, success: true });
} else {
// Si no hay forum topics, devolver un mensaje informativo
return res.json({
threads: [],
success: false,
message: 'El chat no tiene forum topics habilitados o no se pudieron obtener. Puedes obtener el Thread ID manualmente copiando el enlace del tema.',
info: 'Para obtener el Thread ID manualmente: 1. Haz clic derecho en el tema/hilo en Telegram 2. Selecciona "Copiar enlace del tema" 3. El número al final de la URL es el Thread ID (ej: t.me/c/1234567890/8 → Thread ID = 8)'
});
}
} catch (error) {
console.error('Error obteniendo threads de Telegram:', error.message);
res.status(500).json({ error: error.message });
}
});
export default router;