Add Telegram bot integration for real-time alert notifications

- Implemented ITelegramNotificationService and TelegramNotificationService for sending alerts via Telegram.
- Updated MonitoringSettings to include Telegram configuration options.
- Enhanced AlertService to send alerts and resolutions through Telegram.
- Added API endpoints for checking Telegram status and sending test alerts.
- Updated README and TELEGRAM_SETUP.md with setup instructions and features.
- Included example configuration in appsettings.telegram.example.json.
This commit is contained in:
Phoenix
2025-08-07 17:30:02 +08:00
parent 774cdbaf66
commit d6efa9163b
11 changed files with 610 additions and 4 deletions
+29 -1
View File
@@ -21,6 +21,7 @@ namespace ResourceMonitorService.Services
{
private readonly ILogger<AlertService> _logger;
private readonly MonitoringSettings _settings;
private readonly ITelegramNotificationService _telegramService;
private readonly ConcurrentDictionary<string, Alert> _activeAlerts;
private readonly ConcurrentQueue<Alert> _alertHistory;
private readonly Dictionary<string, DateTime> _lastAlertTime;
@@ -29,10 +30,11 @@ namespace ResourceMonitorService.Services
public event EventHandler<Alert>? AlertTriggered;
public event EventHandler<Alert>? AlertResolved;
public AlertService(ILogger<AlertService> logger, IOptions<MonitoringSettings> settings)
public AlertService(ILogger<AlertService> logger, IOptions<MonitoringSettings> settings, ITelegramNotificationService telegramService)
{
_logger = logger;
_settings = settings.Value;
_telegramService = telegramService;
_activeAlerts = new ConcurrentDictionary<string, Alert>();
_alertHistory = new ConcurrentQueue<Alert>();
_lastAlertTime = new Dictionary<string, DateTime>();
@@ -183,6 +185,19 @@ namespace ResourceMonitorService.Services
_logger.LogWarning("Alert triggered: {Message}", alert.Message);
AlertTriggered?.Invoke(this, alert);
// Send Telegram notification
_ = Task.Run(async () =>
{
try
{
await _telegramService.SendAlertAsync(alert);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send Telegram alert notification");
}
});
}
else
{
@@ -264,6 +279,19 @@ namespace ResourceMonitorService.Services
_logger.LogInformation("Alert resolved: {Message}", resolvedAlert.Message);
AlertResolved?.Invoke(this, resolvedAlert);
// Send Telegram resolution notification
_ = Task.Run(async () =>
{
try
{
await _telegramService.SendAlertResolvedAsync(resolvedAlert);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send Telegram resolution notification");
}
});
}
}
}