diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs
index 88144f8..703aaaa 100644
--- a/src/Anubis.Server/AnubisHost.cs
+++ b/src/Anubis.Server/AnubisHost.cs
@@ -39,7 +39,7 @@ internal sealed record HostChanged(HostMode Mode);
/// Everything that needs the database, built once it is reachable and the installation checks out.
internal sealed record AppServices(Database Db, SettingsStore Settings, SecretStore Secrets, AccessStore Access, Backups Backups, Scheduler Scheduler,
- MarketDataService? MarketData = null, TradingService? Trading = null, Laboratory? Lab = null);
+ MarketDataService? MarketData = null, TradingService? Trading = null, Laboratory? Lab = null, TelegramServices? Telegram = null);
///
/// The startup state machine of the server (SPEC 15.1, 15.6): reads the startup configuration, opens the configured
@@ -67,6 +67,7 @@ internal sealed partial class AnubisHost(
private CancellationTokenSource? _schedulerStop;
private MarketDataService? _market;
private TradingService? _trading;
+ private TelegramServices? _telegram;
private Laboratory? _lab;
private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0);
private volatile AppServices? _services;
@@ -80,6 +81,8 @@ internal sealed partial class AnubisHost(
public HostStatus Status => _status;
+ public IClock Clock => clock;
+
/// The running services; null until the first successful start.
public AppServices? Services => _status.Mode == HostMode.Ready ? _services : null;
@@ -333,7 +336,11 @@ internal sealed partial class AnubisHost(
// The laboratory computes on its own thread and reads only local data; the demo shows appendix F and runs none.
_lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger);
- _services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab);
+ // Telegram and the sign of life (SPEC 14): not in the demo, and in tests only with their fake network.
+ _telegram = options.Demo || (overrides is not null && overrides.TelegramHttp is null)
+ ? null
+ : new TelegramServices(this, _db, clock, settings, secrets, Config.HeartbeatUrl, overrides?.TelegramHttp, logger);
+ _services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab, _telegram);
// Before the scheduler writes its first run: how long the bot was away, and which runs it missed (SPEC 5.6).
var lastDues = new Dictionary(StringComparer.Ordinal);
@@ -480,7 +487,7 @@ internal sealed partial class AnubisHost(
var backup = new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone),
async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false))
{ MaxLateness = TimeSpan.FromHours(2), CatchUpWithin = TimeSpan.FromDays(3650) };
- foreach (var job in new[] { backup }.Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []))
+ foreach (var job in new[] { backup }.Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []))
{
scheduler.Add(job, lastDues.TryGetValue(job.Name, out var due) ? due : null);
}
@@ -490,6 +497,7 @@ internal sealed partial class AnubisHost(
var market = _market;
var trading = _trading;
var lab = _lab;
+ var telegram = _telegram;
_schedulerLoop = Task.Run(async () =>
{
using var runs = bus.Subscribe();
@@ -497,6 +505,7 @@ internal sealed partial class AnubisHost(
var collecting = market is null ? Task.CompletedTask : RunMarketDataAsync(market, token);
var dealing = trading is null ? Task.CompletedTask : RunTradingAsync(trading, token);
var testing = lab is null ? Task.CompletedTask : RunLabAsync(lab, token);
+ var writing = telegram is null ? Task.CompletedTask : RunTelegramAsync(telegram, token);
try
{
await scheduler.RunAsync(token).ConfigureAwait(false);
@@ -508,6 +517,7 @@ internal sealed partial class AnubisHost(
await collecting.ConfigureAwait(false);
await dealing.ConfigureAwait(false);
await testing.ConfigureAwait(false);
+ await writing.ConfigureAwait(false);
await recorder.ConfigureAwait(false);
}, CancellationToken.None);
}
@@ -542,6 +552,21 @@ internal sealed partial class AnubisHost(
}
}
+ private async Task RunTelegramAsync(TelegramServices telegram, CancellationToken cancellationToken)
+ {
+ try
+ {
+ await telegram.RunAsync(cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ }
+ catch (Exception ex)
+ {
+ LogTelegramFailed(logger, ex);
+ }
+ }
+
private async Task RunTradingAsync(TradingService trading, CancellationToken cancellationToken)
{
try
@@ -621,6 +646,8 @@ internal sealed partial class AnubisHost(
_trading = null;
_lab?.Dispose();
_lab = null;
+ _telegram?.Dispose();
+ _telegram = null;
}
// Values of the startup configuration that also exist as settings are read-only in the interface (SPEC 13.5).
@@ -673,6 +700,9 @@ internal sealed partial class AnubisHost(
[LoggerMessage(Level = LogLevel.Error, Message = "Market data stopped")]
private static partial void LogMarketDataFailed(ILogger logger, Exception exception);
+ [LoggerMessage(Level = LogLevel.Error, Message = "Telegram stopped")]
+ private static partial void LogTelegramFailed(ILogger logger, Exception exception);
+
[LoggerMessage(Level = LogLevel.Error, Message = "Laboratory stopped")]
private static partial void LogLabFailed(ILogger logger, Exception exception);
diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor
index 55c1aaa..1b7b094 100644
--- a/src/Anubis.Server/Components/Pages/Impostazioni.razor
+++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor
@@ -23,6 +23,11 @@
"capitale" => "Capitale affidato aggiornato e diviso tra le strategie.",
"limiti" => "Limiti di rischio salvati.",
"rischio" => "Impostazione del rischio salvata.",
+ "telegram" => "Telegram funziona: ti ho mandato un messaggio di prova e ho salvato token e chat.",
+ "telegram-prova" => "Messaggio di prova partito: controlla il telefono.",
+ "telegram-tolto" => "Telegram tolto: non ti scrivo più finché non lo rimetti.",
+ "segnale" => "Segnale di vita salvato: la prima chiamata è andata bene, da adesso lo chiamo ogni minuto.",
+ "segnale-tolto" => "Segnale di vita tolto.",
_ => "Fatto.",
})
@@ -33,7 +38,7 @@
}
@@ -186,6 +191,93 @@
}
+
+
Telegram e segnale di vita
+
Su Telegram ti scrivo il riepilogo del mattino, ogni acquisto e vendita con il risultato, gli avvisi di rischio, i blocchi e gli errori. Dalla stessa chat accetto /stato, /posizioni, /oggi, /pausa, /riprendi, /ferma (con conferma) e /aiuto; da altre chat nessun comando. Soldi veri, limiti e chiavi non si cambiano da Telegram.
+
+
Token del bot
@KeyState(_telegramToken)
+
Chat
@KeyState(_telegramChat)
+
Ultimo messaggio partito
@(_queue?.LastSentAt is { } sent ? Format.ShortDate(sent, Shell.Now, Shell.Zone) : "Nessuno")
Facoltativo. Se metti l'indirizzo di un servizio di controllo esterno (per esempio healthchecks.io), lo chiamo ogni minuto. Quando le chiamate si fermano è quel servizio ad avvisarti: è l'unico modo per sapere che il bot è spento quando è spento.
+
+
Indirizzo
@(Host.Services!.Telegram?.ConfiguredHeartbeat is not null ? "Dalla configurazione d'avvio (ANUBIS_HEARTBEAT_URL)" : KeyState(_heartbeat))
+ @if (Host.Services.Telegram is { } tg)
+ {
+
Ultima chiamata riuscita
@(tg.Heartbeat.LastOk is { } beat ? Format.ShortDate(beat, Shell.Now, Shell.Zone) : "Nessuna da quando il bot è partito")
+ @if (tg.Heartbeat.LastError is { } beatError)
+ {
+
@@ -365,6 +457,11 @@
private List _history = [];
private IReadOnlyList _backups = [];
private bool _hasSecondFactor;
+ private SecretStatus _telegramToken = new(Anubis.Notifications.TelegramSettings.TokenSecret, false, false, null);
+ private SecretStatus _telegramChat = new(Anubis.Notifications.TelegramSettings.ChatSecret, false, false, null);
+ private SecretStatus _heartbeat = new(TelegramServices.HeartbeatSecret, false, false, null);
+ private SettingValue _telegramStatus = new(SettingsStore.TelegramStatus.Key, "never", false, null);
+ private Anubis.Notifications.NotificationSummary? _queue;
private string? _draft;
private string? _draftUri;
@@ -397,6 +494,11 @@
_anyLive = await (services.Trading?.Stages ?? new StageBook(services.Db, Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false))).AnyLiveAsync(null, ct);
_backups = services.Backups.List();
+ _telegramToken = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.TokenSecret, ct);
+ _telegramChat = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct);
+ _heartbeat = await services.Secrets.StatusAsync(TelegramServices.HeartbeatSecret, ct);
+ _telegramStatus = await services.Settings.GetAsync(SettingsStore.TelegramStatus.Key, ct);
+ _queue = services.Telegram is { } telegram ? await telegram.Sender.SummaryAsync(ct) : null;
var ledger = new Ledger(services.Db, Clock);
var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock));
var reconciler = new Reconciler(services.Db, Clock, ledger);
@@ -445,6 +547,12 @@
"frase-rischio" => $"Una strategia usa soldi veri: per aggiungere rischio scrivi la frase «{StageBook.RaisePhrase}». Non ho cambiato nulla.",
"password-rischio" => "Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti. Non ho cambiato nulla.",
"retrocessione-rischio" => "Una strategia con soldi veri ha una condizione di retrocessione in corso: finché dura non si aggiunge rischio. Non ho cambiato nulla.",
+ "telegram-rifiutato" => "Telegram non ha accettato token o chat, o non ha risposto: il messaggio di prova non è partito e non ho salvato nulla. Controlla il token di @BotFather e il numero della chat.",
+ "telegram-prova" => "Il messaggio di prova non è partito: controlla token e chat, o riprova tra poco.",
+ "telegram-vuoto" => "Servono il token del bot e il numero della chat.",
+ "telegram-ambiente" => "Token e chat arrivano dalle variabili d'ambiente: si cambiano nella configurazione del container.",
+ "segnale" => "L'indirizzo non va bene: serve https:// (http solo nella rete di casa).",
+ "segnale-fallito" => "Il servizio di controllo non ha risposto bene alla prova: non ho salvato l'indirizzo.",
"scenari" => "Gli scenari non sono validi: una riga ciascuno, con descrizione e tre percentuali separate da punto e virgola.",
_ => PasswordMessages.For(Errore),
diff --git a/src/Anubis.Server/Components/Pages/PrimoAvvio.razor b/src/Anubis.Server/Components/Pages/PrimoAvvio.razor
index 7e94b7a..ab05f99 100644
--- a/src/Anubis.Server/Components/Pages/PrimoAvvio.razor
+++ b/src/Anubis.Server/Components/Pages/PrimoAvvio.razor
@@ -12,7 +12,11 @@
}
else
{
-
Due passi: dove tenere i dati e la password per entrare. Conti, capitale e Telegram si aggiungono dopo, dalle Impostazioni.
+
Due passi: dove tenere i dati e la password per entrare. Conti, capitale, Telegram e segnale di vita si aggiungono dopo, dalle Impostazioni: Telegram ha un pulsante che manda un messaggio di prova.
Su un computer di casa ti consiglio il segnale di vita (Impostazioni, sezione Telegram): un servizio esterno che ti avvisa quando il bot smette di chiamarlo. È l'unico modo per sapere che il bot è spento quando il computer è spento.
+ }
@if (Message is { } message)
{
@message
diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs
index 6d32a75..f880161 100644
--- a/src/Anubis.Server/Endpoints.cs
+++ b/src/Anubis.Server/Endpoints.cs
@@ -195,7 +195,7 @@ internal static partial class Endpoints
api.MapPost("/bot/{command}", async (string command, AnubisHost host, HttpContext context, CancellationToken ct) =>
{
- var (ok, message) = await BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
+ var (ok, message) = await BotCommandAsync(host, command, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return ok ? Results.Json(new { state = message }, _json) : Error(StatusCodes.Status409Conflict, "comando_non_ammesso", message);
});
@@ -255,7 +255,7 @@ internal static partial class Endpoints
/// Pause blocks new entries and keeps stops and exits; "Ferma tutto" is the switch of SPEC 9.3 (its full effect
/// arrives with the engine). Resume works only from a pause, never after "Ferma tutto" (SPEC 14).
///
- internal static async Task<(bool Ok, string Message)> BotCommandAsync(AnubisHost host, string command, HttpContext context, CancellationToken ct)
+ internal static async Task<(bool Ok, string Message)> BotCommandAsync(AnubisHost host, string command, string by, CancellationToken ct)
{
var settings = host.Services!.Settings;
var current = (await settings.GetAsync(SettingsStore.BotState.Key, ct).ConfigureAwait(false)).Value;
@@ -280,7 +280,6 @@ internal static partial class Endpoints
: "Comando non ammesso nello stato attuale del bot.");
}
- var by = context.User.Identity?.Name ?? "utente";
if (host.Services.Trading is { Risk: { } risk } trading)
{
// The switch of SPEC 9.3 goes through the risk engine: it cancels the orders under way and keeps the stops.
@@ -297,6 +296,7 @@ internal static partial class Endpoints
try
{
await risk.RestartAsync(by, ct).ConfigureAwait(false);
+ await NotifyBotAsync(host, "bot_restarted", $"Il bot è ripartito dopo «Ferma tutto» (da {by}).", ct).ConfigureAwait(false);
return (true, target);
}
catch (InvalidOperationException ex)
@@ -307,9 +307,24 @@ internal static partial class Endpoints
}
await settings.SetAsync(SettingsStore.BotState.Key, target, by, ct).ConfigureAwait(false);
+ if (target != current)
+ {
+ // Blocks and unblocks reach the phone (SPEC 14), whoever gave the command.
+ await NotifyBotAsync(host, "bot_" + target, target switch
+ {
+ "paused" => $"Bot in pausa (da {by}): niente nuovi acquisti, stop e uscite proseguono.",
+ "active" => $"Bot ripartito dalla pausa (da {by}).",
+ "stopped" => $"«Ferma tutto» (da {by}): niente nuove posizioni, gli stop restano. Si riparte solo dall'interfaccia.",
+ _ => $"Stato del bot: {target} (da {by}).",
+ }, ct).ConfigureAwait(false);
+ }
+
return (true, target);
}
+ private static Task NotifyBotAsync(AnubisHost host, string code, string message, CancellationToken ct) =>
+ host.Services!.Db.WriteAsync(s => Anubis.Trading.Diary.NotifyAsync(s, host.Clock, code, message, ct), ct);
+
// Live status (SPEC 13.4): one message on connect, one at every change and a heartbeat every few seconds, so the
// page can tell how old its data are and warn when the link drops.
private static async Task StatusSocketAsync(HttpContext context, AnubisHost host, ShellData shell, EventBus bus)
diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs
index d54feb9..1da97e2 100644
--- a/src/Anubis.Server/Forms.cs
+++ b/src/Anubis.Server/Forms.cs
@@ -34,6 +34,11 @@ internal static partial class Forms
signed.MapPost("/chiavi/{broker}", SaveKeysAsync);
signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync);
signed.MapPost("/capitale/{broker}", SetCapitalAsync);
+ signed.MapPost("/telegram", SaveTelegramAsync);
+ signed.MapPost("/telegram/prova", TestTelegramAsync);
+ signed.MapPost("/telegram/togli", RemoveTelegramAsync);
+ signed.MapPost("/segnale-di-vita", SaveHeartbeatAsync);
+ signed.MapPost("/segnale-di-vita/togli", RemoveHeartbeatAsync);
signed.MapPost("/laboratorio", PlanTrialAsync);
signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync);
signed.MapPost("/rischio/limiti", SetLimitsAsync);
@@ -159,7 +164,7 @@ internal static partial class Forms
private static async Task SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var back = Back(form, "/impostazioni");
- if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key)
+ if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key)
{
return Results.Redirect(With(back, "errore", "impostazione"));
}
@@ -176,7 +181,7 @@ internal static partial class Forms
private static async Task BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var back = Back(form, "/");
- var (ok, message) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
+ var (ok, message) = await Endpoints.BotCommandAsync(host, command, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return Results.Redirect(ok ? back : With(back, "errore", message.Contains("STOP", StringComparison.Ordinal) ? "file-stop" : "bot"));
}
@@ -274,6 +279,106 @@ internal static partial class Forms
return Results.Redirect(back + "?ok=chiavi#conti");
}
+ ///
+ /// The bot's Telegram (SPEC 14): a test message first, sent at once; token and chat are saved only when it left.
+ ///
+ private static async Task SaveTelegramAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
+ {
+ const string back = "/impostazioni";
+ if (host.IsDemo || host.Services is not { Telegram: { } telegram } services)
+ {
+ return Results.Redirect(back + "?errore=motore#telegram");
+ }
+
+ if ((await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.TokenSecret, ct).ConfigureAwait(false)).FromEnvironment
+ || (await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct).ConfigureAwait(false)).FromEnvironment)
+ {
+ return Results.Redirect(back + "?errore=telegram-ambiente#telegram");
+ }
+
+ var token = form["token"].ToString().Trim();
+ var chat = form["chat"].ToString().Trim();
+ if (token.Length is 0 or > 200 || chat.Length is 0 or > 40)
+ {
+ return Results.Redirect(back + "?errore=telegram-vuoto#telegram");
+ }
+
+ if (await telegram.TestAsync(new Anubis.Notifications.TelegramSettings(token, chat), ct).ConfigureAwait(false) is not null)
+ {
+ return Results.Redirect(back + "?errore=telegram-rifiutato#telegram");
+ }
+
+ var who = context.User.Identity?.Name ?? "utente";
+ await services.Secrets.SetAsync(Anubis.Notifications.TelegramSettings.TokenSecret, token, who, ct).ConfigureAwait(false);
+ await services.Secrets.SetAsync(Anubis.Notifications.TelegramSettings.ChatSecret, chat, who, ct).ConfigureAwait(false);
+ return Results.Redirect(back + "?ok=telegram#telegram");
+ }
+
+ // The form is bound even when unused: binding it is what makes the antiforgery check run on the route.
+ private static async Task TestTelegramAsync(IFormCollection form, AnubisHost host, CancellationToken ct)
+ {
+ const string back = "/impostazioni";
+ if (host.IsDemo || host.Services is not { Telegram: { } telegram }
+ || await telegram.ReadAsync(ct).ConfigureAwait(false) is not { } settings)
+ {
+ return Results.Redirect(back + "?errore=telegram-vuoto#telegram");
+ }
+
+ return Results.Redirect(await telegram.TestAsync(settings, ct).ConfigureAwait(false) is null ? back + "?ok=telegram-prova#telegram" : back + "?errore=telegram-prova#telegram");
+ }
+
+ private static async Task RemoveTelegramAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
+ {
+ const string back = "/impostazioni";
+ if (host.IsDemo || host.Services is not { } services)
+ {
+ return Results.Redirect(back + "?errore=motore#telegram");
+ }
+
+ var who = context.User.Identity?.Name ?? "utente";
+ await services.Secrets.RemoveAsync(Anubis.Notifications.TelegramSettings.TokenSecret, who, ct).ConfigureAwait(false);
+ await services.Secrets.RemoveAsync(Anubis.Notifications.TelegramSettings.ChatSecret, who, ct).ConfigureAwait(false);
+ return Results.Redirect(back + "?ok=telegram-tolto#telegram");
+ }
+
+ /// The address of the checking service (SPEC 14): called once as a test, saved encrypted only when it answered.
+ private static async Task SaveHeartbeatAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
+ {
+ const string back = "/impostazioni";
+ if (host.IsDemo || host.Services is not { Telegram: { ConfiguredHeartbeat: null } telegram } services)
+ {
+ return Results.Redirect(back + "?errore=motore#telegram");
+ }
+
+ var address = form["indirizzo"].ToString().Trim();
+ if (address.Length is 0 or > 500 || Anubis.Notifications.Heartbeat.Check(address) is not null)
+ {
+ return Results.Redirect(back + "?errore=segnale#telegram");
+ }
+
+ var probe = new Anubis.Notifications.Heartbeat(telegram.Http, host.Clock, _ => Task.FromResult(new Uri(address)), Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance);
+ if (!await probe.BeatAsync(ct).ConfigureAwait(false))
+ {
+ return Results.Redirect(back + "?errore=segnale-fallito#telegram");
+ }
+
+ await services.Secrets.SetAsync(TelegramServices.HeartbeatSecret, address, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
+ await telegram.Heartbeat.BeatAsync(ct).ConfigureAwait(false);
+ return Results.Redirect(back + "?ok=segnale#telegram");
+ }
+
+ private static async Task RemoveHeartbeatAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
+ {
+ const string back = "/impostazioni";
+ if (host.IsDemo || host.Services is not { } services)
+ {
+ return Results.Redirect(back + "?errore=motore#telegram");
+ }
+
+ await services.Secrets.RemoveAsync(TelegramServices.HeartbeatSecret, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
+ return Results.Redirect(back + "?ok=segnale-tolto#telegram");
+ }
+
private static async Task RemoveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
diff --git a/src/Anubis.Server/ServerOptions.cs b/src/Anubis.Server/ServerOptions.cs
index 668fc75..a7f3473 100644
--- a/src/Anubis.Server/ServerOptions.cs
+++ b/src/Anubis.Server/ServerOptions.cs
@@ -76,6 +76,9 @@ internal sealed record ServerOverrides
public Func? MarketSockets { get; init; }
+ /// Answers the Telegram calls and the sign of life instead of the network; tests without it have no Telegram.
+ public HttpMessageHandler? TelegramHttp { get; init; }
+
/// True starts the accounts and the order managers in a test; off by default in tests.
public bool? Trading { get; init; }
}
diff --git a/src/Anubis.Server/TelegramDesk.cs b/src/Anubis.Server/TelegramDesk.cs
new file mode 100644
index 0000000..e223d08
--- /dev/null
+++ b/src/Anubis.Server/TelegramDesk.cs
@@ -0,0 +1,176 @@
+using System.Text;
+using Anubis.Core;
+using Anubis.Data;
+using Anubis.Notifications;
+using Anubis.Trading;
+
+namespace Anubis.Server;
+
+///
+/// The answers of the Telegram commands and the messages the bot writes by itself (SPEC 14), from the same data as
+/// the Panoramica: one world, the simulated one until there is a real account.
+///
+internal sealed class TelegramDesk(AnubisHost host) : ITelegramDesk
+{
+ private const string By = "Telegram";
+
+ private AppServices Services => host.Services ?? throw new InvalidOperationException("Il bot sta ancora partendo: riprova tra poco.");
+
+ private TimeZoneInfo Zone => host.Config.TimeZone;
+
+ public async Task StatusAsync(CancellationToken cancellationToken)
+ {
+ var services = Services;
+ var now = host.Clock.UtcNow;
+ var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
+ var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false);
+ var text = new StringBuilder();
+ text.Append(bot switch { "paused" => "Bot in pausa", "stopped" => "Bot fermo («Ferma tutto»)", _ => "Bot attivo" })
+ .Append(" · solo denaro finto").AppendLine(".");
+ if (overview.HasData)
+ {
+ var today = overview.Cells[0];
+ text.Append("Patrimonio ").Append(Format.Money(overview.Points[^1].Equity)).Append(", oggi ").Append(Format.Money(today.Amount, withSign: true))
+ .Append(" (").Append(Format.Percent(today.Percent, 2, withSign: true)).AppendLine(").");
+ }
+
+ text.Append(Positions(overview.Positions, overview.PositionsWithoutStop));
+ if (overview.OpenOrders > 0)
+ {
+ text.Append(' ').Append(overview.OpenOrders == 1 ? "1 ordine in corso." : $"{overview.OpenOrders} ordini in corso.");
+ }
+
+ text.AppendLine();
+ if (overview.Next.Count > 0 && overview.Next[0] is var next)
+ {
+ text.Append("Prossima mossa: ").Append(next.Time).Append(' ').Append(next.Text).AppendLine(".");
+ }
+
+ return text.ToString().TrimEnd();
+ }
+
+ public async Task PositionsAsync(CancellationToken cancellationToken)
+ {
+ var services = Services;
+ var rows = await services.Db.ReadAsync(s => s.QueryAsync(
+ "SELECT a.name, a.environment, a.base_currency, i.symbol, p.strategy, p.quantity, p.average_price, p.last_price, p.stop_price FROM positions p " +
+ "JOIN accounts a ON a.id = p.account_id JOIN instruments i ON i.id = p.instrument_id WHERE p.quantity > 0 ORDER BY a.name, i.symbol",
+ r => (Account: r.Text("name"), Environment: r.Text("environment"), Currency: r.Text("base_currency"), Symbol: r.Text("symbol"), Strategy: r.Text("strategy"),
+ Quantity: r.Money("quantity"), Average: r.Money("average_price"), Last: r.MoneyOrNull("last_price"), Stop: r.MoneyOrNull("stop_price"))), cancellationToken)
+ .ConfigureAwait(false);
+ var world = rows.Any(r => TradingEnvironments.World(r.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
+ rows = [.. rows.Where(r => TradingEnvironments.World(r.Environment) == world)];
+ if (rows.Count == 0)
+ {
+ return "Nessuna posizione aperta.";
+ }
+
+ var text = new StringBuilder();
+ foreach (var r in rows)
+ {
+ var last = r.Last ?? r.Average;
+ var gain = (last - r.Average) * r.Quantity;
+ text.Append(DiaryText.Shown(r.Symbol)).Append(": ").Append(Format.Quantity(r.Quantity)).Append(" a ").Append(Format.Money(r.Average, r.Currency))
+ .Append(", ora ").Append(Format.Money(last, r.Currency)).Append(" (").Append(Format.Money(gain, r.Currency, withSign: true)).Append("), ")
+ .Append(r.Stop is { } stop ? "stop a " + Format.Money(stop, r.Currency) : "SENZA STOP")
+ .Append(" · ").Append(StrategyNames.Label(r.Strategy)).Append(", ").Append(r.Account).AppendLine();
+ }
+
+ return text.ToString().TrimEnd();
+ }
+
+ public async Task TodayAsync(CancellationToken cancellationToken)
+ {
+ var services = Services;
+ var now = host.Clock.UtcNow;
+ var local = TimeZoneInfo.ConvertTime(now, Zone);
+ var midnight = new DateTimeOffset(local.Date, local.Offset).ToUniversalTime();
+ var entries = await services.Db.ReadAsync(s => s.QueryAsync(
+ "SELECT occurred_at, message FROM journal WHERE kind = @k AND occurred_at >= @from ORDER BY occurred_at",
+ r => (At: r.Moment("occurred_at"), Text: r.Text("message")), ("k", DiaryKinds.Orders), ("from", midnight)), cancellationToken).ConfigureAwait(false);
+ var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false);
+ var text = new StringBuilder();
+ if (overview.HasData)
+ {
+ text.Append("Oggi ").Append(Format.Money(overview.Cells[0].Amount, withSign: true)).Append(" (").Append(Format.Percent(overview.Cells[0].Percent, 2, withSign: true))
+ .AppendLine(").");
+ }
+
+ if (entries.Count == 0)
+ {
+ text.Append("Nessun ordine oggi.");
+ return text.ToString();
+ }
+
+ const int Shown = 15;
+ foreach (var e in entries.TakeLast(Shown))
+ {
+ text.Append(TimeZoneInfo.ConvertTime(e.At, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture)).Append(' ').AppendLine(e.Text);
+ }
+
+ if (entries.Count > Shown)
+ {
+ text.Append("…e altre ").Append(entries.Count - Shown).Append(" righe nel Diario.");
+ }
+
+ return text.ToString().TrimEnd();
+ }
+
+ public Task PauseAsync(CancellationToken cancellationToken) =>
+ CommandAsync("pausa", "In pausa: niente nuovi acquisti; stop e uscite proseguono. /riprendi per ripartire.", cancellationToken);
+
+ public Task ResumeAsync(CancellationToken cancellationToken) => CommandAsync("riprendi", "Ripartito dalla pausa.", cancellationToken);
+
+ public Task StopAllAsync(CancellationToken cancellationToken) =>
+ CommandAsync("ferma", "«Ferma tutto» fatto: ordini in attesa annullati, niente nuove posizioni, gli stop restano. Si riparte solo dall'interfaccia, pagina Rischio.",
+ cancellationToken);
+
+ /// The morning summary (SPEC 14): the night, the positions, what comes today.
+ public async Task MorningAsync(CancellationToken cancellationToken)
+ {
+ var services = Services;
+ var now = host.Clock.UtcNow;
+ var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false);
+ var text = new StringBuilder("Buongiorno.").AppendLine();
+ if (overview.HasData)
+ {
+ text.Append("Patrimonio ").Append(Format.Money(overview.Points[^1].Equity)).Append("; ultimi 7 giorni ").Append(Format.Money(overview.Cells[1].Amount, withSign: true))
+ .AppendLine(".");
+ }
+
+ text.AppendLine(Positions(overview.Positions, overview.PositionsWithoutStop));
+ var local = TimeZoneInfo.ConvertTime(now, Zone).Date;
+ var today = overview.Next.Count == 0 ? [] : services.Scheduler.Upcoming(20)
+ .Where(u => TimeZoneInfo.ConvertTime(u.DueUtc, Zone).Date == local)
+ .Select(u => TimeZoneInfo.ConvertTime(u.DueUtc, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture) + " " + u.Description)
+ .ToList();
+ if (today.Count > 0)
+ {
+ text.AppendLine("Oggi:");
+ foreach (var line in today)
+ {
+ text.AppendLine(line);
+ }
+ }
+
+ return text.ToString().TrimEnd();
+ }
+
+ private static string Positions(int count, int withoutStop) => count switch
+ {
+ 0 => "Nessuna posizione aperta.",
+ 1 => withoutStop == 0 ? "1 posizione, con il suo stop." : "1 posizione, SENZA STOP.",
+ _ => withoutStop == 0 ? $"{count} posizioni, tutte con lo stop." : $"{count} posizioni, {withoutStop} SENZA STOP.",
+ };
+
+ private async Task CommandAsync(string command, string done, CancellationToken cancellationToken)
+ {
+ if (host.IsDemo)
+ {
+ return "Nella modalità dimostrativa il bot non si comanda.";
+ }
+
+ var (ok, message) = await Endpoints.BotCommandAsync(host, command, By, cancellationToken).ConfigureAwait(false);
+ return ok ? done : message;
+ }
+}
diff --git a/src/Anubis.Server/TelegramServices.cs b/src/Anubis.Server/TelegramServices.cs
new file mode 100644
index 0000000..51b11f1
--- /dev/null
+++ b/src/Anubis.Server/TelegramServices.cs
@@ -0,0 +1,159 @@
+using Anubis.Core;
+using Anubis.Db;
+using Anubis.Notifications;
+
+namespace Anubis.Server;
+
+///
+/// Telegram and the sign of life (SPEC 14): the queue sent every few seconds, the commands read as they arrive, the
+/// call to the checking service every minute, the morning summary and the optional periodic status.
+///
+internal sealed class TelegramServices : IDisposable
+{
+ /// The secret that keeps the address of the checking service when the configuration does not give one.
+ public const string HeartbeatSecret = "HEARTBEAT_URL";
+
+ public static readonly TimeOnly MorningAt = new(8, 0);
+ public static readonly TimeOnly EveningAt = new(20, 0);
+
+ private readonly HttpClient _http;
+ private readonly Database _db;
+ private readonly IClock _clock;
+ private readonly SettingsStore _settings;
+ private readonly SecretStore _secrets;
+ private readonly TimeZoneInfo _zone;
+
+ public TelegramServices(AnubisHost host, Database db, IClock clock, SettingsStore settings, SecretStore secrets, string? configuredHeartbeat, HttpMessageHandler? handler,
+ Microsoft.Extensions.Logging.ILogger logger)
+ {
+ ArgumentNullException.ThrowIfNull(host);
+ _db = db;
+ _clock = clock;
+ _settings = settings;
+ _secrets = secrets;
+ _zone = host.Config.TimeZone;
+ _http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false);
+
+ // Longer than the wait of the commands' long polling.
+ _http.Timeout = TimeSpan.FromSeconds(60);
+ Desk = new TelegramDesk(host);
+ Sender = new NotificationSender(db, clock, ReadAsync, Client);
+ Bot = new TelegramBot(clock, ReadAsync, Client, new TelegramCommands(Desk, clock), logger);
+ ConfiguredHeartbeat = configuredHeartbeat;
+ Heartbeat = new Heartbeat(_http, clock, HeartbeatAddressAsync, logger);
+ }
+
+ public TelegramDesk Desk { get; }
+
+ public NotificationSender Sender { get; }
+
+ public TelegramBot Bot { get; }
+
+ public Heartbeat Heartbeat { get; }
+
+ /// The address from the startup configuration (ANUBIS_HEARTBEAT_URL): it wins over the one saved here.
+ public string? ConfiguredHeartbeat { get; }
+
+ /// How often the queue is looked at.
+ public TimeSpan SendEvery { get; init; } = TimeSpan.FromSeconds(10);
+
+ /// The client of Telegram and of the checking service.
+ public HttpClient Http => _http;
+
+ public TelegramClient Client(string token) => new(_http, token);
+
+ public Task ReadAsync(CancellationToken cancellationToken) => TelegramSettings.ReadAsync(_secrets, cancellationToken);
+
+ public async Task HeartbeatAddressAsync(CancellationToken cancellationToken)
+ {
+ var text = ConfiguredHeartbeat ?? await _secrets.RevealAsync(HeartbeatSecret, cancellationToken).ConfigureAwait(false);
+ return string.IsNullOrWhiteSpace(text) || Heartbeat.Check(text) is not null ? null : new Uri(text.Trim());
+ }
+
+ public IReadOnlyList Jobs() =>
+ [
+ new("segnale-di-vita", "Segnale di vita al servizio di controllo", Schedule.Every(TimeSpan.FromMinutes(1)), async ct => await Heartbeat.BeatAsync(ct).ConfigureAwait(false))
+ {
+ MaxLateness = TimeSpan.FromMinutes(2),
+ },
+
+ // The summary is still useful a little late; after four hours the day has moved on (SPEC 5.6).
+ new("riepilogo-mattino", "Riepilogo del mattino su Telegram", Schedule.Daily(MorningAt, _zone), MorningAsync)
+ {
+ MaxLateness = TimeSpan.FromHours(4),
+ CatchUpWithin = TimeSpan.FromHours(4),
+ },
+ new("stato-ogni-ora", "Stato periodico su Telegram, se scelto ogni ora", Schedule.Every(TimeSpan.FromHours(1)), ct => PeriodicAsync("hourly", ct)),
+ new("stato-ogni-giorno", "Stato periodico su Telegram, se scelto ogni giorno", Schedule.Daily(EveningAt, _zone), ct => PeriodicAsync("daily", ct)),
+ ];
+
+ /// Sends the queue and reads the commands until the services stop.
+ public async Task RunAsync(CancellationToken cancellationToken)
+ {
+ var commands = Bot.RunAsync(cancellationToken);
+ try
+ {
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ await Sender.SendDueAsync(cancellationToken).ConfigureAwait(false);
+ await Task.Delay(SendEvery, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ finally
+ {
+ try
+ {
+ await commands.ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ }
+ }
+ }
+
+ ///
+ /// The test of Impostazioni: a message to the chat, sent at once and not through the queue, so the answer says
+ /// whether Telegram took it. Null when it went; otherwise the reason, in the user's words.
+ ///
+ public async Task TestAsync(TelegramSettings telegram, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(telegram);
+ try
+ {
+ var client = Client(telegram.Token);
+ var name = await client.GetMeAsync(cancellationToken).ConfigureAwait(false);
+ await client.SendAsync(telegram.ChatId, $"Anubis: messaggio di prova. Da qui ti scrivo{(name.Length > 0 ? " come @" + name : "")}; scrivi /aiuto per i comandi.",
+ cancellationToken).ConfigureAwait(false);
+ return null;
+ }
+ catch (TelegramException ex)
+ {
+ return ex.Message;
+ }
+ }
+
+ public void Dispose() => _http.Dispose();
+
+ private async Task MorningAsync(CancellationToken cancellationToken)
+ {
+ if (await ReadAsync(cancellationToken).ConfigureAwait(false) is null)
+ {
+ return;
+ }
+
+ var text = await Desk.MorningAsync(cancellationToken).ConfigureAwait(false);
+ await _db.WriteAsync(s => NotificationSender.EnqueueAsync(s, _clock, "morning_summary", text, cancellationToken), cancellationToken).ConfigureAwait(false);
+ }
+
+ private async Task PeriodicAsync(string every, CancellationToken cancellationToken)
+ {
+ if ((await _settings.GetAsync(SettingsStore.TelegramStatus.Key, cancellationToken).ConfigureAwait(false)).Value != every
+ || await ReadAsync(cancellationToken).ConfigureAwait(false) is null)
+ {
+ return;
+ }
+
+ var text = await Desk.StatusAsync(cancellationToken).ConfigureAwait(false);
+ await _db.WriteAsync(s => NotificationSender.EnqueueAsync(s, _clock, "periodic_status", text, cancellationToken), cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Anubis/Core/Settings.cs b/src/Anubis/Core/Settings.cs
index 47ddac9..6c9a2cb 100644
--- a/src/Anubis/Core/Settings.cs
+++ b/src/Anubis/Core/Settings.cs
@@ -41,8 +41,11 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
public static readonly SettingDefinition CentralBankMeetings = new("calendar.central_banks", "Riunioni di Fed e BCE",
Data.CentralBanks.DefaultList, Check: Data.CentralBanks.Check);
+ /// The optional periodic status on Telegram (SPEC 14): never, every hour or every evening.
+ public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]);
+
public static readonly IReadOnlyList All =
- [Theme, Currency, BotState, CentralBankMeetings, .. Risk.RiskSettings.All, Risk.Scenarios.Setting];
+ [Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, .. Risk.RiskSettings.All, Risk.Scenarios.Setting];
private readonly IReadOnlyDictionary _overrides = overrides ?? new Dictionary();
diff --git a/src/Anubis/Notifications/Notifications.cs b/src/Anubis/Notifications/Notifications.cs
new file mode 100644
index 0000000..b6a6364
--- /dev/null
+++ b/src/Anubis/Notifications/Notifications.cs
@@ -0,0 +1,133 @@
+using Anubis.Core;
+using Anubis.Db;
+
+namespace Anubis.Notifications;
+
+/// The state of a notification (SPEC 14): never "sent" before Telegram said ok.
+public static class NotificationStates
+{
+ /// In the queue: not tried yet, or Telegram is not configured.
+ public const string Pending = "pending";
+
+ public const string Sent = "sent";
+
+ /// Tried and refused; tried again at next_attempt_at, or never again when that is empty.
+ public const string Failed = "failed";
+}
+
+/// The bot's Telegram: the token and the one chat it writes to and takes commands from.
+public sealed record TelegramSettings(string Token, string ChatId)
+{
+ public const string TokenSecret = "TELEGRAM_BOT_TOKEN";
+ public const string ChatSecret = "TELEGRAM_CHAT_ID";
+
+ /// Both secrets, or null while either is missing.
+ public static async Task ReadAsync(SecretStore secrets, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(secrets);
+ var token = await secrets.RevealAsync(TokenSecret, cancellationToken).ConfigureAwait(false);
+ var chat = await secrets.RevealAsync(ChatSecret, cancellationToken).ConfigureAwait(false);
+ return string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(chat) ? null : new TelegramSettings(token.Trim(), chat.Trim());
+ }
+}
+
+/// What Impostazioni shows of the queue: the last message that left, what waits, what failed and why.
+public sealed record NotificationSummary(DateTimeOffset? LastSentAt, int Pending, int Retrying, int GaveUp, string? LastError);
+
+///
+/// The Telegram queue (SPEC 14). Every message is written first, then sent: a refusal or a network failure is
+/// recorded and tried again with growing pauses; a message that could not leave within a day is given up, with the
+/// reason, rather than arriving late as if it were news.
+///
+public sealed class NotificationSender(Database db, IClock clock, Func> settings, Func client)
+{
+ /// Older than this, a message is no longer worth sending.
+ public static readonly TimeSpan MaxAge = TimeSpan.FromHours(24);
+
+ public const int MaxAttempts = 8;
+
+ /// At most this many messages per pass: Telegram limits the messages to one chat.
+ public const int Batch = 20;
+
+ /// Writes a message in the queue, in the same transaction as what it tells.
+ public static Task EnqueueAsync(DbSession s, IClock clock, string kind, string message, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(s);
+ ArgumentNullException.ThrowIfNull(clock);
+ return s.ExecuteAsync(
+ "INSERT INTO notifications (id, channel, kind, message, status, attempts, created_at) VALUES (@id, 'telegram', @k, @m, @st, 0, @at)", cancellationToken,
+ ("id", Ids.NewId(clock)), ("k", kind), ("m", message), ("st", NotificationStates.Pending), ("at", clock.UtcNow));
+ }
+
+ /// The pause before attempt + 1: 1, 2, 4, 8, 16, 32, then 60 minutes.
+ public static TimeSpan Pause(int attempts) => TimeSpan.FromMinutes(Math.Min(60, 1 << Math.Clamp(attempts - 1, 0, 6)));
+
+ /// Sends what is due; the answer is how many left. Without Telegram configured everything stays in the queue.
+ public async Task SendDueAsync(CancellationToken cancellationToken)
+ {
+ if (await settings(cancellationToken).ConfigureAwait(false) is not { } telegram)
+ {
+ return 0;
+ }
+
+ var now = clock.UtcNow;
+ var due = await db.ReadAsync(s => s.QueryAsync(
+ "SELECT id, message, attempts, created_at FROM notifications WHERE channel = 'telegram' AND (status = @p OR (status = @f AND next_attempt_at IS NOT NULL AND next_attempt_at <= @now)) " +
+ "ORDER BY created_at, id LIMIT " + Batch.ToString(System.Globalization.CultureInfo.InvariantCulture),
+ r => (Id: r.Id("id"), Message: r.Text("message"), Attempts: r.IsNull("attempts") ? 0 : (int)r.Number("attempts"), Created: r.Moment("created_at")),
+ ("p", NotificationStates.Pending), ("f", NotificationStates.Failed), ("now", now)), cancellationToken).ConfigureAwait(false);
+ var bot = client(telegram.Token);
+ var sent = 0;
+ foreach (var item in due)
+ {
+ if (now - item.Created > MaxAge)
+ {
+ await MarkAsync(item.Id, NotificationStates.Failed, item.Attempts, null, "Non partito entro un giorno: non lo mando più.", cancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ try
+ {
+ await bot.SendAsync(telegram.ChatId, item.Message, cancellationToken).ConfigureAwait(false);
+ await MarkAsync(item.Id, NotificationStates.Sent, item.Attempts + 1, null, null, cancellationToken).ConfigureAwait(false);
+ sent++;
+ }
+ catch (TelegramException ex)
+ {
+ var attempts = item.Attempts + 1;
+ DateTimeOffset? next = ex.Retryable && attempts < MaxAttempts
+ ? clock.UtcNow + (ex.RetryAfter is { } wait && wait > Pause(attempts) ? wait : Pause(attempts))
+ : null;
+ await MarkAsync(item.Id, NotificationStates.Failed, attempts, next, ex.Message, cancellationToken).ConfigureAwait(false);
+ if (ex.Retryable)
+ {
+ // Telegram unreachable or asking to slow down: the others wait for the next pass.
+ break;
+ }
+ }
+ }
+
+ return sent;
+ }
+
+ public Task SummaryAsync(CancellationToken cancellationToken) =>
+ db.ReadAsync(async s =>
+ {
+ var last = await s.FirstOrDefaultAsync("SELECT MAX(sent_at) AS at FROM notifications WHERE channel = 'telegram' AND status = @s",
+ r => r.MomentOrNull("at"), ("s", NotificationStates.Sent)).ConfigureAwait(false);
+ var pending = await s.CountAsync("SELECT COUNT(*) FROM notifications WHERE channel = 'telegram' AND status = @p", ("p", NotificationStates.Pending)).ConfigureAwait(false);
+ var retrying = await s.CountAsync("SELECT COUNT(*) FROM notifications WHERE channel = 'telegram' AND status = @f AND next_attempt_at IS NOT NULL",
+ ("f", NotificationStates.Failed)).ConfigureAwait(false);
+ var gaveUp = await s.CountAsync("SELECT COUNT(*) FROM notifications WHERE channel = 'telegram' AND status = @f AND next_attempt_at IS NULL",
+ ("f", NotificationStates.Failed)).ConfigureAwait(false);
+ var error = await s.FirstOrDefaultAsync(
+ "SELECT last_error FROM notifications WHERE channel = 'telegram' AND status = @f ORDER BY created_at DESC, id DESC LIMIT 1",
+ r => r.TextOrNull("last_error"), ("f", NotificationStates.Failed)).ConfigureAwait(false);
+ return new NotificationSummary(last, (int)pending, (int)retrying, (int)gaveUp, error);
+ }, cancellationToken);
+
+ private Task MarkAsync(Guid id, string status, int attempts, DateTimeOffset? next, string? error, CancellationToken cancellationToken) =>
+ db.WriteAsync(s => s.ExecuteAsync(
+ "UPDATE notifications SET status = @s, attempts = @a, next_attempt_at = @n, last_error = @e, sent_at = @sent WHERE id = @id", cancellationToken,
+ ("s", status), ("a", attempts), ("n", next), ("e", error), ("sent", status == NotificationStates.Sent ? clock.UtcNow : (DateTimeOffset?)null), ("id", id)), cancellationToken);
+}
diff --git a/src/Anubis/Notifications/TelegramBot.cs b/src/Anubis/Notifications/TelegramBot.cs
new file mode 100644
index 0000000..8533aef
--- /dev/null
+++ b/src/Anubis/Notifications/TelegramBot.cs
@@ -0,0 +1,258 @@
+using Anubis.Core;
+using Microsoft.Extensions.Logging;
+
+namespace Anubis.Notifications;
+
+///
+/// What the Telegram commands read and do (SPEC 14), answered in plain Italian. Nothing here turns on real money,
+/// changes a limit or shows a secret: the interface does those, never the phone.
+///
+public interface ITelegramDesk
+{
+ Task StatusAsync(CancellationToken cancellationToken);
+
+ Task PositionsAsync(CancellationToken cancellationToken);
+
+ Task TodayAsync(CancellationToken cancellationToken);
+
+ Task PauseAsync(CancellationToken cancellationToken);
+
+ /// Only from a pause, never after "Ferma tutto" (SPEC 9.3, 14).
+ Task ResumeAsync(CancellationToken cancellationToken);
+
+ /// "Ferma tutto", already confirmed.
+ Task StopAllAsync(CancellationToken cancellationToken);
+}
+
+/// The commands of SPEC 14 and the confirmation of /ferma: two minutes to send /conferma.
+public sealed class TelegramCommands(ITelegramDesk desk, IClock clock)
+{
+ public static readonly TimeSpan ConfirmWithin = TimeSpan.FromMinutes(2);
+
+ public const string Help =
+ "Comandi:\n" +
+ "/stato – come sta il bot\n" +
+ "/posizioni – cosa ho in mano, con gli stop\n" +
+ "/oggi – cosa ho fatto oggi\n" +
+ "/pausa – niente nuovi acquisti, stop e uscite proseguono\n" +
+ "/riprendi – riparto dalla pausa\n" +
+ "/ferma – «Ferma tutto», con conferma\n" +
+ "/aiuto – questo elenco\n" +
+ "Soldi veri, limiti e chiavi si cambiano solo dall'interfaccia.";
+
+ private DateTimeOffset? _stopAskedAt;
+
+ /// The answer to one message; null for a message that is not a command.
+ public async Task AnswerAsync(string text, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(text);
+ var word = text.Trim().Split((char[])[' ', '\n', '\t'], 2)[0];
+ if (!word.StartsWith('/'))
+ {
+ return null;
+ }
+
+ // In a group Telegram adds the bot's name: "/stato@AnubisBot".
+ var command = word[1..].Split('@')[0].ToLowerInvariant();
+ if (command != "conferma")
+ {
+ _stopAskedAt = null;
+ }
+
+ switch (command)
+ {
+ case "start" or "aiuto" or "help":
+ return Help;
+ case "stato":
+ return await desk.StatusAsync(cancellationToken).ConfigureAwait(false);
+ case "posizioni":
+ return await desk.PositionsAsync(cancellationToken).ConfigureAwait(false);
+ case "oggi":
+ return await desk.TodayAsync(cancellationToken).ConfigureAwait(false);
+ case "pausa":
+ return await desk.PauseAsync(cancellationToken).ConfigureAwait(false);
+ case "riprendi":
+ return await desk.ResumeAsync(cancellationToken).ConfigureAwait(false);
+ case "ferma":
+ _stopAskedAt = clock.UtcNow;
+ return "Vuoi davvero «Ferma tutto»? Annullo gli ordini in attesa e non apro nuove posizioni; gli stop restano. " +
+ "Da qui non si riparte: si riparte solo dall'interfaccia, pagina Rischio.\nPer confermare scrivi /conferma entro 2 minuti.";
+ case "conferma":
+ if (_stopAskedAt is { } asked && clock.UtcNow - asked <= ConfirmWithin)
+ {
+ _stopAskedAt = null;
+ return await desk.StopAllAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ _stopAskedAt = null;
+ return "Non c'è niente da confermare: scrivi prima /ferma.";
+ default:
+ return "Non conosco questo comando.\n" + Help;
+ }
+ }
+}
+
+///
+/// Reads the messages sent to the bot and answers the commands (SPEC 14). Only the chat of the settings is obeyed;
+/// the others get no answer at all. A message older than five minutes, found after a stop of the bot, is not
+/// obeyed: a /pausa of yesterday must not pause today.
+///
+public sealed partial class TelegramBot(IClock clock, Func> settings, Func client,
+ TelegramCommands commands, ILogger logger)
+{
+ public static readonly TimeSpan StaleAfter = TimeSpan.FromMinutes(5);
+
+ /// How long one call waits for a message on Telegram's side.
+ public int WaitSeconds { get; init; } = 25;
+
+ /// The pause after a failure, or while Telegram is not configured.
+ public TimeSpan Retry { get; init; } = TimeSpan.FromSeconds(30);
+
+ private long _offset;
+
+ /// One read of the messages; the answer is how many commands were obeyed.
+ public async Task PollOnceAsync(CancellationToken cancellationToken)
+ {
+ if (await settings(cancellationToken).ConfigureAwait(false) is not { } telegram)
+ {
+ return -1;
+ }
+
+ var bot = client(telegram.Token);
+ var updates = await bot.GetUpdatesAsync(_offset, WaitSeconds, cancellationToken).ConfigureAwait(false);
+ var obeyed = 0;
+ foreach (var update in updates)
+ {
+ _offset = Math.Max(_offset, update.UpdateId + 1);
+ if (update.ChatId != telegram.ChatId)
+ {
+ LogStranger(logger, update.ChatId ?? "?");
+ continue;
+ }
+
+ if (update.Text is not { } text || update.Date is not { } date || clock.UtcNow - date > StaleAfter)
+ {
+ continue;
+ }
+
+ string? answer;
+ try
+ {
+ answer = await commands.AnswerAsync(text, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ LogCommandFailed(logger, ex);
+ answer = "Non ci sono riuscito: " + Redactor.Redact(ex.Message);
+ }
+
+ if (answer is not null)
+ {
+ obeyed++;
+ await bot.SendAsync(telegram.ChatId, answer, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ return obeyed;
+ }
+
+ /// The loop: reads, answers, and after a failure waits and tries again.
+ public async Task RunAsync(CancellationToken cancellationToken)
+ {
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ TimeSpan? pause = null;
+ try
+ {
+ if (await PollOnceAsync(cancellationToken).ConfigureAwait(false) < 0)
+ {
+ pause = Retry;
+ }
+ }
+ catch (TelegramException ex)
+ {
+ LogPollFailed(logger, ex.Message);
+ pause = ex.RetryAfter is { } after && after > Retry ? after : Retry;
+ }
+
+ if (pause is { } wait)
+ {
+ await Task.Delay(wait, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ }
+
+ [LoggerMessage(Level = LogLevel.Warning, Message = "Telegram message from another chat ignored: {Chat}")]
+ private static partial void LogStranger(ILogger logger, string chat);
+
+ [LoggerMessage(Level = LogLevel.Warning, Message = "Telegram read failed: {Error}")]
+ private static partial void LogPollFailed(ILogger logger, string error);
+
+ [LoggerMessage(Level = LogLevel.Error, Message = "Telegram command failed")]
+ private static partial void LogCommandFailed(ILogger logger, Exception ex);
+}
+
+///
+/// The sign of life (SPEC 14): a call to an outside checking service every minute. When the calls stop, that
+/// service warns the user: the only way to know the bot is off while it is off.
+///
+public sealed partial class Heartbeat(HttpClient http, IClock clock, Func> address, ILogger logger)
+{
+ public DateTimeOffset? LastOk { get; private set; }
+
+ public string? LastError { get; private set; }
+
+ /// True when the call went through; false when there is no address or it failed.
+ public async Task BeatAsync(CancellationToken cancellationToken)
+ {
+ if (await address(cancellationToken).ConfigureAwait(false) is not { } url)
+ {
+ return false;
+ }
+
+ try
+ {
+ using var response = await http.GetAsync(url, cancellationToken).ConfigureAwait(false);
+ if (response.IsSuccessStatusCode)
+ {
+ LastOk = clock.UtcNow;
+ LastError = null;
+ return true;
+ }
+
+ LastError = $"Il servizio ha risposto {(int)response.StatusCode}.";
+ }
+ catch (HttpRequestException ex)
+ {
+ LastError = "Il servizio non risponde: " + Redactor.Redact(ex.Message);
+ }
+ catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested)
+ {
+ LastError = "Il servizio non ha risposto in tempo.";
+ }
+
+ LogFailed(logger, LastError);
+ return false;
+ }
+
+ /// An address the interface accepts: https, or http only on this computer or the local network.
+ public static string? Check(string value)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ {
+ return null;
+ }
+
+ if (!Uri.TryCreate(value.Trim(), UriKind.Absolute, out var uri) || uri.Scheme is not ("https" or "http"))
+ {
+ return "Serve un indirizzo che inizi con https://.";
+ }
+
+ return uri.Scheme == "http" && !(uri.IsLoopback || uri.Host.EndsWith(".local", StringComparison.OrdinalIgnoreCase) || System.Net.IPAddress.TryParse(uri.Host, out _))
+ ? "Fuori dalla rete di casa serve https://."
+ : null;
+ }
+
+ [LoggerMessage(Level = LogLevel.Warning, Message = "Heartbeat failed: {Error}")]
+ private static partial void LogFailed(ILogger logger, string error);
+}
diff --git a/src/Anubis/Notifications/TelegramClient.cs b/src/Anubis/Notifications/TelegramClient.cs
index 469d859..5635b76 100644
--- a/src/Anubis/Notifications/TelegramClient.cs
+++ b/src/Anubis/Notifications/TelegramClient.cs
@@ -35,6 +35,9 @@ public sealed class TelegramException : Exception
public TimeSpan? RetryAfter { get; }
}
+/// A message to the bot: who wrote it (the chat), what and when.
+public sealed record TelegramUpdate(long UpdateId, string? ChatId, string? Text, DateTimeOffset? Date);
+
///
/// The Telegram Bot API (SPEC 14): plain text messages to the user's chat. The token is part of the address, so the
/// address is never logged; errors carry only Telegram's own description.
@@ -43,6 +46,8 @@ public sealed class TelegramClient
{
public static readonly Uri DefaultBase = new("https://api.telegram.org/");
+ private static readonly string[] MessagesOnly = ["message"];
+
private readonly HttpClient _http;
private readonly string _token;
private readonly Uri _base;
@@ -70,6 +75,40 @@ public sealed class TelegramClient
cancellationToken).ConfigureAwait(false);
}
+ ///
+ /// The messages sent to the bot after , waiting up to for
+ /// one (long polling). The next call passes the last update's id plus one, which tells Telegram they were read.
+ ///
+ public async Task> GetUpdatesAsync(long offset, int waitSeconds, CancellationToken cancellationToken)
+ {
+ using var answer = await CallAsync("getUpdates", new Dictionary { ["offset"] = offset, ["timeout"] = waitSeconds, ["allowed_updates"] = MessagesOnly },
+ cancellationToken).ConfigureAwait(false);
+ var updates = new List();
+ foreach (var item in answer.RootElement.GetProperty("result").EnumerateArray())
+ {
+ string? chat = null;
+ string? text = null;
+ DateTimeOffset? date = null;
+ if (item.TryGetProperty("message", out var message))
+ {
+ chat = message.TryGetProperty("chat", out var c) && c.TryGetProperty("id", out var id) ? id.GetRawText().Trim('"') : null;
+ text = message.TryGetProperty("text", out var t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null;
+ date = message.TryGetProperty("date", out var d) && d.TryGetInt64(out var seconds) ? DateTimeOffset.FromUnixTimeSeconds(seconds) : null;
+ }
+
+ updates.Add(new TelegramUpdate(item.GetProperty("update_id").GetInt64(), chat, text, date));
+ }
+
+ return updates;
+ }
+
+ /// The bot's own name: the test of Impostazioni, which proves the token works without writing to anyone.
+ public async Task GetMeAsync(CancellationToken cancellationToken)
+ {
+ using var answer = await CallAsync("getMe", new Dictionary(), cancellationToken).ConfigureAwait(false);
+ return answer.RootElement.GetProperty("result").TryGetProperty("username", out var name) ? name.GetString() ?? "" : "";
+ }
+
/// One call of the Bot API; the answer's result when Telegram says ok.
public async Task CallAsync(string method, object body, CancellationToken cancellationToken)
{
diff --git a/src/Anubis/Trading/Diary.cs b/src/Anubis/Trading/Diary.cs
index 39e9f7c..d812944 100644
--- a/src/Anubis/Trading/Diary.cs
+++ b/src/Anubis/Trading/Diary.cs
@@ -18,7 +18,7 @@ public static class DiaryKinds
///
/// The bot's diary and its notices (SPEC 13.6): short sentences in Italian, in the first person. A notice is also
-/// queued for Telegram; the sender arrives with Phase 6, the queue is kept from now.
+/// queued for Telegram (SPEC 14), in the same transaction.
///
public static class Diary
{
@@ -36,7 +36,6 @@ public static class Diary
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock);
await WriteAsync(s, clock, DiaryKinds.System, code, message, null, cancellationToken).ConfigureAwait(false);
- await s.ExecuteAsync("INSERT INTO notifications (id, channel, kind, message, status, created_at) VALUES (@id, 'telegram', @k, @m, 'pending', @at)", cancellationToken,
- ("id", Ids.NewId(clock)), ("k", code), ("m", message), ("at", clock.UtcNow)).ConfigureAwait(false);
+ await Notifications.NotificationSender.EnqueueAsync(s, clock, code, message, cancellationToken).ConfigureAwait(false);
}
}
diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs
index c8dbb5d..7e2412f 100644
--- a/src/Anubis/Trading/OrderManager.cs
+++ b/src/Anubis/Trading/OrderManager.cs
@@ -786,9 +786,12 @@ public sealed partial class OrderManager : IDisposable
}
var reason = fill.Side == OrderSide.Sell && row.Purpose is OrderPurpose.Stop or OrderPurpose.Protective ? ReasonCatalog.Text("stop") : null;
- await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill",
- DiaryText.Fill(fill.Side, fill.Quantity, instrument?.Symbol ?? "?", instrument?.IsCrypto ?? false, fill.Price, _account.Currency, reason, closed),
+ var text = DiaryText.Fill(fill.Side, fill.Quantity, instrument?.Symbol ?? "?", instrument?.IsCrypto ?? false, fill.Price, _account.Currency, reason, closed);
+ await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", text,
new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp, outcome.TradeId, Account = _account.Name }, cancellationToken).ConfigureAwait(false);
+
+ // Every purchase and sale reaches the phone, with the result when it closes a trade (SPEC 14).
+ await Notifications.NotificationSender.EnqueueAsync(s, _clock, "fill", _account.Name + ": " + text, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
if (row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null)
{
diff --git a/tests/Anubis.Tests/ServerHarness.cs b/tests/Anubis.Tests/ServerHarness.cs
index 065a83a..376366a 100644
--- a/tests/Anubis.Tests/ServerHarness.cs
+++ b/tests/Anubis.Tests/ServerHarness.cs
@@ -76,7 +76,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable
}
public static async Task StartAsync(string platform, IReadOnlyDictionary environment, string? dataDir = null,
- string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null, bool trading = false)
+ string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null, bool trading = false, HttpMessageHandler? telegramHttp = null)
{
var owns = dataDir is null;
dataDir ??= TempFolder.Create("server");
@@ -90,6 +90,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable
MarketHttp = marketHttp,
MarketSockets = marketHttp is null ? null : () => new FakeSocket(),
Trading = trading,
+ TelegramHttp = telegramHttp,
});
await app.StartAsync().ConfigureAwait(false);
var cookies = new CookieContainer();
diff --git a/tests/Anubis.Tests/TelegramTests.cs b/tests/Anubis.Tests/TelegramTests.cs
new file mode 100644
index 0000000..cb55257
--- /dev/null
+++ b/tests/Anubis.Tests/TelegramTests.cs
@@ -0,0 +1,363 @@
+using System.Collections.Concurrent;
+using System.Net;
+using System.Text;
+using System.Text.Json;
+using Anubis.Core;
+using Anubis.Notifications;
+using Anubis.Server;
+using Microsoft.Extensions.Logging.Abstractions;
+
+namespace Anubis.Tests;
+
+/// Telegram and the sign of life (issue #52, SPEC 14), against a fake Telegram server.
+[TestClass]
+public sealed class TelegramTests
+{
+ private const string Token = "123456:fake-token-for-tests_abcdefghijklmnop";
+ private const string Chat = "424242";
+ private static readonly CancellationToken _none = CancellationToken.None;
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public async Task EveryMessageHasItsStateAndAFailureIsTriedAgainLater()
+ {
+ await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
+ var telegram = new FakeTelegram();
+ TelegramSettings? configured = null;
+ using var http = new HttpClient(telegram);
+ var sender = new NotificationSender(rig.Db, rig.Clock, _ => Task.FromResult(configured), token => new TelegramClient(http, token));
+ await EnqueueAsync(rig, "uno", "due").ConfigureAwait(false);
+
+ // Without Telegram the messages wait in the queue: never "sent".
+ Assert.AreEqual(0, await sender.SendDueAsync(_none).ConfigureAwait(false));
+ Assert.AreEqual(new NotificationSummary(null, 2, 0, 0, null), await sender.SummaryAsync(_none).ConfigureAwait(false));
+
+ // Telegram slows us down: the first fails, the second waits for the next pass.
+ configured = new TelegramSettings(Token, Chat);
+ telegram.Refuse = "sendMessage";
+ telegram.RefusalStatus = HttpStatusCode.TooManyRequests;
+ Assert.AreEqual(0, await sender.SendDueAsync(_none).ConfigureAwait(false));
+ var states = await StatesAsync(rig).ConfigureAwait(false);
+ Assert.AreEqual("failed/1/Telegram ha risposto 429: Too Many Requests: retry after 90", states["uno"].Text);
+ Assert.AreEqual(rig.Clock.UtcNow.AddSeconds(90), states["uno"].Next, "Telegram's own wait, longer than the first pause of a minute.");
+ Assert.AreEqual("pending/0/", states["due"].Text);
+
+ // Back up: what is due leaves, the failed one when its time comes.
+ telegram.Refuse = null;
+ Assert.AreEqual(1, await sender.SendDueAsync(_none).ConfigureAwait(false));
+ rig.Clock.Advance(TimeSpan.FromSeconds(90));
+ Assert.AreEqual(1, await sender.SendDueAsync(_none).ConfigureAwait(false));
+ states = await StatesAsync(rig).ConfigureAwait(false);
+ Assert.AreEqual(("sent/2/", "sent/1/"), (states["uno"].Text, states["due"].Text));
+ Assert.AreEqual(2, telegram.Sent.Count(m => m.Chat == Chat));
+ Assert.AreEqual(new NotificationSummary(rig.Clock.UtcNow, 0, 0, 0, null), await sender.SummaryAsync(_none).ConfigureAwait(false));
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public async Task ARefusalIsNotTriedAgainAndAMessageOlderThanADayIsGivenUp()
+ {
+ await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
+ var telegram = new FakeTelegram { Refuse = "sendMessage", RefusalStatus = HttpStatusCode.BadRequest };
+ using var http = new HttpClient(telegram);
+ var sender = new NotificationSender(rig.Db, rig.Clock, _ => Task.FromResult(new TelegramSettings(Token, Chat)),
+ token => new TelegramClient(http, token));
+ await EnqueueAsync(rig, "rifiutato").ConfigureAwait(false);
+ await sender.SendDueAsync(_none).ConfigureAwait(false);
+ var states = await StatesAsync(rig).ConfigureAwait(false);
+ Assert.AreEqual("failed/1/Telegram ha risposto 400: Bad Request: chat not found", states["rifiutato"].Text);
+ Assert.IsNull(states["rifiutato"].Next, "A refusal is final: the same message would be refused again.");
+
+ telegram.Refuse = null;
+ await EnqueueAsync(rig, "vecchio").ConfigureAwait(false);
+ rig.Clock.Advance(TimeSpan.FromHours(25));
+ Assert.AreEqual(0, await sender.SendDueAsync(_none).ConfigureAwait(false));
+ states = await StatesAsync(rig).ConfigureAwait(false);
+ Assert.AreEqual("failed/0/Non partito entro un giorno: non lo mando più.", states["vecchio"].Text);
+ Assert.IsEmpty(telegram.Sent);
+ var summary = await sender.SummaryAsync(_none).ConfigureAwait(false);
+ Assert.AreEqual((0, 0, 2), (summary.Pending, summary.Retrying, summary.GaveUp));
+
+ // The pauses between attempts grow up to an hour.
+ Assert.AreEqual("1 2 4 8 16 32 60 60", string.Join(" ", Enumerable.Range(1, 8).Select(a => NotificationSender.Pause(a).TotalMinutes)));
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public async Task FermaWantsAConfirmationWithinTwoMinutes()
+ {
+ var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
+ var desk = new FakeDesk();
+ var commands = new TelegramCommands(desk, clock);
+
+ Assert.Contains("/conferma entro 2 minuti", (await commands.AnswerAsync("/ferma", _none).ConfigureAwait(false))!);
+ Assert.AreEqual(0, desk.Stops);
+ clock.Advance(TimeSpan.FromSeconds(100));
+ Assert.AreEqual("fermato", await commands.AnswerAsync("/conferma", _none).ConfigureAwait(false));
+ Assert.AreEqual(1, desk.Stops);
+
+ // Too late, or another command in between: nothing to confirm.
+ await commands.AnswerAsync("/ferma", _none).ConfigureAwait(false);
+ clock.Advance(TimeSpan.FromMinutes(3));
+ Assert.Contains("niente da confermare", (await commands.AnswerAsync("/conferma", _none).ConfigureAwait(false))!);
+ await commands.AnswerAsync("/ferma", _none).ConfigureAwait(false);
+ await commands.AnswerAsync("/stato", _none).ConfigureAwait(false);
+ Assert.Contains("niente da confermare", (await commands.AnswerAsync("/conferma", _none).ConfigureAwait(false))!);
+ Assert.AreEqual(1, desk.Stops);
+
+ // The other commands, the bot's name of a group, help, and plain text that is no command.
+ Assert.AreEqual("stato", await commands.AnswerAsync("/stato@AnubisBot", _none).ConfigureAwait(false));
+ Assert.AreEqual("posizioni", await commands.AnswerAsync("/POSIZIONI", _none).ConfigureAwait(false));
+ Assert.AreEqual("oggi", await commands.AnswerAsync(" /oggi grazie", _none).ConfigureAwait(false));
+ Assert.AreEqual("pausa", await commands.AnswerAsync("/pausa", _none).ConfigureAwait(false));
+ Assert.AreEqual("riprendi", await commands.AnswerAsync("/riprendi", _none).ConfigureAwait(false));
+ Assert.AreEqual(TelegramCommands.Help, await commands.AnswerAsync("/aiuto", _none).ConfigureAwait(false));
+ Assert.StartsWith("Non conosco questo comando.", (await commands.AnswerAsync("/compra BTC", _none).ConfigureAwait(false))!);
+ Assert.IsNull(await commands.AnswerAsync("ciao", _none).ConfigureAwait(false));
+ Assert.DoesNotContain("limiti", TelegramCommands.Help.Split('\n')[0]);
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public async Task OnlyTheChatOfTheSettingsIsObeyedAndOldMessagesAreNot()
+ {
+ var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
+ var telegram = new FakeTelegram();
+ using var http = new HttpClient(telegram);
+ var desk = new FakeDesk();
+ var bot = new TelegramBot(clock, _ => Task.FromResult(new TelegramSettings(Token, Chat)), token => new TelegramClient(http, token),
+ new TelegramCommands(desk, clock), NullLogger.Instance);
+
+ telegram.Write("999", "/pausa", clock.UtcNow);
+ telegram.Write(Chat, "/pausa", clock.UtcNow - TimeSpan.FromHours(20));
+ telegram.Write(Chat, "/stato", clock.UtcNow);
+ Assert.AreEqual(1, await bot.PollOnceAsync(_none).ConfigureAwait(false));
+ Assert.AreEqual((Chat, "stato"), telegram.Sent.Single());
+ Assert.AreEqual(0, desk.Pauses, "Neither the stranger's /pausa nor yesterday's.");
+
+ // The next read tells Telegram the first three were read.
+ Assert.AreEqual(0, await bot.PollOnceAsync(_none).ConfigureAwait(false));
+ Assert.AreEqual(4, telegram.LastOffset);
+
+ // Without Telegram configured the loop only waits.
+ var idle = new TelegramBot(clock, _ => Task.FromResult(null), token => new TelegramClient(http, token), new TelegramCommands(desk, clock),
+ NullLogger.Instance);
+ Assert.AreEqual(-1, await idle.PollOnceAsync(_none).ConfigureAwait(false));
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public async Task TheSignOfLifeCallsTheServiceAndSaysWhenItFails()
+ {
+ var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
+ var calls = 0;
+ var fake = new FakeHttp().On(u => u.Host == "hc.example", _ => FakeHttp.Respond("OK", ++calls == 2 ? HttpStatusCode.ServiceUnavailable : HttpStatusCode.OK));
+ using var http = fake.Client();
+ Uri? address = null;
+ var beat = new Heartbeat(http, clock, _ => Task.FromResult(address), NullLogger.Instance);
+ Assert.IsFalse(await beat.BeatAsync(_none).ConfigureAwait(false), "No address, no call.");
+ Assert.IsEmpty(fake.Requests);
+
+ address = new Uri("https://hc.example/ping/abc");
+ Assert.IsTrue(await beat.BeatAsync(_none).ConfigureAwait(false));
+ Assert.AreEqual(clock.UtcNow, beat.LastOk);
+ clock.Advance(TimeSpan.FromMinutes(1));
+ Assert.IsFalse(await beat.BeatAsync(_none).ConfigureAwait(false));
+ Assert.AreEqual(("Il servizio ha risposto 503.", clock.UtcNow - TimeSpan.FromMinutes(1)), (beat.LastError, beat.LastOk));
+
+ Assert.IsNull(Heartbeat.Check("https://hc-ping.com/uuid"));
+ Assert.IsNull(Heartbeat.Check("http://192.168.30.23:8000/ping/x"));
+ Assert.IsNotNull(Heartbeat.Check("http://hc-ping.com/uuid"));
+ Assert.IsNotNull(Heartbeat.Check("ftp://example.com"));
+ Assert.IsNotNull(Heartbeat.Check("non è un indirizzo"));
+ }
+
+ ///
+ /// The acceptance criterion of SPEC 14 with the real server: commands from the phone change the bot's state, the
+ /// changes reach the phone, a stranger is ignored, and after "Ferma tutto" the phone cannot restart the bot.
+ ///
+ [TestMethod]
+ [TestCategory(Category.Integration)]
+ public async Task TheCommandsWorkFromThePhoneThroughTheRealServer()
+ {
+ var telegram = new FakeTelegram();
+ var env = ServerHarness.DockerSqlite();
+ env["TELEGRAM_BOT_TOKEN"] = Token;
+ env["TELEGRAM_CHAT_ID"] = Chat;
+ await using var server = await ServerHarness.StartAsync("docker", env, telegramHttp: telegram).ConfigureAwait(false);
+ var services = server.Host.Services!;
+ async Task AskAsync(string text, string chat = Chat)
+ {
+ var before = telegram.Sent.Count;
+ telegram.Write(chat, text, DateTimeOffset.UtcNow);
+ var until = DateTimeOffset.UtcNow.AddSeconds(20);
+ while (DateTimeOffset.UtcNow < until)
+ {
+ if (telegram.Sent.Skip(before).FirstOrDefault(m => m.Chat == chat && !m.Text.Contains("(da Telegram)", StringComparison.Ordinal)) is { Text: { } answer })
+ {
+ return answer;
+ }
+
+ await Task.Delay(50).ConfigureAwait(false);
+ }
+
+ return "(nessuna risposta)";
+ }
+
+ async Task StateAsync() => (await services.Settings.GetAsync(SettingsStore.BotState.Key, _none).ConfigureAwait(false)).Value;
+
+ Assert.StartsWith("Bot attivo", await AskAsync("/stato").ConfigureAwait(false));
+ Assert.AreEqual("Nessuna posizione aperta.", await AskAsync("/posizioni").ConfigureAwait(false));
+ Assert.AreEqual("Nessun ordine oggi.", await AskAsync("/oggi").ConfigureAwait(false));
+
+ Assert.StartsWith("In pausa", await AskAsync("/pausa").ConfigureAwait(false));
+ Assert.AreEqual("paused", await StateAsync().ConfigureAwait(false));
+ await WaitForAsync(() => telegram.Sent.Any(m => m.Text.StartsWith("Bot in pausa (da Telegram)", StringComparison.Ordinal))).ConfigureAwait(false);
+
+ Assert.AreEqual("(nessuna risposta)", await AskAsync("/riprendi", "777").ConfigureAwait(false), "Another chat gets nothing.");
+ Assert.AreEqual("paused", await StateAsync().ConfigureAwait(false));
+ Assert.AreEqual("Ripartito dalla pausa.", await AskAsync("/riprendi").ConfigureAwait(false));
+ Assert.AreEqual("active", await StateAsync().ConfigureAwait(false));
+
+ Assert.Contains("/conferma", await AskAsync("/ferma").ConfigureAwait(false));
+ Assert.AreEqual("active", await StateAsync().ConfigureAwait(false));
+ Assert.StartsWith("«Ferma tutto» fatto", await AskAsync("/conferma").ConfigureAwait(false));
+ Assert.AreEqual("stopped", await StateAsync().ConfigureAwait(false));
+ Assert.Contains("riattivalo dalla pagina Rischio", await AskAsync("/riprendi").ConfigureAwait(false));
+ Assert.AreEqual("stopped", await StateAsync().ConfigureAwait(false));
+
+ // Every notice has its state, and the Impostazioni page shows the last message that left.
+ await WaitForAsync(() => telegram.Sent.Any(m => m.Text.StartsWith("«Ferma tutto» (da Telegram)", StringComparison.Ordinal))).ConfigureAwait(false);
+ var notices = await services.Db.ReadAsync(s => s.QueryAsync("SELECT kind, status FROM notifications", r => r.Text("kind") + "/" + r.Text("status")), _none)
+ .ConfigureAwait(false);
+ Assert.Contains("bot_paused/sent", notices);
+ Assert.Contains("bot_active/sent", notices);
+ Assert.IsFalse(telegram.Sent.Any(m => m.Text.Contains(Token, StringComparison.Ordinal)));
+ await server.SignInFirstTimeAsync().ConfigureAwait(false);
+ var page = await server.TextAsync("/impostazioni").ConfigureAwait(false);
+ Assert.Contains("Telegram e segnale di vita", page);
+ Assert.Contains("Token e chat arrivano dalle variabili", page);
+ Assert.DoesNotContain(Token, page);
+ }
+
+ private static async Task WaitForAsync(Func condition)
+ {
+ var until = DateTimeOffset.UtcNow.AddSeconds(20);
+ while (!condition())
+ {
+ Assert.IsLessThan(until, DateTimeOffset.UtcNow, "Timed out.");
+ await Task.Delay(50).ConfigureAwait(false);
+ }
+ }
+
+ private static Task EnqueueAsync(TradingRig rig, params string[] messages) =>
+ rig.Db.WriteAsync(async s =>
+ {
+ foreach (var message in messages)
+ {
+ await NotificationSender.EnqueueAsync(s, rig.Clock, "test", message, _none).ConfigureAwait(false);
+ rig.Clock.Advance(TimeSpan.FromMilliseconds(1));
+ }
+ }, _none);
+
+ private static async Task> StatesAsync(TradingRig rig) =>
+ (await rig.QueryAsync("SELECT message, status, attempts, last_error, next_attempt_at FROM notifications",
+ r => (Message: r.Text("message"), Text: r.Text("status") + "/" + r.Number("attempts") + "/" + r.TextOrNull("last_error"), Next: r.MomentOrNull("next_attempt_at")))
+ .ConfigureAwait(false)).ToDictionary(x => x.Message, x => (x.Text, x.Next));
+
+ private sealed class FakeDesk : ITelegramDesk
+ {
+ public int Stops { get; private set; }
+
+ public int Pauses { get; private set; }
+
+ public Task StatusAsync(CancellationToken cancellationToken) => Task.FromResult("stato");
+
+ public Task PositionsAsync(CancellationToken cancellationToken) => Task.FromResult("posizioni");
+
+ public Task TodayAsync(CancellationToken cancellationToken) => Task.FromResult("oggi");
+
+ public Task PauseAsync(CancellationToken cancellationToken)
+ {
+ Pauses++;
+ return Task.FromResult("pausa");
+ }
+
+ public Task ResumeAsync(CancellationToken cancellationToken) => Task.FromResult("riprendi");
+
+ public Task StopAllAsync(CancellationToken cancellationToken)
+ {
+ Stops++;
+ return Task.FromResult("fermato");
+ }
+ }
+}
+
+///
+/// A Telegram Bot API on the test's side: messages written by the test come back from getUpdates, sendMessage is
+/// recorded, and one method can be made to refuse. getUpdates answers at once (no long wait) after a short pause.
+///
+internal sealed class FakeTelegram : HttpMessageHandler
+{
+ private readonly ConcurrentQueue<(long Id, string Chat, string Text, DateTimeOffset Date)> _updates = new();
+ private long _nextId = 1;
+
+ public List<(string Chat, string Text)> Sent { get; } = [];
+
+ public long LastOffset { get; private set; }
+
+ /// The method that fails, with .
+ public string? Refuse { get; set; }
+
+ public HttpStatusCode RefusalStatus { get; set; } = HttpStatusCode.BadRequest;
+
+ public void Write(string chat, string text, DateTimeOffset at) => _updates.Enqueue((Interlocked.Increment(ref _nextId) - 1, chat, text, at));
+
+ protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ var method = request.RequestUri!.AbsolutePath.Split('/')[^1];
+ using var body = JsonDocument.Parse(request.Content is null ? "{}" : await request.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false));
+ if (method == Refuse)
+ {
+ return RefusalStatus == HttpStatusCode.TooManyRequests
+ ? Json(RefusalStatus, """{"ok":false,"error_code":429,"description":"Too Many Requests: retry after 90","parameters":{"retry_after":90}}""")
+ : Json(RefusalStatus, """{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}""");
+ }
+
+ switch (method)
+ {
+ case "getMe":
+ return Json(HttpStatusCode.OK, """{"ok":true,"result":{"id":1,"is_bot":true,"username":"AnubisProvaBot"}}""");
+ case "sendMessage":
+ lock (Sent)
+ {
+ Sent.Add((body.RootElement.GetProperty("chat_id").GetString()!, body.RootElement.GetProperty("text").GetString()!));
+ }
+
+ return Json(HttpStatusCode.OK, """{"ok":true,"result":{"message_id":1}}""");
+ case "getUpdates":
+ var offset = body.RootElement.TryGetProperty("offset", out var o) ? o.GetInt64() : 0;
+ LastOffset = offset;
+ while (_updates.TryPeek(out var first) && first.Id < offset)
+ {
+ _updates.TryDequeue(out _);
+ }
+
+ if (_updates.IsEmpty)
+ {
+ await Task.Delay(30, cancellationToken).ConfigureAwait(false);
+ }
+
+ var items = _updates.ToArray().Where(u => u.Id >= offset).Select(u => new
+ {
+ update_id = u.Id,
+ message = new { message_id = u.Id, date = u.Date.ToUnixTimeSeconds(), chat = new { id = long.Parse(u.Chat, System.Globalization.CultureInfo.InvariantCulture) }, text = u.Text },
+ });
+ return Json(HttpStatusCode.OK, JsonSerializer.Serialize(new { ok = true, result = items }));
+ default:
+ return Json(HttpStatusCode.NotFound, """{"ok":false,"description":"Not Found"}""");
+ }
+ }
+
+ private static HttpResponseMessage Json(HttpStatusCode status, string json) => new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
+}