Send Telegram notices, answer phone commands and call the heartbeat (refs #52)
Every notice is written to the queue in the same transaction as what it tells, then sent every ten seconds. Each has a state: pending, sent, or failed with its error. Network failures and 429s are retried with growing pauses (Telegram's own wait when it gives one). Refusals are final. A notice that could not leave within a day is given up instead of arriving late. Every fill now also reaches the phone, and so do pause, resume and restart. Commands are read by long polling and obeyed only from the configured chat and only when fresh, so yesterday's /pausa never pauses today. They are /stato, /posizioni, /oggi, /pausa, /riprendi, /ferma (confirmed with /conferma within two minutes) and /aiuto. Restarting after "Ferma tutto", real money, limits and keys stay in the interface. Also added: - the heartbeat call every minute when an address is configured; - the morning summary at 08:00, caught up within four hours; - an optional hourly or evening status; - a Telegram section in Impostazioni: test-before-save, a test button, the queue's state and the last successful heartbeat; - on desktop, the first-run page recommends the heartbeat. Tests run against a fake Telegram server, including the commands through the real server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d00dfbd32f
commit
84c540786c
16 files changed
+1416
-17
No files matched your search
@@ -39,7 +39,7 @@ internal sealed record HostChanged(HostMode Mode);
|
||||
|
||||
/// <summary>Everything that needs the database, built once it is reachable and the installation checks out.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// 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;
|
||||
|
||||
/// <summary>The running services; null until the first successful start.</summary>
|
||||
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<string, DateTimeOffset>(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<JobRun>();
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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.",
|
||||
})</p>
|
||||
@@ -33,7 +38,7 @@
|
||||
}
|
||||
|
||||
<nav class="tabs" aria-label="Sezioni delle impostazioni">
|
||||
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#dati">Dati</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#telegram">Telegram</a><a href="#dati">Dati</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||
</nav>
|
||||
|
||||
<section class="panel" id="aspetto">
|
||||
@@ -186,6 +191,93 @@
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="panel" id="telegram">
|
||||
<h2>Telegram e segnale di vita</h2>
|
||||
<p class="hint">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.</p>
|
||||
<dl class="facts">
|
||||
<dt>Token del bot</dt><dd>@KeyState(_telegramToken)</dd>
|
||||
<dt>Chat</dt><dd>@KeyState(_telegramChat)</dd>
|
||||
<dt>Ultimo messaggio partito</dt><dd>@(_queue?.LastSentAt is { } sent ? Format.ShortDate(sent, Shell.Now, Shell.Zone) : "Nessuno")</dd>
|
||||
@if (_queue is { } q && (q.Pending > 0 || q.Retrying > 0 || q.GaveUp > 0))
|
||||
{
|
||||
<dt>In attesa</dt><dd>@q.Pending in coda@(q.Retrying > 0 ? $", {q.Retrying} da ritentare" : "")@(q.GaveUp > 0 ? $", {q.GaveUp} non partiti" : "")</dd>
|
||||
}
|
||||
@if (_queue?.LastError is { } lastError)
|
||||
{
|
||||
<dt>Ultimo errore</dt><dd class="loss">@lastError</dd>
|
||||
}
|
||||
</dl>
|
||||
@if (Shell.IsDemo)
|
||||
{
|
||||
<p class="hint">Nella modalità dimostrativa Telegram non si usa.</p>
|
||||
}
|
||||
else if (_telegramToken.FromEnvironment || _telegramChat.FromEnvironment)
|
||||
{
|
||||
<p class="hint">Token e chat arrivano dalle variabili d'ambiente: si cambiano nella configurazione del container.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form method="post" action="/azioni/telegram" class="form" autocomplete="off">
|
||||
<AntiforgeryToken />
|
||||
<label for="tg-token">Token del bot (da @@BotFather)</label>
|
||||
<input id="tg-token" name="token" type="password" autocomplete="off" spellcheck="false" maxlength="200" required />
|
||||
<label for="tg-chat">Numero della chat</label>
|
||||
<input id="tg-chat" name="chat" inputmode="numeric" autocomplete="off" spellcheck="false" maxlength="40" required />
|
||||
<button class="btn" type="submit">Prova e salva</button>
|
||||
</form>
|
||||
<p class="hint">Prima di salvarli mando un messaggio di prova: se non parte, non salvo nulla. Il token non lo rimostro mai.</p>
|
||||
}
|
||||
@if (!Shell.IsDemo && _telegramToken.IsSet && _telegramChat.IsSet)
|
||||
{
|
||||
<form method="post" action="/azioni/telegram/prova" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit">Manda un messaggio di prova</button></form>
|
||||
@if (!_telegramToken.FromEnvironment && !_telegramChat.FromEnvironment)
|
||||
{
|
||||
<form method="post" action="/azioni/telegram/togli" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit" data-confirm="Tolgo token e chat? Non ti scrivo più su Telegram finché non li rimetti.">Togli Telegram</button></form>
|
||||
}
|
||||
}
|
||||
|
||||
<h3>Stato periodico</h3>
|
||||
<form method="post" action="/azioni/impostazioni/@SettingsStore.TelegramStatus.Key" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="/impostazioni#telegram" />
|
||||
<label for="tg-status">@SettingsStore.TelegramStatus.Label</label>
|
||||
<select id="tg-status" name="valore" disabled="@(_telegramStatus.ReadOnly || Shell.IsDemo)" data-autosubmit>
|
||||
@foreach (var value in SettingsStore.TelegramStatus.Allowed!)
|
||||
{
|
||||
<option value="@value" selected="@(value == _telegramStatus.Value)">@(value switch { "hourly" => "Ogni ora", "daily" => "Ogni sera alle 20:00", _ => "Mai" })</option>
|
||||
}
|
||||
</select>
|
||||
<button class="btn btn-small" type="submit">Salva</button>
|
||||
</form>
|
||||
|
||||
<h3>Segnale di vita</h3>
|
||||
<p class="hint">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.</p>
|
||||
<dl class="facts">
|
||||
<dt>Indirizzo</dt><dd>@(Host.Services!.Telegram?.ConfiguredHeartbeat is not null ? "Dalla configurazione d'avvio (ANUBIS_HEARTBEAT_URL)" : KeyState(_heartbeat))</dd>
|
||||
@if (Host.Services.Telegram is { } tg)
|
||||
{
|
||||
<dt>Ultima chiamata riuscita</dt><dd>@(tg.Heartbeat.LastOk is { } beat ? Format.ShortDate(beat, Shell.Now, Shell.Zone) : "Nessuna da quando il bot è partito")</dd>
|
||||
@if (tg.Heartbeat.LastError is { } beatError)
|
||||
{
|
||||
<dt>Ultimo errore</dt><dd class="loss">@beatError</dd>
|
||||
}
|
||||
}
|
||||
</dl>
|
||||
@if (!Shell.IsDemo && Host.Services.Telegram is { ConfiguredHeartbeat: null })
|
||||
{
|
||||
<form method="post" action="/azioni/segnale-di-vita" class="form-inline" autocomplete="off">
|
||||
<AntiforgeryToken />
|
||||
<label for="hb-url">Indirizzo</label>
|
||||
<input id="hb-url" name="indirizzo" type="url" autocomplete="off" spellcheck="false" maxlength="500" placeholder="https://hc-ping.com/…" required />
|
||||
<button class="btn btn-small" type="submit">Prova e salva</button>
|
||||
</form>
|
||||
@if (_heartbeat.IsSet)
|
||||
{
|
||||
<form method="post" action="/azioni/segnale-di-vita/togli" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit">Togli il segnale di vita</button></form>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="panel" id="dati">
|
||||
|
||||
<h2>Dati</h2>
|
||||
@@ -365,6 +457,11 @@
|
||||
private List<SettingChange> _history = [];
|
||||
private IReadOnlyList<BackupInfo> _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),
|
||||
|
||||
@@ -12,7 +12,11 @@
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>Due passi: dove tenere i dati e la password per entrare. Conti, capitale e Telegram si aggiungono dopo, dalle Impostazioni.</p>
|
||||
<p>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.</p>
|
||||
@if (Host.Config.Platform == Anubis.Platform.PlatformKind.Desktop)
|
||||
{
|
||||
<p class="hint">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.</p>
|
||||
}
|
||||
@if (Message is { } message)
|
||||
{
|
||||
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
|
||||
|
||||
@@ -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).
|
||||
/// </summary>
|
||||
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)
|
||||
|
||||
+107
-2
@@ -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<IResult> 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<IResult> 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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The bot's Telegram (SPEC 14): a test message first, sent at once; token and chat are saved only when it left.
|
||||
/// </summary>
|
||||
private static async Task<IResult> 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<IResult> 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<IResult> 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");
|
||||
}
|
||||
|
||||
/// <summary>The address of the checking service (SPEC 14): called once as a test, saved encrypted only when it answered.</summary>
|
||||
private static async Task<IResult> 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<Uri?>(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<IResult> 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<IResult> RemoveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
const string back = "/impostazioni";
|
||||
|
||||
@@ -76,6 +76,9 @@ internal sealed record ServerOverrides
|
||||
|
||||
public Func<Anubis.Brokers.IWebSocketTransport>? MarketSockets { get; init; }
|
||||
|
||||
/// <summary>Answers the Telegram calls and the sign of life instead of the network; tests without it have no Telegram.</summary>
|
||||
public HttpMessageHandler? TelegramHttp { get; init; }
|
||||
|
||||
/// <summary>True starts the accounts and the order managers in a test; off by default in tests.</summary>
|
||||
public bool? Trading { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
using System.Text;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Notifications;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<string> 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<string> 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<string> 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<string> PauseAsync(CancellationToken cancellationToken) =>
|
||||
CommandAsync("pausa", "In pausa: niente nuovi acquisti; stop e uscite proseguono. /riprendi per ripartire.", cancellationToken);
|
||||
|
||||
public Task<string> ResumeAsync(CancellationToken cancellationToken) => CommandAsync("riprendi", "Ripartito dalla pausa.", cancellationToken);
|
||||
|
||||
public Task<string> 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);
|
||||
|
||||
/// <summary>The morning summary (SPEC 14): the night, the positions, what comes today.</summary>
|
||||
public async Task<string> 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<string> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Notifications;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class TelegramServices : IDisposable
|
||||
{
|
||||
/// <summary>The secret that keeps the address of the checking service when the configuration does not give one.</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>The address from the startup configuration (ANUBIS_HEARTBEAT_URL): it wins over the one saved here.</summary>
|
||||
public string? ConfiguredHeartbeat { get; }
|
||||
|
||||
/// <summary>How often the queue is looked at.</summary>
|
||||
public TimeSpan SendEvery { get; init; } = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>The client of Telegram and of the checking service.</summary>
|
||||
public HttpClient Http => _http;
|
||||
|
||||
public TelegramClient Client(string token) => new(_http, token);
|
||||
|
||||
public Task<TelegramSettings?> ReadAsync(CancellationToken cancellationToken) => TelegramSettings.ReadAsync(_secrets, cancellationToken);
|
||||
|
||||
public async Task<Uri?> 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<ScheduledJob> 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)),
|
||||
];
|
||||
|
||||
/// <summary>Sends the queue and reads the commands until the services stop.</summary>
|
||||
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)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public async Task<string?> 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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user