signal-bot/signal_bot/stats/render_day.py
Krzysztof kuhy Rudnicki 46db2e7753 feat: the message event log, and the nightly report built on it
The tally was one integer per person, deleted after each post. Nothing
dated survived it, so weeks, months, records, streaks and weekday
averages were all unanswerable. This replaces it with an append-only
per-message log holding metadata only -- never a message body -- and
rebuilds the nightly report on top.

What changes for the group: a photo posted without a caption now counts
(it was worth zero), stickers count, the bot's own messages no longer
do, people who said nothing appear with a 0, and the report covers the
previous full calendar day in Europe/Warsaw instead of "since the last
post" -- which used to merge two days whenever a group went quiet.

Notable decisions, each with the trap it avoids:

- Events and people are PERMANENT_TABLES: neither forget_group nor a
  future SCHEMA_VERSION bump may drop them. Both paths used to cost a
  day's counter and would now cost the entire history, and forget_group
  fires on a listing that merely omits members.
- is_own comes from which envelope branch carried the payload, not from
  comparing identities. The account is spelled as a uuid on some frames
  and a +E.164 number on others, so any comparison misses one of them.
- The roster is stashed in refresh(), not _adopt(), which returns early
  once the watched set stops changing -- i.e. always, in the steady
  state.
- The roster matches on uuid OR number because /v1/groups spells kuhy as
  +48516501330 while his messages carry an ACI uuid. Joining on uuid
  alone would have listed him twice every night, once with 0.
- Members whose display name we have never seen are counted, not named:
  their only spellings are a uuid or a phone number.
- (group, uuid, sent_at_ms) is the primary key, so a websocket
  redelivery after a reconnect cannot inflate the counts.
- Days come from a stored Warsaw date string, never a timestamp range:
  2026-03-29 is 23 hours long and 2026-10-25 is 25.
- Polish number agreement is a real rule with a 12-14 exception, so
  "44 znaki" and "45 znaków" are both spelled correctly.

config.py and startup.py were two lines under the 250-line cap and both
had to grow, so config_env and startup_retry come out of them first, as
pure moves.

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

103 lines
3.9 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Rendering one day as the block the group reads.
Plain text, because that is all Signal renders. No markdown, and no column
padding: Signal uses a proportional font, so ``ljust`` lines up in a terminal
and on nobody's phone. A separator that does not depend on glyph widths is the
only spelling that looks the same in both places.
The block is capped at MAX_LINES so the nightly post stays something people
read rather than scroll past. When it has to give something up it gives up
speakers, never the highlight -- a leaderboard with the interesting part cut
off is worse than a shorter leaderboard.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Final
from signal_bot.stats import text
from signal_bot.stats.periods import pl_date, pl_day_month
if TYPE_CHECKING:
from signal_bot.stats.queries_day import DayRow, DayTotals
MAX_LINES: Final = 12
CROWN: Final = "\U0001f451"
CAMERA: Final = "\U0001f4f7"
CHART: Final = "\U0001f4ca"
def _media(count: int) -> str:
"""The camera marker, outside any padded column so it cannot misalign."""
return f" ({count} {CAMERA})" if count else ""
def person_line(row: DayRow, place: int) -> str:
"""One person's line: a crown for first place, otherwise a rank."""
lead = CROWN if place == 1 else f"{place}."
return f"{lead} {row.display_name} — {row.messages}{_media(row.media)}"
def silence_line(rows: list[DayRow], unnamed: int) -> str:
"""Everyone who said nothing, in one line, or "" when everybody spoke.
``unnamed`` are group members who have never written here at all. They are
counted rather than named on purpose: the listing knows them only as a raw
uuid or a phone number, and printing either into a group chat is a leak.
"""
names = [row.display_name for row in rows if row.is_silent]
if unnamed:
names.append(f"i {text.people(unnamed)} bez ani jednej wiadomości tutaj")
return "Cisza: " + ", ".join(names) if names else ""
def summary_line(totals: DayTotals) -> str:
"""Commands and average length -- the two facts that qualify the count."""
if not totals.messages:
return ""
parts = [f"średnio {text.characters(totals.average_length)}"]
if totals.commands:
parts.insert(0, f"z tego {text.commands(totals.commands)}")
return parts[0].capitalize() + (f", {parts[1]}." if len(parts) > 1 else ".")
def render_day(
day: str,
rows: list[DayRow],
totals: DayTotals,
*,
since: str | None = None,
unnamed: int = 0,
highlights: list[str] | None = None,
heading: str | None = None,
) -> str:
"""Compose the day block, trimmed to MAX_LINES."""
header = (
heading
or f"{CHART} {pl_date(day)} — {text.messages(totals.messages)}{_media(totals.media)}"
)
tail = [line for line in (silence_line(rows, unnamed), summary_line(totals)) if line]
picks = highlights or []
if since:
tail.append(f"(liczymy od {pl_day_month(since)})")
# Everything except the speakers is mandatory, and at least one highlight
# slot is reserved before any speaker is allowed a line.
reserved = len(tail) + min(len(picks), 1)
spoke = [row for row in rows if not row.is_silent]
# At least one, so the truncation line below always has a line to occupy.
# The tail cannot realistically reach eleven lines, but a floor here is
# cheaper than a defensive branch nothing can ever exercise.
room = max(1, MAX_LINES - 1 - reserved)
people = [person_line(row, i + 1) for i, row in enumerate(spoke[:room])]
if room < len(spoke):
hidden = spoke[room - 1 :]
total = sum(r.messages for r in hidden)
people[-1] = f"…i {text.people(len(hidden))} więcej (razem {text.messages(total)})"
lines = [header, *people]
lines.extend(picks[: max(0, MAX_LINES - len(lines) - len(tail))])
lines.extend(tail)
return "\n".join(lines)