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:
Alby96andClaude Opus 5.5 committed 2026-11-11 19:53:55 +01:00
1 parent d00dfbd32f
commit 84c540786c
16 files changed
+1416 -17

No files matched your search

+176
View File
@@ -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;
}
}