59 lines
2.1 KiB
C#
59 lines
2.1 KiB
C#
|
using System;
|
||
|
using Telegram.Bot;
|
||
|
using Telegram.Bot.Types.Enums;
|
||
|
using Telegram.Bot.Types.ReplyMarkups;
|
||
|
|
||
|
namespace Monithor.api {
|
||
|
public class Alerting {
|
||
|
public class TelegramTarget {
|
||
|
public TelegramTarget(TelegramBotClient client, string chatId, IMonitor monitor, string statusPageRoute, string displayName) {
|
||
|
_client = client;
|
||
|
_chatId = chatId;
|
||
|
Monitor = monitor;
|
||
|
_statusPageRoute = statusPageRoute;
|
||
|
_displayName = displayName;
|
||
|
}
|
||
|
|
||
|
private readonly TelegramBotClient _client;
|
||
|
private readonly string _chatId;
|
||
|
public readonly IMonitor Monitor;
|
||
|
private readonly string _statusPageRoute;
|
||
|
private readonly string _displayName;
|
||
|
|
||
|
public async void SendMessage() {
|
||
|
var statusPageBtn = new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("Open status page", $"https://{_statusPageRoute}"));
|
||
|
var message = GetMessage(Monitor, _displayName);
|
||
|
try {
|
||
|
await _client.SendTextMessageAsync(_chatId, message, ParseMode.Default, replyMarkup: statusPageBtn);
|
||
|
}
|
||
|
catch (Exception e) {
|
||
|
Console.WriteLine(e);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private static string GetMessage(IMonitor mon, string displayName) {
|
||
|
return mon.Status switch {
|
||
|
MonitorStatus.Up => $"🟢 {displayName} is UP.\n" + $"Outage duration: {mon.ResolvedAt.Subtract(mon.StartedAt).ToStringCustom()}",
|
||
|
|
||
|
MonitorStatus.Recovering => $"🟡 {displayName} is recovering.",
|
||
|
MonitorStatus.Down => $"🔴 {displayName} is DOWN.\n" + $"Cause: {mon.LastValue}\n" + $"Outage started {mon.StartedAt:yyyy'-'MM'-'dd HH':'mm':'ss %K}",
|
||
|
MonitorStatus.Unknown => null,
|
||
|
MonitorStatus.Validating => null,
|
||
|
_ => null
|
||
|
};
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public static class TimeSpanExtensions {
|
||
|
public static string ToStringCustom(this TimeSpan timeSpan) {
|
||
|
var retstr = $"{timeSpan.Seconds}s";
|
||
|
if (timeSpan.Minutes > 0)
|
||
|
retstr = $"{timeSpan.Minutes}m {retstr}";
|
||
|
if (Math.Floor(timeSpan.TotalHours) > 0)
|
||
|
retstr = $"{Math.Floor(timeSpan.TotalHours)}h {retstr}";
|
||
|
|
||
|
return retstr;
|
||
|
}
|
||
|
}
|
||
|
}
|