signal-bot/signal_bot/stats/commands.py
Krzysztof kuhy Rudnicki f535aab1eb
Some checks are pending
CI / check (push) Waiting to run
release: 0.1.1 «Pius I» — commands that explain themselves
Two things the group hit within minutes of 0.1.0, both reported by real
users rather than found by a test.

Somebody typed !korona, got "Za mało danych — wróć za kilka dni." and
nothing else. That answer tells them neither what the command does nor
what it will eventually show, which makes it worse than useless on a
release day when almost every command is empty by design. Every command
now leads with what it is, and the empty answer says what it will show
once there is history and which date it is counting from.

And somebody asked whether "Najczęściej piszesz o 12:00" meant the whole
hour 12-13. It did, and the label did not say so. It now reads "między
12:00 a 13:00". Same fix in kind for the nightly summary line, which
said "średnio 47 znaków" without saying per what -- now "na wiadomość".

A one-line wording fix takes the next pope exactly like a feature does,
per DOCS-changelog.md. Exercised in testbot at the unbumped version
first: !korona, !ja, !dni and !rekordy all ran clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 20:09:14 +02:00

219 lines
7.5 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The `!` commands that read the statistics.
None of them takes an argument. ``registry.resolve`` matches the whole folded
message body against a trigger, so `!ja mithra` resolves to nothing; teaching
it to split on whitespace would silently make `!kot pls` fire where today it
does nothing, which is a behaviour change with its own blast radius. Each
question gets its own trigger instead.
`!wczoraj` renders through exactly the same path as the nightly post. That is
not a convenience: the bot cannot trigger its own 21:37 report on demand, so
without a command that produces byte-identical text there would be no way to
check the headline output of this release short of waiting for the evening.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from signal_bot.animals import load_aliases
from signal_bot.stats import curiosities, periods, records, streaks
from signal_bot.stats.backfill import backfilled_day
from signal_bot.stats.facts import gather
from signal_bot.stats.highlights import SLOTS, select
from signal_bot.stats.queries_day import day_rows, day_totals, with_silent
from signal_bot.stats.queries_period import (
Trend,
every_day,
period_rows,
total_for,
weekday_buckets,
)
from signal_bot.stats.render_day import DayView, render_day
from signal_bot.stats.render_extra import (
ME_TITLE,
favourite_hour,
render_crown,
render_me,
render_records,
render_weekdays,
)
from signal_bot.stats.render_period import render_period
if TYPE_CHECKING:
from signal_bot.decorators import Decorator
from signal_bot.registry import CommandContext, CommandRegistry
from signal_bot.stats.periods import Period
def _day_block(ctx: CommandContext, day: str, heading: str | None = None) -> str:
"""Render one day exactly as the nightly report does."""
store = ctx.store
rows = with_silent(
day_rows(store.events, ctx.group_id, day),
[(p.uuid, p.display_name) for p in store.events.people(ctx.group_id)],
)
if not any(not row.is_silent for row in rows):
return "Nikt jeszcze nic nie napisał tego dnia."
backfilled = backfilled_day(store, ctx.group_id)
facts = gather(store.events, ctx.group_id, day, rows, exclude=backfilled)
picks = select(curiosities.for_day(facts), SLOTS)
return render_day(
day,
rows,
day_totals(rows),
DayView(
since=store.events.first_day(ctx.group_id),
approximate=backfilled == day,
highlights=tuple(pick.text for pick in picks),
heading=heading,
),
)
def _period_block(ctx: CommandContext, period: Period, *, podium: bool = False) -> str:
"""Render one period against the one before it."""
store = ctx.store
before = periods.previous(period)
trend = Trend(
now=total_for(store.events, ctx.group_id, period.start, period.end),
before=total_for(store.events, ctx.group_id, before.start, before.end),
)
return render_period(
period,
period_rows(store.events, ctx.group_id, period),
trend,
since=store.events.first_day(ctx.group_id),
podium=podium,
)
async def today(ctx: CommandContext) -> None:
"""`!staty` -- the day so far."""
await ctx.reply(_day_block(ctx, periods.today(), heading="Dziś, na razie:"))
async def yesterday(ctx: CommandContext) -> None:
"""`!wczoraj` -- byte-identical to what the nightly post said."""
await ctx.reply(_day_block(ctx, periods.previous_day()))
async def week(ctx: CommandContext) -> None:
"""`!tydzień` -- this week against last week."""
await ctx.reply(_period_block(ctx, periods.week_of(periods.today())))
async def month(ctx: CommandContext) -> None:
"""`!miesiąc` -- this month, with a podium."""
await ctx.reply(_period_block(ctx, periods.month_of(periods.today()), podium=True))
async def year(ctx: CommandContext) -> None:
"""`!rok` -- this year against last year."""
await ctx.reply(_period_block(ctx, periods.year_of(periods.today())))
async def all_records(ctx: CommandContext) -> None:
"""`!rekordy` -- every all-time record the group has set."""
store = ctx.store
exclude = backfilled_day(store, ctx.group_id)
history = every_day(store.events, ctx.group_id, exclude=exclude)
personal = []
for person in store.events.people(ctx.group_id):
best = records.personal_best(store.events, ctx.group_id, person.uuid, exclude=exclude)
if best is not None:
personal.append((person.display_name, best))
personal.sort(key=lambda pair: (-pair[1].value, pair[0]))
await ctx.reply(
render_records(
history,
records.most_media_day(store.events, ctx.group_id, exclude=exclude),
records.longest_silence(history, periods.today()) if history else None,
personal,
store.events.first_day(ctx.group_id),
)
)
async def crown(ctx: CommandContext) -> None:
"""`!korona` -- who holds it, who held it longest, who has held it most."""
store = ctx.store
winners = streaks.daily_winners(
store.events, ctx.group_id, exclude=backfilled_day(store, ctx.group_id)
)
await ctx.reply(
render_crown(
winners,
store.events.people(ctx.group_id),
store.events.first_day(ctx.group_id),
)
)
async def weekdays(ctx: CommandContext) -> None:
"""`!dni` -- the Monday-to-Sunday picture."""
store = ctx.store
history = every_day(store.events, ctx.group_id, exclude=backfilled_day(store, ctx.group_id))
await ctx.reply(
render_weekdays(
weekday_buckets(history),
periods.weekday_of(periods.today()),
store.events.first_day(ctx.group_id),
)
)
async def me(ctx: CommandContext) -> None:
"""`!ja` -- the asker's own numbers."""
store = ctx.store
uuid = ctx.message.source_uuid
exclude = backfilled_day(store, ctx.group_id)
everyone = period_rows(
store.events,
ctx.group_id,
periods.Period("all", "0000-01-01", "9999-12-31", "wszystko"),
)
mine = next((row for row in everyone if row.uuid == uuid), None)
if mine is None:
await ctx.reply(f"{ME_TITLE}\n\nNie mam jeszcze od ciebie ani jednej wiadomości.")
return
total = sum(row.messages for row in everyone)
winners = streaks.daily_winners(store.events, ctx.group_id, exclude=exclude)
running = [s for s in streaks.current_streaks(winners) if s.uuid == uuid]
await ctx.reply(
render_me(
mine.display_name,
mine.messages,
records.personal_best(store.events, ctx.group_id, uuid, exclude=exclude),
round(mine.messages / total * 100) if total else 0,
favourite_hour(store.events, ctx.group_id, uuid),
running[0].length if running else 0,
)
)
HANDLERS = {
"stats_today": today,
"stats_yesterday": yesterday,
"stats_week": week,
"stats_month": month,
"stats_year": year,
"stats_records": all_records,
"stats_crown": crown,
"stats_weekdays": weekdays,
"stats_me": me,
}
def register_stats_commands(
registry: CommandRegistry,
*,
decorate: Decorator | None = None,
aliases: dict[str, list[str]] | None = None,
) -> None:
"""Register every statistics command under its triggers from aliases.json."""
table = load_aliases() if aliases is None else aliases
for name, handler in HANDLERS.items():
registry.register(name, table[name], decorate(handler) if decorate else handler)