# 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 ```env # 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 ```typescript 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 ```typescript // 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 1. **System Notifications**: General system alerts 2. **User Registration**: New user signups 3. **User Activity**: User actions and events 4. **Exercise Completion**: Exercise finished 5. **Module Completion**: Module finished 6. **Achievements**: Badges and milestones 7. **Error Notifications**: System errors 8. **Security Alerts**: Security events 9. **Performance Monitoring**: Performance metrics ### Creating Custom Templates ```typescript 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 ```typescript 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 ```typescript 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 ```bash # 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 ```typescript 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 ```typescript import { getWorkerHealth } from './workers/notification-sender.worker'; const workerHealth = await getWorkerHealth(); console.log(workerHealth); // { // healthy: true, // queueStats: { ... }, // workerRunning: true // } ``` ## Error Handling ### Common Errors 1. **Rate Limiting (429)** - Automatic retry with exponential backoff - Configurable retry delay and max attempts 2. **Bot Blocked (403)** - User must unblock the bot in Telegram - Check admin chat ID is correct 3. **Invalid Token (401)** - Verify `TELEGRAM_BOT_TOKEN` is correct - Regenerate token via @BotFather if needed 4. **Chat Not Found (400)** - Verify `TELEGRAM_ADMIN_CHAT_ID` is correct - Start a conversation with the bot first ### Debugging ```typescript 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 ```typescript // 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 ```typescript class NotificationService { // Send system notification sendSystemNotification(title, message, details?): Promise // Notify new user registration notifyNewUser(data): Promise // Notify module completion notifyModuleCompleted(data): Promise // Notify top 10 entry notifyTop10Entry(data): Promise // Notify system error notifySystemError(data): Promise // Send daily summary sendDailySummary(date?): Promise // Get statistics getStatistics(): Promise // Retry failed notifications retryFailedNotifications(limit?): Promise // Health check healthCheck(): Promise } ``` ### TelegramClient ```typescript class TelegramClient { // Send text message sendMessage(chatId, text, options?): Promise // Send photo sendPhoto(chatId, photo, caption?, options?): Promise // Send document sendDocument(chatId, document, caption?, options?): Promise // Get bot info getMe(): Promise // Health check healthCheck(): Promise } ``` ## Troubleshooting ### Notifications Not Sending 1. Check Telegram is enabled: `TELEGRAM_ENABLED=true` 2. Verify bot token is valid 3. Confirm admin chat ID is correct 4. Check Redis connection for worker queue 5. Review logs for error messages ### Queue Backing Up 1. Increase worker concurrency: `WORKER_CONCURRENCY=5` 2. Check for rate limiting issues 3. Verify network connectivity to Telegram API 4. Consider reducing notification frequency ### High Failure Rate 1. Check Telegram API status 2. Verify bot permissions 3. Review error messages in logs 4. Check for rate limiting (429 errors) 5. Validate message formatting ## Contributing When adding new notification types: 1. Create template in `templates/` directory 2. Add message type to `TelegramMessageType` enum 3. Add convenience method to `NotificationService` 4. Update this documentation 5. 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`