✨ Características: - 45 ejercicios universitarios (Basic → Advanced) - Renderizado LaTeX profesional - IA generativa (Z.ai/DashScope) - Docker 9 servicios - Tests 123/123 pasando - Seguridad enterprise (JWT, XSS, Rate limiting) 🐳 Infraestructura: - Next.js 14 + Node.js 20 - PostgreSQL 15 + Redis 7 - Docker Compose completo - Nginx + SSL ready 📚 Documentación: - 5 informes técnicos completos - README profesional - Scripts de deployment automatizados Estado: Producción lista ✅
10 KiB
10 KiB
Telegram Notifications Module
Overview
The Telegram Notifications Module provides a complete backend-only notification system for the Math Platform. It sends administrative alerts to a Telegram bot, keeping admins informed about user activities, system errors, and important events.
Architecture
backend/
├── src/
│ ├── config/
│ │ └── telegram.ts # Telegram configuration & settings
│ ├── modules/
│ │ └── notification/
│ │ ├── notification.service.ts # Main notification service
│ │ ├── index.ts # Module exports
│ │ └── telegram/
│ │ ├── telegram.client.ts # HTTP client for Telegram API
│ │ └── templates/ # Message templates
│ │ ├── index.ts # Template factory
│ │ ├── alert.template.ts
│ │ ├── progress.template.ts
│ │ └── achievement.template.ts
│ ├── workers/
│ │ └── notification-sender.worker.ts # Async job processor
│ └── scripts/
│ └── test-telegram.ts # Test script
Features
- Async Queue Processing: Uses Bull with Redis for reliable job processing
- Retry Logic: Automatic retry with exponential backoff on failures
- Rich Templates: Pre-built templates for different notification types
- Type Safety: Full TypeScript support with proper interfaces
- Error Handling: Comprehensive error handling and logging
- Rate Limiting: Built-in rate limiting to avoid Telegram API limits
- Health Checks: Monitor notification system health
Configuration
Environment Variables
# Telegram Configuration
TELEGRAM_BOT_TOKEN="your-telegram-bot-token-here"
TELEGRAM_ADMIN_CHAT_ID="your-chat-id-here"
TELEGRAM_ENABLED=true
# Optional Configuration
TELEGRAM_API_URL="https://api.telegram.org"
TELEGRAM_TIMEOUT=10000
TELEGRAM_MAX_RETRIES=3
TELEGRAM_RETRY_DELAY=1000
TELEGRAM_PARSE_MODE="HTML"
TELEGRAM_DISABLE_WEB_PAGE_PREVIEW=true
TELEGRAM_MIN_PRIORITY="NORMAL"
Priority Levels
Notifications can be filtered by priority:
LOW: Informational notifications (user activity, exercise completion)NORMAL: Regular notifications (module completion, achievements)HIGH: Important notifications (errors, performance issues)URGENT: Critical notifications (security alerts)
Usage
Basic Notifications
import { notificationService } from './modules/notification';
// System Notification
await notificationService.sendSystemNotification(
'Server Started',
'The application server has started successfully',
{ port: 3001, environment: 'production' }
);
// User Registration
await notificationService.notifyNewUser({
userId: 'user-123',
anonymousId: 'anon-456',
username: 'john_doe',
email: 'john@example.com',
registeredAt: new Date().toISOString(),
ipAddress: '192.168.1.1',
});
// Error Notification
await notificationService.notifySystemError({
errorType: 'DatabaseError',
errorMessage: 'Failed to connect to database',
stackTrace: 'Error: ...',
path: '/api/users',
method: 'POST',
statusCode: 500,
});
Advanced Usage
// Module Completion
await notificationService.notifyModuleCompleted({
userId: 'user-123',
anonymousId: 'anon-456',
moduleName: 'Vectores y Espacios Vectoriales',
moduleType: 'FUNDAMENTOS',
finalScore: 95,
totalPoints: 1250,
exercisesCompleted: 45,
timeSpentMinutes: 120,
startedAt: startDate.toISOString(),
completedAt: new Date().toISOString(),
});
// Achievement Notification
await notificationService.notifyTop10Entry({
userId: 'user-123',
anonymousId: 'anon-456',
position: 5,
points: 2500,
exercisesCompleted: 120,
streak: 15,
});
// Daily Summary (scheduled task)
await notificationService.sendDailySummary(new Date());
Templates
Available Templates
- System Notifications: General system alerts
- User Registration: New user signups
- User Activity: User actions and events
- Exercise Completion: Exercise finished
- Module Completion: Module finished
- Achievements: Badges and milestones
- Error Notifications: System errors
- Security Alerts: Security events
- Performance Monitoring: Performance metrics
Creating Custom Templates
import { TelegramTemplateFactory } from './modules/notification/telegram/templates';
// Format message using template factory
const { content, messageType, priority } = TelegramTemplateFactory.formatMessage(
TelegramMessageType.SYSTEM,
{
title: 'Custom Alert',
message: 'Something important happened',
details: { key: 'value' }
}
);
// Send custom notification
await notificationService.sendNotification(
TelegramMessageType.SYSTEM,
data,
{ priority: TelegramPriority.HIGH }
);
Worker & Queue
Queue Management
import {
getNotificationQueue,
getQueueStats,
pauseQueue,
resumeQueue
} from './modules/notification';
// Get queue statistics
const stats = await getQueueStats();
console.log(stats);
// { waiting: 5, active: 2, completed: 100, failed: 3, ... }
// Pause queue (maintenance)
await pauseQueue();
// Resume queue
await resumeQueue();
Retry Failed Notifications
import { retryFailedNotifications } from './modules/notification';
// Retry up to 10 failed notifications
const retriedCount = await retryFailedNotifications(10);
console.log(`Retried ${retriedCount} notifications`);
Testing
Run Test Script
# Test all Telegram notifications
npm run test:telegram
# Or directly with tsx
npx tsx src/scripts/test-telegram.ts
Test Coverage
The test script validates:
- Telegram client connection
- System notifications
- User registration notifications
- Error notifications
- Module completion notifications
- Achievement notifications
- Queue statistics
Health Monitoring
Check Notification Health
const health = await notificationService.healthCheck();
console.log(health);
// {
// healthy: true,
// telegram: true,
// stats: {
// total: 100,
// pending: 5,
// sent: 90,
// failed: 5,
// todaySent: 25,
// todayFailed: 2
// }
// }
Worker Health
import { getWorkerHealth } from './workers/notification-sender.worker';
const workerHealth = await getWorkerHealth();
console.log(workerHealth);
// {
// healthy: true,
// queueStats: { ... },
// workerRunning: true
// }
Error Handling
Common Errors
-
Rate Limiting (429)
- Automatic retry with exponential backoff
- Configurable retry delay and max attempts
-
Bot Blocked (403)
- User must unblock the bot in Telegram
- Check admin chat ID is correct
-
Invalid Token (401)
- Verify
TELEGRAM_BOT_TOKENis correct - Regenerate token via @BotFather if needed
- Verify
-
Chat Not Found (400)
- Verify
TELEGRAM_ADMIN_CHAT_IDis correct - Start a conversation with the bot first
- Verify
Debugging
import { logger } from './shared/utils/logger';
// Enable debug logging
logger.level = 'debug';
// Check Telegram configuration
import { telegramConfig } from './config/telegram';
console.log(telegramConfig.healthCheck());
Production Considerations
Security
- Never commit bot tokens to version control
- Use environment variables for sensitive data
- Implement rate limiting per notification type
- Monitor for abuse patterns
Performance
- Use async queue for all notifications
- Don't block main thread with Telegram calls
- Implement proper error recovery
- Monitor queue depth and processing time
Monitoring
// Set up monitoring (example with cron)
import cron from 'node-cron';
// Check queue health every 5 minutes
cron.schedule('*/5 * * * *', async () => {
const stats = await getQueueStats();
if (stats.failed > 10) {
// Alert admins about high failure rate
await notificationService.sendSystemNotification(
'High Notification Failure Rate',
`${stats.failed} notifications have failed`,
{ stats }
);
}
});
API Reference
NotificationService
class NotificationService {
// Send system notification
sendSystemNotification(title, message, details?): Promise<NotificationResult>
// Notify new user registration
notifyNewUser(data): Promise<CreateNotificationResult>
// Notify module completion
notifyModuleCompleted(data): Promise<CreateNotificationResult>
// Notify top 10 entry
notifyTop10Entry(data): Promise<CreateNotificationResult>
// Notify system error
notifySystemError(data): Promise<CreateNotificationResult>
// Send daily summary
sendDailySummary(date?): Promise<CreateNotificationResult>
// Get statistics
getStatistics(): Promise<NotificationStatistics>
// Retry failed notifications
retryFailedNotifications(limit?): Promise<void>
// Health check
healthCheck(): Promise<HealthCheckResult>
}
TelegramClient
class TelegramClient {
// Send text message
sendMessage(chatId, text, options?): Promise<MessageResult>
// Send photo
sendPhoto(chatId, photo, caption?, options?): Promise<MessageResult>
// Send document
sendDocument(chatId, document, caption?, options?): Promise<MessageResult>
// Get bot info
getMe(): Promise<TelegramBotInfo>
// Health check
healthCheck(): Promise<HealthCheckResult>
}
Troubleshooting
Notifications Not Sending
- Check Telegram is enabled:
TELEGRAM_ENABLED=true - Verify bot token is valid
- Confirm admin chat ID is correct
- Check Redis connection for worker queue
- Review logs for error messages
Queue Backing Up
- Increase worker concurrency:
WORKER_CONCURRENCY=5 - Check for rate limiting issues
- Verify network connectivity to Telegram API
- Consider reducing notification frequency
High Failure Rate
- Check Telegram API status
- Verify bot permissions
- Review error messages in logs
- Check for rate limiting (429 errors)
- Validate message formatting
Contributing
When adding new notification types:
- Create template in
templates/directory - Add message type to
TelegramMessageTypeenum - Add convenience method to
NotificationService - Update this documentation
- Add tests for new notification type
License
MIT
Support
For issues or questions:
- Check logs in
logs/combined.log - Review Telegram API documentation: https://core.telegram.org/bots/api
- Test configuration using:
npm run test:telegram