Compare commits

...

4 Commits

Author SHA1 Message Date
a167b72fc1 feat: nine commands for asking the statistics questions
Some checks are pending
CI / check (push) Waiting to run
!staty, !wczoraj, !tydzień, !miesiąc, !rok, !rekordy, !korona, !dni and
!ja, under 29 triggers with both Polish spellings of each.

None takes an argument. registry.resolve matches the whole folded 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. Each question gets its own trigger instead.

!wczoraj renders through the same code path as the nightly post, which
is not a convenience: the bot cannot trigger its own 21:37 report, so
without byte-identical output there is no way to check the headline
feature of this release short of waiting for the evening.

Two guards worth naming:

- test_every_trigger_is_unique builds the whole registry.
  DuplicateTriggerError subclasses ValueError, and ValueError is in
  startup_retry.RETRYABLE -- so a colliding alias would not crash the
  bot, it would retry forever logging "signal-cli not reachable yet".
  Checked at test time instead of never.
- No trigger may contain a digit: fold() maps 0134578 onto letters, so
  "!7dni" would resolve as "!tdni". Also asserted.

Every command answers on an empty history rather than crashing, which is
the state the group will actually be in for the next few days: records,
the crown and the weekday table all say "za mało danych" because their
only day so far is the backfilled one, and they exclude it.

Verified against a copy of the live database -- all nine render
correctly on the real group's data.

One test bug caught while writing it: it seeded "today" and excluded
2026-08-30, which on the day it was written were the same date, so it
passed for the wrong reason. Fixed dates now.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 19:49:41 +02:00
d21b823aa2 feat: the nightly post notices things
Around twenty things could be said about a day. Saying all of them is a
wall nobody reads; saying whichever three are computed first is
arbitrary. So each candidate declares a priority and a magnitude and the
picker takes the top few, with two rules that make the result readable:
one line per family, so "set a record", "had 60% of the day" and "kept
the crown" do not become three sentences about the same person; and
fully deterministic ordering, so a day renders identically twice.

Nine candidates so far: personal records with what they beat, the
group's busiest day ever, a photo record, crown streaks (naming everyone
when it is shared), a silence broken, a monologue, one person dominating
the day, an unusual showing for that weekday, and a night owl.

Every candidate is (DayFacts) -> Highlight | None with the same
signature. On day one of this release almost all of them return None,
and a shape where "not yet" is the ordinary case is much easier to get
right than one where every guard is bespoke.

Two off-by-ones fixed by writing the sentence out and checking it:

- "odezwał się po 3 dniach ciszy" was counting four. The day somebody
  last spoke is not silent, and neither is the day they came back on, so
  the gap excludes both ends. The function is now named for that.
- A personal record on somebody's first ever day was being announced as
  a record. It is, trivially, and saying so every time is noise.

Verified against the live database, read-only on a copy: the real group
renders correctly at 324 messages, claims no average length for the
backfilled day, and fires no highlights at all -- which is right, since
there is one day of history for them to stand against.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 19:43:55 +02:00
0ada9c5056 feat: periods, records and the crown
The queries the statistics are made of, all derived rather than cached --
two sources of truth for one number is how a leaderboard comes to
disagree with itself, and this history is small enough that recomputing
is free.

Periods take an inclusive span of stored Warsaw day strings, never a
range of timestamps, so a daylight-saving change cannot move a boundary.
Trend reports None rather than 0 when there is no previous period:
"nothing to compare against yet" and "no change" are different
statements and the group will read them differently.

A tie shares the crown and keeps every tied run alive, per kuhy's call.
Streaks count *recorded* days, so a day nobody spoke does not end a run
-- there was no crown to lose -- and neither does a day the bot was
offline for, which it could not have judged.

Every record excludes the backfilled day. It is a 22-hour window filed
as a day, and leaving it in would hand somebody a personal best they
never set.

Two bugs found by running the code rather than reading it:

- current_streaks reported every streak as zero. Ending somebody's run
  dropped them from the tally along with the length they had already
  accumulated, so the surviving dict was empty by the time it returned.
  Now the run ends and the count it reached is kept.
- daily_winners depended on SQLite's grouping order to find a day's
  leader. It happened to work because uuids sorted conveniently in the
  fixtures. Ordering by messages DESC makes the first row per day the
  leader by construction, which is both correct and obviously so.

No suppressions: the period queries compare an exclusion parameter
against '' instead of pasting half a WHERE clause into an f-string,
which is a SQL-injection shape even when every input is a constant.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 19:38:54 +02:00
faeb756cdd feat: block binaries from a public repo, and write down the real attachment frame
Two halves of the same ask: the message database is private and must
stay that way.

The database was already gitignored, and the event table is pinned by a
test that asserts its exact column set so no message body can be quietly
added. What was missing was any defence against a binary reaching this
*public* repo at all -- and the proof it was missing was sitting in the
tree: three `bottles/**/indexeddb.sqlite` files, committed in "register
the bot as its own Signal account". Their contents turned out to be
harmless (one row, 120 bytes, a userPreferences store from
developer.android.com), but the path into history was real.

So the shared gate from ~/utils is wired in, the three files are
untracked, and .gitignore now blocks *.sqlite3 along with its -wal and
-shm companions rather than only the one filename.

The second half is the attachment envelope, captured from the live API
rather than assumed -- which is what 0.0.3 taught. A caption-less PNG
posted in the real group confirmed `attachments[].contentType`, and
settled something that was not guessable: a photo with no caption sends
`message: null`. That is exactly the frame `should_count` used to value
at zero.

Verified end to end on production data, not a fixture: the frame at
19:31:16 was recorded as media_kind=image, media_count=1, char_len=0,
filed under 2026-08-30 hour 19.

The doc also records the fields nothing reads yet, and one open question
left deliberately open: `caption` is a field on the attachment and was
null here, so whether a captioned photo puts its text in `message` or in
`attachments[].caption` has not been observed. If it is the latter,
char_len is recording 0 for those. DEBUG stays on until a `caption: str`
settles it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 19:32:41 +02:00
25 changed files with 2480 additions and 9 deletions

9
.gitignore vendored
View File

@ -166,3 +166,12 @@ cython_debug/
*.jpg
*.gif
nohup.out
# The message database is private and never leaves this machine. A live
# SQLite database is three files, so all three are named.
*.sqlite3
*.sqlite3-wal
*.sqlite3-shm
# Wine/Bottles scratch dir, never part of the bot.
bottles/

View File

@ -45,6 +45,16 @@ repos:
language: pygrep
types: [python]
# This repository is public and holds a private message database. The
# database is gitignored, but three binary SQLite files reached the
# history anyway before this gate existed, so .gitignore is evidently
# not the whole defence. Exceptions go in .binary-allowlist.
- id: no-binaries
name: no binary or image files
entry: scripts/check_no_binaries.sh
language: script
pass_filenames: true
# The shared 250-line cap. Checks only the files in the commit, so an
# unrelated commit never breaks. No baseline, no allowlist -- those are
# suppressions. The exemption list lives with the checker in ~/utils so

View File

@ -28,6 +28,52 @@ Reference for the two JSON frames `signal-cli-rest-api` pushes down
}
```
## A message with an attachment
Captured from the live API on 2026-08-30 with `LOG_LEVEL=DEBUG`, which makes
the dispatcher log each frame's shape (keys and types, never values -- see
`signal_bot/envelope_shape.py`). This is a caption-less PNG posted in the real
group, reproduced exactly as the logger described it:
```
{account: str, envelope: {
dataMessage: {
attachments: [{caption: null, contentType: 'image/png', filename: null,
height: int, id: str, size: int, uploadTimestamp: int,
width: int} x1],
expiresInSeconds: int,
groupInfo: {groupId: str, groupName: str, revision: int, type: 'DELIVER'},
isExpirationUpdate: bool,
message: null,
timestamp: int,
viewOnce: bool},
serverDeliveredTimestamp: int, serverReceivedTimestamp: int,
source: str, sourceDevice: int, sourceName: str,
sourceNumber: str, sourceUuid: str, timestamp: int}}
```
Three things this settles, none of which were guessable:
- `attachments` is a list of objects and the type lives in `contentType`. That
is what `models._attachments` reads and what `counting.media_kind` maps.
- **A caption-less photo sends `message: null`**, not `""` and not an absent
key. Before 0.1.0 `should_count` ended in `bool(message.text)`, so every one
of these was silently worth nothing.
- Read them off the *resolved* payload from `_payload()`, never off
`envelope["dataMessage"]` -- see "The trap this caused" below.
Fields nothing reads yet, recorded so the next person does not have to capture
them again: `expiresInSeconds`, `isExpirationUpdate`, `viewOnce`,
`groupInfo.groupName`, `groupInfo.revision`, and the attachment's `caption`,
`filename`, `width`, `height`, `size` and `uploadTimestamp`.
**Open question, deliberately not assumed.** `caption` is a field on the
attachment, and it was `null` here because this photo had none. Whether a
photo *with* a caption puts the text in `message` or in `attachments[].caption`
has not been observed yet. `char_len` currently measures `message` only, so if
it turns out to be the latter, captioned photos are recording a length of 0.
Leave `LOG_LEVEL=DEBUG` on and watch for `caption: str` to settle it.
## Somebody changed the membership: `groupInfo.type` is `UPDATE`
The only frame that names *who* added the bot to a group, which is what

26
scripts/check_no_binaries.sh Executable file
View File

@ -0,0 +1,26 @@
#!/bin/bash
# ============================================================================
# Thin delegate to the shared gate in ~/utils.
#
# Copying the logic here is what lets one repo's idea of the rule drift from
# every other repo's, so this script only locates the shared checker and
# forwards its arguments.
# ============================================================================
set -euo pipefail
readonly SHARED_GATE="${UTILS_ROOT:-$HOME/utils}/scripts/check_no_binaries.sh"
main() {
if [[ ! -x "$SHARED_GATE" ]]; then
echo "Error: shared gate not found at $SHARED_GATE" >&2
echo " Clone github.com/kuhyx/utils to ~/utils, or set" >&2
echo " UTILS_ROOT to where it lives." >&2
exit 1
fi
exec bash "$SHARED_GATE" "$@"
}
main "$@"

View File

@ -1,18 +1,87 @@
{
"_comment": "Command trigger words, including the styled Unicode variants people actually type. These live as data, not source, because they are data: adding an alias should never mean touching Python.",
"cat": [
"!kot", "!koty", "!kots", "!cat", "!cats", "!meow", "!miau",
"!ᴋᴏᴛ", "!𝓴𝓸𝓽", "!𝗸𝗼𝘁"
"!kot",
"!koty",
"!kots",
"!cat",
"!cats",
"!meow",
"!miau",
"!ᴋᴏᴛ",
"!𝓴𝓸𝓽",
"!𝗸𝗼𝘁"
],
"dog": [
"!pies", "!psy", "!dog", "!dogs", "!woof", "!szczek",
"!𝗽𝗶𝗲𝘀", "!͓̽p͓̽i͓̽e͓̽s͓̽"
"!pies",
"!psy",
"!dog",
"!dogs",
"!woof",
"!szczek",
"!𝗽𝗶𝗲𝘀",
"!͓̽p͓̽i͓̽e͓̽s͓̽"
],
"gecko": [
"!gekon", "!gekony", "!geko", "!gecko", "!geckon", "!geckos"
"!gekon",
"!gekony",
"!geko",
"!gecko",
"!geckon",
"!geckos"
],
"pope": [
"!papież", "!papiez", "!papieze", "!papieża", "!papa",
"!pope", "!popes", "!pontifex", "!𝗽𝗮𝗽𝗶𝗲𝘇"
"!papież",
"!papiez",
"!papieze",
"!papieża",
"!papa",
"!pope",
"!popes",
"!pontifex",
"!𝗽𝗮𝗽𝗶𝗲𝘇"
],
"stats_today": [
"!staty",
"!statystyki",
"!stats",
"!dziś",
"!dzis"
],
"stats_yesterday": [
"!wczoraj",
"!yesterday"
],
"stats_week": [
"!tydzień",
"!tydzien",
"!week"
],
"stats_month": [
"!miesiąc",
"!miesiac",
"!month"
],
"stats_year": [
"!rok",
"!year"
],
"stats_records": [
"!rekordy",
"!rekord",
"!records"
],
"stats_crown": [
"!korona",
"!crown"
],
"stats_weekdays": [
"!dni",
"!days"
],
"stats_me": [
"!ja",
"!moje",
"!mnie"
]
}

View File

@ -23,8 +23,11 @@ from signal_bot.http_client import ImageFetcher
from signal_bot.popes_command import register_pope_command
from signal_bot.portraits import PortraitCache
from signal_bot.registry import CommandRegistry
from signal_bot.stats import periods
from signal_bot.stats import curiosities, periods
from signal_bot.stats.backfill import backfilled_day
from signal_bot.stats.commands import register_stats_commands
from signal_bot.stats.facts import gather
from signal_bot.stats.highlights import SLOTS, select
from signal_bot.stats.nightly import days_to_report, mark_reported
from signal_bot.stats.queries_day import day_rows, day_totals, with_silent
from signal_bot.stats.render_day import DayView, render_day
@ -104,13 +107,17 @@ class Bot:
return True
named = self.store.events.roster(group_id, self.directory.member_identities(group_id))
with_zeros = with_silent(rows, [(p.uuid, p.display_name) for p in named])
backfilled = backfilled_day(self.store, group_id)
facts = gather(self.store.events, group_id, day, with_zeros, exclude=backfilled)
picks = select(curiosities.for_day(facts), SLOTS)
text = render_day(
day,
with_zeros,
day_totals(with_zeros),
DayView(
since=self.store.events.first_day(group_id),
approximate=backfilled_day(self.store, group_id) == day,
approximate=backfilled == day,
highlights=tuple(pick.text for pick in picks),
),
)
try:
@ -165,6 +172,7 @@ def build_bot(
PortraitCache(fetcher, config.commons_api_url),
decorate=rate_limit,
)
register_stats_commands(registry, decorate=rate_limit)
dispatcher = Dispatcher(
config=config,
directory=directory,

View File

@ -0,0 +1,204 @@
# 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 (
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,
)
)
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)))
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())))
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("Nie 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)

View File

@ -0,0 +1,231 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The things the bot might notice about a day.
Every candidate has the same signature -- ``(DayFacts) -> Highlight | None`` --
and returns None when it has nothing to say or not enough history to say it.
That uniformity is deliberate: on day one of this release almost all of them
return None, and a shape that makes "not yet" the ordinary case is far easier
to get right than one where each guard is bespoke.
Priorities are set so a record beats a trend, and anything about a person
beats anything about an average.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Final
from signal_bot.stats import facts as day_facts
from signal_bot.stats import records, streaks, text
from signal_bot.stats.highlights import (
CROWN,
RECORD,
TIMING,
TREND,
VOICE,
Highlight,
ratio,
)
from signal_bot.stats.periods import WEEKDAY_PLURAL, pl_day_month
if TYPE_CHECKING:
from signal_bot.stats.facts import DayFacts
TROPHY: Final = "\U0001f3c6"
CROWN_EMOJI: Final = "\U0001f451"
CALENDAR: Final = "\U0001f4c5"
CAMERA: Final = "\U0001f4f7"
OWL: Final = "\U0001f989"
SPEAKER: Final = "\U0001f4e2"
# How different from the usual a day has to be before it is worth a line.
WEEKDAY_THRESHOLD: Final = 0.25
DOMINANT_SHARE: Final = 50
MIN_BASELINE_DAYS: Final = 3
LONG_SILENCE: Final = 3
NIGHT_OWL_HOUR: Final = 2
# A record, a streak or a monologue is only interesting once there is
# something for it to stand against -- one day is not a history.
MIN_DAYS_FOR_A_RECORD: Final = 2
MIN_PHOTOS_FOR_A_RECORD: Final = 2
MIN_STREAK: Final = 2
MIN_MESSAGES_FOR_A_MONOLOGUE: Final = 2
MIN_SPEAKERS_FOR_A_SHARE: Final = 2
def personal_record(facts: DayFacts) -> Highlight | None:
"""Somebody beat their own best day ever."""
for row in facts.speakers:
best = day_facts.personal_record(facts, row.uuid)
if best is None:
continue
previous = records.previous_best(
facts.events, facts.group_id, row.uuid, facts.day, exclude=facts.exclude
)
if previous is None:
continue
beaten = f" (poprzedni {previous.value}, {pl_day_month(previous.day)})"
return Highlight(
kind="personal_record",
family=RECORD,
priority=100,
magnitude=ratio(best.value, previous.value),
text=f"{TROPHY} {row.display_name} {best.value} — rekord życiowy{beaten}",
)
return None
def group_record_day(facts: DayFacts) -> Highlight | None:
"""The group's busiest day ever, and it is today."""
busiest = records.busiest_day(facts.history)
if busiest is None or busiest.day != facts.day or len(facts.history) < MIN_DAYS_FOR_A_RECORD:
return None
others = [n for d, n in facts.history.items() if d != facts.day]
return Highlight(
kind="group_record_day",
family=RECORD,
priority=95,
magnitude=ratio(busiest.value, max(others)),
text=f"{TROPHY} najgadatliwszy dzień w historii: {text.messages(busiest.value)}",
)
def media_record(facts: DayFacts) -> Highlight | None:
"""The most photos the group has ever posted in a day."""
record = records.most_media_day(facts.events, facts.group_id, exclude=facts.exclude)
if record is None or record.day != facts.day or record.value < MIN_PHOTOS_FOR_A_RECORD:
return None
return Highlight(
kind="media_record",
family=RECORD,
priority=90,
magnitude=float(record.value),
text=f"{CAMERA} rekord zdjęć: {record.value} w jeden dzień",
)
def crown_streak(facts: DayFacts) -> Highlight | None:
"""Somebody has held the crown several days running."""
running = [s for s in streaks.current_streaks(facts.winners) if s.last_day == facts.day]
if not running or running[0].length < MIN_STREAK:
return None
best = running[0]
longest = streaks.longest_ever(facts.winners)
record = " — rekord!" if longest and longest.length == best.length else ""
names = " i ".join(s.display_name for s in running if s.length == best.length)
return Highlight(
kind="crown_streak",
family=CROWN,
priority=80,
magnitude=float(best.length),
text=f"{CROWN_EMOJI} {names} z koroną {text.days(best.length)} z rzędu{record}",
)
def silence_broken(facts: DayFacts) -> Highlight | None:
"""Somebody spoke after several days of saying nothing."""
for row in facts.speakers:
theirs = facts.person_days(row.uuid)
before = {d: n for d, n in theirs.items() if d < facts.day}
gap = records.days_silent_before(facts.history, before, facts.day)
if gap >= LONG_SILENCE:
return Highlight(
kind="silence_broken",
family=VOICE,
priority=75,
magnitude=float(gap),
text=f"{SPEAKER} {row.display_name} odezwał się po {text.days(gap)} ciszy",
)
return None
def only_one_spoke(facts: DayFacts) -> Highlight | None:
"""A monologue: exactly one person wrote all day."""
if len(facts.speakers) != 1 or facts.totals.messages < MIN_MESSAGES_FOR_A_MONOLOGUE:
return None
return Highlight(
kind="only_one_spoke",
family=VOICE,
priority=65,
magnitude=float(facts.totals.messages),
text=f"{SPEAKER} cały dzień mówił tylko {facts.speakers[0].display_name}",
)
def dominant_share(facts: DayFacts) -> Highlight | None:
"""One person accounted for most of the day on their own."""
if len(facts.speakers) < MIN_SPEAKERS_FOR_A_SHARE or not facts.totals.messages:
return None
top = facts.speakers[0]
share = round(top.messages / facts.totals.messages * 100)
if share < DOMINANT_SHARE:
return None
return Highlight(
kind="dominant_share",
family=VOICE,
priority=60,
magnitude=share / 100,
text=f"{SPEAKER} {top.display_name} to {share}% dzisiejszych wiadomości",
)
def weekday_average(facts: DayFacts) -> Highlight | None:
"""Today stands well away from what this weekday usually looks like."""
others = facts.same_weekday_before
if len(others) < MIN_BASELINE_DAYS:
return None
mean = sum(others) / len(others)
difference = ratio(facts.totals.messages, mean)
if difference < WEEKDAY_THRESHOLD:
return None
direction = "więcej" if facts.totals.messages > mean else "mniej"
return Highlight(
kind="weekday_average",
family=TREND,
priority=50,
magnitude=difference,
text=(
f"{CALENDAR} {WEEKDAY_PLURAL[facts.weekday]} mają średnio "
f"{round(mean)} — dziś o {round(difference * 100)}% {direction}"
),
)
def night_owl(facts: DayFacts) -> Highlight | None:
"""Somebody was still writing in the small hours."""
row = facts.events.connection.execute(
"""
SELECT display_name, local_hour
FROM message_events
WHERE group_id = ? AND day = ? AND local_hour BETWEEN ? AND ?
ORDER BY local_hour DESC, sent_at_ms DESC LIMIT 1
""",
(facts.group_id, facts.day, 0, NIGHT_OWL_HOUR),
).fetchone()
if row is None:
return None
return Highlight(
kind="night_owl",
family=TIMING,
priority=55,
magnitude=float(NIGHT_OWL_HOUR - row["local_hour"] + 1),
text=f"{OWL} {row['display_name']} pisał o {row['local_hour']:02d}:00",
)
ALL = (
personal_record,
group_record_day,
media_record,
crown_streak,
silence_broken,
only_one_spoke,
dominant_share,
weekday_average,
night_owl,
)
def for_day(facts: DayFacts) -> list[Highlight | None]:
"""Run every candidate against a day."""
return [candidate(facts) for candidate in ALL]

107
signal_bot/stats/facts.py Normal file
View File

@ -0,0 +1,107 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Everything known about one day, gathered once.
The candidates in ``curiosities`` each need some slice of the same handful of
queries. Gathering them once and passing this around keeps the night's work to
a fixed number of queries however many candidates are added later, and gives
every candidate the same uniform signature -- which is what makes the "not
enough history yet" guards mechanical to write and to test.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from signal_bot.stats import records, streaks
from signal_bot.stats.periods import weekday_of
from signal_bot.stats.queries_day import DayTotals, day_totals
from signal_bot.stats.queries_period import every_day, weekday_buckets
if TYPE_CHECKING:
from signal_bot.stats.events import EventStore
from signal_bot.stats.queries_day import DayRow
@dataclass(frozen=True, slots=True)
class DayFacts:
"""One day, plus the history it has to be interesting against."""
day: str
rows: list[DayRow]
totals: DayTotals
# Messages per recorded day across the whole history, the backfilled day
# already removed. Missing days are silences, not zeros.
history: dict[str, int]
winners: dict[str, list[tuple[str, str]]]
events: EventStore
group_id: str
exclude: str | None
@property
def leaders(self) -> list[tuple[str, str]]:
"""Whoever holds today's crown, as (uuid, display name). Ties included."""
return self.winners.get(self.day, [])
@property
def speakers(self) -> list[DayRow]:
"""Everyone who actually wrote today, most talkative first."""
return [row for row in self.rows if not row.is_silent]
@property
def weekday(self) -> int:
"""0 for Monday through 6 for Sunday."""
return weekday_of(self.day)
@property
def same_weekday_before(self) -> list[int]:
"""Every earlier day that fell on the same weekday.
Today is excluded, so "wtorki mają średnio 74" is a claim about the
other Tuesdays rather than one that quietly includes the day it is
being compared against.
"""
buckets = weekday_buckets({d: n for d, n in self.history.items() if d < self.day})
return buckets.get(self.weekday, [])
def person_days(self, uuid: str) -> dict[str, int]:
"""One person's messages per day, across the whole history."""
rows = self.events.connection.execute(
"""
SELECT day, COUNT(*) AS messages
FROM message_events
WHERE group_id = ? AND uuid = ? AND day <> ?
GROUP BY day
""",
(self.group_id, uuid, self.exclude or ""),
).fetchall()
return {r["day"]: r["messages"] for r in rows}
def gather(
events: EventStore,
group_id: str,
day: str,
rows: list[DayRow],
*,
exclude: str | None = None,
) -> DayFacts:
"""Run the shared queries once and bundle them up."""
return DayFacts(
day=day,
rows=rows,
totals=day_totals(rows),
history=every_day(events, group_id, exclude=exclude),
winners=streaks.daily_winners(events, group_id, exclude=exclude),
events=events,
group_id=group_id,
exclude=exclude,
)
def personal_record(facts: DayFacts, uuid: str) -> records.DayRecord | None:
"""Today's count, if it is that person's best ever, else None."""
best = records.personal_best(facts.events, facts.group_id, uuid, exclude=facts.exclude)
if best is None or best.day != facts.day:
return None
return best

View File

@ -0,0 +1,86 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Choosing the two or three things worth saying about a day.
There are around twenty things the bot could say every night. Saying all of
them is a wall of text nobody reads, and saying whichever three happen to be
computed first is arbitrary. So every candidate declares a priority and a
magnitude, and the picker takes the top few.
Two rules make the result readable rather than merely short:
* **One per family.** "Mithra set a personal record", "Mithra had 60% of the
day" and "Mithra kept the crown" are three sentences about the same thing.
Families collapse them to the strongest.
* **Fully deterministic.** No clock, no randomness, and ties break on the
candidate's own name, so the same day always produces the same post. A
nightly report that reshuffles itself between two renders reads as a bug.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Final
if TYPE_CHECKING:
from collections.abc import Sequence
# Families. Anything in the same one is a restatement of the same fact.
RECORD: Final = "record"
CROWN: Final = "crown"
TREND: Final = "trend"
TIMING: Final = "timing"
VOICE: Final = "voice"
# How many highlight lines a day block has room for. Lives here rather than
# beside either caller, so the nightly post and !wczoraj cannot drift apart.
SLOTS: Final = 3
@dataclass(frozen=True, slots=True)
class Highlight:
"""One thing worth saying, and how much it wants saying."""
kind: str
family: str
priority: int
magnitude: float
text: str
def select(candidates: Sequence[Highlight | None], slots: int) -> list[Highlight]:
"""Pick at most ``slots`` highlights, strongest first, one per family.
Args:
candidates: Every candidate, with None for the ones that did not
fire. Callers pass the whole list rather than filtering, so a
candidate that never fires is still visible in the code.
slots: How many lines the renderer has room for.
Returns:
The chosen highlights, most important first.
"""
fired = sorted(
(candidate for candidate in candidates if candidate is not None),
key=lambda c: (-c.priority, -c.magnitude, c.kind),
)
chosen: list[Highlight] = []
seen: set[str] = set()
for candidate in fired:
if candidate.family in seen:
continue
seen.add(candidate.family)
chosen.append(candidate)
if len(chosen) == slots:
break
return chosen
def ratio(value: float, baseline: float) -> float:
"""How far a value stands from its baseline, as a comparable fraction.
Used as ``magnitude`` so that "double the usual Tuesday" and "three times
the usual message length" can be ranked against each other at all. The
baseline is floored at one so a first-ever measurement does not divide by
zero and does not come out infinitely interesting.
"""
return abs(value - baseline) / max(baseline, 1)

View File

@ -0,0 +1,173 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Weeks, months, years, and the per-weekday picture.
Every query takes an inclusive span of stored Warsaw day strings, so a
daylight-saving change cannot move a boundary -- see ``stats.periods``.
Several of them take ``exclude``: the one day carried over from the pre-0.1.0
counter has real totals but no hours, no lengths, and a 22-hour window
pretending to be a day. It belongs in a total and nowhere near an average.
The exclusion is a bound parameter compared against ``''`` rather than a
clause pasted into the statement. No real day is the empty string, so one
static query serves both cases -- and the alternative, an f-string holding
half a WHERE clause, is a SQL-injection shape even when every input is a
module constant.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from signal_bot.stats.periods import weekday_of
from signal_bot.stats.queries_day import DayRow
if TYPE_CHECKING:
from signal_bot.stats.events import EventStore
from signal_bot.stats.periods import Period
PERIOD_ROWS = """
SELECT uuid,
display_name,
COUNT(*) AS messages,
SUM(media_count) AS media,
SUM(is_command) AS commands,
SUM(char_len) AS chars
FROM message_events
WHERE group_id = ? AND day BETWEEN ? AND ? AND day <> ?
GROUP BY uuid
ORDER BY messages DESC, display_name ASC
"""
DAILY_SERIES = """
SELECT day, COUNT(*) AS messages
FROM message_events
WHERE group_id = ? AND day BETWEEN ? AND ? AND day <> ?
GROUP BY day
ORDER BY day
"""
EVERY_DAY = """
SELECT day, COUNT(*) AS messages
FROM message_events
WHERE group_id = ? AND day <> ?
GROUP BY day
ORDER BY day
"""
def period_rows(
events: EventStore,
group_id: str,
period: Period,
*,
exclude: str | None = None,
) -> list[DayRow]:
"""Everyone who wrote during a period, most talkative first."""
rows = events.connection.execute(
PERIOD_ROWS, (group_id, period.start, period.end, exclude or "")
).fetchall()
return [
DayRow(
uuid=r["uuid"],
display_name=r["display_name"],
messages=r["messages"],
media=r["media"],
commands=r["commands"],
chars=r["chars"],
)
for r in rows
]
def daily_series(
events: EventStore,
group_id: str,
start: str,
end: str,
*,
exclude: str | None = None,
) -> dict[str, int]:
"""Messages per day across a span, missing days absent rather than zero.
The caller decides what a missing day means: for a streak it is silence,
for an average it is a day nobody was there to record.
"""
rows = events.connection.execute(DAILY_SERIES, (group_id, start, end, exclude or "")).fetchall()
return {r["day"]: r["messages"] for r in rows}
def every_day(
events: EventStore,
group_id: str,
*,
exclude: str | None = None,
) -> dict[str, int]:
"""Messages per day across the whole history."""
rows = events.connection.execute(EVERY_DAY, (group_id, exclude or "")).fetchall()
return {r["day"]: r["messages"] for r in rows}
def weekday_buckets(days: dict[str, int]) -> dict[int, list[int]]:
"""Bucket a day series by weekday, 0=Monday through 6=Sunday.
Returns the days themselves rather than a mean, so a caller can see how
many a figure rests on: "wtorki mają średnio 74" off a single Tuesday is a
number that should not be said out loud.
"""
buckets: dict[int, list[int]] = {}
for day, messages in days.items():
buckets.setdefault(weekday_of(day), []).append(messages)
return buckets
def total_for(
events: EventStore,
group_id: str,
start: str,
end: str,
*,
exclude: str | None = None,
) -> int:
"""How many messages a span holds."""
return sum(daily_series(events, group_id, start, end, exclude=exclude).values())
@dataclass(frozen=True, slots=True)
class Trend:
"""One period measured against the one before it."""
now: int
before: int
@property
def delta(self) -> int:
"""Absolute change, which may be negative."""
return self.now - self.before
@property
def percent(self) -> int | None:
"""Rounded percentage change, or None when there is no baseline.
None rather than 0: "nothing to compare against yet" is a different
statement from "no change", and the renderers say each differently.
"""
if not self.before:
return None
return round(self.delta / self.before * 100)
@property
def arrow(self) -> str:
"""An arrow, or "" when there is nothing to compare against."""
if self.percent is None or self.delta == 0:
return ""
return "↑" if self.delta > 0 else "↓"
def share_of_voice(rows: list[DayRow]) -> list[tuple[str, int]]:
"""Each person's percentage of the messages, largest first."""
total = sum(row.messages for row in rows)
if not total:
return []
return [(row.display_name, round(row.messages / total * 100)) for row in rows]

180
signal_bot/stats/records.py Normal file
View File

@ -0,0 +1,180 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""All-time records: busiest days, quietest days, personal bests, silences.
Everything here is derived by query rather than kept in a cache table. Two
sources of truth for one number is how a leaderboard comes to disagree with
itself, and the history is small enough that recomputing is free.
The backfilled day is excluded from every record. It is a 22-hour window
filed as a day, so leaving it in would hand somebody a personal best they
never set -- see ``stats.backfill``.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from signal_bot.stats.periods import shift
if TYPE_CHECKING:
from signal_bot.stats.events import EventStore
PERSON_DAYS = """
SELECT day, COUNT(*) AS messages
FROM message_events
WHERE group_id = ? AND uuid = ? AND day <> ?
GROUP BY day
ORDER BY messages DESC, day ASC
"""
MEDIA_DAYS = """
SELECT day, SUM(media_count) AS media
FROM message_events
WHERE group_id = ? AND day <> ?
GROUP BY day
HAVING media > 0
ORDER BY media DESC, day ASC
"""
@dataclass(frozen=True, slots=True)
class DayRecord:
"""One day and the number that makes it a record."""
day: str
value: int
def busiest_day(days: dict[str, int]) -> DayRecord | None:
"""The day with the most messages, earliest day winning a tie."""
if not days:
return None
day = min(days, key=lambda d: (-days[d], d))
return DayRecord(day, days[day])
def quietest_day(days: dict[str, int]) -> DayRecord | None:
"""The quietest day on which anybody spoke at all.
Days with no messages are absent from the series rather than zero, and
that is the right reading: a day nobody spoke is a silence, which
``longest_silence`` measures. A "quietest day" of zero would just name
whichever day the bot happened to be offline.
"""
if not days:
return None
day = min(days, key=lambda d: (days[d], d))
return DayRecord(day, days[day])
def personal_best(
events: EventStore,
group_id: str,
uuid: str,
*,
exclude: str | None = None,
) -> DayRecord | None:
"""Somebody's busiest day ever, or None if they have never written."""
row = events.connection.execute(PERSON_DAYS, (group_id, uuid, exclude or "")).fetchone()
return DayRecord(row["day"], row["messages"]) if row else None
def previous_best(
events: EventStore,
group_id: str,
uuid: str,
before: str,
*,
exclude: str | None = None,
) -> DayRecord | None:
"""Somebody's best day *excluding* one day, for "poprzedni rekord".
Announcing "rekord życiowy: 76" is worth little without what it beat, and
the day being announced must not be its own previous best.
"""
rows = events.connection.execute(PERSON_DAYS, (group_id, uuid, exclude or "")).fetchall()
for row in rows:
if row["day"] != before:
return DayRecord(row["day"], row["messages"])
return None
def most_media_day(
events: EventStore,
group_id: str,
*,
exclude: str | None = None,
) -> DayRecord | None:
"""The day carrying the most photos and videos."""
row = events.connection.execute(MEDIA_DAYS, (group_id, exclude or "")).fetchone()
return DayRecord(row["day"], row["media"]) if row else None
@dataclass(frozen=True, slots=True)
class Silence:
"""A stretch of days on which nobody wrote anything."""
start: str
end: str
days: int
def longest_silence(days: dict[str, int], until: str) -> Silence | None:
"""The longest run of consecutive silent days, up to and including ``until``.
Walks the calendar rather than the recorded days, because the whole point
is the days that are *missing* from the series. Returns None when the
history is too short to contain a gap.
"""
if not days:
return None
spoke = set(days)
first = min(spoke)
best: Silence | None = None
run_start: str | None = None
day = first
while day <= until:
if day in spoke:
if run_start is not None:
run = _silence(run_start, shift(day, -1))
best = run if best is None or run.days > best.days else best
run_start = None
elif run_start is None:
run_start = day
day = shift(day, 1)
if run_start is not None:
run = _silence(run_start, until)
best = run if best is None or run.days > best.days else best
return best
def _silence(start: str, end: str) -> Silence:
"""Build a Silence, counting both ends."""
length = 1
day = start
while day < end:
day = shift(day, 1)
length += 1
return Silence(start, end, length)
def days_silent_before(days: dict[str, int], uuid_days: dict[str, int], until: str) -> int:
"""Recorded days between somebody's last message and ``until``, exclusive.
Both ends are excluded, which is what makes "odezwał się po 3 dniach
ciszy" true rather than off by one: the day they last spoke was not
silent, and neither is the day they came back on.
Bounded by the group's own recorded days, so somebody who joined last week
is not reported as having been silent for a year, and a stretch the bot
was offline for does not count against them.
"""
if not days:
return 0
if not uuid_days:
return sum(1 for day in days if day < until)
last = max(uuid_days)
return sum(1 for day in days if last < day < until)

View File

@ -0,0 +1,146 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The on-demand answers: records, the crown, one person, the weekdays.
Each of these is asked for rather than pushed, so each says something even
when there is nothing interesting yet -- "za mało danych" is a useful answer
to a question, where it would be noise in a nightly post nobody asked for.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Final
from signal_bot.stats import records, streaks, text
from signal_bot.stats.periods import WEEKDAY_PLURAL, pl_day_month
if TYPE_CHECKING:
from signal_bot.stats.events import EventStore, Person
from signal_bot.stats.records import DayRecord
TROPHY: Final = "\U0001f3c6"
CROWN: Final = "\U0001f451"
CALENDAR: Final = "\U0001f4c5"
CAMERA: Final = "\U0001f4f7"
QUIET: Final = "\U0001f92b"
NOTHING_YET: Final = "Za mało danych — wróć za kilka dni."
def _record_line(label: str, record: DayRecord | None, unit: str) -> str | None:
"""One "label: value (date)" line, or None when there is no record yet."""
if record is None:
return None
return f"{label}: {record.value} {unit} ({pl_day_month(record.day)})"
def render_records(
history: dict[str, int],
media: DayRecord | None,
silence: records.Silence | None,
personal: list[tuple[str, DayRecord]],
) -> str:
"""Every all-time record the group has set."""
lines = [f"{TROPHY} Rekordy"]
candidates = [
_record_line("Najwięcej w jeden dzień", records.busiest_day(history), "wiadomości"),
_record_line("Najciszej (ale ktoś pisał)", records.quietest_day(history), "wiadomości"),
_record_line(f"Najwięcej zdjęć {CAMERA}", media, "zdjęć"),
]
lines.extend(line for line in candidates if line)
if silence:
lines.append(
f"{QUIET} Najdłuższa cisza: {text.days(silence.days)} "
f"({pl_day_month(silence.start)} - {pl_day_month(silence.end)})"
)
if personal:
lines.append("")
lines.append("Rekordy życiowe:")
lines.extend(
f" {name} — {record.value} ({pl_day_month(record.day)})" for name, record in personal
)
return "\n".join(lines) if len(lines) > 1 else NOTHING_YET
def render_crown(
winners: dict[str, list[tuple[str, str]]],
people: list[Person],
) -> str:
"""Who holds the crown now, who held it longest, and who has held it most."""
if not winners:
return NOTHING_YET
# Both are guaranteed once winners is non-empty, which the guard above
# already established: the latest day always has at least one holder, and
# a day with a holder is a run of at least one.
current = streaks.current_streaks(winners)
# `or current[0]` is a type narrowing, not a fallback: longest_ever only
# returns None for an empty history, which the guard above ruled out.
longest = streaks.longest_ever(winners) or current[0]
names = " i ".join(s.display_name for s in current if s.length == current[0].length)
lines = [
f"{CROWN} Korona",
f"Teraz: {names} — {text.days(current[0].length)} z rzędu",
(
f"Najdłuższa seria: {longest.display_name} — {text.days(longest.length)} "
f"(do {pl_day_month(longest.last_day)})"
),
]
held = sorted(
((person.display_name, streaks.held_days(winners, person.uuid)) for person in people),
key=lambda pair: (-pair[1], pair[0]),
)
lines.append("")
lines.append("Dni z koroną łącznie:")
lines.extend(f" {name} — {text.days(days)}" for name, days in held if days)
return "\n".join(lines)
def render_weekdays(buckets: dict[int, list[int]], today: int) -> str:
"""The Monday-to-Sunday picture, with today's weekday called out."""
if not buckets:
return NOTHING_YET
lines = [f"{CALENDAR} Dni tygodnia"]
for index in range(len(WEEKDAY_PLURAL)):
days = buckets.get(index)
if not days:
continue
mean = round(sum(days) / len(days))
marker = " ← dziś" if index == today else ""
lines.append(
f"{WEEKDAY_PLURAL[index]}: średnio {mean} ({text.days(len(days))} w historii){marker}"
)
return "\n".join(lines)
def render_me(
name: str,
total: int,
best: DayRecord | None,
share: int,
favourite_hour: int | None,
streak: int,
) -> str:
"""One person's own numbers."""
lines = [f"{name} — {text.messages(total)} w historii"]
if best:
lines.append(f"{TROPHY} Rekord życiowy: {best.value} ({pl_day_month(best.day)})")
lines.append(f"Udział w rozmowie: {share}%")
if favourite_hour is not None:
lines.append(f"Najczęściej piszesz o {favourite_hour:02d}:00")
if streak:
lines.append(f"{CROWN} Korona: {text.days(streak)} z rzędu")
return "\n".join(lines)
def favourite_hour(events: EventStore, group_id: str, uuid: str) -> int | None:
"""The hour somebody writes most in, or None if they never have."""
row = events.connection.execute(
"""
SELECT local_hour, COUNT(*) AS messages
FROM message_events
WHERE group_id = ? AND uuid = ?
GROUP BY local_hour
ORDER BY messages DESC, local_hour ASC
LIMIT 1
""",
(group_id, uuid),
).fetchone()
return row["local_hour"] if row else None

View File

@ -0,0 +1,85 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Rendering a week, a month or a year.
Same rules as the day block: plain text, no padding, and the count separated
from the name by a dash rather than by spaces that only line up in a terminal.
Longer than the nightly post on purpose. These are asked for, not pushed, so
somebody who typed `!miesiąc` has already agreed to read a month.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Final
from signal_bot.stats import text
from signal_bot.stats.periods import pl_day_month
if TYPE_CHECKING:
from signal_bot.stats.periods import Period
from signal_bot.stats.queries_day import DayRow
from signal_bot.stats.queries_period import Trend
MEDALS: Final = ("\U0001f947", "\U0001f948", "\U0001f949")
CHART: Final = "\U0001f4ca"
BAR_WIDTH: Final = 10
MAX_ROWS: Final = 12
def bar(share: int) -> str:
"""A share of voice as a text bar. Blocks, because Signal has no charts."""
filled = round(share / 100 * BAR_WIDTH)
return "█" * filled + "░" * (BAR_WIDTH - filled)
def trend_line(trend: Trend, what: str) -> str:
"""One line comparing a period with the one before it.
Says "first one" rather than "0%" when there is no baseline: the group
should not be told a period is unchanged when there is nothing to have
changed from.
"""
if trend.percent is None:
return f"({what}: pierwszy taki okres w historii)"
if not trend.delta:
return f"({what}: dokładnie tyle samo co poprzednio)"
direction = "więcej" if trend.delta > 0 else "mniej"
return f"{trend.arrow} {abs(trend.percent)}% {direction} niż {what}"
def _row(row: DayRow, place: int, total: int, *, podium: bool) -> str:
"""One person's line, with a medal or a rank and a share bar."""
lead = MEDALS[place - 1] if podium and place <= len(MEDALS) else f"{place}."
share = round(row.messages / total * 100) if total else 0
return f"{lead} {row.display_name} — {row.messages} {bar(share)} {share}%"
def render_period(
period: Period,
rows: list[DayRow],
trend: Trend,
*,
since: str | None = None,
podium: bool = False,
) -> str:
"""Compose a period summary."""
total = sum(row.messages for row in rows)
media = sum(row.media for row in rows)
extra = f" ({media} \U0001f4f7)" if media else ""
lines = [f"{CHART} {period.label} — {text.messages(total)}{extra}"]
if not rows:
lines.append("Nikt nic nie napisał.")
return "\n".join(lines)
shown = rows[:MAX_ROWS]
lines.extend(_row(row, i + 1, total, podium=podium) for i, row in enumerate(shown))
if len(rows) > MAX_ROWS:
hidden = rows[MAX_ROWS:]
rest = sum(row.messages for row in hidden)
lines.append(f"…i {text.people(len(hidden))} więcej (razem {text.messages(rest)})")
lines.append(trend_line(trend, "poprzednio"))
if since:
lines.append(f"(liczymy od {pl_day_month(since)})")
return "\n".join(lines)

126
signal_bot/stats/streaks.py Normal file
View File

@ -0,0 +1,126 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Who holds the crown, and for how long.
A tie shares the crown and keeps every tied streak alive. That is a decision,
not an oversight: breaking somebody's forty-day run on a technicality is the
kind of thing that starts an argument in a group chat, and "we were both first"
is what the people involved would say anyway.
Streaks count *recorded* days, not calendar days. A day nobody spoke does not
end a run -- there was no crown to lose -- and neither does a day the bot was
offline for, which it could not have judged.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Iterable
from signal_bot.stats.events import EventStore
DAILY_COUNTS = """
SELECT day, uuid, display_name, COUNT(*) AS messages
FROM message_events
WHERE group_id = ? AND day <> ?
GROUP BY day, uuid
ORDER BY day ASC, messages DESC, display_name ASC
"""
@dataclass(frozen=True, slots=True)
class Streak:
"""A run of consecutive recorded days holding the crown."""
uuid: str
display_name: str
length: int
last_day: str
def daily_winners(
events: EventStore,
group_id: str,
*,
exclude: str | None = None,
) -> dict[str, list[tuple[str, str]]]:
"""Who led each recorded day, as (uuid, display_name), ties included."""
rows = events.connection.execute(DAILY_COUNTS, (group_id, exclude or "")).fetchall()
best: dict[str, int] = {}
winners: dict[str, list[tuple[str, str]]] = {}
for row in rows:
day, count = row["day"], row["messages"]
# Ordered messages-first, so the day's leader is always the row that
# creates the entry and everything after it either ties or loses.
if day not in best:
best[day] = count
winners[day] = [(row["uuid"], row["display_name"])]
elif count == best[day]:
winners[day].append((row["uuid"], row["display_name"]))
return winners
def current_streaks(winners: dict[str, list[tuple[str, str]]]) -> list[Streak]:
"""Everyone whose run reaches the most recent recorded day.
Sorted longest first, then by name, so two people on the same run are
reported in a stable order rather than whichever the dict happened to
yield.
"""
if not winners:
return []
days = sorted(winners)
latest = days[-1]
holders = dict(winners[latest])
lengths = dict.fromkeys(holders, 0)
running = set(holders)
for day in reversed(days):
today = {uuid for uuid, _ in winners[day]}
for uuid in sorted(running):
if uuid in today:
lengths[uuid] += 1
else:
# Their run ended on this day. What they had already
# accumulated is kept -- dropping them from the tally, as an
# earlier spelling did, reported every streak as zero.
running.discard(uuid)
if not running:
break
return sorted(
(Streak(uuid, holders[uuid], length, latest) for uuid, length in lengths.items()),
key=lambda s: (-s.length, s.display_name),
)
def longest_ever(winners: dict[str, list[tuple[str, str]]]) -> Streak | None:
"""The longest crown run anybody has ever put together."""
running: dict[str, int] = {}
names: dict[str, str] = {}
best: Streak | None = None
for day in sorted(winners):
today = dict(winners[day])
names.update(today)
running = {uuid: running.get(uuid, 0) + 1 for uuid in today}
for uuid, length in running.items():
if (
best is None
or length > best.length
or (length == best.length and names[uuid] < best.display_name)
):
best = Streak(uuid, names[uuid], length, day)
return best
def held_days(winners: dict[str, list[tuple[str, str]]], uuid: str) -> int:
"""How many days somebody has held the crown in total, ties included."""
return sum(1 for holders in winners.values() if any(u == uuid for u, _ in holders))
def names_of(holders: Iterable[tuple[str, str]]) -> list[str]:
"""Display names of a day's crown holders, alphabetical for stability."""
return sorted(name for _, name in holders)

64
tests/stats_seed.py Normal file
View File

@ -0,0 +1,64 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""A deterministic history to run the period, record and streak queries over.
Not a conftest fixture: it is a builder several test modules call with a
different history each, rather than one shared shape. Counts come from
arithmetic, never from ``random`` -- a fixture that changes between runs turns
a real failure into a flake.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from signal_bot.stats.events import MessageEvent
if TYPE_CHECKING:
from signal_bot.store import Store
GROUP = "group-a=="
MITHRA = ("u-mithra", "Mithra")
KUHY = ("u-kuhy", "kuhy")
IGA = ("u-iga", "Iga")
@dataclass(frozen=True, slots=True)
class Shape:
"""The optional detail of a seeded day, so ``wrote`` stays legible."""
media: int = 0
hour: int = 12
chars: int = 10
commands: int = 0
group_id: str = GROUP
def wrote(
store: Store,
day: str,
who: tuple[str, str],
count: int,
shape: Shape | None = None,
) -> None:
"""Put ``count`` messages from one person into one group on one day."""
shape = shape or Shape()
uuid, name = who
for index in range(count):
store.events.record(
MessageEvent(
group_id=shape.group_id,
uuid=uuid,
display_name=name,
# Unique within (group, uuid) so the primary key does not
# absorb them, and stable so two runs agree.
sent_at_ms=int(day.replace("-", "")) * 1000 + index,
day=day,
local_hour=shape.hour,
media_kind="image" if index < shape.media else "",
media_count=1 if index < shape.media else 0,
char_len=shape.chars,
is_command=index < shape.commands,
)
)
store.events.note_person(shape.group_id, uuid, name, "", day)

View File

@ -0,0 +1,177 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The `!` commands, end to end through a real store."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
import pytest
from signal_bot.animals import load_aliases
from signal_bot.folding import fold
from signal_bot.registry import CommandRegistry
from signal_bot.stats import periods
from signal_bot.stats.backfill import BACKFILL_KEY
from signal_bot.stats.commands import HANDLERS, register_stats_commands
from tests.stats_seed import GROUP, IGA, KUHY, MITHRA, Shape, wrote
if TYPE_CHECKING:
from signal_bot.store import Store
TODAY = periods.today()
YESTERDAY = periods.previous_day()
@dataclass
class Sender:
"""The bit of IncomingMessage the handlers actually read."""
source_uuid: str = KUHY[0]
@dataclass
class FakeContext:
"""A CommandContext stand-in that records what was said back."""
store: Store
group_id: str = GROUP
message: Sender = field(default_factory=Sender)
replies: list[str] = field(default_factory=list)
async def reply(self, text: str) -> None:
"""Record the answer instead of sending it."""
self.replies.append(text)
async def run(store: Store, name: str, uuid: str = KUHY[0]) -> str:
"""Run one command and return what it said."""
ctx = FakeContext(store=store, message=Sender(source_uuid=uuid))
await HANDLERS[name](ctx)
return ctx.replies[0]
def test_every_trigger_is_unique_across_the_whole_registry() -> None:
"""A collision raises DuplicateTriggerError, which is a ValueError.
That matters more than it looks: build_bot runs inside create_runtime, and
ValueError is in startup_retry.RETRYABLE. A colliding alias would not
crash the bot -- it would retry forever, logging "signal-cli not reachable
yet", which is the wrong diagnosis entirely. This test is the thing that
catches it instead.
"""
registry = CommandRegistry()
register_stats_commands(registry)
names = {command.name for command in registry.commands}
assert names == set(HANDLERS)
def test_no_trigger_contains_a_digit() -> None:
"""fold() maps digits onto letters, so "!7dni" resolves as "!tdni"."""
table = load_aliases()
for name in HANDLERS:
for trigger in table[name]:
assert not any(character.isdigit() for character in trigger), trigger
def test_polish_spellings_fold_together() -> None:
"""Somebody typing !tydzien and somebody typing !tydzień want the same thing."""
assert fold("!tydzień") == fold("!tydzien")
assert fold("!miesiąc") == fold("!miesiac")
@pytest.mark.parametrize("name", list(HANDLERS))
async def test_every_command_answers_on_an_empty_history(store: Store, name: str) -> None:
"""Day one of this release: every command says something, none crashes."""
assert await run(store, name)
async def test_today_and_yesterday_are_different_days(store: Store) -> None:
wrote(store, TODAY, MITHRA, 4)
wrote(store, YESTERDAY, KUHY, 7)
assert "Dziś, na razie:" in await run(store, "stats_today")
assert "Mithra" in await run(store, "stats_today")
assert "kuhy" in await run(store, "stats_yesterday")
async def test_yesterday_renders_the_nightly_block_verbatim(store: Store) -> None:
"""The only way to check the headline output without waiting for 21:37."""
wrote(store, YESTERDAY, MITHRA, 5)
answer = await run(store, "stats_yesterday")
assert answer.startswith("📊 ")
assert "👑 Mithra — 5" in answer
async def test_a_day_nobody_wrote_on_says_so(store: Store) -> None:
assert "Nikt jeszcze nic nie napisał" in await run(store, "stats_yesterday")
async def test_the_week_shows_a_share_bar(store: Store) -> None:
wrote(store, TODAY, MITHRA, 8)
wrote(store, TODAY, KUHY, 2)
answer = await run(store, "stats_week")
assert "Mithra — 8" in answer
assert "80%" in answer
assert "█" in answer
async def test_the_month_puts_medals_on_the_podium(store: Store) -> None:
wrote(store, TODAY, MITHRA, 8)
wrote(store, TODAY, KUHY, 5)
wrote(store, TODAY, IGA, 2)
answer = await run(store, "stats_month")
assert "🥇 Mithra" in answer
assert "🥈 kuhy" in answer
assert "🥉 Iga" in answer
async def test_a_first_period_says_so_rather_than_claiming_no_change(store: Store) -> None:
wrote(store, TODAY, MITHRA, 8)
assert "pierwszy taki okres w historii" in await run(store, "stats_year")
async def test_me_reports_the_asker(store: Store) -> None:
wrote(store, TODAY, KUHY, 6, Shape(hour=23))
wrote(store, TODAY, MITHRA, 2)
answer = await run(store, "stats_me")
assert "kuhy — 6 wiadomości w historii" in answer
assert "Udział w rozmowie: 75%" in answer
assert "Najczęściej piszesz o 23:00" in answer
async def test_me_is_honest_with_somebody_who_never_wrote(store: Store) -> None:
wrote(store, TODAY, MITHRA, 4)
assert "ani jednej wiadomości" in await run(store, "stats_me", uuid="u-nobody")
async def test_records_and_crown_fill_in_once_there_is_history(store: Store) -> None:
wrote(store, periods.shift(TODAY, -2), MITHRA, 9)
wrote(store, periods.shift(TODAY, -1), MITHRA, 4)
wrote(store, TODAY, KUHY, 3)
records = await run(store, "stats_records")
assert "Najwięcej w jeden dzień: 9" in records
assert "Rekordy życiowe:" in records
crown = await run(store, "stats_crown")
assert "Najdłuższa seria: Mithra" in crown
assert "Dni z koroną łącznie:" in crown
async def test_records_skips_somebody_with_no_days_left_after_exclusions(
store: Store,
) -> None:
"""Somebody whose only day was the backfilled one has no record to show.
Fixed dates, not periods.today(): on the day this was written those were
the same date, and the test passed for the wrong reason.
"""
wrote(store, "2026-08-01", IGA, 40)
wrote(store, "2026-08-15", MITHRA, 5)
store.set_meta(GROUP, BACKFILL_KEY, "2026-08-01")
rendered = await run(store, "stats_records")
assert "Mithra" in rendered
assert "Iga" not in rendered
async def test_weekdays_marks_today(store: Store) -> None:
wrote(store, TODAY, MITHRA, 5)
assert "← dziś" in await run(store, "stats_weekdays")

View File

@ -0,0 +1,228 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""What the bot notices about a day, and what it stays quiet about."""
from __future__ import annotations
from typing import TYPE_CHECKING
from signal_bot.stats import curiosities
from signal_bot.stats.facts import DayFacts, gather
from signal_bot.stats.highlights import Highlight, ratio, select
from signal_bot.stats.queries_day import day_rows, with_silent
from tests.stats_seed import GROUP, IGA, KUHY, MITHRA, Shape, wrote
if TYPE_CHECKING:
from signal_bot.store import Store
def facts_for(store: Store, day: str, roster: list[tuple[str, str]] | None = None) -> DayFacts:
"""Gather a day the way publish_report does."""
rows = with_silent(day_rows(store.events, GROUP, day), roster or [])
return gather(store.events, GROUP, day, rows)
def test_day_one_notices_nothing(store: Store) -> None:
"""Almost every candidate has no history to stand against yet."""
wrote(store, "2026-09-01", KUHY, 3)
fired = [c for c in curiosities.for_day(facts_for(store, "2026-09-01")) if c]
assert [c.kind for c in fired] == ["only_one_spoke"]
def test_facts_expose_the_days_crown_holders(store: Store) -> None:
wrote(store, "2026-09-01", MITHRA, 4)
wrote(store, "2026-09-01", KUHY, 4)
wrote(store, "2026-09-01", IGA, 1)
assert sorted(n for _, n in facts_for(store, "2026-09-01").leaders) == ["Mithra", "kuhy"]
assert facts_for(store, "2026-09-09").leaders == []
def test_a_personal_record_reports_what_it_beat(store: Store) -> None:
wrote(store, "2026-09-01", MITHRA, 5)
wrote(store, "2026-09-02", KUHY, 1)
wrote(store, "2026-09-02", MITHRA, 9)
found = curiosities.personal_record(facts_for(store, "2026-09-02"))
assert found is not None
assert "Mithra 9 — rekord życiowy (poprzedni 5, 1 września)" in found.text
def test_a_first_ever_day_is_not_announced_as_a_record(store: Store) -> None:
"""Everybody's first day is their best; saying so every time is noise."""
wrote(store, "2026-09-01", MITHRA, 5)
assert curiosities.personal_record(facts_for(store, "2026-09-01")) is None
def test_the_busiest_day_ever(store: Store) -> None:
wrote(store, "2026-09-01", KUHY, 3)
wrote(store, "2026-09-02", KUHY, 9)
found = curiosities.group_record_day(facts_for(store, "2026-09-02"))
assert found is not None
assert "najgadatliwszy dzień w historii: 9 wiadomości" in found.text
def test_a_quiet_day_is_not_a_record(store: Store) -> None:
wrote(store, "2026-09-01", KUHY, 9)
wrote(store, "2026-09-02", KUHY, 3)
assert curiosities.group_record_day(facts_for(store, "2026-09-02")) is None
def test_a_media_record_needs_more_than_one_photo(store: Store) -> None:
wrote(store, "2026-09-01", KUHY, 3, Shape(media=1))
assert curiosities.media_record(facts_for(store, "2026-09-01")) is None
wrote(store, "2026-09-02", KUHY, 4, Shape(media=3))
found = curiosities.media_record(facts_for(store, "2026-09-02"))
assert found is not None
assert "rekord zdjęć: 3" in found.text
def test_a_crown_streak_needs_two_days(store: Store) -> None:
wrote(store, "2026-09-01", MITHRA, 5)
wrote(store, "2026-09-01", KUHY, 1)
assert curiosities.crown_streak(facts_for(store, "2026-09-01")) is None
wrote(store, "2026-09-02", MITHRA, 5)
wrote(store, "2026-09-02", KUHY, 1)
found = curiosities.crown_streak(facts_for(store, "2026-09-02"))
assert found is not None
assert "Mithra z koroną 2 dni z rzędu" in found.text
def test_a_shared_crown_names_everyone(store: Store) -> None:
for day in ("2026-09-01", "2026-09-02"):
wrote(store, day, MITHRA, 4)
wrote(store, day, KUHY, 4)
found = curiosities.crown_streak(facts_for(store, "2026-09-02"))
assert found is not None
assert "Mithra i kuhy z koroną" in found.text
def test_breaking_a_silence(store: Store) -> None:
wrote(store, "2026-09-01", IGA, 2)
for day in ("2026-09-02", "2026-09-03", "2026-09-04"):
wrote(store, day, KUHY, 3)
wrote(store, "2026-09-05", IGA, 1)
wrote(store, "2026-09-05", KUHY, 9)
found = curiosities.silence_broken(facts_for(store, "2026-09-05"))
assert found is not None
assert "Iga odezwał się po 3 dni ciszy" in found.text
def test_a_short_gap_is_not_worth_mentioning(store: Store) -> None:
wrote(store, "2026-09-01", IGA, 2)
wrote(store, "2026-09-02", KUHY, 3)
wrote(store, "2026-09-03", IGA, 2)
assert curiosities.silence_broken(facts_for(store, "2026-09-03")) is None
def test_a_monologue(store: Store) -> None:
wrote(store, "2026-09-01", KUHY, 7)
found = curiosities.only_one_spoke(facts_for(store, "2026-09-01"))
assert found is not None
assert "cały dzień mówił tylko kuhy" in found.text
def test_one_single_message_is_not_a_monologue(store: Store) -> None:
wrote(store, "2026-09-01", KUHY, 1)
assert curiosities.only_one_spoke(facts_for(store, "2026-09-01")) is None
def test_dominating_the_day(store: Store) -> None:
wrote(store, "2026-09-01", MITHRA, 8)
wrote(store, "2026-09-01", KUHY, 2)
found = curiosities.dominant_share(facts_for(store, "2026-09-01"))
assert found is not None
assert "Mithra to 80% dzisiejszych wiadomości" in found.text
def test_an_evenly_shared_day_is_not_dominated(store: Store) -> None:
wrote(store, "2026-09-01", MITHRA, 5)
wrote(store, "2026-09-01", KUHY, 4)
wrote(store, "2026-09-01", IGA, 4)
assert curiosities.dominant_share(facts_for(store, "2026-09-01")) is None
def test_a_weekday_needs_a_baseline_before_it_can_be_unusual(store: Store) -> None:
"""Two Tuesdays are not an average worth quoting."""
wrote(store, "2026-09-01", KUHY, 5)
wrote(store, "2026-09-08", KUHY, 50)
assert curiosities.weekday_average(facts_for(store, "2026-09-08")) is None
def test_an_unusual_weekday(store: Store) -> None:
for day in ("2026-09-01", "2026-09-08", "2026-09-15"):
wrote(store, day, KUHY, 10)
wrote(store, "2026-09-22", KUHY, 30)
found = curiosities.weekday_average(facts_for(store, "2026-09-22"))
assert found is not None
assert "wtorki mają średnio 10 — dziś o 200% więcej" in found.text
def test_a_typical_weekday_says_nothing(store: Store) -> None:
for day in ("2026-09-01", "2026-09-08", "2026-09-15", "2026-09-22"):
wrote(store, day, KUHY, 10)
assert curiosities.weekday_average(facts_for(store, "2026-09-22")) is None
def test_a_quiet_weekday_reads_as_fewer(store: Store) -> None:
for day in ("2026-09-01", "2026-09-08", "2026-09-15"):
wrote(store, day, KUHY, 20)
wrote(store, "2026-09-22", KUHY, 5)
found = curiosities.weekday_average(facts_for(store, "2026-09-22"))
assert found is not None
assert "mniej" in found.text
def test_a_night_owl(store: Store) -> None:
wrote(store, "2026-09-01", KUHY, 3, Shape(hour=1))
found = curiosities.night_owl(facts_for(store, "2026-09-01"))
assert found is not None
assert "kuhy pisał o 01:00" in found.text
def test_an_ordinary_evening_is_not_a_night_owl(store: Store) -> None:
wrote(store, "2026-09-01", KUHY, 3, Shape(hour=22))
assert curiosities.night_owl(facts_for(store, "2026-09-01")) is None
def test_one_line_per_family(store: Store) -> None:
"""Three sentences about the same person are one fact, not three."""
picks = select(
[
Highlight("a", "voice", 60, 1.0, "A"),
Highlight("b", "voice", 50, 1.0, "B"),
Highlight("c", "record", 40, 1.0, "C"),
],
3,
)
assert [p.kind for p in picks] == ["a", "c"]
def test_selection_is_ordered_and_bounded() -> None:
picks = select(
[
Highlight("low", "one", 10, 1.0, ""),
None,
Highlight("high", "two", 90, 1.0, ""),
Highlight("mid", "three", 50, 1.0, ""),
],
2,
)
assert [p.kind for p in picks] == ["high", "mid"]
def test_ties_break_on_name_so_a_day_renders_the_same_twice() -> None:
picks = select(
[
Highlight("zebra", "one", 50, 1.0, ""),
Highlight("alpha", "two", 50, 1.0, ""),
],
2,
)
assert [p.kind for p in picks] == ["alpha", "zebra"]
def test_nothing_to_say_is_an_empty_list() -> None:
assert select([None, None], 3) == []
def test_ratio_survives_a_zero_baseline() -> None:
assert ratio(5, 0) == 5.0
assert ratio(10, 5) == 1.0

View File

@ -0,0 +1,121 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Weeks, months, years, trends and the per-weekday picture."""
from __future__ import annotations
from typing import TYPE_CHECKING
from signal_bot.stats import periods
from signal_bot.stats.queries_period import (
Trend,
daily_series,
every_day,
period_rows,
share_of_voice,
total_for,
weekday_buckets,
)
from tests.stats_seed import GROUP, IGA, KUHY, MITHRA, Shape, wrote
if TYPE_CHECKING:
from signal_bot.store import Store
# 2026-08-31 is a Monday, so this spans one ISO week exactly.
WEEK = periods.week_of("2026-09-01")
PREVIOUS = periods.previous(WEEK)
def history(store: Store) -> None:
"""A full week, plus one day in the week before it."""
wrote(store, "2026-08-25", KUHY, 8)
wrote(store, "2026-08-31", MITHRA, 10, Shape(media=2, commands=1))
wrote(store, "2026-09-01", MITHRA, 20)
wrote(store, "2026-09-01", KUHY, 10)
wrote(store, "2026-09-02", IGA, 5)
def test_period_rows_are_ordered_by_volume(store: Store) -> None:
history(store)
rows = period_rows(store.events, GROUP, WEEK)
assert [(r.display_name, r.messages) for r in rows] == [
("Mithra", 30),
("kuhy", 10),
("Iga", 5),
]
def test_period_rows_carry_media_commands_and_length(store: Store) -> None:
history(store)
mithra = period_rows(store.events, GROUP, WEEK)[0]
assert (mithra.media, mithra.commands, mithra.chars) == (2, 1, 300)
def test_a_period_stops_at_its_own_boundary(store: Store) -> None:
"""The 25th belongs to the previous week and must not leak in."""
history(store)
assert total_for(store.events, GROUP, WEEK.start, WEEK.end) == 45
assert total_for(store.events, GROUP, PREVIOUS.start, PREVIOUS.end) == 8
def test_daily_series_omits_days_nobody_spoke(store: Store) -> None:
"""Absent, not zero: the caller decides what a missing day means."""
history(store)
series = daily_series(store.events, GROUP, WEEK.start, WEEK.end)
assert series == {"2026-08-31": 10, "2026-09-01": 30, "2026-09-02": 5}
def test_every_day_spans_the_whole_history(store: Store) -> None:
history(store)
assert set(every_day(store.events, GROUP)) == {
"2026-08-25",
"2026-08-31",
"2026-09-01",
"2026-09-02",
}
def test_weekday_buckets_index_monday_as_zero(store: Store) -> None:
history(store)
buckets = weekday_buckets(every_day(store.events, GROUP))
# 2026-08-25 is a Tuesday, 08-31 a Monday, 09-01 a Tuesday, 09-02 a Wednesday.
assert buckets[0] == [10]
assert sorted(buckets[1]) == [8, 30]
assert buckets[2] == [5]
def test_trend_reports_direction_and_size() -> None:
trend = Trend(now=45, before=30)
assert (trend.delta, trend.percent, trend.arrow) == (15, 50, "↑")
down = Trend(now=15, before=30)
assert (down.delta, down.percent, down.arrow) == (-15, -50, "↓")
def test_a_flat_period_gets_no_arrow() -> None:
assert Trend(now=30, before=30).arrow == ""
assert Trend(now=30, before=30).percent == 0
def test_no_baseline_is_not_the_same_as_no_change() -> None:
"""The first week ever has nothing to compare against, and says so."""
first = Trend(now=45, before=0)
assert first.percent is None
assert first.arrow == ""
assert first.delta == 45
def test_share_of_voice(store: Store) -> None:
history(store)
rows = period_rows(store.events, GROUP, WEEK)
assert share_of_voice(rows) == [("Mithra", 67), ("kuhy", 22), ("Iga", 11)]
def test_share_of_voice_of_nothing_is_empty() -> None:
assert share_of_voice([]) == []
def test_the_backfilled_day_can_be_left_out_of_every_query(store: Store) -> None:
history(store)
assert total_for(store.events, GROUP, WEEK.start, WEEK.end, exclude="2026-09-01") == 15
assert "2026-09-01" not in every_day(store.events, GROUP, exclude="2026-09-01")
rows = period_rows(store.events, GROUP, WEEK, exclude="2026-09-01")
assert [r.display_name for r in rows] == ["Mithra", "Iga"]

137
tests/test_stats_records.py Normal file
View File

@ -0,0 +1,137 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""All-time records, and the silences between them."""
from __future__ import annotations
from typing import TYPE_CHECKING
from signal_bot.stats.queries_period import every_day
from signal_bot.stats.records import (
busiest_day,
days_silent_before,
longest_silence,
most_media_day,
personal_best,
previous_best,
quietest_day,
)
from tests.stats_seed import GROUP, IGA, KUHY, MITHRA, Shape, wrote
if TYPE_CHECKING:
from signal_bot.store import Store
def history(store: Store) -> None:
"""Four days, a two-day gap, ties, and somebody who stops writing."""
wrote(store, "2026-09-01", MITHRA, 10, Shape(media=3))
wrote(store, "2026-09-01", KUHY, 5)
wrote(store, "2026-09-02", MITHRA, 4)
wrote(store, "2026-09-02", KUHY, 4)
wrote(store, "2026-09-03", IGA, 2)
# 09-04 and 09-05 silent.
wrote(store, "2026-09-06", KUHY, 9, Shape(media=1))
def test_no_history_yields_no_records(store: Store) -> None:
"""Day one of this release: everything empty, nothing crashing."""
days = every_day(store.events, GROUP)
assert busiest_day(days) is None
assert quietest_day(days) is None
assert longest_silence(days, "2026-09-06") is None
assert most_media_day(store.events, GROUP) is None
assert personal_best(store.events, GROUP, "u-kuhy") is None
def test_busiest_and_quietest(store: Store) -> None:
history(store)
days = every_day(store.events, GROUP)
assert busiest_day(days).day == "2026-09-01"
assert busiest_day(days).value == 15
assert quietest_day(days).day == "2026-09-03"
assert quietest_day(days).value == 2
def test_the_quietest_day_is_one_somebody_spoke_on(store: Store) -> None:
"""A silent day is a silence, not a quiet day, and is measured separately."""
history(store)
days = every_day(store.events, GROUP)
assert quietest_day(days).value > 0
assert "2026-09-04" not in days
def test_a_tie_on_the_busiest_day_goes_to_the_earlier(store: Store) -> None:
wrote(store, "2026-09-02", KUHY, 7)
wrote(store, "2026-09-01", MITHRA, 7)
assert busiest_day(every_day(store.events, GROUP)).day == "2026-09-01"
def test_personal_best_and_what_it_beat(store: Store) -> None:
history(store)
best = personal_best(store.events, GROUP, "u-kuhy")
assert (best.day, best.value) == ("2026-09-06", 9)
previous = previous_best(store.events, GROUP, "u-kuhy", "2026-09-06")
assert (previous.day, previous.value) == ("2026-09-01", 5)
def test_a_first_ever_day_has_nothing_to_beat(store: Store) -> None:
"""The "poprzedni rekord" clause has to be omitted, not printed as 0."""
wrote(store, "2026-09-01", IGA, 3)
assert previous_best(store.events, GROUP, "u-iga", "2026-09-01") is None
def test_most_media_day(store: Store) -> None:
history(store)
record = most_media_day(store.events, GROUP)
assert (record.day, record.value) == ("2026-09-01", 3)
def test_a_history_with_no_media_has_no_media_record(store: Store) -> None:
wrote(store, "2026-09-01", KUHY, 4)
assert most_media_day(store.events, GROUP) is None
def test_longest_silence(store: Store) -> None:
history(store)
gap = longest_silence(every_day(store.events, GROUP), "2026-09-06")
assert (gap.start, gap.end, gap.days) == ("2026-09-04", "2026-09-05", 2)
def test_a_silence_running_to_today_counts(store: Store) -> None:
"""The gap the group is currently in is the one worth mentioning."""
wrote(store, "2026-09-01", KUHY, 1)
gap = longest_silence(every_day(store.events, GROUP), "2026-09-05")
assert (gap.start, gap.end, gap.days) == ("2026-09-02", "2026-09-05", 4)
def test_an_unbroken_history_has_no_silence(store: Store) -> None:
wrote(store, "2026-09-01", KUHY, 1)
wrote(store, "2026-09-02", KUHY, 1)
assert longest_silence(every_day(store.events, GROUP), "2026-09-02") is None
def test_the_gap_excludes_both_the_last_word_and_the_return(store: Store) -> None:
"""What makes "odezwał się po 3 dniach" true instead of off by one."""
history(store)
days = every_day(store.events, GROUP)
mithra = {d: n for d, n in days.items() if d in {"2026-09-01", "2026-09-02"}}
# Recorded days are 09-01, 09-02, 09-03 and 09-06. Mithra last wrote on
# the 2nd, so only the 3rd sits between that and a return on the 6th.
assert days_silent_before(days, mithra, "2026-09-06") == 1
assert days_silent_before(days, {"2026-09-06": 9}, "2026-09-06") == 0
def test_somebody_who_never_wrote_is_silent_for_every_day_before_now(store: Store) -> None:
history(store)
days = every_day(store.events, GROUP)
assert days_silent_before(days, {}, "2026-09-06") == len(days) - 1
assert days_silent_before({}, {}, "2026-09-06") == 0
def test_the_backfilled_day_is_kept_out_of_records(store: Store) -> None:
"""A 22-hour window filed as a day must not become somebody's best."""
wrote(store, "2026-08-30", MITHRA, 98)
wrote(store, "2026-09-01", MITHRA, 10)
assert personal_best(store.events, GROUP, "u-mithra").value == 98
excluded = personal_best(store.events, GROUP, "u-mithra", exclude="2026-08-30")
assert (excluded.day, excluded.value) == ("2026-09-01", 10)
assert "2026-08-30" not in every_day(store.events, GROUP, exclude="2026-08-30")

View File

@ -0,0 +1,120 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Rendering a period, and the on-demand answers."""
from __future__ import annotations
from signal_bot.stats import periods
from signal_bot.stats.events import Person
from signal_bot.stats.queries_day import DayRow
from signal_bot.stats.queries_period import Trend
from signal_bot.stats.records import DayRecord, Silence
from signal_bot.stats.render_extra import (
NOTHING_YET,
render_crown,
render_me,
render_records,
render_weekdays,
)
from signal_bot.stats.render_period import MAX_ROWS, bar, render_period, trend_line
WEEK = periods.week_of("2026-09-01")
def rows(spec: list[tuple[str, int]]) -> list[DayRow]:
"""Build period rows from (name, messages) pairs."""
return [
DayRow(f"u{i}", name, messages, 0, 0, messages * 10)
for i, (name, messages) in enumerate(spec)
]
def test_a_period_with_nobody_in_it() -> None:
rendered = render_period(WEEK, [], Trend(0, 0))
assert "Nikt nic nie napisał." in rendered
def test_the_bar_fills_with_the_share() -> None:
assert bar(0) == "░" * 10
assert bar(100) == "█" * 10
assert bar(50) == "█████░░░░░"
def test_trend_says_first_rather_than_no_change() -> None:
"""Zero percent and "nothing to compare against" are different claims."""
assert "pierwszy taki okres" in trend_line(Trend(now=10, before=0), "poprzednio")
assert "dokładnie tyle samo" in trend_line(Trend(now=10, before=10), "poprzednio")
assert "↑ 50% więcej" in trend_line(Trend(now=15, before=10), "poprzednio")
assert "↓ 50% mniej" in trend_line(Trend(now=5, before=10), "poprzednio")
def test_a_long_period_is_truncated_with_its_total() -> None:
many = rows([(f"Osoba {i:02d}", 20 - i) for i in range(MAX_ROWS + 4)])
rendered = render_period(WEEK, many, Trend(100, 90))
assert "…i 4 osoby więcej" in rendered
assert len([line for line in rendered.split("\n") if line.startswith(("1.", "2."))]) >= 1
def test_medals_only_appear_on_a_podium() -> None:
three = rows([("A", 3), ("B", 2), ("C", 1)])
assert "🥇" in render_period(WEEK, three, Trend(6, 5), podium=True)
assert "🥇" not in render_period(WEEK, three, Trend(6, 5))
def test_records_with_nothing_recorded_says_so() -> None:
assert render_records({}, None, None, []) == NOTHING_YET
def test_records_reports_each_kind_it_has() -> None:
rendered = render_records(
{"2026-09-01": 10, "2026-09-03": 2},
DayRecord("2026-09-01", 4),
Silence("2026-09-04", "2026-09-06", 3),
[("Mithra", DayRecord("2026-09-01", 9))],
)
assert "Najwięcej w jeden dzień: 10" in rendered
assert "Najciszej (ale ktoś pisał): 2" in rendered
assert "Najwięcej zdjęć" in rendered
assert "Najdłuższa cisza: 3 dni" in rendered
assert "Mithra — 9" in rendered
def test_the_crown_with_no_history() -> None:
assert render_crown({}, []) == NOTHING_YET
def test_the_crown_reports_now_longest_and_totals() -> None:
winners = {
"2026-09-01": [("u1", "Mithra")],
"2026-09-02": [("u1", "Mithra")],
"2026-09-03": [("u2", "kuhy")],
}
people = [Person("u1", "Mithra", ""), Person("u2", "kuhy", "")]
rendered = render_crown(winners, people)
assert "Teraz: kuhy — 1 dzień z rzędu" in rendered
assert "Najdłuższa seria: Mithra — 2 dni" in rendered
assert "Mithra — 2 dni" in rendered
def test_weekdays_with_no_history() -> None:
assert render_weekdays({}, 0) == NOTHING_YET
def test_weekdays_skips_days_never_recorded() -> None:
rendered = render_weekdays({0: [10, 20], 4: [5]}, 4)
assert "poniedziałki: średnio 15" in rendered
assert "piątki: średnio 5" in rendered
assert "← dziś" in rendered
assert "wtorki" not in rendered
def test_me_omits_what_it_does_not_know() -> None:
"""No record, no favourite hour, no streak: three clauses that vanish."""
rendered = render_me("kuhy", 3, None, 10, None, 0)
assert rendered == "kuhy — 3 wiadomości w historii\nUdział w rozmowie: 10%"
def test_me_reports_everything_it_does_know() -> None:
rendered = render_me("kuhy", 30, DayRecord("2026-09-01", 12), 40, 23, 2)
assert "Rekord życiowy: 12 (1 września)" in rendered
assert "Najczęściej piszesz o 23:00" in rendered
assert "Korona: 2 dni z rzędu" in rendered

118
tests/test_stats_streaks.py Normal file
View File

@ -0,0 +1,118 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The crown: who holds it, for how long, and what a tie does to a run."""
from __future__ import annotations
from typing import TYPE_CHECKING
from signal_bot.stats.streaks import (
current_streaks,
daily_winners,
held_days,
longest_ever,
names_of,
)
from tests.stats_seed import GROUP, IGA, KUHY, MITHRA, wrote
if TYPE_CHECKING:
from signal_bot.store import Store
def test_no_history_has_no_crown(store: Store) -> None:
winners = daily_winners(store.events, GROUP)
assert winners == {}
assert current_streaks(winners) == []
assert longest_ever(winners) is None
assert held_days(winners, "u-kuhy") == 0
def test_the_busiest_person_holds_the_day(store: Store) -> None:
wrote(store, "2026-09-01", MITHRA, 10)
wrote(store, "2026-09-01", KUHY, 5)
winners = daily_winners(store.events, GROUP)
assert names_of(winners["2026-09-01"]) == ["Mithra"]
def test_a_tie_shares_the_crown(store: Store) -> None:
"""kuhy's call: shared, because the alternative starts arguments."""
wrote(store, "2026-09-01", MITHRA, 4)
wrote(store, "2026-09-01", KUHY, 4)
wrote(store, "2026-09-01", IGA, 1)
winners = daily_winners(store.events, GROUP)
assert names_of(winners["2026-09-01"]) == ["Mithra", "kuhy"]
def test_a_tie_keeps_every_tied_run_alive(store: Store) -> None:
"""Three days, both tied throughout: both hold a three-day streak."""
for day in ("2026-09-01", "2026-09-02", "2026-09-03"):
wrote(store, day, MITHRA, 3)
wrote(store, day, KUHY, 3)
streaks = current_streaks(daily_winners(store.events, GROUP))
assert [(s.display_name, s.length) for s in streaks] == [("Mithra", 3), ("kuhy", 3)]
def test_a_run_survives_a_day_nobody_spoke(store: Store) -> None:
"""There was no crown to lose on a silent day, so the run continues."""
wrote(store, "2026-09-01", KUHY, 5)
# 09-02 and 09-03 silent.
wrote(store, "2026-09-04", KUHY, 5)
streaks = current_streaks(daily_winners(store.events, GROUP))
assert [(s.display_name, s.length) for s in streaks] == [("kuhy", 2)]
def test_losing_a_day_ends_a_run_but_keeps_what_it_reached(store: Store) -> None:
"""The bug this test exists for reported every streak as zero."""
wrote(store, "2026-09-01", MITHRA, 10)
wrote(store, "2026-09-02", MITHRA, 10)
wrote(store, "2026-09-03", MITHRA, 4)
wrote(store, "2026-09-03", KUHY, 4)
wrote(store, "2026-09-06", KUHY, 9)
streaks = current_streaks(daily_winners(store.events, GROUP))
assert [(s.display_name, s.length) for s in streaks] == [("kuhy", 2)]
assert streaks[0].last_day == "2026-09-06"
def test_longest_ever_survives_the_run_that_set_it_ending(store: Store) -> None:
wrote(store, "2026-09-01", MITHRA, 10)
wrote(store, "2026-09-02", MITHRA, 10)
wrote(store, "2026-09-03", MITHRA, 10)
wrote(store, "2026-09-04", KUHY, 10)
best = longest_ever(daily_winners(store.events, GROUP))
assert (best.display_name, best.length, best.last_day) == ("Mithra", 3, "2026-09-03")
def test_held_days_counts_shared_days_for_everyone_tied(store: Store) -> None:
wrote(store, "2026-09-01", MITHRA, 10)
wrote(store, "2026-09-02", MITHRA, 4)
wrote(store, "2026-09-02", KUHY, 4)
winners = daily_winners(store.events, GROUP)
assert held_days(winners, "u-mithra") == 2
assert held_days(winners, "u-kuhy") == 1
assert held_days(winners, "u-iga") == 0
def test_somebody_who_merely_took_part_holds_nothing(store: Store) -> None:
"""Neither leader nor tied: the common case, and the one worth pinning."""
wrote(store, "2026-09-01", MITHRA, 10)
wrote(store, "2026-09-01", KUHY, 4)
wrote(store, "2026-09-01", IGA, 1)
winners = daily_winners(store.events, GROUP)
assert names_of(winners["2026-09-01"]) == ["Mithra"]
assert held_days(winners, "u-iga") == 0
def test_streak_order_is_stable(store: Store) -> None:
"""Longest first, then by name -- not whichever the dict happened to yield."""
wrote(store, "2026-09-01", MITHRA, 3)
wrote(store, "2026-09-01", KUHY, 3)
wrote(store, "2026-09-01", IGA, 3)
streaks = current_streaks(daily_winners(store.events, GROUP))
assert [s.display_name for s in streaks] == ["Iga", "Mithra", "kuhy"]
def test_the_backfilled_day_can_be_left_out(store: Store) -> None:
wrote(store, "2026-08-30", MITHRA, 98)
wrote(store, "2026-09-01", KUHY, 5)
winners = daily_winners(store.events, GROUP, exclude="2026-08-30")
assert "2026-08-30" not in winners
assert [s.display_name for s in current_streaks(winners)] == ["kuhy"]