Compare commits

...

4 Commits

Author SHA1 Message Date
f535aab1eb release: 0.1.1 «Pius I» — commands that explain themselves
Some checks are pending
CI / check (push) Waiting to run
Two things the group hit within minutes of 0.1.0, both reported by real
users rather than found by a test.

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

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

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 20:09:14 +02:00
86417fb4ae release: 0.1.0 «Hygin» — the statistics release
The tally becomes a message history. Ordinal 9 lands on 0.1.0 by
arithmetic rather than by choice, which is a pleasant coincidence for a
release this size.

What changes for the group, in the four bullets they will read: photos
and videos now count (a caption-less photo was worth zero, so everyone's
numbers jumped), people who said nothing appear at 0, nine new commands,
and the bot remembers history from 30 August 2026.

What changes underneath: an append-only per-message log holding metadata
and never a body; days that are calendar days in Europe/Warsaw rather
than "since the last post"; records, crown streaks and weekday averages;
weekly and monthly summaries; and reports that survive an outage instead
of being lost.

Exercised in testbot before this bump, per DOCS-changelog.md: all nine
commands ran clean, and kuhy confirmed the rendering on a real phone --
the one check that could not be done from here, since Signal's
proportional font is why the columns are separated by a dash rather than
padded.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 20:00:58 +02:00
f4b57d9c2e docs: describe what the bot actually does now
The README still described a counter that increments and resets, which
stopped being true two commits ago. The behaviour that replaced it does
not fit in a README section, so it moves to DOCS-statistics.md: what is
recorded and what deliberately is not, why a day is a stored Warsaw date
string and what breaks if it stops being one, what happens to counts and
to reports across an outage, why 2026-08-30 is marked and excluded from
every average, and how to read a wire format with LOG_LEVEL=DEBUG.

README keeps eight lines and a pointer, which puts it at exactly 250.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 19:58:25 +02:00
0ef2e4b021 feat: weekly, monthly and year-in-review posts, keyed off the day reported
A Sunday closes a week, a month's last day closes the month, and
31 December closes the year. Keyed off the day being *reported* rather
than off today, which is the only reading that stays right when the bot
has been offline: catching up on a week-old Sunday now also posts that
week's summary, and there is a test asserting the five messages a
three-day outage produces.

One scheduler, a date predicate. Three background tasks firing at the
same wall-clock time into the same group is three independent ways for
an evening to go wrong, for no gain over an if-statement. A failed
period summary is deliberately best-effort and runs after the day has
been marked, so it cannot make the bot re-post the daily one tomorrow.

Also: the quote frame arrived while this was being written, and it
carries a trap. `quote` has its own nested `attachments` array holding
the *quoted* message's media -- so a text reply to somebody's photo has
attachments in the payload that belong to somebody else. Reading them
would credit the replier with a photo they did not post, in a group
where people reply to photos constantly, inflating one number without
ever looking wrong.

The parser already read the top level only and is correct. It is now
pinned by a test built from the exact captured frame, and written up in
DOCS-signal-envelopes.md, because "it happens to be right" and "it
cannot silently stop being right" are different things. This is the same
wrong-nesting-level mistake that once made the bot ignore its own
stickers.

test_bot.py went past the 250-line cap on the way, so the report and
catch-up tests move into files named for what they cover.

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

View File

@ -38,6 +38,23 @@ this repo: describe what changes for them. 0.0.1 shipped a bullet about
`/healthz`, an endpoint bound to 127.0.0.1 that nobody in a Signal group can
reach, and it was rightly called out.
## 0.1.1 — Pius I
- komendy mówią teraz, co pokazują — `!korona` na pustych danych tłumaczy,
co się w niej pojawi, zamiast samego "za mało danych"
- `!ja` pisze "między 12:00 a 13:00" zamiast "o 12:00" — bo to godzina, a
nie moment
## 0.1.0 — Hygin
- podsumowanie liczy teraz zdjęcia i filmy — zdjęcie bez podpisu było
wcześniej warte zero, więc liczby wszystkim podskoczyły
- kto nic nie napisał, pojawia się z zerem
- nowe komendy: !staty, !wczoraj, !tydzień, !miesiąc, !rok, !rekordy,
!korona, !dni, !ja
- bot pamięta historię: rekordy życiowe, serie z koroną, średnie dni
tygodnia. Liczymy od 30 sierpnia 2026
## 0.0.7 — Telesfor
- nowa komenda `!papież` (działa też jako `!papiez`, `!papa`, `!pope`) — bot

View File

@ -74,6 +74,41 @@ 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.
## A reply carries `quote` -- with its own attachments
Also captured live, on 2026-08-30. This is a *text* reply to somebody else's
photo:
```
dataMessage: {
expiresInSeconds: int, isExpirationUpdate: bool, viewOnce: bool,
groupInfo: {groupId: str, groupName: str, revision: int, type: 'DELIVER'},
message: str,
quote: {
attachments: [{contentType: 'image/jpeg', filename: str,
thumbnail: {caption: null, contentType: 'image/jpeg',
filename: str, height: int, id: str, size: int,
uploadTimestamp: int, width: int}} x1],
author: str, authorNumber: str, authorUuid: str, id: int, text: str},
timestamp: int}
```
**`quote` has its own `attachments` array**, holding the *quoted* message's
media. There is no top-level `attachments` here at all, because the replier
sent only text.
So anything looking for attachments must read them off the top level of the
resolved payload and nowhere else. Searching the payload for an `attachments`
key would credit the replier with a photo somebody else posted -- and in a
group where people reply to photos constantly, that inflates one number
without ever looking wrong. It is the same wrong-nesting-level mistake that
once made the bot ignore its own stickers.
`quote.text` is the quoted message's body, and is not read for the same
reason: it is somebody else's message, already counted when they sent it.
`tests/test_models.py::test_a_quoted_photo_is_not_the_replier_s_photo` pins
this against the exact frame above.
## Somebody changed the membership: `groupInfo.type` is `UPDATE`
The only frame that names *who* added the bot to a group, which is what

90
DOCS-statistics.md Normal file
View File

@ -0,0 +1,90 @@
# Statistics
## What is recorded
One row per message in `message_events`: sender uuid and the display name they
had at the time, the Signal send timestamp, the Warsaw day and hour, the media
kind and count, the character length, and whether it was a command or a reply.
**Never the message body.** `tests/test_stats_events.py` asserts the column set
exactly, so a later edit cannot quietly add one. Reactions are not messages and
stay out. The bot's own posts never count — decided by which envelope branch
carried the payload, not by comparing identities, because the account is
spelled as a uuid on some frames and a +E.164 number on others.
A photo posted without a caption counts. Before 0.1.0 it was worth zero, which
is why everyone's numbers jumped on release.
## Days
A day is a calendar day in **Europe/Warsaw**, computed when the event is
recorded and stored as a string. Every query groups on that string rather than
on a range of timestamps, because Warsaw days are not all 24 hours long —
2026-03-29 is 23 and 2026-10-25 is 25 — and a timestamp range moves the
boundary twice a year.
Two consequences worth knowing before editing anything here:
- "Yesterday" is `date - timedelta(days=1)` on the *date*. Subtracting 86400
seconds lands at 23:00 the previous evening on a short day.
- Elapsed-time arithmetic must convert to UTC first. Subtracting two aware
datetimes that share a tzinfo gives the *wall-clock* difference, so the naive
spelling reports every day as exactly 24 hours and hides the bug.
## The nightly report
Posted at `REPORT_HOUR:REPORT_MINUTE` for the previous full day: the table,
members who said nothing at 0, a summary line, and up to three highlights
chosen from around twenty candidates — one per family, so a record, a share
and a crown streak about the same person do not become three lines.
Capped at twelve lines. Names are not padded: Signal renders a proportional
font, so `ljust` lines up in a terminal and on nobody's phone.
Only people whose display name has been seen are named. Somebody who has never
written is counted, not named — the group listing knows them only as a raw
uuid or a phone number, and printing either into a chat is a leak.
## Outages
Nothing is ever deleted, and the last day reported is recorded per group.
- **Missed counts** come back on their own. An event carries Signal's own send
timestamp, signal-cli keeps receiving in json-rpc mode while the bot is
down, and the replay on reconnect is absorbed by the `(group, uuid,
sent_at_ms)` primary key. Messages sent during an outage are filed under the
day they were actually sent.
- **Missed reports** are posted when the bot returns, oldest first, bounded at
a week. A day nobody spoke on is marked settled rather than reconsidered
forever; a day whose *send* failed is left unmarked so the next run retries
it.
## The backfilled day
2026-08-30 in the real group is carried over from the pre-0.1.0 counter, which
had no timestamps. Its totals are real; its hours and lengths are not, and its
window was 22 hours rather than a day. It is marked in `group_meta`, claims no
average message length, and is excluded from every record and average — a
merged day would otherwise hand somebody a personal best they never set.
The counter could not be split across the two days it spanned. Four places
were checked for a real inbound timestamp: journald (commands only),
signal-cli's `account.db` (no inbound table), Signal Desktop (unlinked, and it
does not backfill on link), and `signal-api/attachments` (dated, but media
only and with no sender). The attachment mtimes put 12 files on 29 August
against 79 on the 30th inside that window, which is why the whole counter sits
on the 30th.
## Debugging the wire format
`LOG_LEVEL=DEBUG` makes the dispatcher log each frame's *shape* — keys and
value types, never values, with a small allowlist for MIME and groupInfo types
that are format rather than content. Libraries stay at WARNING whatever the
bot is set to.
journalctl --user -u signal-bot -f | grep 'envelope shape'
Captured shapes live in `DOCS-signal-envelopes.md`. Read that before changing
anything that parses an envelope: `quote` carries its own nested `attachments`
array belonging to the *quoted* message, and counting it would credit a
replier with somebody else's photo.

View File

@ -1,6 +1,7 @@
# signal-bot
A Signal group bot: `!cat` / `!dog` / `!gekon` image commands and a daily tally.
A Signal group bot: `!cat` / `!dog` / `!gekon` image commands, `!papież`, and
group message statistics.
Runs on its **own registered Signal number** (or, if you prefer, as a linked
device on an existing account) via
@ -221,15 +222,14 @@ quietly posting the day's report into one group's chat.
The `per_group_isolation` scenario is the gate: one person asks in both groups
inside a single cooldown window and must get two images, one in each.
## Daily tally
## Statistics
Every non-sticker, non-reaction message in a watched group increments its
sender's count **for that group**. At `REPORT_HOUR:REPORT_MINUTE` (default
21:37) each group is posted its own tally, in its own chat, and reset. A group
where nobody spoke is logged and **not** posted into — otherwise every quiet
group the bot has ever been added to would get a nightly ping. A group that
refuses the report keeps its counts and does not cost the others theirs.
Counts live in SQLite and survive a restart.
One row of metadata per message — sender, Warsaw day, hour, media, length —
and **never the message body**. At `REPORT_HOUR:REPORT_MINUTE` (default 21:37)
each group gets its report for the previous full calendar day: silent members
at 0, up to three highlights. Sundays close a week, month ends a month. Ask it
things: `!staty` `!wczoraj` `!tydzień` `!miesiąc` `!rok` `!rekordy` `!korona`
`!dni` `!ja`. Full behaviour: `DOCS-statistics.md`.
## Develop

View File

@ -1,6 +1,6 @@
[project]
name = "signal-bot"
version = "0.0.7"
version = "0.1.1"
description = "A Signal group bot: image commands and daily message tallies."
readme = "README.md"
license = "MIT"

View File

@ -28,9 +28,11 @@ 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.nightly import closing_periods, days_to_report, mark_reported
from signal_bot.stats.queries_day import day_rows, day_totals, with_silent
from signal_bot.stats.queries_period import Trend, period_rows, total_for
from signal_bot.stats.render_day import DayView, render_day
from signal_bot.stats.render_period import render_period
from signal_bot.versioning import POPE, __version__
if TYPE_CHECKING:
@ -95,6 +97,7 @@ class Bot:
# rather than skipping the day forever.
break
mark_reported(self.store, group_id, day)
await self._report_closing(group_id, day)
async def _report_one(self, group_id: str, day: str) -> bool:
"""Post one group's report for one day. False means try again later."""
@ -127,6 +130,33 @@ class Bot:
return False
return True
async def _report_closing(self, group_id: str, day: str) -> None:
"""Post the week, month or year that ended with this day, if any.
Best effort and deliberately after the day has been marked: a failed
weekly summary must not make the bot re-post the daily one tomorrow.
"""
for period in closing_periods(day):
before = periods.previous(period)
trend = Trend(
now=total_for(self.store.events, group_id, period.start, period.end),
before=total_for(self.store.events, group_id, before.start, before.end),
)
rows = period_rows(self.store.events, group_id, period)
if not rows:
continue
text = render_period(
period,
rows,
trend,
since=self.store.events.first_day(group_id),
podium=period.kind != "week",
)
try:
await self.transport.send_text(text, group_id)
except Exception:
logger.exception("%s summary failed for group %s", period.kind, group_id)
async def announce_release(self) -> None:
"""Tell every watched group about a version it has not seen yet."""
await announce_all(

View File

@ -32,6 +32,7 @@ from signal_bot.stats.queries_period import (
)
from signal_bot.stats.render_day import DayView, render_day
from signal_bot.stats.render_extra import (
ME_TITLE,
favourite_hour,
render_crown,
render_me,
@ -130,6 +131,7 @@ async def all_records(ctx: CommandContext) -> None:
records.most_media_day(store.events, ctx.group_id, exclude=exclude),
records.longest_silence(history, periods.today()) if history else None,
personal,
store.events.first_day(ctx.group_id),
)
)
@ -140,14 +142,26 @@ async def crown(ctx: CommandContext) -> None:
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)))
await ctx.reply(
render_crown(
winners,
store.events.people(ctx.group_id),
store.events.first_day(ctx.group_id),
)
)
async def weekdays(ctx: CommandContext) -> None:
"""`!dni` -- the Monday-to-Sunday picture."""
store = ctx.store
history = every_day(store.events, ctx.group_id, exclude=backfilled_day(store, ctx.group_id))
await ctx.reply(render_weekdays(weekday_buckets(history), periods.weekday_of(periods.today())))
await ctx.reply(
render_weekdays(
weekday_buckets(history),
periods.weekday_of(periods.today()),
store.events.first_day(ctx.group_id),
)
)
async def me(ctx: CommandContext) -> None:
@ -162,7 +176,7 @@ async def me(ctx: CommandContext) -> None:
)
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.")
await ctx.reply(f"{ME_TITLE}\n\nNie mam jeszcze od ciebie ani jednej wiadomości.")
return
total = sum(row.messages for row in everyone)
winners = streaks.daily_winners(store.events, ctx.group_id, exclude=exclude)

View File

@ -18,10 +18,11 @@ fortnight of back-posts.
from __future__ import annotations
import datetime as dt
import logging
from typing import TYPE_CHECKING, Final
from signal_bot.stats.periods import shift
from signal_bot.stats.periods import Period, month_of, shift, week_of, year_of
if TYPE_CHECKING:
from signal_bot.store import Store
@ -61,6 +62,33 @@ def days_to_report(store: Store, group_id: str, latest: str) -> list[str]:
return days[-CATCHUP_LIMIT:]
SUNDAY: Final = 6
LAST_DAY_OF_DECEMBER: Final = "12-31"
def closing_periods(day: str) -> list[Period]:
"""The longer periods that ended with ``day``, in the order to post them.
Keyed off the day being *reported*, not off today. The nightly post covers
yesterday, so a week is complete exactly when yesterday was a Sunday --
which is also the only reading that stays correct when the bot has been
offline and is catching up on a week-old day.
No separate scheduler for these. Three background tasks firing at the same
wall-clock time into the same group is three independent ways for the
evening to go wrong, for no gain over an if-statement.
"""
date = dt.date.fromisoformat(day)
closing = []
if date.weekday() == SUNDAY:
closing.append(week_of(day))
if shift(day, 1)[8:] == "01":
closing.append(month_of(day))
if day.endswith(LAST_DAY_OF_DECEMBER):
closing.append(year_of(day))
return closing
def mark_reported(store: Store, group_id: str, day: str) -> None:
"""Record that a day no longer owes this group a report.

View File

@ -62,7 +62,9 @@ def summary_line(totals: DayTotals, *, approximate: bool = False) -> str:
"""
if not totals.messages:
return ""
parts = [] if approximate else [f"średnio {text.characters(totals.average_length)}"]
parts = (
[] if approximate else [f"średnio {text.characters(totals.average_length)} na wiadomość"]
)
if totals.commands:
parts.insert(0, f"z tego {text.commands(totals.commands)}")
if not parts:

View File

@ -22,7 +22,42 @@ CROWN: Final = "\U0001f451"
CALENDAR: Final = "\U0001f4c5"
CAMERA: Final = "\U0001f4f7"
QUIET: Final = "\U0001f92b"
NOTHING_YET: Final = "Za mało danych — wróć za kilka dni."
HOURS_IN_A_DAY: Final = 24
# Every command says what it is, whether or not it has data yet. Somebody
# typing !korona on day one used to get "za mało danych" and nothing else,
# which tells them neither what the command does nor when it will work.
TITLES: Final = {
"crown": f"{CROWN} Korona — kto danego dnia napisał najwięcej wiadomości",
"records": f"{TROPHY} Rekordy — najlepsze i najgorsze dni w historii grupy",
"weekdays": f"{CALENDAR} Dni tygodnia — ile średnio piszecie w każdy z nich",
}
# What each will show once there is enough history, so the empty answer is
# still an answer.
PROMISES: Final = {
"crown": (
"Pokażę: kto ma koronę teraz, jak długą serię, kto miał najdłuższą "
"w historii i ile dni każdy ją nosił."
),
"records": (
"Pokażę: najgadatliwszy dzień, najcichszy, dzień z największą liczbą "
"zdjęć, najdłuższą ciszę i rekord życiowy każdego z was."
),
"weekdays": (
"Pokażę: średnią liczbę wiadomości w poniedziałki, wtorki i tak dalej "
"— czyli czy weekendy są gadatliwsze od środy."
),
}
def nothing_yet(what: str, since: str | None = None) -> str:
"""The empty answer, which still says what the command is for.
A bare "za mało danych" tells somebody neither what they asked for nor
when it will work, which is exactly what happened within minutes of
0.1.0 going out.
"""
started = f"Liczę od {pl_day_month(since)}. " if since else ""
return "\n".join([TITLES[what], "", f"{started}Jeszcze za mało danych.", PROMISES[what]])
def _record_line(label: str, record: DayRecord | None, unit: str) -> str | None:
@ -37,9 +72,10 @@ def render_records(
media: DayRecord | None,
silence: records.Silence | None,
personal: list[tuple[str, DayRecord]],
since: str | None = None,
) -> str:
"""Every all-time record the group has set."""
lines = [f"{TROPHY} Rekordy"]
lines = [TITLES["records"]]
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"),
@ -57,16 +93,17 @@ def render_records(
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
return "\n".join(lines) if len(lines) > 1 else nothing_yet("records", since)
def render_crown(
winners: dict[str, list[tuple[str, str]]],
people: list[Person],
since: str | None = None,
) -> str:
"""Who holds the crown now, who held it longest, and who has held it most."""
if not winners:
return NOTHING_YET
return nothing_yet("crown", since)
# 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.
@ -76,7 +113,7 @@ def render_crown(
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",
TITLES["crown"],
f"Teraz: {names} — {text.days(current[0].length)} z rzędu",
(
f"Najdłuższa seria: {longest.display_name} — {text.days(longest.length)} "
@ -93,11 +130,11 @@ def render_crown(
return "\n".join(lines)
def render_weekdays(buckets: dict[int, list[int]], today: int) -> str:
def render_weekdays(buckets: dict[int, list[int]], today: int, since: str | None = None) -> str:
"""The Monday-to-Sunday picture, with today's weekday called out."""
if not buckets:
return NOTHING_YET
lines = [f"{CALENDAR} Dni tygodnia"]
return nothing_yet("weekdays", since)
lines = [TITLES["weekdays"]]
for index in range(len(WEEKDAY_PLURAL)):
days = buckets.get(index)
if not days:
@ -110,6 +147,9 @@ def render_weekdays(buckets: dict[int, list[int]], today: int) -> str:
return "\n".join(lines)
ME_TITLE: Final = "Twoje liczby w tej grupie"
def render_me(
name: str,
total: int,
@ -119,12 +159,15 @@ def render_me(
streak: int,
) -> str:
"""One person's own numbers."""
lines = [f"{name} — {text.messages(total)} w historii"]
lines = [ME_TITLE, "", 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")
lines.append(
f"Najczęściej piszesz między {favourite_hour:02d}:00 a "
f"{(favourite_hour + 1) % HOURS_IN_A_DAY:02d}:00"
)
if streak:
lines.append(f"{CROWN} Korona: {text.days(streak)} z rzędu")
return "\n".join(lines)

View File

@ -28,7 +28,7 @@ PATCHES_PER_MINOR: Final = 8
# Which release this build is. Bump by one per release; everything else,
# including the version string in pyproject.toml, follows from it.
RELEASE_ORDINAL: Final = 8
RELEASE_ORDINAL: Final = 10
_POPES_FILE: Final = Path(__file__).with_name("popes.json")

View File

@ -4,31 +4,25 @@
from __future__ import annotations
import datetime as dt
from dataclasses import dataclass
from typing import TYPE_CHECKING
import httpx
from signal_bot.bot import Bot, build_bot, now_local
from signal_bot.discovery import GroupDirectory
from signal_bot.liveness import Liveness
from signal_bot.stats.events import MessageEvent
from signal_bot.stats.nightly import LAST_REPORTED_KEY, mark_reported
from signal_bot.stats.periods import WARSAW
from signal_bot.transport_fake import FakeTransport
from signal_bot.trust import InviteTrust
from tests.conftest import (
SECOND_GROUP,
WATCHED_GROUP,
envelope,
group_entry,
listing_client,
mock_client,
)
if TYPE_CHECKING:
from signal_bot.config import Config
from signal_bot.discovery import GroupDirectory
from signal_bot.store import Store
from signal_bot.transport_fake import FakeTransport
# The report covers the previous full day, so the tests freeze "now" and
@ -75,105 +69,6 @@ def test_build_bot_registers_the_animal_commands(
assert bot.dispatcher.registry.resolve("!pies") is not None
async def test_publish_report_posts_each_group_its_own_tally(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
"""Every group gets its own counts, in its own chat, and only its own."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 1)
wrote(store, SECOND_GROUP, "u2", "Bob", 2)
await _bot(config, store, transport, directory).publish_report()
assert [m.recipient for m in transport.sent] == [WATCHED_GROUP, SECOND_GROUP]
assert "Alice" in transport.texts[0]
assert "Bob" in transport.texts[1]
assert "Alice" not in transport.texts[1]
async def test_the_report_covers_yesterday_not_today(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
"""Today's traffic belongs to tomorrow's report, not tonight's."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 1, day=YESTERDAY)
wrote(store, WATCHED_GROUP, "u2", "Bob", 9, day="2026-09-02")
await _bot(config, store, transport, directory).publish_report()
assert "Alice" in transport.texts[0]
assert "Bob" not in transport.texts[0]
async def test_a_missed_day_is_posted_when_the_bot_returns(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
"""An outage over 21:37 used to lose that day's report entirely."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 2, day="2026-08-30")
wrote(store, WATCHED_GROUP, "u1", "Alice", 3, day="2026-08-31")
wrote(store, WATCHED_GROUP, "u1", "Alice", 4, day=YESTERDAY)
mark_reported(store, WATCHED_GROUP, "2026-08-29")
await _bot(config, store, transport, directory).publish_report()
assert len(transport.texts) == 3
assert "30 sierpnia" in transport.texts[0]
assert "31 sierpnia" in transport.texts[1]
assert "1 września" in transport.texts[2]
assert store.meta(WATCHED_GROUP, LAST_REPORTED_KEY) == YESTERDAY
async def test_a_day_nobody_spoke_is_settled_not_retried_forever(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
wrote(store, WATCHED_GROUP, "u1", "Alice", 1, day=YESTERDAY)
mark_reported(store, WATCHED_GROUP, "2026-08-30")
await _bot(config, store, transport, directory).publish_report()
assert len(transport.texts) == 1
assert store.meta(WATCHED_GROUP, LAST_REPORTED_KEY) == YESTERDAY
async def test_a_failed_send_leaves_its_day_unmarked(
config: Config, store: Store, directory: GroupDirectory
) -> None:
"""So the next run retries it instead of losing the day silently."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 1, day=YESTERDAY)
mark_reported(store, WATCHED_GROUP, "2026-08-31")
transport = RefusingTransport(refuses=WATCHED_GROUP)
await _bot(config, store, transport, directory).publish_report()
assert store.meta(WATCHED_GROUP, LAST_REPORTED_KEY) == "2026-08-31"
async def test_publishing_twice_posts_once(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
"""The marker is what stops a restart re-posting the same day."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 3)
bot = _bot(config, store, transport, directory)
await bot.publish_report()
await bot.publish_report()
assert len(transport.texts) == 1
async def test_nothing_is_deleted_after_publishing(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
"""The log is append-only; a second run renders the same day again."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 3)
bot = _bot(config, store, transport, directory)
await bot.publish_report()
first = transport.texts[0]
store.set_meta(WATCHED_GROUP, LAST_REPORTED_KEY, "2026-08-31")
await bot.publish_report()
assert transport.texts[1] == first
async def test_publish_report_falls_back_to_uuid_when_unnamed(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
wrote(store, WATCHED_GROUP, "u1", "u1", 1)
await _bot(config, store, transport, directory).publish_report()
assert "u1" in transport.texts[0]
async def test_listen_dispatches_every_frame(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
@ -183,53 +78,3 @@ async def test_listen_dispatches_every_frame(
"SELECT COUNT(*) AS n FROM message_events WHERE group_id = ?", (WATCHED_GROUP,)
).fetchone()
assert row["n"] == 1
@dataclass
class RefusingTransport(FakeTransport):
"""A transport that rejects one group, the way a removal from it would."""
refuses: str = ""
async def send_text(self, text: str, recipient: str) -> None:
"""Record the send, unless this is the group that refuses them."""
if recipient == self.refuses:
msg = "removed from the group"
raise RuntimeError(msg)
await super().send_text(text, recipient)
async def test_one_group_failing_its_report_does_not_cost_the_others(
config: Config, store: Store, directory: GroupDirectory
) -> None:
"""A failed send must not skip the next group."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 1)
wrote(store, SECOND_GROUP, "u2", "Bob", 1)
transport = RefusingTransport(refuses=WATCHED_GROUP)
await _bot(config, store, transport, directory).publish_report()
assert [m.recipient for m in transport.sent] == [SECOND_GROUP]
assert "Bob" in transport.texts[0]
async def test_a_quiet_group_is_logged_rather_than_posted_into(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
"""The bot sits in every group it was added to; a nightly ping is noise."""
wrote(store, SECOND_GROUP, "u2", "Bob", 1)
await _bot(config, store, transport, directory).publish_report()
assert [m.recipient for m in transport.sent] == [SECOND_GROUP]
async def test_the_report_follows_the_live_group_set(
config: Config, store: Store, transport: FakeTransport
) -> None:
"""Groups come from the directory, not from .env, so a new one is included."""
client = listing_client([group_entry(WATCHED_GROUP), group_entry(SECOND_GROUP)])
directory = GroupDirectory(config, client, store, InviteTrust(()))
await directory.refresh()
wrote(store, WATCHED_GROUP, "u1", "Alice", 1)
wrote(store, SECOND_GROUP, "u2", "Bob", 1)
await _bot(config, store, transport, directory).publish_report()
assert [m.recipient for m in transport.sent] == [WATCHED_GROUP, SECOND_GROUP]

148
tests/test_bot_catchup.py Normal file
View File

@ -0,0 +1,148 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Coming back from an outage: the days and the periods the bot still owes."""
from __future__ import annotations
import datetime as dt
from typing import TYPE_CHECKING
import httpx
from signal_bot.bot import build_bot
from signal_bot.liveness import Liveness
from signal_bot.stats.nightly import LAST_REPORTED_KEY, mark_reported
from signal_bot.stats.periods import WARSAW
from signal_bot.transport_fake import FakeTransport
from tests.conftest import WATCHED_GROUP, mock_client
from tests.test_bot_report import YESTERDAY, RefusingTransport, _bot, wrote
if TYPE_CHECKING:
from signal_bot.config import Config
from signal_bot.discovery import GroupDirectory
from signal_bot.store import Store
async def test_a_missed_day_is_posted_when_the_bot_returns(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
"""An outage over 21:37 used to lose that day's report entirely."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 2, day="2026-08-30")
wrote(store, WATCHED_GROUP, "u1", "Alice", 3, day="2026-08-31")
wrote(store, WATCHED_GROUP, "u1", "Alice", 4, day=YESTERDAY)
mark_reported(store, WATCHED_GROUP, "2026-08-29")
await _bot(config, store, transport, directory).publish_report()
# Five, not three: catching up on the days also catches up the periods
# that closed inside them. The 30th was a Sunday and the 31st ended
# August, so each is followed by its own summary.
assert len(transport.texts) == 5
assert "30 sierpnia" in transport.texts[0]
assert "tydzień 35" in transport.texts[1]
assert "31 sierpnia" in transport.texts[2]
assert "sierpień 2026" in transport.texts[3]
assert "1 września" in transport.texts[4]
assert store.meta(WATCHED_GROUP, LAST_REPORTED_KEY) == YESTERDAY
async def test_a_day_nobody_spoke_is_settled_not_retried_forever(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
wrote(store, WATCHED_GROUP, "u1", "Alice", 1, day=YESTERDAY)
mark_reported(store, WATCHED_GROUP, "2026-08-30")
await _bot(config, store, transport, directory).publish_report()
assert len(transport.texts) == 1
assert store.meta(WATCHED_GROUP, LAST_REPORTED_KEY) == YESTERDAY
async def test_a_failed_send_leaves_its_day_unmarked(
config: Config, store: Store, directory: GroupDirectory
) -> None:
"""So the next run retries it instead of losing the day silently."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 1, day=YESTERDAY)
mark_reported(store, WATCHED_GROUP, "2026-08-31")
transport = RefusingTransport(refuses=WATCHED_GROUP)
await _bot(config, store, transport, directory).publish_report()
assert store.meta(WATCHED_GROUP, LAST_REPORTED_KEY) == "2026-08-31"
async def test_publishing_twice_posts_once(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
"""The marker is what stops a restart re-posting the same day."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 3)
bot = _bot(config, store, transport, directory)
await bot.publish_report()
await bot.publish_report()
assert len(transport.texts) == 1
async def test_a_sunday_also_posts_the_week(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
"""One scheduler, a date predicate -- not three tasks racing at 21:37."""
sunday = "2026-08-30"
wrote(store, WATCHED_GROUP, "u1", "Alice", 4, day="2026-08-28")
wrote(store, WATCHED_GROUP, "u1", "Alice", 6, day=sunday)
mark_reported(store, WATCHED_GROUP, "2026-08-29")
at_monday = dt.datetime(2026, 8, 31, 21, 37, tzinfo=WARSAW)
client = mock_client(lambda r: httpx.Response(200))
bot = build_bot(
config,
client,
store,
transport,
directory,
Liveness(config, client),
clock=lambda: at_monday,
)
await bot.publish_report()
assert len(transport.texts) == 2
assert "Niedziela, 30 sierpnia" in transport.texts[0]
assert "tydzień 35" in transport.texts[1]
async def test_an_ordinary_day_posts_only_the_day(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
wrote(store, WATCHED_GROUP, "u1", "Alice", 4)
await _bot(config, store, transport, directory).publish_report()
assert len(transport.texts) == 1
async def test_a_failing_weekly_summary_does_not_unmark_the_day(
config: Config, store: Store, directory: GroupDirectory
) -> None:
"""The day was posted; retrying it tomorrow would repeat it."""
sunday = "2026-08-30"
wrote(store, WATCHED_GROUP, "u1", "Alice", 6, day=sunday)
mark_reported(store, WATCHED_GROUP, "2026-08-29")
class RefuseSecond(FakeTransport):
"""Lets the day through and rejects everything after it."""
async def send_text(self, text: str, recipient: str) -> None:
if self.sent:
msg = "no"
raise RuntimeError(msg)
await super().send_text(text, recipient)
transport = RefuseSecond()
client = mock_client(lambda r: httpx.Response(200))
bot = build_bot(
config,
client,
store,
transport,
directory,
Liveness(config, client),
clock=lambda: dt.datetime(2026, 8, 31, 21, 37, tzinfo=WARSAW),
)
await bot.publish_report()
assert store.meta(WATCHED_GROUP, LAST_REPORTED_KEY) == sunday

156
tests/test_bot_report.py Normal file
View File

@ -0,0 +1,156 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The nightly report: which day, which groups, and catching up after an outage."""
from __future__ import annotations
import datetime as dt
from dataclasses import dataclass
from typing import TYPE_CHECKING
import httpx
from signal_bot.bot import Bot, build_bot
from signal_bot.discovery import GroupDirectory
from signal_bot.liveness import Liveness
from signal_bot.stats.events import MessageEvent
from signal_bot.stats.nightly import LAST_REPORTED_KEY
from signal_bot.stats.periods import WARSAW
from signal_bot.transport_fake import FakeTransport
from signal_bot.trust import InviteTrust
from tests.conftest import (
SECOND_GROUP,
WATCHED_GROUP,
group_entry,
listing_client,
mock_client,
)
if TYPE_CHECKING:
from signal_bot.config import Config
from signal_bot.store import Store
# The report covers the previous full day, so the tests freeze "now" and
# write their events into the day before it.
NOW = dt.datetime(2026, 9, 2, 21, 37, tzinfo=WARSAW)
YESTERDAY = "2026-09-01"
def _bot(config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory) -> Bot:
client = mock_client(lambda r: httpx.Response(200))
return build_bot(
config, client, store, transport, directory, Liveness(config, client), clock=lambda: NOW
)
def wrote(
store: Store, group_id: str, uuid: str, name: str, times: int, *, day: str = YESTERDAY
) -> None:
"""Put ``times`` messages from one person into one group on one day."""
for i in range(times):
store.events.record(
MessageEvent(
group_id=group_id,
uuid=uuid,
display_name=name,
sent_at_ms=i + 1,
day=day,
local_hour=12,
char_len=5,
)
)
store.events.note_person(group_id, uuid, name, "", day)
async def test_publish_report_posts_each_group_its_own_tally(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
"""Every group gets its own counts, in its own chat, and only its own."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 1)
wrote(store, SECOND_GROUP, "u2", "Bob", 2)
await _bot(config, store, transport, directory).publish_report()
assert [m.recipient for m in transport.sent] == [WATCHED_GROUP, SECOND_GROUP]
assert "Alice" in transport.texts[0]
assert "Bob" in transport.texts[1]
assert "Alice" not in transport.texts[1]
async def test_the_report_covers_yesterday_not_today(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
"""Today's traffic belongs to tomorrow's report, not tonight's."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 1, day=YESTERDAY)
wrote(store, WATCHED_GROUP, "u2", "Bob", 9, day="2026-09-02")
await _bot(config, store, transport, directory).publish_report()
assert "Alice" in transport.texts[0]
assert "Bob" not in transport.texts[0]
async def test_nothing_is_deleted_after_publishing(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
"""The log is append-only; a second run renders the same day again."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 3)
bot = _bot(config, store, transport, directory)
await bot.publish_report()
first = transport.texts[0]
store.set_meta(WATCHED_GROUP, LAST_REPORTED_KEY, "2026-08-31")
await bot.publish_report()
assert transport.texts[1] == first
async def test_publish_report_falls_back_to_uuid_when_unnamed(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
wrote(store, WATCHED_GROUP, "u1", "u1", 1)
await _bot(config, store, transport, directory).publish_report()
assert "u1" in transport.texts[0]
@dataclass
class RefusingTransport(FakeTransport):
"""A transport that rejects one group, the way a removal from it would."""
refuses: str = ""
async def send_text(self, text: str, recipient: str) -> None:
"""Record the send, unless this is the group that refuses them."""
if recipient == self.refuses:
msg = "removed from the group"
raise RuntimeError(msg)
await super().send_text(text, recipient)
async def test_one_group_failing_its_report_does_not_cost_the_others(
config: Config, store: Store, directory: GroupDirectory
) -> None:
"""A failed send must not skip the next group."""
wrote(store, WATCHED_GROUP, "u1", "Alice", 1)
wrote(store, SECOND_GROUP, "u2", "Bob", 1)
transport = RefusingTransport(refuses=WATCHED_GROUP)
await _bot(config, store, transport, directory).publish_report()
assert [m.recipient for m in transport.sent] == [SECOND_GROUP]
assert "Bob" in transport.texts[0]
async def test_a_quiet_group_is_logged_rather_than_posted_into(
config: Config, store: Store, transport: FakeTransport, directory: GroupDirectory
) -> None:
"""The bot sits in every group it was added to; a nightly ping is noise."""
wrote(store, SECOND_GROUP, "u2", "Bob", 1)
await _bot(config, store, transport, directory).publish_report()
assert [m.recipient for m in transport.sent] == [SECOND_GROUP]
async def test_the_report_follows_the_live_group_set(
config: Config, store: Store, transport: FakeTransport
) -> None:
"""Groups come from the directory, not from .env, so a new one is included."""
client = listing_client([group_entry(WATCHED_GROUP), group_entry(SECOND_GROUP)])
directory = GroupDirectory(config, client, store, InviteTrust(()))
await directory.refresh()
wrote(store, WATCHED_GROUP, "u1", "Alice", 1)
wrote(store, SECOND_GROUP, "u2", "Bob", 1)
await _bot(config, store, transport, directory).publish_report()
assert [m.recipient for m in transport.sent] == [WATCHED_GROUP, SECOND_GROUP]

View File

@ -99,3 +99,65 @@ def test_malformed_group_info_reads_as_direct_message(group_info: object) -> Non
message = parse_envelope(raw)
assert message is not None
assert message.is_direct_message
# The exact shape of a live frame captured on 2026-08-30: a text reply to
# somebody else's photo. The photo is nested inside `quote`, not at the top
# level, and counting it would credit the replier with a photo they did not
# post -- the same wrong-nesting-level mistake that once made the bot ignore
# its own stickers.
REPLY_TO_A_PHOTO = json.dumps(
{
"envelope": {
"sourceUuid": "u1",
"sourceName": "Mithra",
"sourceNumber": None,
"timestamp": 1756576440000,
"dataMessage": {
"timestamp": 1756576440000,
"message": "ha",
"viewOnce": False,
"expiresInSeconds": 0,
"isExpirationUpdate": False,
"groupInfo": {
"groupId": WATCHED_GROUP,
"groupName": "x",
"revision": 1,
"type": "DELIVER",
},
"quote": {
"id": 1756576000000,
"author": "x",
"authorNumber": "+15555550123",
"authorUuid": "u2",
"text": "",
"attachments": [
{
"contentType": "image/jpeg",
"filename": "photo.jpg",
"thumbnail": {
"contentType": "image/jpeg",
"caption": None,
"id": "t",
"size": 1,
"width": 1,
"height": 1,
"filename": "thumb.jpg",
"uploadTimestamp": 1756576000000,
},
}
],
},
},
}
}
)
def test_a_quoted_photo_is_not_the_replier_s_photo() -> None:
"""`quote` carries its own attachments array. Only the top level counts."""
message = parse_envelope(REPLY_TO_A_PHOTO)
assert message is not None
assert message.attachment_types == ()
assert message.is_reply is True
assert message.text == "ha"

View File

@ -136,7 +136,7 @@ async def test_me_reports_the_asker(store: Store) -> None:
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
assert "Najczęściej piszesz między 23:00 a 00:00" in answer
async def test_me_is_honest_with_somebody_who_never_wrote(store: Store) -> None:

View File

@ -5,9 +5,12 @@ from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from signal_bot.stats.nightly import (
CATCHUP_LIMIT,
LAST_REPORTED_KEY,
closing_periods,
days_to_report,
mark_reported,
)
@ -73,3 +76,26 @@ def test_a_month_boundary_is_crossed_by_the_date(store: Store) -> None:
"2026-09-01",
"2026-09-02",
]
@pytest.mark.parametrize(
("day", "expected"),
[
# A Sunday closes a week.
("2026-09-06", ["tydzień 36"]),
# The last day of a month closes it.
("2026-09-30", ["wrzesień 2026"]),
# 31 December closes both the month and the year.
("2026-12-31", ["grudzień 2026", "2026"]),
# A Sunday mid-month closes the week only.
("2026-08-30", ["tydzień 35"]),
# An ordinary Tuesday closes nothing.
("2026-09-15", []),
# 28 February in a leap year is not a month end.
("2028-02-28", []),
("2028-02-29", ["luty 2028"]),
],
)
def test_closing_periods(day: str, expected: list[str]) -> None:
"""Keyed off the day being reported, so a catch-up still gets it right."""
assert [period.label for period in closing_periods(day)] == expected

View File

@ -51,7 +51,7 @@ def test_the_nightly_block_for_a_real_day() -> None:
"6. Cezary Bizoń — 15\n"
"🏆 Mithra 76 — rekord życiowy (poprzedni 71)\n"
"Cisza: Marek\n"
"Średnio 47 znaków.\n"
"Średnio 47 znaków na wiadomość.\n"
"(liczymy od 30 sierpnia)"
)
assert len(rendered.split("\n")) <= MAX_LINES
@ -66,7 +66,7 @@ def test_a_day_with_no_media_shows_no_camera() -> None:
def test_commands_are_broken_out() -> None:
day = rows([("kuhy", 10, 0)], commands=4)
assert summary_line(day_totals(day)) == "Z tego 4 komendy, średnio 47 znaków."
assert summary_line(day_totals(day)) == "Z tego 4 komendy, średnio 47 znaków na wiadomość."
def test_an_approximate_day_claims_no_average_length() -> None:

View File

@ -9,7 +9,7 @@ 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,
ME_TITLE,
render_crown,
render_me,
render_records,
@ -60,8 +60,25 @@ def test_medals_only_appear_on_a_podium() -> None:
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_an_empty_command_still_says_what_it_is_for() -> None:
"""A bare "za mało danych" tells nobody what they asked for.
Reported by the group within minutes of 0.1.0: somebody typed !korona,
got only that line, and learned neither what the command does nor when
it would work.
"""
for rendered in (
render_records({}, None, None, [], "2026-08-30"),
render_crown({}, [], "2026-08-30"),
render_weekdays({}, 0, "2026-08-30"),
):
assert "Jeszcze za mało danych." in rendered
assert "Pokażę:" in rendered
assert "Liczę od 30 sierpnia." in rendered
def test_an_empty_command_without_a_start_date_omits_it() -> None:
assert "Liczę od" not in render_crown({}, [])
def test_records_reports_each_kind_it_has() -> None:
@ -78,10 +95,6 @@ def test_records_reports_each_kind_it_has() -> None:
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")],
@ -95,10 +108,6 @@ def test_the_crown_reports_now_longest_and_totals() -> None:
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
@ -110,11 +119,11 @@ def test_weekdays_skips_days_never_recorded() -> None:
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%"
assert rendered == f"{ME_TITLE}\n\nkuhy — 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 "Najczęściej piszesz między 23:00 a 00:00" in rendered
assert "Korona: 2 dni z rzędu" in rendered