Spaces:
Sleeping
Sleeping
Merge pull request #24 from josesalazar2025/feature/telegram-bot-api
Browse files
backend/src/alerts/alerts.service.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
| 22 |
import { z } from 'zod';
|
| 23 |
import { alertsRepository } from './alerts.repository.js';
|
| 24 |
import { watchlistRepository } from '../watchlist/watchlist.repository.js';
|
| 25 |
-
import { sendMessage } from './telegram.client.js';
|
| 26 |
import { emitPriceAlert } from '../socket/broadcaster.js';
|
| 27 |
import { logger } from '../utils/logger.js';
|
| 28 |
|
|
@@ -49,10 +49,7 @@ export const alertsService = {
|
|
| 49 |
const recent = await alertsRepository.findRecent(user.id, market.id, 'price_threshold', DEDUP_WINDOW_MS);
|
| 50 |
if (recent) continue;
|
| 51 |
|
| 52 |
-
const
|
| 53 |
-
const threshold = (alertThreshold * 100).toFixed(1);
|
| 54 |
-
const message =
|
| 55 |
-
`<b>Price Alert</b>\n${market.question}\nYES: ${pct}% β₯ threshold ${threshold}%`;
|
| 56 |
|
| 57 |
await alertsRepository.create({ userId: user.id, marketId: market.id, type: 'price_threshold', message });
|
| 58 |
await sendMessage(user.telegramChatId, message);
|
|
|
|
| 22 |
import { z } from 'zod';
|
| 23 |
import { alertsRepository } from './alerts.repository.js';
|
| 24 |
import { watchlistRepository } from '../watchlist/watchlist.repository.js';
|
| 25 |
+
import { sendMessage, formatPriceAlert } from './telegram.client.js';
|
| 26 |
import { emitPriceAlert } from '../socket/broadcaster.js';
|
| 27 |
import { logger } from '../utils/logger.js';
|
| 28 |
|
|
|
|
| 49 |
const recent = await alertsRepository.findRecent(user.id, market.id, 'price_threshold', DEDUP_WINDOW_MS);
|
| 50 |
if (recent) continue;
|
| 51 |
|
| 52 |
+
const message = formatPriceAlert(market.question, market.yesPrice, alertThreshold);
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
await alertsRepository.create({ userId: user.id, marketId: market.id, type: 'price_threshold', message });
|
| 55 |
await sendMessage(user.telegramChatId, message);
|
backend/src/alerts/telegram.client.js
CHANGED
|
@@ -1,32 +1,91 @@
|
|
| 1 |
/**
|
| 2 |
-
*
|
| 3 |
*
|
| 4 |
* Responsabilidades:
|
| 5 |
* - sendMessage(chatId, text) β POST a api.telegram.org/bot<TOKEN>/sendMessage.
|
|
|
|
|
|
|
|
|
|
| 6 |
* - Parse_mode: HTML (permite formato basico: <b>, <i>).
|
| 7 |
-
* - Si falta TELEGRAM_BOT_TOKEN o chatId,
|
| 8 |
* - Errores de red se capturan y loguean como warn (no bloquean el flujo).
|
|
|
|
| 9 |
*
|
| 10 |
* Consumido por:
|
| 11 |
* - alerts.service.js β processAll() cuando se dispara una alerta.
|
| 12 |
*
|
| 13 |
* Seguridad:
|
| 14 |
* - El token se lee de variables de entorno (nunca hardcodeado).
|
| 15 |
-
* -
|
| 16 |
*/
|
| 17 |
|
| 18 |
import { httpPost } from '../utils/httpClient.js';
|
| 19 |
import { config } from '../config.js';
|
| 20 |
import { logger } from '../utils/logger.js';
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
export async function sendMessage(chatId, text) {
|
| 23 |
if (!config.TELEGRAM_BOT_TOKEN || !chatId) return;
|
| 24 |
try {
|
| 25 |
-
await httpPost(
|
| 26 |
`https://api.telegram.org/bot${config.TELEGRAM_BOT_TOKEN}/sendMessage`,
|
| 27 |
{ chat_id: chatId, text, parse_mode: 'HTML' },
|
| 28 |
{ retries: 1, timeout: 8_000 },
|
| 29 |
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
} catch (err) {
|
| 31 |
logger.warn({ err: err.message, chatId }, 'telegram send failed');
|
| 32 |
}
|
|
|
|
| 1 |
/**
|
| 2 |
+
* Cliente de integracion con Telegram Bot API.
|
| 3 |
*
|
| 4 |
* Responsabilidades:
|
| 5 |
* - sendMessage(chatId, text) β POST a api.telegram.org/bot<TOKEN>/sendMessage.
|
| 6 |
+
* - formatPriceAlert(question, yesPrice, threshold) β construye mensaje HTML
|
| 7 |
+
* escapando entidades del input de usuario.
|
| 8 |
+
* - escapeHtml(text) β escapa caracteres HTML sensibles (&, <, >, ").
|
| 9 |
* - Parse_mode: HTML (permite formato basico: <b>, <i>).
|
| 10 |
+
* - Si falta TELEGRAM_BOT_TOKEN o chatId, sendMessage retorna silenciosamente.
|
| 11 |
* - Errores de red se capturan y loguean como warn (no bloquean el flujo).
|
| 12 |
+
* - Respuestas de Telegram con ok: false se loguean como warn y no lanzan excepcion.
|
| 13 |
*
|
| 14 |
* Consumido por:
|
| 15 |
* - alerts.service.js β processAll() cuando se dispara una alerta.
|
| 16 |
*
|
| 17 |
* Seguridad:
|
| 18 |
* - El token se lee de variables de entorno (nunca hardcodeado).
|
| 19 |
+
* - Todo texto dinamico se escapa via escapeHtml antes de inyectarse en HTML.
|
| 20 |
*/
|
| 21 |
|
| 22 |
import { httpPost } from '../utils/httpClient.js';
|
| 23 |
import { config } from '../config.js';
|
| 24 |
import { logger } from '../utils/logger.js';
|
| 25 |
|
| 26 |
+
/**
|
| 27 |
+
* Escapa caracteres especiales HTML para evitar inyeccion
|
| 28 |
+
* cuando se usa parse_mode='HTML' en la API de Telegram.
|
| 29 |
+
*
|
| 30 |
+
* @param {string} text - Texto a escapar.
|
| 31 |
+
* @returns {string} Texto con entidades HTML escapadas (&, <, >, ").
|
| 32 |
+
*/
|
| 33 |
+
export function escapeHtml(text) {
|
| 34 |
+
if (typeof text !== 'string') return String(text ?? '');
|
| 35 |
+
return text
|
| 36 |
+
.replace(/&/g, '&')
|
| 37 |
+
.replace(/</g, '<')
|
| 38 |
+
.replace(/>/g, '>')
|
| 39 |
+
.replace(/"/g, '"');
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
/**
|
| 43 |
+
* Formatea un mensaje de alerta de precio en HTML para Telegram.
|
| 44 |
+
*
|
| 45 |
+
* Escapa automaticamente la pregunta del mercado para evitar inyeccion HTML.
|
| 46 |
+
* Los tags <b> son intencionales y no se escapan.
|
| 47 |
+
*
|
| 48 |
+
* @param {string} question - Pregunta del mercado (se escapa automaticamente).
|
| 49 |
+
* @param {number} yesPrice - Precio YES actual (0-1).
|
| 50 |
+
* @param {number} threshold - Umbral que se cruzo (0-1).
|
| 51 |
+
* @returns {string} Mensaje formateado en HTML.
|
| 52 |
+
*/
|
| 53 |
+
export function formatPriceAlert(question, yesPrice, threshold) {
|
| 54 |
+
const safeQuestion = escapeHtml(question);
|
| 55 |
+
const pct = (yesPrice * 100).toFixed(1);
|
| 56 |
+
const thr = (threshold * 100).toFixed(1);
|
| 57 |
+
return `<b>Price Alert</b>\n${safeQuestion}\nYES: ${pct}% β₯ threshold ${thr}%`;
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
/**
|
| 61 |
+
* Envia un mensaje de texto a un chat de Telegram via Bot API.
|
| 62 |
+
*
|
| 63 |
+
* Si TELEGRAM_BOT_TOKEN no esta configurado o chatId es falsy, la funcion
|
| 64 |
+
* retorna silenciosamente sin realizar peticion.
|
| 65 |
+
*
|
| 66 |
+
* Ante errores de red o respuestas con ok: false de Telegram, se loguea un
|
| 67 |
+
* warning y la funcion retorna sin lanzar excepcion, evitando interrumpir
|
| 68 |
+
* el flujo del scheduler.
|
| 69 |
+
*
|
| 70 |
+
* @param {string|number} chatId - Identificador del chat de Telegram.
|
| 71 |
+
* @param {string} text - Texto del mensaje (debe estar ya formateado en HTML).
|
| 72 |
+
* @returns {Promise<void>}
|
| 73 |
+
*/
|
| 74 |
export async function sendMessage(chatId, text) {
|
| 75 |
if (!config.TELEGRAM_BOT_TOKEN || !chatId) return;
|
| 76 |
try {
|
| 77 |
+
const result = await httpPost(
|
| 78 |
`https://api.telegram.org/bot${config.TELEGRAM_BOT_TOKEN}/sendMessage`,
|
| 79 |
{ chat_id: chatId, text, parse_mode: 'HTML' },
|
| 80 |
{ retries: 1, timeout: 8_000 },
|
| 81 |
);
|
| 82 |
+
if (result && result.ok === false) {
|
| 83 |
+
logger.warn(
|
| 84 |
+
{ chatId, description: result.description, errorCode: result.error_code },
|
| 85 |
+
'telegram API returned ok=false',
|
| 86 |
+
);
|
| 87 |
+
return;
|
| 88 |
+
}
|
| 89 |
} catch (err) {
|
| 90 |
logger.warn({ err: err.message, chatId }, 'telegram send failed');
|
| 91 |
}
|