Compare commits

...

46 Commits

Author SHA1 Message Date
6c98917dfa fix: the operator's uuid was still a fixture in the envelope-shape test
Some checks are pending
CI / check (push) Waiting to run
The scrub before this one caught the truncated spelling in the document and
missed the one in the test, which held the first half of a real Signal uuid
and the account name beside it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017w1HZ3cZ7neL3rFdQ6VMBA
2026-08-30 23:04:42 +02:00
770abed001 fix: take real people, numbers and a member's uuid out of a public repository
This repository is public, and five things in it were not invented.

The worst was mine, today: the tagger's help text used the group's actual
first names and nicknames as its worked example, in a file that is on
GitHub. It uses ala/basia/celina now, like every other example here.

The rest predate this work. DOCS-signal-envelopes.md carried the operator's
own phone number and the bot's, captured from a live envelope; conftest.py
had the same number as its trusted inviter; and test_trust.py pinned a group
member's full Signal uuid as a fixture. Numbers keep their shape so the
documents still show what a real envelope looks like, but no digit of them
belongs to anybody.

Comments that reached for a real first name to illustrate the diacritic case
now use an invented one.

None of this removes them from the history, which is a separate decision.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017w1HZ3cZ7neL3rFdQ6VMBA
2026-08-30 23:01:26 +02:00
b7ee16a416 fix: the tagger ends on a screen, not on a button that stops working
Clicking "dalej" on the last photo did nothing, because move() clamped at
the end. Everything had in fact been saved -- each toggle writes tags.json
on the spot -- but the only way to find that out was to stop the tagger and
read its summary, so the last photo answered "did that work?" with silence.

The end of the album is now a screen: it says Gotowe, prints how many photos
each command has, and offers a way back into the photos.

The counts are distinct files rather than a sum per reading. A photo showing
two of the three people an "either of them" entry covers is one photo that
command can return, and summing claimed it twice.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017w1HZ3cZ7neL3rFdQ6VMBA
2026-08-30 22:57:45 +02:00
c39e843baf fix: the evening report is one message, not one per thing it has to say
Tomorrow's run would have posted four times into the same group: the day
the bot owed from the catch-up, the week that closed inside it, today, and
August's summary. Four notifications in one evening is how a daily tally
becomes something people mute.

They are blocks in a single message now, separated by a rule because Signal
renders no markdown. That also makes the send atomic: the group gets all of
it or none of it, and nothing is marked either way, where before a day was
marked before its own weekly summary had even been attempted -- so a summary
that failed was simply lost.

The composition moved to reporting.py, both because bot.py hit the 250-line
cap and because it is worth having pure: "what would the group be told?" is
now answerable with no transport and no send.

The closing-time caveat reads the clock instead of REPORT_HOUR. The
scheduled run fires at the configured minute and still says exactly that; a
run started by hand at some other hour now tells the truth rather than
repeating a time nobody waited for.

The 0.1.6 entry gains a bullet rather than taking a new version: no group has
been told about 0.1.6 yet -- every one of them is still recorded at 0.1.5 --
so the release it describes has not happened from their side.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017w1HZ3cZ7neL3rFdQ6VMBA
2026-08-30 22:49:51 +02:00
2cc7c88d81 fix: the tagger pre-selected a group, which is how an album reaches the wrong chat
The first group in the account's listing was checked by default, and the
first group in this account's listing is a test group. Somebody who typed
the names, hit save and never looked at the radios would have scoped a
private album to the wrong chat -- silently, because the commands then
simply do nothing in the chat they were meant for. Nothing is pre-selected
now, and saving without a group is refused.

Also replaces a test of mine that failed one run in sixteen: it drew a
two-way random choice five times and demanded both outcomes. The property
worth pinning is that a choice lands on a reading that *has* photos, which
is deterministic when only one of them does.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017w1HZ3cZ7neL3rFdQ6VMBA
2026-08-30 22:41:42 +02:00
581a42c88e fix: the release preview can be run, and can preview a group's real delta
Two things it could not do, both found trying to preview this release.

It read SELFTEST_GROUPS off os.environ before anything had loaded .env, so
its own documented invocation refused every group unless the variable had
been exported by hand. Fail-closed, so it never posted anywhere wrong -- it
simply never posted at all.

And it always rendered the delta from the *running* build, which is empty
once the bump is committed. Three releases landing together are still one
announcement to a group recorded three versions back, so --seen renders what
that group will actually be shown rather than what the current build would
add.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017w1HZ3cZ7neL3rFdQ6VMBA
2026-08-30 22:37:22 +02:00
d00a646f17 release: 0.2.0 «Urbanus I» — a private photo album, and a tagger for it
Per-person photo commands, where the mechanism is public and the album is
not. Nothing identifying is in this repository: who the people are, what
fires their photos and which file shows whom all live in one directory
outside it, and the tests, the docs and the offline e2e run use three
invented people instead.

Several names in one message intersect -- "!alfa beta" is a photo with both
-- and where an entry offers a choice the bot picks among the readings that
actually have a photo, so a question the album could answer is not refused.
A combination nobody photographed gets one line rather than silence, which
from the group's side is indistinguishable from a broken bot.

Scoping is enforced in the dispatcher, not in the handler: a command the
group is not allowed resolves to nothing, so it is not answered, not counted
as a command, and never named in a log line outside its own groups. A
handler that quietly returned would leak all three. Commands are named by
pseudonym (pack:p1), so the journal and command_uses say somebody asked for
a photo and nothing about whose.

Video works: the attachment goes out as data:video/mp4;filename=...;base64,
which is the container's own spelling, read off its /swagger/doc.json.
Told it is a photo, Signal renders a clip as an unplayable file.

tool/tagger.py serves one page on loopback to fill the album in -- names are
typed into the page, never as arguments, and it prints how many photos each
command would have when it stops, because a command with zero is dead on
arrival.

Also renames the real people who were still sitting in the stats test
fixtures. They remain in the history; the point is that nothing new is
added to it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017w1HZ3cZ7neL3rFdQ6VMBA
2026-08-30 22:35:41 +02:00
116e229488 release: 0.1.7 «Callistus I» — a version now says which pope, and when
"Wersja 0.1.7 «Callistus I»" told nobody whether Callistus was the
fifteenth pope or the hundredth, and the changelog was the one place the
ladder is actually read. pope_line() derives both facts from popes.json --
the ordinal, and the `reign` string exactly as the table spells it, so the
one reigning pope keeps his single year instead of being padded into a
range he never had.

It appears in all four places a version is named: the group announcement
(header and every block of a backlog), each section of DOCS-changelog.md,
/healthz, and the !papiez caption, which now describes the release's pope
in the same sentence it uses for every other one.

The changelog's copy is checked rather than trusted, like the heading name
already was: a test walks the raw file and compares each line against
popes.json, so a hand-edited ordinal fails here instead of in a group.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017w1HZ3cZ7neL3rFdQ6VMBA
2026-08-30 22:12:09 +02:00
8fe642a159 release: 0.1.6 «Zephyrinus» — 21:37 reports today, not yesterday
The scheduler fired exactly on time tonight and posted nothing, because
publish_report covered the previous full day and the bot's first recorded
day was today: "no messages in group.MmxtV1RD... on 2026-08-29". Correct by
code, a day late to everybody reading the group.

So the report covers the day it runs on. The count closes at the report
time and render_day says so, because a total that quietly omits three hours
is worse than one that admits to it. Everything that made a late day
recoverable stays: the per-group marker still prevents a double post, and
days_to_report still yields every day an outage swallowed.

closing_periods keeps taking a day rather than reading a clock, so a week
now closes on the Sunday evening it ends -- off a day that is itself still
running -- and a catch-up on a week-old Sunday still gets it right.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017w1HZ3cZ7neL3rFdQ6VMBA
2026-08-30 22:09:13 +02:00
c82c75ed5f release: 0.1.5 «Victor I» — the version has a face now
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 21:44:20 +02:00
c038793600 fix: the release preview sends the app's User-Agent, which Commons requires
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 21:43:33 +02:00
69bd651ef9 feat: preview the next release's announcement in a test group, without releasing
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 21:41:44 +02:00
9c6dbe7748 test: the render tests get their own file, under the 250-line cap
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 21:34:23 +02:00
dc823a2ce4 fix: a refused attachment no longer costs a group its release notes
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 21:33:56 +02:00
b70c18bbc1 feat: releases are named in Latin, and land with the pope's portrait and article
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 21:28:41 +02:00
144f5de28c release: 0.1.4 «Eleuteriusz» — the list of commands lives in the chat now
Thirteen commands, and the only list of them was a README table nobody in a
Signal group can read — which had itself gone stale two releases earlier,
still advertising four commands after nine more had shipped. 0.1.1 gave each
command an output that says what the command is; that only helps once you
already know to type it.

!pomoc (also !pomocy, !help, !komendy, !commands) prints all fourteen,
grouped, one Polish line each.

The interesting part is that it cannot go stale. CommandRegistry.register now
takes the description as a REQUIRED argument, so a command that does not
explain itself does not compile; and render_help prints any command that
help_command.GROUPS forgot to file, under no heading, rather than dropping
it. Two independent ways to fail closed, because the README proved that a
hand-maintained second list is a list that drifts.

Command also gained `primary`, the first raw alias. The trigger set could not
supply it: those are folded skeletons in an unordered frozenset, so all that
survives of "!papież" there is "!papiez", and the styled Unicode aliases come
out as zalgo. aliases.json already lists the canonical Polish spelling first.

The full trigger table moves to DOCS-commands.md. It did not fit in README —
that file was already sitting exactly on the shared 250-line cap, and the
gate caught the overflow on the first commit attempt.

Exercised in testbot at the unbumped version before this bump: the live
dispatcher ran it and posted the list, journal clean. pytest 708 green at
100% branch coverage, e2e green including a new scenario that asserts !pomoc
mentions a command registered by a different module.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017w1HZ3cZ7neL3rFdQ6VMBA
2026-08-30 21:08:02 +02:00
3a79447ce2 release: 0.1.3 «Soter» — the wait it tells you is the wait that works
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 20:43:28 +02:00
a925928f12 fix: a refused command no longer re-arms its own cooldown
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 20:39:14 +02:00
ed51aaf3eb release: 0.1.2 «Anicet» — the favourite hour is a real one
Ships the fix in 8fb053b, which had been running unreleased since the
live database was migrated.

!ja was reporting the same hour, 12:00, to every member of the group.
That was the placeholder hour on the 342 messages carried over from the
pre-0.1.0 counter, which have no timestamps — and favourite_hour was the
one query that never excluded the backfilled day, so the synthetic noons
outvoted every real evening. The genuine answer is 19:00-21:00.

The absent hour is now -1 rather than a real-looking 12, and hour
queries filter it out, so forgetting the exclusion can no longer invent
an answer. Somebody whose only messages are backfilled gets no hour line
at all instead of a made-up one.

Exercised in testbot before the bump; kuhy confirmed the release.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 20:18:22 +02:00
8fb053bb3b fix: !ja told everybody their favourite hour was noon
Reported from the group: the same "Najczęściej piszesz między 12:00 a
13:00" line came back for Ala and for Jan Nowak, which is too much
of a coincidence to be a statistic.

It was the backfill. The 342 messages carried over from the pre-0.1.0
counter have no timestamps, so the seeded rows got a placeholder hour of
12 -- and favourite_hour was the one query that never excluded the
backfilled day. For every person those synthetic noons outnumbered every
real message they had sent since, so all seven got the same answer. The
genuine hours are 19-21: this group talks in the evening.

The comment above that placeholder said "the day is marked anyway, so
nothing that cares about hours will read these", which is exactly the
kind of reasoning that stops being true the moment somebody adds a
query. So the fix is not another `exclude` argument to remember: the
absent hour is now -1, which no real hour can be, and hour queries
filter `local_hour >= 0`. Forgetting the exclusion can no longer invent
an answer, and night_owl gets the same guard even though its 0..2 window
happened to miss the old placeholder.

Live database migrated with the service stopped and a backup taken: 342
rows moved from noon to unknown. Verified afterwards on the real data --
Ala 19:00, Jan Nowak 19:00, kuhy 20:00, and the two people whose
only messages are backfilled correctly get no hour line at all.

Not released. Sitting at 0.1.1 until kuhy says otherwise.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 20:15:20 +02:00
752e04a8f4 release: 0.1.1 «Pius I» — commands that explain themselves
Two things the group hit within minutes of 0.1.0, both reported by real
users rather than found by a test.

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

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

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 20:09:14 +02:00
c2fb3c5fac 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
cb35f5a248 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
84d2e7a9d1 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
56307201b0 feat: nine commands for asking the statistics questions
!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 ala" 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
22fead7d18 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
6a6ba3a51a 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
cd02d4b4ec 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
b5a33b558c feat: the bot can describe an envelope without quoting anybody
DOCS-signal-envelopes.md exists because this wire format is not obvious
and guessing at it has cost real bugs -- the sticker read off the wrong
nesting level, and 0.0.3's !gekon shipping green on an assumption nobody
had checked against the live API. The recurring cost is that answering
"what does a frame with an attachment actually look like?" needed a code
change, a restart, and somebody sending one at the right moment.

So at DEBUG the dispatcher now logs each frame's *shape*: keys and value
types, never values. Two fields keep their values because they are wire
format rather than anything a person said -- a MIME type and a groupInfo
type. A message body, a name, a number, a uuid, quoted text and a
sticker id all come out as "str". An album collapses to one element and
a count instead of printing the same dict twenty times.

Verified against a live frame: the body, the quoted text, the uuid and
the phone number do not survive, and contentType does.

This also had to fix DEBUG being unusable. LOG_LEVEL=DEBUG set the root
logger, which turns on httpx, httpcore and asyncio; the bot polls a
group listing every 30 seconds, so the one interesting line arrived
buried and journald started dropping. Libraries are now held at WARNING
whatever the bot is set to -- at INFO httpx was already emitting an
"HTTP Request: GET ... 200 OK" line every thirty seconds, forever.
Measured on the running unit: 17 library lines per minute down to 2.

Two bugs in that setup found by its own tests rather than by review:
basicConfig is a documented no-op once the root logger has a handler, so
the level silently did not apply under pytest; and the floor belongs at
INFO too, not only below it.

A self-send does not produce a capturable attachment envelope, by the
way -- signal-cli emits no syncMessage for a send made over the same
connection. Two probe images returned HTTP 201 and no frame came back,
so the inbound shape still needs a human to post one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 19:29:06 +02:00
16e066f4ba feat: survive an outage, and keep the counts that predate the event log
Two gaps kuhy pointed at, both about not losing messages the bot was not
awake for.

Missed *counts* already worked and now have a test saying so: an event
is keyed by 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 primary key. Messages sent during an outage come back
filed under the day they were actually sent.

Missed *reports* did not. A bot that was down at 21:37 never posted that
day and never went back for it. The last day reported is now written
down per group, so returning from an outage posts every day it owes,
oldest first, bounded at a week. A day nobody spoke on is marked settled
rather than reconsidered forever; a day whose send *failed* is
deliberately left unmarked so the next run retries it.

The pre-0.1.0 counter is carried over rather than discarded: 342
messages across four groups, 319 of them in the real group. What the
counter cannot say is when, so before assuming, four places were checked
for a real inbound timestamp -- journald (commands only), signal-cli's
account.db (19 tables, none inbound; message_send_log is the bot's own
outgoing resend buffer), Signal Desktop (unlinked, empty, and it does
not backfill on link), and signal-api/attachments (the one dated
artifact). The attachment mtimes put 12 files on 29 Aug against 79 on
30 Aug inside the counter's window, which is why the whole counter is
filed under 30 Aug rather than split.

That day is marked in group_meta, and a marked day claims no average
message length -- those messages have a count but no lengths, so
"średnio 0 znaków" would be a measurement nobody took. The mark is also
what will keep the day out of personal records: a merged 22-hour day
would otherwise hand somebody a record they never set.

render_day's options move into a DayView value object; the keyword list
had reached eight and this renderer is about to be shared by several
commands that each want a different subset.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 19:23:53 +02:00
2f04d67f53 feat: the message event log, and the nightly report built on it
The tally was one integer per person, deleted after each post. Nothing
dated survived it, so weeks, months, records, streaks and weekday
averages were all unanswerable. This replaces it with an append-only
per-message log holding metadata only -- never a message body -- and
rebuilds the nightly report on top.

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

Notable decisions, each with the trap it avoids:

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

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 19:14:43 +02:00
2e2e00be96 release: 0.0.7 «Telesfor» — !papież, and the bot can test itself
Adds !papież / !papiez / !pope: a random pope as a photo, captioned with his
Latin name, reign and pl.wikipedia link. popes.json already carried a Commons
portrait filename for all 267 and nothing had ever consumed it.

The Latin name comes from the Latin column of Poczet papieży, not from the
la.wikipedia sitelink. The sitelink resolved for all 267 and was still wrong:
la.wikipedia numbers several popes differently, so #154 came out as
"Stefan IX — Stephanus X" in a single caption, which reads as an off-by-one.
The table's own column says "Stephanus Nonus" and cannot disagree with the
name beside it. LATIN_OVERRIDES ships empty; it is a tripwire, not a backlog.

Portraits are cached on disk under CacheDirectory=signal-bot, named from the
ordinal so no upstream string ever reaches a path, and bounded at 267 entries
so nothing needs evicting. Verified that CacheDirectory wins against
ProtectHome=read-only before relying on it.

Also adds POST /_selftest and scripts/selftest.sh. Signal never delivers an
account its own sends, so no command has ever been exercised end-to-end
without asking a human to type it. This injects a real frame into the live
dispatcher; it is loopback-only and refuses any group not in SELFTEST_GROUPS,
which is empty by default.

Verified against the real endpoints, not just the fake: 267/267 portraits
resolve on Commons, regeneration is byte-identical on every previously
shipped field, and !papież was driven 7 times through the live dispatcher in
testbot, returning distinct popes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 17:06:25 +02:00
1ee7d0a6bf release: 0.0.6 «Sykstus I»
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 15:44:42 +02:00
ecbf0377b2 fix: a signal-api that is not up yet no longer kills the bot at boot
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 15:23:42 +02:00
16ed0f9b02 release: 0.0.5 «Aleksander I»
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 15:00:27 +02:00
ed50dbb87d docs: record the traps this session hit
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 14:44:28 +02:00
ca7b56fffb fix: commands resolve when typed on another alphabet's keyboard
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 14:22:43 +02:00
1fb15a6412 release: 0.0.4 «Ewaryst»
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 23:41:31 +02:00
45445ab11d fix: !gekon really is random (iNaturalist ignores order_by=random)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 23:35:53 +02:00
fd6cdc9abf release: 0.0.3 «Klemens I»
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 23:28:38 +02:00
3a08b7958d feat: !gekon posts a research-grade gecko photo
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 23:26:40 +02:00
c875414ee6 feat: answer the message that asked, not just the room
A "!cat" in a busy group produced a cat picture floating loose in the chat with
nothing tying it to whoever asked. Replies now quote the triggering message.

The container advertises this and always could: /v1/about reports
capabilities {"v2/send": ["quotes", "mentions"]}, and /v2/send takes
quote_timestamp, quote_author and quote_message. What was missing was on this
side -- parse_envelope discarded the envelope's timestamp, which is the id
Signal quotes a message by, so nothing downstream could have built a quote even
in principle. IncomingMessage now carries it, preferring the payload's own
value over the envelope's for the case where they ever disagree.

Quote is a value object rather than three more parameters threaded through
every send: the Transport protocol has five methods and two of them send.
CommandContext grows reply_image() so quoting lives in one place instead of
each handler reaching for ctx.transport itself, which is what animals.py did.

quote_of() returns None when the timestamp or author is missing. Answering the
room is a worse reply than a quoted one but a much better outcome than a
payload the container rejects.

The e2e gate learned to tell the two apart: Expectation.quotes demands a send
either does or does not point at a message, defaulting to None so the ten
existing scenarios stay indifferent. Without it the fake would have accepted an
unquoted reply as a pass.

Verified in the testbot group on a real Signal client before this bump, per
kuhy's rule that a bump is a publish rather than a checkpoint: he sent !cat and
confirmed the picture renders attached to his message as a reply.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-29 23:01:01 +02:00
5f0d7c1c35 feat: name every release after a pope, and tell the group when one lands
Release n is pope n, so the version is a fact about the ordinal rather than a
judgement about the size of a change. The constraint that fixes the scheme is
Jan Pawel II at 2.13.7: eight patches per minor with majors opening at ordinals
33 and 153 gives (264 - 153) = 13 * 8 + 7 exactly, and both earlier majors
happen to divide evenly by eight too, so no bracket needs a fudge factor. The
anchors are not arbitrary -- 33 is Sylwester I, pope through the Edict of Milan
and Nicaea, and 153 is Wiktor II, the first pope elected after the 1054 schism.

popes.json is scraped by tool/gen_popes.py rather than recalled, because
antipopes, Benedykt IX's three separate reigns and the Stefan II question all
shift the count and being wrong by one moves Jan Pawel II off 2.13.7 silently.
The generator refuses to write a list that is not 267 contiguous entries with
Jan Pawel II at 264. A second, independent parse of the same page agreed on
every ordinal, which is the only reason to believe either.

On startup each watched group is told about the releases it has not seen. A
group with no record has seen none of them, so the first announcement starts at
0.0.0 "Swiety Piotr Apostol" rather than skipping to whatever is current --
watching the ladder start at Peter is the point of naming releases after popes.
A group added years from now would otherwise be handed the whole backlog, so
the message is capped at ten releases and says how many it left out. The
version is recorded before the message is sent: with Restart=always and
RestartSec=5, a crash between the two would re-announce on every restart, and a
missed announcement is far cheaper than a looping one.

DOCS-changelog.md is the single source -- the bot parses it, so there is no
second machine-readable copy to drift. It is DOCS-, not CHANGELOG.md, because
the md-naming gate allows four namespaces and that is not one of them.

Deliberately NOT bumping SCHEMA_VERSION for the new group_meta table:
_apply_schema drops every table on a bump, so bumping to add a table would have
thrown away the live tallies to gain nothing. Verified against the real
database -- group_meta appeared and all four counts survived the restart.

The schema moves to its own module so store.py stays under the 250-line cap,
and /healthz now names the build, because there was previously no way to ask a
running bot which version it is.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-29 22:51:20 +02:00
19b61cb916 chore: drop the last references to a command this repo no longer has
The vote and rate-limit gates were salvaged from an old command that is gone;
the docstring still named it, and test_store.py used its name as the arbitrary
string for the vote-dedup fixture. Neither reference means anything now, and
the pre-rewrite history that did contain it has been dropped, so these were the
only two left in the tree.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-29 22:32:12 +02:00
901512c1f0 fix: never let the trust gate un-watch a group it already adopted
_permitted feeds both _join_pending and _adopt, and _adopt treats anything
missing from its result as a removal: it drops the group, purges its tally
with store.forget_group and logs "no longer a member". So one listing whose
membership no longer vouches -- the same group has been seen spelling a
member as +E.164 in one row and as a bare uuid in another, and a row can
come back with no members field at all -- would silently un-watch a live
group and delete its counts, all three claims false.

That is exactly the narrowing discovery.py's own docstring forbids ("a
failed refresh never narrows the set"), reintroduced by the gate one commit
earlier. Adoption is itself the vouch, so an already-watched id short-
circuits the check; only groups the bot has never adopted are tested.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KbjfWdAyHbCubac7wJKJZW
2026-08-29 19:04:39 +02:00
fa63bed8d8 feat: refuse to look healthy while deaf, and heal the container by itself
Today the bot was up, healthy and answering nothing for three hours. A host
firewall change (fixed in testsAndMisc 334c0cd9) cut every Docker container
off the internet; signal-cli lost Signal and reconnected in a loop from
15:32:50 onward. Nothing noticed:

  - the container's own healthcheck answered 204
  - /v1/groups answered 200 out of local state, so discovery saw no change
  - the bot's WebSocket to the container stayed OPEN, so the transport's
    reconnect logic never fired
  - /healthz answered {"status": "ok"} the entire time

The only symptom was silence, which is also what a quiet evening looks like.

signal_bot/liveness.py asks the one question that cannot be answered from a
cache -- GET /v1/devices, which needs a live round trip -- but only after
SILENCE_SECONDS (120) with no frame of any kind, so a busy group costs
nothing and an idle one costs one request per window. Three consecutive
failures and /healthz answers 503 with the reason. Verified end to end in
scripts/e2e.sh against the real process: 503 after 84s with the fake's
connection cut, back to 200 on its own 30s after restoring it.

scripts/signal_api_watchdog.sh + a two-minute user timer do the recovery the
bot cannot do for itself, since a wedged bot cannot restart the container it
depends on. Two tiers, so the steady state costs no Signal round trip at
all: the bot's own /healthz first, the authenticated probe only when that is
not 200. It stops after 3 restarts in 6 hours and escalates instead -- a
deregistered account or a blocked network is not fixable by restarting, and
a restart loop would hide it. Its own bash suite stubs curl and docker and
drives every branch including the give-up cap.

signal_bot/trust.py answers the other half: TRUSTED_INVITERS decides who may
put this bot in a group. The gate sits in GroupDirectory._permitted, which
both _join_pending and _adopt already route through -- gating only invites
would gate the door nobody uses, since prime_profile.sh exists precisely so
that an add becomes a direct join. Evidence is either the group-update
envelope, which is the only frame naming an inviter, or a trusted identity
being a full member in the listing. A refusal is logged once, with that
group's members, so the operator can see which string to add.

verify_allowlist moved to membership.py to keep discovery.py under the
250-line gate; it was already the module that owns MembershipError.

Verified live, by stopping the container by hand and touching nothing else:

  18:54:35  docker stop signal-api
  18:56:36  liveness: failure 1 of 3 after 123s of silence
  18:57:36  failure 3 of 3 -> /healthz answers 503 from 18:57:45
  18:58:18  watchdog: probe failed (1/2)
  19:00:28  watchdog: probe failed (2/2) -> docker restart signal-api
  19:00:36  liveness: receive path recovered after 8 failed probe(s)
  19:01:13  watchdog: signal-api is back

Six minutes, unattended, against three hours of silence this afternoon. All
four real groups are still adopted with TRUSTED_INVITERS=+48123456789 set,
and no group was refused.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KbjfWdAyHbCubac7wJKJZW
2026-08-29 19:01:55 +02:00
166 changed files with 17311 additions and 942 deletions

View File

@ -38,9 +38,49 @@ REPORT_MINUTE=
# Optional. Per-user, per-command cooldown in seconds. Default: 10
COOLDOWN_SECONDS=
# Optional but recommended. Comma-separated +E.164 numbers -- or member
# UUIDs, which is how /v1/groups spells anybody the account has never
# messaged -- allowed to add this bot to a group.
#
# Empty means anyone who knows the number can pull the bot into a group and
# have it answer there. With it set, "add the bot" is still the whole setup
# for you, and a stranger's group is refused with one WARNING naming that
# group's members, so you can see exactly which string to add here.
TRUSTED_INVITERS=
# Optional. How long the bot may hear nothing at all -- no message, no
# receipt, no typing indicator -- before it probes /v1/devices to find out
# whether it has gone deaf. Three failed probes and /healthz turns 503.
# Default: 120. scripts/e2e.sh sets it to 0 to prove the gate really fires.
SILENCE_SECONDS=
# Optional. Image APIs. Overridden by scripts/e2e.sh to serve local fixtures.
CAT_API_URL=
DOG_API_URL=
GECKO_API_URL=
COMMONS_API_URL=
# Optional. Where !papież keeps the 267 papal portraits it has downloaded.
# Default: $CACHE_DIRECTORY/portraits under systemd (the unit sets
# CacheDirectory=signal-bot), otherwise $XDG_CACHE_HOME/signal-bot/portraits.
PORTRAIT_CACHE_DIR=
# Optional. Groups scripts/selftest.sh may make the bot post into. Empty by
# default, which makes POST /_selftest refuse everything -- Signal never
# delivers an account its own sends, so this is the only way to exercise a
# command without a second account, and it posts for real.
SELFTEST_GROUPS=
# Optional, and private. The album the per-person photo commands draw
# from: a directory holding people.json, tags.json and media/. Everything
# identifying lives in there and nothing about it is in this repository --
# see DOCS-photo-pack.md, and tool/tagger.py for how it gets filled in.
#
# Leave it empty and the bot looks in $STATE_DIRECTORY/pack (systemd) and
# then $XDG_DATA_HOME/signal-bot/pack. Not finding one is normal: the
# commands simply do not exist. Naming one that is not there, or one whose
# manifest cannot be honoured, fails startup rather than every command.
PHOTO_PACK_DIR=
# Optional. Where the /healthz readiness probe binds.
# Default: 127.0.0.1:8137 -- deliberately not 8000, which unrelated dev

View File

@ -56,3 +56,9 @@ jobs:
# The real bot against the fake Signal server. No account, no network.
- name: end-to-end
run: ./scripts/e2e.sh
# Boot order reversed: the bot starts first and Signal appears later,
# which is what a reboot looks like and what put the unit in `failed`
# for eight hours on 2026-08-30.
- name: cold start
run: ./scripts/cold_start.sh

22
.gitignore vendored
View File

@ -164,5 +164,27 @@ cython_debug/
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
*.jpg
*.jpeg
*.png
*.webp
*.gif
*.mp4
nohup.out
# The private photo album. It lives outside this repository -- in
# ~/.local/share/signal-bot/pack -- and these names exist so that a stray
# copy inside it cannot be committed by accident. people.json and tags.json
# are the two files that hold the names; media/ holds the photos.
people.json
tags.json
media/
pack/
# 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
@ -98,6 +108,15 @@ repos:
language: system
types: [shell]
# The watchdog is bash, so pytest cannot reach it. Its own suite stubs
# curl and docker and drives every branch, including the give-up cap.
- id: watchdog-tests
name: watchdog behaviour (bash)
entry: scripts/test_watchdog.sh
language: system
pass_filenames: false
files: ^scripts/(signal_api_watchdog|test_watchdog)\.sh$
# 100% branch coverage, no omits. Runs on every commit: coverage is the
# whole point of the suite, and a partial run cannot prove it.
- id: pytest

224
DOCS-changelog.md Normal file
View File

@ -0,0 +1,224 @@
# Changelog
Releases are named after the popes, in order: release *n* is pope *n*. The
version number is a pure function of that ordinal — see `signal_bot/versioning.py`
for the two constants and why they are what they are. The short version is that
Jan Paweł II has to land on 2.13.7, and everything else follows.
**The name is Latin, and it is derived, not typed.** `latin_name()` in
`signal_bot/versioning.py` builds it from `popes.json`: the Latin stem plus the
Roman numeral off the Polish name. So 0.0.3 is «Clemens I», not «Klemens I» and
not the raw `latin` field's «Clemens Romanus»; 3.0.4 will be «Leo XIV», not «Leo
Decimus Quartus». Ask the code rather than guessing:
```
python -c 'from signal_bot.versioning import *; print(latin_name(pope_for(14)))'
```
The same string goes in the release commit subject, in `/healthz`, and in the
heading below.
The bot reads this file. The heading format is load-bearing:
```
## <version> — <pope name>
- <one change, in Polish, as the group will read it>
```
Add the new section at the top when you bump `RELEASE_ORDINAL`. Anything that
is not a `##` heading or a `-` bullet under one is ignored, so prose between
releases is free. The heading *name* is checked rather than trusted —
`tests/test_changelog.py` asserts it equals `latin_name()` for that version —
and the announcement reads `popes.json` regardless, so a typo here fails the
suite instead of reaching a group.
**Preview the announcement before you bump.** Because a bump is a publish,
the announcement was the one feature that could never be exercised first.
`tool/preview_release.py testbot` posts exactly what the next release would
say, into one test group, touching neither `RELEASE_ORDINAL` nor any
`announced_version` row; `--print-only` renders it without sending. It is
fail-closed on `SELFTEST_GROUPS`, so it cannot post a release that does not
exist into the group that would believe it. Write the `##` section below
first -- the preview reads it, so what you see is what ships.
**A release announcement is a photo now.** It carries the pope's portrait, his
Latin name and his pl.wikipedia article, the same three things `!papież` posts.
Only for the pope in the header: a backlog announcement lists up to ten
releases, and ten attachments is the wall the cap exists to avoid. If Commons
will not serve the portrait the announcement still goes out, as text — the
`announced_version` marker is written before the send, so a failure there would
otherwise cost that group its release notes permanently.
**Every release takes the next pope, however small.** A one-line fix consumes
an ordinal exactly like a feature does; the ladder tracks releases, not
importance. 0.0.4 and 0.0.5 were both bug fixes. Do not try to squeeze a fix
out at the current version to "save" a pope -- there are 267 of them.
**A version bump is a publish, not a checkpoint.** Restarting the service after
one posts these bullets into every watched group, including the real one. So
exercise the feature in a test group — `testbot`, `catbot`, `finaltestbot`,
each just you and the bot — *before* bumping `RELEASE_ORDINAL`, tagging or
restarting. To try something at the current version without announcing, leave
`RELEASE_ORDINAL` alone and restart. Green unit tests and a green
`scripts/e2e.sh` are **not** sufficient evidence: `e2e.sh` runs against the
local fake, so it proves the wiring and nothing about how Signal renders the
result or how the real upstream API behaves. 0.0.3 shipped a `!gekon` that
passed every gate and posted the same photo every time, because the one thing
nobody had done was call the real endpoint twice.
**Write bullets the group can notice.** The audience is people in a chat, not
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.2.0 — Urbanus I
papież nr 17 z 267, pontyfikat 222-230
- nowe komendy ze zdjęciami: każda osoba ma swoją, a kilka naraz
(`!ktos !ktos2`) daje zdjęcie, na którym są wszyscy naraz
- jak takiego zdjęcia nie ma, bot mówi to jednym zdaniem zamiast milczeć
- filmiki też działają — lecą jako filmiki, a nie jako plik, którego nie da
się odtworzyć
- te komendy istnieją tylko w tej jednej grupie: w każdej innej nie ma ich
wcale, `!pomoc` ich tam nie pokazuje i bot na nie nie odpowiada
- zdjęcia i imiona nie są w kodzie bota ani nigdzie w internecie — leżą w
jednym katalogu na komputerze i nigdy go nie opuszczają
## 0.1.7 — Callistus I
papież nr 16 z 267, pontyfikat 217-222
- każda wersja mówi teraz, którym z kolei papieżem jest jej patron i w jakich
latach panował — w ogłoszeniu nowej wersji, w changelogu i przy `!papież`
- `!papież` pisze to samo zdaniem, którym opisuje każdego innego papieża, więc
nie trzeba już zgadywać, czy «Callistus I» to ten piętnasty, czy szesnasty
## 0.1.6 — Zephyrinus
papież nr 15 z 267, pontyfikat 199-217
- statystyki o 21:37 są od teraz o **dzisiejszym** dniu, a nie o wczorajszym —
wieczorny post pokazuje wreszcie ten dzień, który właśnie mijał
- licznik zamyka się o 21:37, więc to, co napiszecie później, wpada do jutra;
post sam to mówi, żeby liczba nie udawała całej doby
- **jedna wiadomość, nie kilka**: dzień, tydzień, miesiąc i to, co bot
przegapił, są blokami w jednym poście, a nie osobnymi powiadomieniami
- dzień, którego bot przegapił (bo go nie było o 21:37), nadal zostanie
wysłany później — nic nie ginie
## 0.1.5 — Victor I
papież nr 14 z 267, pontyfikat 189-199
- ogłoszenie nowej wersji przychodzi teraz ze zdjęciem papieża, po którym ta
wersja się nazywa, i z linkiem do jego strony na polskiej Wikipedii —
dokładnie tak, jak robi to `!papież`
- wersje nazywają się od teraz po łacinie: ta jest «Victor I», a nie
«Wiktor I», a poprzednia była «Eleutherius», nie «Eleuteriusz»
## 0.1.4 — Eleutherius
papież nr 13 z 267, pontyfikat 175-189
- `!pomoc` (albo `!help`) wypisuje wszystkie komendy i mówi jednym zdaniem,
co każda robi — do tej pory nigdzie na czacie nie było ich listy
## 0.1.3 — Soterius
papież nr 12 z 267, pontyfikat 166-175
- "POCZEKAJ 1 SEKUND" odmienia się wreszcie po polsku — teraz jest
1 SEKUNDĘ, 2 SEKUNDY, 5 SEKUND
- odczekanie tego, co bot każe, wreszcie działa: dotąd każda nieudana próba
po cichu przedłużała blokadę, więc kto grzecznie czekał, ten dostawał
odmowę w kółko
## 0.1.2 — Anicetus
papież nr 11 z 267, pontyfikat 155-166
- `!ja` pokazywał wszystkim tę samą godzinę (12:00) — to był artefakt
danych sprzed przebudowy licznika, a nie wasze zwyczaje. Teraz pokazuje
prawdziwe godziny, a komu ich nie znamy, temu nie zmyśla
## 0.1.1 — Pius I
papież nr 10 z 267, pontyfikat 140-155
- 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 — Hyginus
papież nr 9 z 267, pontyfikat 136-140
- 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 — Telesphorus
papież nr 8 z 267, pontyfikat 125-136
- nowa komenda `!papież` (działa też jako `!papiez`, `!papa`, `!pope`) — bot
wrzuca losowego papieża: zdjęcie, imię po łacinie, lata pontyfikatu i link
do polskiej Wikipedii. Do wyboru jest cała lista, 267 papieży od Świętego
Piotra do Leona XIV — czyli ci sami, po których nazywają się wersje bota
## 0.0.6 — Xystus I
papież nr 7 z 267, pontyfikat 115-125
- po restarcie komputera bot wraca sam — wcześniej, jeśli włączył się zanim
Signal był gotowy, poddawał się po 25 sekundach i milczał do końca dnia;
30 sierpnia stało się to na osiem godzin
## 0.0.5 — Alexander I
papież nr 6 z 267, pontyfikat 105-115
- komendy działają teraz niezależnie od tego, na jakiej klawiaturze je piszesz
— `!gekon` napisany rosyjskimi literami (albo jako `!g3ck0`) wreszcie
odpowiada, wcześniej bot go po prostu ignorował
## 0.0.4 — Evaristus
papież nr 5 z 267, pontyfikat 97-105
- `!gekon` pokazuje teraz za każdym razem innego gekona — wcześniej wrzucał
w kółko to samo zdjęcie
## 0.0.3 — Clemens I
papież nr 4 z 267, pontyfikat 88-97
- nowa komenda `!gekon` — bot wrzuca losowe zdjęcie gekona; działa też
`!gecko`, `!geckon`, `!geko`, `!gekony` i `!geckos`
## 0.0.2 — Anacletus
papież nr 3 z 267, pontyfikat 76-88
- bot odpowiada teraz na konkretną wiadomość, cytując ją — w ruchliwej
rozmowie widać, czyje `!cat` to jest
## 0.0.1 — Linus
papież nr 2 z 267, pontyfikat 64-76
- wersje bota nazywają się teraz imionami kolejnych papieży
- po aktualizacji bot ogłasza w grupie nową wersję i listę zmian
- `/healthz` pokazuje wersję i papieża, więc widać co naprawdę działa
## 0.0.0 — Petrus
papież nr 1 z 267, pontyfikat 33-64
- bot taki, jaki był przed drabinką papieską: `!cat`, `!dog` i dzienne podsumowanie

51
DOCS-commands.md Normal file
View File

@ -0,0 +1,51 @@
# Commands
The copy that matters is not this file: `!pomoc` prints the same list **in the
group**, in Polish, one line of description per command. That version is built
from the command registry at run time and cannot drift, because
`CommandRegistry.register` takes the description as a required argument and
`help_command.render_help` prints any command its `GROUPS` table forgot to
file anyway, under no heading.
This file is the trigger reference — every spelling that resolves, which
`!pomoc` deliberately does not print.
| Command | Aliases |
|---|---|
| cat | `!kot` `!koty` `!kots` `!cat` `!cats` `!meow` `!miau` + styled variants |
| dog | `!pies` `!psy` `!dog` `!dogs` `!woof` `!szczek` + styled variants |
| gecko | `!gekon` `!gekony` `!geko` `!gecko` `!geckon` `!geckos` |
| pope | `!papież` `!papiez` `!papieze` `!papieża` `!papa` `!pope` `!popes` `!pontifex` + styled variants |
| 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` |
| help | `!pomoc` `!pomocy` `!help` `!komendy` `!commands` |
Aliases live in `signal_bot/aliases.json`, not in source, because they are
data: adding one should never mean touching Python.
## Why `!pomoc` shows the first alias and not a trigger
`Command.triggers` is a `frozenset` of **folded skeletons** — `folding.py`
runs NFKC, strips diacritics and maps Cyrillic/Greek/small-caps/leet
lookalikes onto ASCII, so that `!gecko` typed on a Russian keyboard still
resolves. Everything that makes those triggers robust also makes them
unprintable: the set has no order, `!papież` survives only as `!papiez`, and
the styled variants come out as zalgo.
So `Command.primary` holds the first *raw* trigger instead, which
`aliases.json` lists as the canonical Polish spelling for every command.
Two consequences worth remembering, both from `folding.py`:
- A command name can never contain a digit — `fold` maps `0134578` onto
letters, so `!7dni` would resolve as `!tdni`.
- The styled Unicode aliases in the table above are redundant now; folding
covers them. They are kept because removing an alias can only take
something away.

46
DOCS-latency.md Normal file
View File

@ -0,0 +1,46 @@
# Latency: where the 3.7 seconds actually go
Measured on the live bot, 2026-08-29, for one real `!cat` in the production
group. Every number here came from `journalctl --user -u signal-bot.service`,
not from a model of the system.
```
22:59:37.984 running command cat
22:59:38.370 GET api.thecatapi.com/…/search 200 386 ms
22:59:39.054 GET s3…/MjA2MDgxMA.jpg 200 684 ms
22:59:41.702 POST localhost:9922/v2/send 201 2648 ms
```
Fetching the picture — the JSON lookup plus the download — is **1.07 s of the
3.7 s**. `POST /v2/send` on its own is **2.65 s**, and that is the
signal-cli-rest-api container uploading the attachment to Signal. It is 72% of
the wall clock and none of it is this repo's code.
## The consequence for the latency release
The plan proposed an image prefetch pool as "the single biggest win": keep N
pre-fetched, pre-base64'd images per command in memory so a command costs one
send instead of *fetch JSON → download → encode*. The measurement says that
buys 3.7 s → about 2.7 s. Worth having, but it is not the biggest win and it
does not get anywhere near a sub-second reply, because the send is untouched.
**Do not design the latency release on the plan's assumption.** Before
building anything, measure these two separately:
1. A **text-only** reply, end to end. That isolates `POST /v2/send` without an
attachment and says how much of the 2.65 s is upload versus fixed overhead.
2. Whether signal-cli can **reuse an already-uploaded attachment id**, so a
repeated image costs a reference rather than a fresh upload. If it can,
that is the real win and it makes the prefetch pool far more valuable,
because the pool could hold ids instead of bytes.
Head-of-line blocking is a separate, confirmed problem and does not need
re-measuring: `bot.py` awaits each frame to completion, so one slow upstream
fetch delays every other message behind it. Dispatching each frame as its own
task under a bounded semaphore fixes that regardless of what the send costs.
## Rule
An upstream latency claim gets measured before it gets designed around. The
prefetch-pool assumption survived a whole planning pass and was wrong by more
than a factor of two in the direction that mattered.

View File

@ -0,0 +1,83 @@
# Going deaf, not being up yet, and who may add the bot
Three gates, each from a failure that looked like nothing at the time. All
are referenced from the README; this is the detail.
## When it cannot hear
On 2026-08-29 the bot was up, healthy and deaf for three hours. A host
firewall change cut every Docker container off the internet, `signal-cli`
lost its connection to Signal and reconnected in a loop, and **every** health
signal stayed green: the container's own healthcheck answered 204,
`/v1/groups` answered 200 from local state, the bot's WebSocket to the
container stayed open, and `/healthz` answered `{"status": "ok"}`. The only
symptom was silence, which is also what a quiet evening looks like.
Two things now make that impossible to miss:
- **`signal_bot/liveness.py`** — after `SILENCE_SECONDS` (120 by default)
with no frame of any kind, the bot probes `/v1/devices/<number>`, the one
endpoint that needs a live round trip to Signal. Three consecutive
failures and `/healthz` answers **503** with the reason, and every failure
is a `WARNING` in the journal. Worst case from the last envelope to a red
`/healthz` is 120 + 3×30 ≈ 3.5 minutes.
- **`scripts/signal_api_watchdog.sh`**, on a two-minute user timer — probes
the same endpoint from outside the process, restarts the container after
two consecutive failures, and **stops after 3 restarts in 6 hours**,
escalating with `notify-send` and a journald `ERROR` instead. A
deregistered account or a blocked network is not fixable by restarting,
and a forever-restart loop would hide it. `scripts/install_service.sh`
installs and arms it beside the bot's own unit.
```bash
systemctl --user list-timers signal-api-watchdog.timer
journalctl --user -u signal-api-watchdog.service -n 20
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8137/healthz
```
## When it is not up yet
On 2026-08-30 the machine rebooted. The bot started before the `signal-api`
container was ready, its first HTTP call raised
`RemoteProtocolError: Server disconnected without sending a response`,
uvicorn reported `Application startup failed. Exiting.`, and `RestartSec=5`
with `StartLimitBurst=5` gave the container **25 seconds** to appear. It took
minutes. The unit landed in `failed` and stayed there for eight hours, and
the group had no bot for all of them.
`After=docker.service` cannot fix this and never could: dockerd being up says
nothing about the container inside it, and signal-cli then spends further
minutes loading the account. So the connection is no longer part of starting
up. `signal_bot/startup.py` serves first and connects afterwards:
- uvicorn begins serving immediately, and `/healthz` answers **503** with
`{"status": "connecting"}` and the actual error until the bot is connected.
A booting bot is visibly unhealthy rather than absent.
- The retry backs off 5s → 60s and never gives up. Recovery needs nobody.
- Errors no retry can fix are still fatal, and still land the unit in
`failed` where `systemctl --user --failed` shows them: a container in the
wrong `MODE`, a `GROUP_IDS` entry naming a group the bot is genuinely not
in, a missing `PHONE_NUMBER`, a taken port.
The distinction that makes the last point safe: a `GROUP_IDS` entry is only
judged against a group listing that was **actually read**. A failed listing
leaves the watched set empty, and convicting the allowlist on that would turn
"the container is not up yet" into a verdict nothing can retry.
`scripts/cold_start.sh` is the proof, and runs in CI: it boots the bot with
nothing at the other end, asserts the process stays up and says why, then
starts the fake Signal server underneath it and asserts the bot recovers
unaided with all four groups rediscovered.
## Who may add the bot to a group
`TRUSTED_INVITERS` in `.env` is a comma-separated list of `+E.164` numbers,
or the member UUIDs `/v1/groups` uses for anybody the account has never
messaged. Empty means anyone who knows the number can pull the bot into a
group and be answered there, and the bot says so in a `WARNING` at startup.
With it set, adding the bot is still the whole setup for you: a group is
adopted when a group-update envelope says a trusted identity added the bot,
or when a trusted identity is a full member of it in the listing. Anything
else is refused once, loudly, with that group's member list in the log so
you can see which string to add.

109
DOCS-photo-pack.md Normal file
View File

@ -0,0 +1,109 @@
# The photo pack
A pack is a private album the bot posts from: `!alfa` returns a random photo
of alfa, and `!alfa beta` returns one with both of them on it.
**Nothing about a real pack is in this repository, and nothing ever will be.**
Who the people are, what somebody types to get their photo and which file
shows whom live in one directory outside the repo. This document, the tests
and the offline end-to-end run all use the same invented people — alfa, beta,
gamma — so the mechanism can be public while the album stays private.
## Where it lives
```
~/.local/share/signal-bot/pack/
people.json # the commands, and the only place names exist
tags.json # which file shows whom
media/ # the photos and videos themselves
```
Found in this order: `PHOTO_PACK_DIR`, then `$STATE_DIRECTORY/pack` (what
systemd hands a **system** unit), then `$XDG_DATA_HOME/signal-bot/pack`.
`StateDirectory=` is deliberately **not** in the unit this repo installs:
for a *user* unit systemd resolves it below `$XDG_STATE_HOME`, which is not
where the album is. Discovery finds the same directory, and leaving
`PHOTO_PACK_DIR` unset is what keeps a not-yet-filled-in pack from turning
`Restart=always` into a restart loop.
Two absences, deliberately different:
- a pack **nobody named** that is not there, or that has no `people.json`
yet, is an installation without an album: the commands do not exist, and
that is the normal case on every machine and in the whole test suite;
- a pack named in `PHOTO_PACK_DIR` that is missing, or whose manifest cannot
be honoured, **fails startup**. `load_config` raising is an answer, and a
bot that came up healthy and said "no such photo" forever would not be.
## people.json
```json
{
"groups": ["group.WlRKbExYZGhkR05vWldRdA=="],
"people": [
{"key": "p1", "triggers": ["!alfa", "!alfka"]},
{"key": "p2", "triggers": ["!beta"]}
],
"combos": [
{"key": "c1", "triggers": ["!oboje"], "all_of": ["p1", "p2"]},
{"key": "c2", "triggers": ["!ktokolwiek"], "any_of": ["p1", "p2"]}
]
}
```
- **`groups` is the whole privacy guarantee.** In any other group these are
not commands at all: not answered, not counted as a command, not named in a
log line. A handler that quietly returned would still leak all three, which
is why the *dispatcher* enforces it — `registry.resolve_with_args` takes the
group and gives back nothing outside it.
- **`key` is a pseudonym**, and the only identifier that reaches the journal
or the `command_uses` table. A command is `pack:p1`; reading either says
somebody asked for a photo and nothing about whose.
- **`all_of` means one photo with all of them; `any_of` means either**, and
where a choice exists the bot picks among the readings that actually have a
photo, so a combination that could be answered is not refused.
- Triggers may not contain a digit — `folding.py` maps `0134578` onto letters,
so `!alfa7` is not what you typed. Two spellings that fold the same are fine
*within one entry* (`!celina`/`!celiną` is one person written twice) and
refused across two.
## tags.json
```json
{"alfa.png": ["p1"], "both.png": ["p1", "p2"], "clip.mp4": ["p1"]}
```
A tag naming a file that is not in `media/` fails startup: a renamed file
would otherwise drop out of the album in silence. An empty list means "seen,
nobody in it", which is how the tagger records a photo you skipped.
Videos work. The attachment goes out as
`data:video/mp4;filename=<name>;base64,<data>` — the spelling is the
container's own, from its `/swagger/doc.json` — because told it is a photo,
Signal renders a clip as a file nobody can play.
## Filling it in: tool/tagger.py
```sh
python tool/tagger.py --import ~/photos # copy the files in, then tag
python tool/tagger.py # carry on where you left off
```
It serves one page on `127.0.0.1:8140`: the item, a numbered button per
person, `1`–`9` to toggle, `→`/`←` to move. Every toggle rewrites `tags.json`
atomically, so closing the tab loses nothing. Names are typed **into the
page**, never as arguments — an argument would land in the shell history —
and the group is picked from the live `/v1/groups` listing rather than pasted.
When you stop it, it prints how many items were never opened and how many
photos each command would have. **A command showing `0` is dead on arrival**;
that is the number to check before restarting the bot, not after somebody in
the group tries it.
## Running the mechanism without an album
`scripts/e2e.sh` writes a synthetic pack with `tool/e2e_pack.py` and proves,
offline and with no Signal account, that one name posts a photo, two names
intersect, an impossible combination gets one line and no attachment, a video
leaves as a video, and the same command in another group produces **zero**
sends.

47
DOCS-selftest.md Normal file
View File

@ -0,0 +1,47 @@
# Testing a command without a second Signal account
Signal never delivers an account its own sends. The bot cannot type `!kot` at
itself, so until now every command was verified one of two weak ways: by asking
a human to type it, or by rebuilding the object graph in a scratch script. The
first proves nothing about the path between the websocket and the handler; the
second is not the wiring that runs in production.
`POST /_selftest` injects a real envelope frame into the **live** dispatcher.
Everything downstream of the socket read is the code that actually serves the
group: envelope parsing, the scoping gate, the tally, trigger resolution, the
cooldown decorator and the real REST transport. Only the socket read is skipped.
## Using it
Name the groups it may post into -- in `.env`, because the service reads it:
```
SELFTEST_GROUPS=testbot,catbot,finaltestbot
```
Then:
```sh
scripts/selftest.sh testbot '!papież' 3
```
`SELFTEST_INTERVAL` (default 11s) spaces the calls past the per-user cooldown;
the self-test is always the same author, so a tighter loop just exercises the
cooldown instead of the command.
## What it will not do
It **posts for real**, into a real group. Two things keep that from becoming a
way to make the bot say anything anywhere:
- The endpoint lives on the same loopback bind as `/healthz`, never a public one.
- `SELFTEST_GROUPS` is **empty by default**, and any group not named in it is
refused with 403. So a fresh checkout cannot post into the production group
even by accident.
## Why the author matters
The reply quotes whoever asked, and `quote_author` has to be somebody Signal can
resolve -- a made-up uuid comes back as `The user ... is not registered` and the
whole send fails. `resolve_group` therefore attributes the message to a real
member of the target group who is not the bot.

View File

@ -28,11 +28,132 @@ 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.
## 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
`signal_bot/trust.py` needs. It carries no `message` at all, so it counts
toward nothing and answers nothing; `source`/`sourceNumber` is the person
who made the change. Captured live on 2026-08-29:
```json
{
"envelope": {
"source": "+48123456789",
"sourceNumber": "+48123456789",
"sourceUuid": "b1c2d3e4-…",
"sourceName": "kuhy",
"sourceDevice": 1,
"timestamp": 1788006851503,
"dataMessage": {
"timestamp": 1788006851503,
"message": null,
"groupInfo": { "groupId": "6/gEwRkqs/…", "groupName": "testbot", "type": "UPDATE" }
}
},
"account": "+420111222333"
}
```
Note `source` here is a **phone number**, not the display name this document
used to show for `dataMessage`. Both spellings have been observed, which is
why `models.py` reads the sender's number from `sourceNumber` and nothing
trusts `source`.
## From the bot's own account: `syncMessage.sentMessage`
Because the bot runs as a *linked device*, the account's own outgoing messages
When the account is deployed as a *linked device*, its own outgoing messages
come back as sync messages. Same fields, one level deeper.
> **This deployment never receives them.** The bot registers its own number as
> its own primary device and has no linked devices, so Signal sends it no copy
> of its own traffic. The consequence to know before you try to test anything:
> the bot **cannot self-trigger a command**. Posting `!cat` from the bot's
> number into a group does nothing whatsoever — a human has to type it, and
> `journalctl --user -u signal-bot.service` showing `running command …` is how
> you confirm it landed. The parsing below stays because the linked-device
> deployment is still supported, not because it fires here.
```json
{
"envelope": {
@ -68,7 +189,7 @@ were counted as messages. Four consecutive commits (`f1931b8`, `b325126`,
## No `groupInfo` means a direct message
A frame without `groupInfo` arrived in a one-to-one conversation. A linked
device receives every one of those on the account, so `counting.watched_group`
device would receive every one of those on the account, so `counting.watched_group`
rejects them explicitly rather than relying on a falsy comparison. See the
`scoping` scenario in `fake_signal/scenarios/`.

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` image commands and a daily message 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
@ -141,9 +142,9 @@ journalctl --user -u signal-bot.service -f
`Restart=always` brings it back from a crash; lingering (checked by the
installer, because without it the promise is false) starts it at boot with
nobody logged in. `StartLimitBurst=5` stops a config error — a missing
a pinned group it cannot join, a taken port — from hiding inside a
permanent restart loop.
nobody logged in. A container that is not up yet is no longer fatal — the bot
serves a 503 `/healthz` and keeps retrying — so `StartLimitBurst=5` is left
doing only what it was for: catching a config error in a restart loop.
The health probe binds `127.0.0.1:8137` (`BIND_PORT`). Not 8000: that port
attracts unrelated dev servers, and 8137 sits below the ephemeral range so
@ -182,21 +183,27 @@ Two independent reasons, both verified rather than assumed:
`Cannot add user: no_add_managed_profile is enabled`. This is the Android 11
COMP deprecation and is unchanged through Android 16.
## When it cannot hear, and who may add it
The bot was up, healthy and deaf for three hours on 2026-08-29, and dead in
`failed` for eight after the 2026-08-30 reboot. `/healthz` now has three
answers — `ok`, `connecting`, `deaf` — a two-minute timer restarts the
container, and `TRUSTED_INVITERS` decides who may add this bot to a group:
[DOCS-liveness-and-trust.md](DOCS-liveness-and-trust.md).
## Commands
| Command | Aliases |
|---|---|
| cat | `!kot` `!koty` `!kots` `!cat` `!cats` `!meow` `!miau` + styled variants |
| dog | `!pies` `!psy` `!dog` `!dogs` `!woof` `!szczek` + styled variants |
`!pomoc` (or `!help`) prints every command **in the group**, in Polish, one
line of description each. It is built from the registry at run time and
`CommandRegistry.register` takes that description as a required argument, so a
command cannot be added without appearing there. Every trigger that resolves,
and why the printed spelling is not one of them:
[DOCS-commands.md](DOCS-commands.md).
Aliases live in `signal_bot/aliases.json`, not in source. Each command is
rate-limited per user, per command — the original bot shared one 10-second
window across everybody.
`signal_bot/decorators.py` also ships `daily_limit` and `vote_gated` (run only
once N distinct people ask, within a window). Both are generic and tested;
attach them to any command.
Aliases live in `signal_bot/aliases.json`, not in source. Each command is rate-limited per
user, per command — the original bot shared one 10-second window across everybody.
`signal_bot/decorators.py` also ships `daily_limit` and `vote_gated` (run only once N distinct people ask, within a window). Both are generic and tested; attach them to any command.
## Watching more than one group
`GROUP_IDS` takes a comma-separated list, so one process can serve a test
@ -206,36 +213,37 @@ group and the production group at once:
GROUP_IDS=group.<base64-of-test>,group.<base64-of-prod>
```
Everything downstream is keyed by group. A command is answered **in the group
that asked and nowhere else**; cooldowns, daily limits, votes and the tally
are per group, so a `!cat` in the test group neither throttles nor counts
against the production one. There is no reply-target setting to get wrong —
Everything downstream is keyed by group. A command is answered **in the group that asked and nowhere
else**; cooldowns, daily limits, votes and the tally are per group, so a `!cat` in the test group neither
throttles nor counts against the production one. There is no reply-target setting to get wrong —
`GROUP_ID_SEND` was removed, and setting it now fails startup rather than
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.
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
```sh
pytest # 189 tests, 100% branch coverage, no network
pytest # 708 tests, 100% branch coverage, no network
pre-commit run --all-files # ruff ALL + mypy strict + 250-line cap + gates
./scripts/e2e.sh # the real bot against the fake server
```
No `# noqa`, no `# type: ignore`, no coverage omits. Docs on the wire format
are in [DOCS-signal-envelopes.md](DOCS-signal-envelopes.md).
No `# noqa`, no `# type: ignore`, no coverage omits. Never bump `SCHEMA_VERSION` to add a table —
read `signal_bot/schema.py` first; a bump DROPs every table and throws the live tallies away, while
`CREATE TABLE IF NOT EXISTS` is additive and safe. Wire format: [DOCS-signal-envelopes.md](DOCS-signal-envelopes.md).
Releases are named after the popes, in order and in Latin — 0.1.4 is «Eleutherius» — and a bump publishes to the group as the pope's portrait, name and article: [DOCS-changelog.md](DOCS-changelog.md). Latency: [DOCS-latency.md](DOCS-latency.md).
Signal never delivers an account its own sends: `scripts/selftest.sh testbot '!papież' 3` drives the live dispatcher instead, [DOCS-selftest.md](DOCS-selftest.md).
## Licence

View File

@ -35,6 +35,23 @@ def build_api_router() -> APIRouter:
headers={"X-Device-Name": device_name},
)
@router.get("/v1/devices/{number}")
async def devices(request: Request, number: str) -> JSONResponse:
"""The endpoint the deafness gate probes.
Answers from Signal, never from local state, which is exactly why
the bot uses it to tell "quiet" apart from "deaf".
"""
state = _state(request)
if number not in state.accounts:
return JSONResponse({"error": f"{number} is not registered"}, status_code=400)
if not state.connection_alive:
return JSONResponse(
{"error": "Failed to get linked devices: Closed unexpectedly"},
status_code=400,
)
return JSONResponse([{"id": 1, "name": "", "created": 0, "last_seen": 0}])
@router.post("/v2/send")
async def send(request: Request, payload: dict[str, Any]) -> JSONResponse:
_state(request).record_send(payload)

View File

@ -29,6 +29,13 @@ def build_control_router() -> APIRouter:
delivered += 1
return {"delivered": delivered}
@router.post("/connection")
async def set_connection(request: Request, body: dict[str, Any]) -> dict[str, bool]:
"""Cut or restore signal-cli's connection to Signal."""
state = _state(request)
state.connection_alive = bool(body.get("alive", True))
return {"alive": state.connection_alive}
@router.post("/groups")
async def set_groups(request: Request, groups: list[dict[str, Any]]) -> dict[str, int]:
"""Replace the group list, so the group picker can be rehearsed offline."""

View File

@ -1,5 +1,5 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Local stand-ins for thecatapi and dog.ceo, shaped like the real responses."""
"""Local stand-ins for the image APIs, shaped like the real responses."""
from __future__ import annotations
@ -27,8 +27,33 @@ def build_fixture_router() -> APIRouter:
async def dog_api(request: Request) -> dict[str, str]:
return {"message": _image_url(request)}
@router.get("/gecko-api")
async def gecko_api(request: Request) -> dict[str, object]:
state: State = request.app.state.fake
photo = {"url": f"{state.base_url}/_fixtures/photos/square.png"}
return {"results": [{"photos": [photo]}]}
# Commons answers an imageinfo query, not a fixed URL. Echoing the
# requested titles= back proves the bot asked for the pope it drew,
# rather than a hard-coded file that would hide a lookup regression.
@router.get("/commons-api")
async def commons_api(request: Request) -> dict[str, object]:
page = {
"title": request.query_params.get("titles", ""),
"imageinfo": [{"thumburl": _image_url(request)}],
}
return {"query": {"pages": [page]}}
@router.get("/image.png")
async def image() -> Response:
return Response(content=PIXEL_PNG, media_type="image/png")
# Only the rewritten URL is served. iNaturalist names a square thumbnail
# and the bot is supposed to swap it for the full-size photo, so a
# regression in that rewrite must fail the run with a 404 rather than
# quietly posting a 75px image nobody looks at closely.
@router.get("/photos/large.png")
async def large_photo() -> Response:
return Response(content=PIXEL_PNG, media_type="image/png")
return router

View File

@ -5,7 +5,7 @@ from __future__ import annotations
import json
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Final
import yaml
@ -100,6 +100,9 @@ class Expectation:
kind: str = "text"
to: str = "reply"
contains: str | None = None
# True demands the send quote the message that triggered it; False demands
# it not. None (the default) leaves existing scenarios indifferent.
quotes: bool | None = None
@dataclass(frozen=True, slots=True)
@ -146,13 +149,31 @@ def load_scenario(path: Path) -> Scenario:
)
# How signal-cli-rest-api spells an attachment whose type the bot stated.
# Anything else is bare base64, which is what an ordinary photo travels as.
_VIDEO_PREFIX: Final = "data:video/"
def describe(payload: dict[str, Any]) -> tuple[str, str, str]:
"""Reduce a captured send to (kind, recipient, body) for comparison."""
kind = "image" if payload.get("base64_attachments") else "text"
"""Reduce a captured send to (kind, recipient, body) for comparison.
"video" is its own kind so a scenario can assert that a clip went out as
a clip: told it is a photo, Signal renders an unplayable file, and every
other check in this harness would still pass.
"""
attachments = payload.get("base64_attachments") or []
kind = "text"
if attachments:
kind = "video" if str(attachments[0]).startswith(_VIDEO_PREFIX) else "image"
recipients = payload.get("recipients") or [""]
return kind, str(recipients[0]), str(payload.get("message", ""))
def quotes(payload: dict[str, Any]) -> bool:
"""True when a captured send points at a specific message."""
return bool(payload.get("quote_timestamp"))
def check(scenario: Scenario, sent: list[dict[str, Any]], groups: dict[str, str]) -> list[str]:
"""Compare captured sends against expectations, returning failure lines."""
failures: list[str] = []
@ -170,4 +191,6 @@ def check(scenario: Scenario, sent: list[dict[str, Any]], groups: dict[str, str]
failures.append(f"[{index}] recipient: expected {want_to}, got {recipient}")
if expected.contains is not None and expected.contains not in body:
failures.append(f"[{index}] body: {expected.contains!r} not in {body!r}")
if expected.quotes is not None and quotes(sent[index]) != expected.quotes:
failures.append(f"[{index}] quotes: expected {expected.quotes}")
return failures

View File

@ -0,0 +1,5 @@
name: "!gecko typed on a Russian keyboard still resolves"
inject:
- { text: "!gеckо", uuid: uuid-bob, name: Bob }
expect:
- { kind: image, to: reply }

View File

@ -0,0 +1,5 @@
name: "!gekon posts a gecko photo, fetched from the rewritten full-size URL"
inject:
- { text: "!gekon", uuid: uuid-alice, name: Alice }
expect:
- { kind: image, to: reply }

View File

@ -0,0 +1,7 @@
# Fresh uuid: one bot process serves every scenario and the cooldown lives in
# SQLite, so a shared actor would leak a refusal into this file.
name: "!pomoc lists every command, including ones from other modules"
inject:
- { text: "!pomoc", uuid: uuid-helen, name: Helen }
expect:
- { kind: text, to: reply, contains: "!gekon" }

View File

@ -0,0 +1,7 @@
# The whole point of the feature: several names mean "a photo with all of
# them", and only both.png is tagged with p1 and p2 at once.
name: "two names ask for a photo with both people on it"
inject:
- { text: "!alfa beta", uuid: uuid-pack-two, name: Pack2 }
expect:
- { kind: image, to: reply }

View File

@ -0,0 +1,7 @@
# The private album, against a synthetic pack the e2e script writes: the real
# one lives outside this repository and must never be needed to run the suite.
name: "!alfa posts a photo from the private album"
inject:
- { text: "!alfa", uuid: uuid-pack-one, name: Pack1 }
expect:
- { kind: image, to: reply }

View File

@ -0,0 +1,7 @@
# A combination nobody photographed is answered, not met with silence: from
# the group's side, silence is indistinguishable from a broken bot.
name: "a combination with no photo gets one line and no attachment"
inject:
- { text: "!beta gamma", uuid: uuid-pack-three, name: Pack3 }
expect:
- { kind: text, to: reply, contains: "NIE MAM TAKIEGO" }

View File

@ -0,0 +1,7 @@
# The privacy guarantee. In a group the pack does not list, "!alfa" is not a
# command at all: no photo, no refusal, nothing -- a refusal would itself
# announce that the album exists.
name: "the album does not exist in a group it was not given to"
inject:
- { text: "!alfa", group: second, uuid: uuid-pack-five, name: Pack5 }
expect: []

View File

@ -0,0 +1,7 @@
# Told it is a photo, Signal renders a clip as a file nobody can play. The
# harness reads the data URI the bot sent, so this fails if the type is lost.
name: "a tagged video leaves as a video, not as a photo"
inject:
- { text: "!wideo", uuid: uuid-pack-four, name: Pack4 }
expect:
- { kind: video, to: reply }

View File

@ -0,0 +1,5 @@
name: "!papież posts a portrait captioned with the pope's Latin name and article"
inject:
- { text: "!papież", uuid: uuid-alice, name: Alice }
expect:
- { kind: image, to: reply }

View File

@ -0,0 +1,5 @@
name: "a command answers the message that asked, not just the room"
inject:
- { text: "!cat", uuid: uuid-quoted, name: Quoted }
expect:
- { kind: image, to: reply, quotes: true }

View File

@ -31,6 +31,9 @@ class State:
accounts: list[str] = field(default_factory=list)
pending: dict[str, str] = field(default_factory=dict)
groups: list[dict[str, Any]] = field(default_factory=list)
# Whether signal-cli can reach Signal. False reproduces the 2026-08-29
# outage: local state still answers, anything needing a round trip 400s.
connection_alive: bool = True
def reset(self) -> None:
"""Forget captured sends and attachments."""

View File

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

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 "$@"

153
scripts/cold_start.sh Executable file
View File

@ -0,0 +1,153 @@
#!/bin/bash
# ============================================================================
# Prove the bot survives being started before Signal exists.
#
# The failure this reproduces: on 2026-08-30 the machine rebooted, the bot
# started before the signal-api container was ready, its first HTTP call
# raised, and systemd's start limit put the unit in `failed` -- where it
# stayed for eight hours while the container had been healthy for most of
# them. Nobody noticed, because nothing was watching the unit.
#
# So: boot the bot with nothing at the other end, then start the fake Signal
# server underneath it and assert the bot recovers on its own. Uses the same
# protocol-faithful fake as e2e.sh. No container, no account, no network.
# ============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
readonly REPO_ROOT
readonly PYTHON="${PYTHON:-$REPO_ROOT/.venv/bin/python}"
readonly FAKE_PORT="${FAKE_PORT:-8097}"
readonly BOT_PORT="${BOT_PORT:-8096}"
readonly FAKE_URL="http://127.0.0.1:${FAKE_PORT}"
readonly HEALTH="http://127.0.0.1:${BOT_PORT}/healthz"
# Four groups, because "rediscovers all four groups" is the acceptance
# condition the real deployment is judged on. Both spellings of each id
# are real base64, exactly as /v1/groups reports them: the canonical
# `group.<b64>` form is the base64 of the internal form.
readonly GROUP_ROWS='[{"id":"group.WTI5c1pDMXZibVV0WjNKdmRYQXRhV1F0TXpJdFlubDBaWE1oSVNFaElTRT0=","internal_id":"Y29sZC1vbmUtZ3JvdXAtaWQtMzItYnl0ZXMhISEhISE=","name":"cold-one","member":true,"joinable":true},{"id":"group.WTI5c1pDMTBkMjh0WjNKdmRYQXRhV1F0TXpJdFlubDBaWE1oSVNFaElTRT0=","internal_id":"Y29sZC10d28tZ3JvdXAtaWQtMzItYnl0ZXMhISEhISE=","name":"cold-two","member":true,"joinable":true},{"id":"group.WTI5c1pDMTBhSEpsWlMxbmNtOTFjQzFwWkMwek1pMWllWFJsY3lFaElTRT0=","internal_id":"Y29sZC10aHJlZS1ncm91cC1pZC0zMi1ieXRlcyEhISE=","name":"cold-three","member":true,"joinable":true},{"id":"group.WTI5c1pDMW1iM1Z5TFdkeWIzVndMV2xrTFRNeUxXSjVkR1Z6SVNFaElTRT0=","internal_id":"Y29sZC1mb3VyLWdyb3VwLWlkLTMyLWJ5dGVzISEhISE=","name":"cold-four","member":true,"joinable":true}]'
FAKE_PID=""
BOT_PID=""
TEMP_DIR=""
cleanup() {
if [[ -n "$BOT_PID" ]]; then
kill "$BOT_PID" 2>/dev/null || true
fi
if [[ -n "$FAKE_PID" ]]; then
kill "$FAKE_PID" 2>/dev/null || true
fi
wait 2>/dev/null || true
if [[ -n "$TEMP_DIR" && -d "$TEMP_DIR" ]]; then
rm -rf "$TEMP_DIR"
fi
}
trap cleanup EXIT
die() {
echo "Error: $1" >&2
if [[ -n "$TEMP_DIR" && -f "${TEMP_DIR}/bot.log" ]]; then
echo "--- last 20 lines of the bot log ---" >&2
tail -20 "${TEMP_DIR}/bot.log" >&2
fi
exit 1
}
validate_requirements() {
if [[ ! -x "$PYTHON" ]]; then
echo "Error: no interpreter at $PYTHON. Run: uv venv .venv && uv pip install -e '.[dev]'" >&2
exit 1
fi
command -v curl >/dev/null || die "curl is required"
}
health_code() {
curl -s -o /dev/null -m 5 -w '%{http_code}' "$HEALTH" || true
}
# Poll /healthz until it reports this status, or give up after $2 seconds.
wait_for_status() {
local want="$1" budget="$2" waited=0 status=""
while ((waited < budget)); do
status="$(curl -s -m 5 "$HEALTH" | tr -d ' ' | grep -o '"status":"[a-z]*"' || true)"
if [[ "$status" == "\"status\":\"${want}\"" ]]; then
printf '%s' "$waited"
return 0
fi
sleep 1
waited=$((waited + 1))
done
die "/healthz never reported '${want}' (last: ${status:-no answer})"
}
start_the_bot_with_nothing_to_talk_to() {
echo "== booting the bot on :${BOT_PORT}, pointed at a fake that is not running"
env -u CAT_API \
PHONE_NUMBER="+15550000000" \
GROUP_IDS="" \
TRUSTED_INVITERS="" \
API_BASE_URL="$FAKE_URL" \
DATABASE_PATH="${TEMP_DIR}/cold.sqlite3" \
BIND_PORT="$BOT_PORT" \
"$PYTHON" -m signal_bot >"${TEMP_DIR}/bot.log" 2>&1 &
BOT_PID=$!
}
# Step 2 of the acceptance test: the process must stay up and say why it is
# unhealthy. The old code exited 3 here and systemd gave up 25 seconds later.
prove_it_stays_up_and_says_why() {
local waited
waited="$(wait_for_status connecting 30)"
echo "== /healthz answered 503 'connecting' after ${waited}s"
kill -0 "$BOT_PID" 2>/dev/null || die "the bot exited instead of waiting"
[[ "$(health_code)" == "503" ]] || die "'connecting' was not served as 503"
curl -s "$HEALTH" | grep -q "ConnectError" ||
die "/healthz went red without naming the connection failure"
}
bring_signal_up_underneath_it() {
echo "== starting the fake Signal server on :${FAKE_PORT}"
"$PYTHON" -m uvicorn fake_signal.server:app \
--host 127.0.0.1 --port "$FAKE_PORT" --log-level warning &
FAKE_PID=$!
local attempt=0
until curl -sf "${FAKE_URL}/v1/about" >/dev/null 2>&1; do
attempt=$((attempt + 1))
((attempt < 100)) || die "the fake never came up"
sleep 0.1
done
curl -sf -X POST "${FAKE_URL}/_control/accounts" \
-H 'Content-Type: application/json' -d '["+15550000000"]' >/dev/null
curl -sf -X POST "${FAKE_URL}/_control/groups" \
-H 'Content-Type: application/json' -d "$GROUP_ROWS" >/dev/null
}
# Step 4: nobody restarts anything. The bot's own retry loop has to notice.
prove_it_recovers_unaided() {
local waited found
# The backoff ceiling is 60s, so one full window plus slack.
waited="$(wait_for_status ok 150)"
echo "== /healthz recovered on its own after ${waited}s, with no intervention"
found="$(grep -c 'watching 4 group(s)' "${TEMP_DIR}/bot.log" || true)"
[[ "$found" != "0" ]] || die "the bot came up without rediscovering all four groups"
echo "== all four groups rediscovered"
}
main() {
validate_requirements
TEMP_DIR="$(mktemp -d)"
start_the_bot_with_nothing_to_talk_to
prove_it_stays_up_and_says_why
bring_signal_up_underneath_it
prove_it_recovers_unaided
echo "== cold start passed"
}
main "$@"

View File

@ -58,6 +58,11 @@ cleanup() {
}
trap cleanup EXIT
die() {
echo "Error: $1" >&2
exit 1
}
wait_for_url() {
local url="$1" name="$2" attempt=0
until curl -sf "$url" >/dev/null 2>&1; do
@ -109,19 +114,34 @@ main() {
-H 'Content-Type: application/json' \
-d "[{\"id\":\"${WATCHED_GROUP}\",\"internal_id\":\"${WATCHED_GROUP_INTERNAL}\",\"name\":\"e2e\",\"member\":true,\"joinable\":true},{\"id\":\"${SECOND_GROUP}\",\"internal_id\":\"${SECOND_GROUP_INTERNAL}\",\"name\":\"e2e-second\",\"member\":true,\"joinable\":true}]" >/dev/null
# GROUP_IDS deliberately empty: the bot discovers its groups from the
# account, which is the configuration real deployments now use. Set
# rather than merely unset, because load_dotenv() would otherwise let
# the developer's own .env decide what this test run watches.
# GROUP_IDS and TRUSTED_INVITERS deliberately empty: the bot discovers
# its groups from the account, which is the configuration real
# deployments use. Set rather than merely unset, because load_dotenv()
# would otherwise let the developer's own .env decide what this run
# watches -- and a TRUSTED_INVITERS there would refuse every fixture
# group. The gate itself is covered in tests/test_trust.py.
# The album is private and lives outside this repository, so the run
# builds a synthetic one: three invented people, a combination and a
# video, scoped to the watched group so the scoping scenario can prove
# it does not exist in the second one.
echo "== writing a synthetic photo pack"
"$PYTHON" "$REPO_ROOT/tool/e2e_pack.py" --dir "${TEMP_DIR}/pack" --group "$WATCHED_GROUP"
echo "== booting the bot on :${BOT_PORT}, pointed at the fake"
env -u CAT_API \
PHONE_NUMBER="+15550000000" \
GROUP_IDS="" \
TRUSTED_INVITERS="" \
API_BASE_URL="$FAKE_URL" \
DATABASE_PATH="${TEMP_DIR}/e2e.sqlite3" \
CAT_API_URL="${FAKE_URL}/_fixtures/cat-api" \
DOG_API_URL="${FAKE_URL}/_fixtures/dog-api" \
GECKO_API_URL="${FAKE_URL}/_fixtures/gecko-api" \
COMMONS_API_URL="${FAKE_URL}/_fixtures/commons-api" \
PORTRAIT_CACHE_DIR="${TEMP_DIR}/portraits" \
PHOTO_PACK_DIR="${TEMP_DIR}/pack" \
BIND_PORT="$BOT_PORT" \
SILENCE_SECONDS=0 \
"$PYTHON" -m signal_bot &
BOT_PID=$!
wait_for_url "http://127.0.0.1:${BOT_PORT}/healthz" "bot"
@ -140,6 +160,43 @@ main() {
--group "fourth=${FOURTH_GROUP_INTERNAL}" \
--group "fourth_reply=${FOURTH_GROUP}" \
--group "other=${OTHER_GROUP}"
prove_the_deafness_gate
}
# The gate that did not exist on 2026-08-29, proven against the real process:
# with signal-cli unable to reach Signal, /healthz must go red rather than
# keep answering 200 while nothing arrives.
prove_the_deafness_gate() {
local health="http://127.0.0.1:${BOT_PORT}/healthz"
echo "== cutting the fake's connection to Signal"
curl -sf -X POST "${FAKE_URL}/_control/connection" \
-H 'Content-Type: application/json' -d '{"alive": false}' >/dev/null
local code="" waited=0
while ((waited < 150)); do
code="$(curl -s -o /dev/null -w '%{http_code}' "$health")"
[[ "$code" == "503" ]] && break
sleep 1
waited=$((waited + 1))
done
[[ "$code" == "503" ]] || die "/healthz still answers ${code} with the connection cut"
curl -s "$health" | grep -q "Closed unexpectedly" ||
die "/healthz went red without saying why"
echo "== /healthz turned 503 and named the reason after ${waited}s"
echo "== restoring the connection"
curl -sf -X POST "${FAKE_URL}/_control/connection" \
-H 'Content-Type: application/json' -d '{"alive": true}' >/dev/null
waited=0
while ((waited < 150)); do
code="$(curl -s -o /dev/null -w '%{http_code}' "$health")"
[[ "$code" == "200" ]] && break
sleep 1
waited=$((waited + 1))
done
[[ "$code" == "200" ]] || die "/healthz stayed ${code} after the connection came back"
echo "== /healthz recovered on its own after ${waited}s"
}
main "$@"

View File

@ -18,6 +18,8 @@ readonly SCRIPT_NAME
readonly UNIT_NAME="signal-bot.service"
readonly UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
readonly TEMPLATE="${REPO_ROOT}/scripts/${UNIT_NAME}"
readonly WATCHDOG_UNITS=("signal-api-watchdog.service" "signal-api-watchdog.timer")
readonly WATCHDOG_TIMER="signal-api-watchdog.timer"
readonly DEFAULT_PORT=8137
VERIFY_ONLY="false"
@ -51,6 +53,12 @@ validate_requirements() {
die "no ${REPO_ROOT}/.env -- run scripts/register_bot.sh first"
[[ -x "${REPO_ROOT}/run.sh" ]] || die "no executable ${REPO_ROOT}/run.sh"
[[ -f "$TEMPLATE" ]] || die "no unit template at $TEMPLATE"
[[ -x "${REPO_ROOT}/scripts/signal_api_watchdog.sh" ]] ||
die "no executable ${REPO_ROOT}/scripts/signal_api_watchdog.sh"
local unit
for unit in "${WATCHDOG_UNITS[@]}"; do
[[ -f "${REPO_ROOT}/scripts/${unit}" ]] || die "no unit template for ${unit}"
done
}
# Without linger, a user unit dies at logout and never starts at boot.
@ -79,6 +87,18 @@ install_unit() {
echo "== installed and started ${UNIT_DIR}/${UNIT_NAME}"
}
# The bot cannot restart the container it depends on from inside a wedged
# event loop, so recovery from a dead Signal connection lives in a timer.
install_watchdog() {
local unit
for unit in "${WATCHDOG_UNITS[@]}"; do
sed "s|@REPO_ROOT@|${REPO_ROOT}|g" "${REPO_ROOT}/scripts/${unit}" >"${UNIT_DIR}/${unit}"
done
systemctl --user daemon-reload
systemctl --user enable --now "$WATCHDOG_TIMER" >/dev/null
echo "== installed and armed ${UNIT_DIR}/${WATCHDOG_TIMER}"
}
# Report what actually happened, not that the commands returned 0.
verify() {
local port="$1"
@ -90,6 +110,12 @@ verify() {
signal_wait_for_url "http://127.0.0.1:${port}/healthz" "signal-bot" 60
echo "== active, and answering on http://127.0.0.1:${port}/healthz"
echo "== enabled at boot: $(systemctl --user is-enabled "$UNIT_NAME")"
if ! systemctl --user is-active --quiet "$WATCHDOG_TIMER"; then
echo "Error: ${WATCHDOG_TIMER} is not active; nothing will recover a dead" >&2
echo " connection to Signal automatically." >&2
return 1
fi
systemctl --user list-timers --no-pager "$WATCHDOG_TIMER" | sed -n '2p'
}
main() {
@ -100,6 +126,7 @@ main() {
if [[ "$VERIFY_ONLY" != "true" ]]; then
require_linger
install_unit
install_watchdog
fi
verify "$port"

64
scripts/selftest.sh Executable file
View File

@ -0,0 +1,64 @@
#!/bin/bash
# ============================================================================
# Type a command at the running bot on its own behalf.
#
# Signal never delivers an account its own sends, so this is the only way to
# exercise a command end-to-end without a second Signal account. It posts for
# real, into a real group -- SELFTEST_GROUPS decides which.
#
# scripts/selftest.sh testbot '!papież' 5
# ============================================================================
set -euo pipefail
SCRIPT_NAME="$(basename "$0")"
readonly SCRIPT_NAME
readonly BOT="http://127.0.0.1:${BIND_PORT:-8137}"
GROUP="${1:-}"
TEXT="${2:-}"
TIMES="${3:-1}"
usage() {
echo "Usage: $SCRIPT_NAME <group-name> <text> [times]"
echo " The group must be listed in SELFTEST_GROUPS, or the bot refuses."
exit 0
}
validate_requirements() {
if [[ -z "$GROUP" || -z "$TEXT" ]]; then
echo "Error: group and text are required" >&2
usage
fi
if ! command -v jq >/dev/null; then
echo "Error: jq is required" >&2
exit 1
fi
if ! curl -sf "${BOT}/healthz" >/dev/null; then
echo "Error: no healthy bot at ${BOT}" >&2
exit 1
fi
}
main() {
validate_requirements
local reply status
for ((i = 1; i <= TIMES; i++)); do
reply="$(curl -s -X POST "${BOT}/_selftest" \
-H 'Content-Type: application/json' \
--data "$(jq -nc --arg g "$GROUP" --arg t "$TEXT" '{group:$g,text:$t}')")"
status="$(jq -r '.status' <<<"$reply")"
if [[ "$status" != "delivered" ]]; then
echo " ${i}/${TIMES} ${status}: $(jq -r '.reason // "?"' <<<"$reply")" >&2
exit 1
fi
echo " ${i}/${TIMES} delivered ${TEXT} to ${GROUP}"
# The cooldown is per user per command, and the self-test is always
# the same user, so a tighter loop just proves the cooldown works.
[[ $i -lt $TIMES ]] && sleep "${SELFTEST_INTERVAL:-11}"
done
echo "== done; look at ${GROUP} in Signal"
}
main "$@"

View File

@ -0,0 +1,22 @@
# Installed to ~/.config/systemd/user/ by scripts/install_service.sh, which
# substitutes @REPO_ROOT@. Edit this template, never the installed copy.
[Unit]
Description=Restart signal-cli-rest-api when it can no longer reach Signal
Documentation=file://@REPO_ROOT@/README.md
After=docker.service
Wants=docker.service
[Service]
Type=oneshot
WorkingDirectory=@REPO_ROOT@
# PHONE_NUMBER, API_BASE_URL and BIND_PORT come from the same file the bot
# reads, so the watchdog can never probe a different account than the bot.
EnvironmentFile=@REPO_ROOT@/.env
ExecStart=@REPO_ROOT@/scripts/signal_api_watchdog.sh
# A oneshot under a timer has no memory of its own: the failure counter and
# the restart history have to live somewhere that survives the exit.
StateDirectory=signal-api-watchdog
# Deliberately NOT ProtectHome: StateDirectory for a user unit writes under
# $HOME/.local/state, which a read-only home would make fail.
NoNewPrivileges=true

View File

@ -0,0 +1,15 @@
# Installed to ~/.config/systemd/user/ by scripts/install_service.sh.
[Unit]
Description=Probe signal-cli's connection to Signal every two minutes
[Timer]
# Two minutes: the bot's own gate needs ~2 min of silence plus three probes
# to admit it is deaf, so checking faster would only ask before it knows.
OnBootSec=2min
OnUnitActiveSec=2min
AccuracySec=10s
Unit=signal-api-watchdog.service
[Install]
WantedBy=timers.target

View File

@ -4,16 +4,24 @@
[Unit]
Description=Signal group bot
Documentation=file://@REPO_ROOT@/README.md
# The bot's only outbound dependency is signal-cli-rest-api in Docker. That
# container runs --restart=always, so it comes back by itself, but Docker has
# to exist before the bot's first connection attempt.
# The bot's only outbound dependency is signal-cli-rest-api in Docker. This
# ordering is worth having and is NOT a fix: dockerd being up says nothing
# about whether the container inside it has finished starting, and signal-cli
# then spends further minutes loading the account. systemd cannot express
# "after that container is ready", so the bot retries the connection itself
# (signal_bot/startup.py) and serves an unhealthy /healthz meanwhile.
After=network-online.target docker.service
Wants=network-online.target
# A config error -- missing GROUP_IDS, a port that is taken -- exits non-zero
# instantly, and would otherwise spin forever at RestartSec. Five failures in
# a minute stops the unit in `failed` state, which is visible in `systemctl
# --user status`, instead of hiding as a permanent restart loop.
StartLimitIntervalSec=60
# The start limit now only has to catch answers, not outages. A config error
# -- a missing PHONE_NUMBER, a taken port, a container in the wrong mode --
# exits almost instantly and would otherwise spin forever, so five of those
# stop the unit in `failed`, which shows up in `systemctl --user --failed`.
#
# The arithmetic: 5 starts x RestartSec=30 is 120s, comfortably inside the
# 300s window, so a genuine config error still trips the limit. What used to
# trip it was 5 x 5s = 25s of a container being slow to boot; on 2026-08-30
# that left the group with no bot for eight hours.
StartLimitIntervalSec=300
StartLimitBurst=5
[Service]
@ -21,10 +29,16 @@ Type=exec
WorkingDirectory=@REPO_ROOT@
# run.sh execs the interpreter, so this PID is the bot itself.
ExecStart=@REPO_ROOT@/run.sh
# `always`, not `on-failure`: this process has no correct reason to exit 0.
# `always`, not `on-failure`: the bot never exits on its own except when
# startup hits something no retry can fix, and that path asks uvicorn to
# shut down cleanly -- so exit 0 must still count as a restart.
Restart=always
RestartSec=5
# The bot writes only its SQLite tally database, inside the repo.
RestartSec=30
# The bot writes its SQLite tally database inside the repo, and papal
# portraits into the cache directory. CacheDirectory= is load-bearing:
# ProtectHome=read-only makes the rest of $HOME immutable, and systemd
# exempts only the directory it created, exporting it as $CACHE_DIRECTORY.
CacheDirectory=signal-bot
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict

179
scripts/signal_api_watchdog.sh Executable file
View File

@ -0,0 +1,179 @@
#!/bin/bash
# ============================================================================
# Restart signal-cli-rest-api when it can no longer reach Signal.
#
# Nothing else notices this failure. On 2026-08-29 the container's own
# healthcheck answered 204, /v1/groups answered 200 out of local state, and
# the bot's WebSocket to it stayed open, while signal-cli reconnected to
# Signal in a loop for three hours and not one message arrived. Docker cannot
# see it, so a timer asks the one question that needs a real round trip.
#
# Runs from signal-api-watchdog.timer as a oneshot, so every counter lives on
# disk: the process has no memory of the previous firing.
# ============================================================================
set -euo pipefail
SCRIPT_NAME="$(basename "$0")"
readonly SCRIPT_NAME
readonly API="${API_BASE_URL:-http://localhost:9922}"
readonly BOT="http://127.0.0.1:${BIND_PORT:-8137}/healthz"
readonly CONTAINER="${SIGNAL_CONTAINER:-signal-api}"
readonly STATE_DIR="${STATE_DIRECTORY:-${XDG_STATE_HOME:-$HOME/.local/state}/signal-api-watchdog}"
# Overridable so the tests can drive the whole ladder without waiting.
readonly PROBE_TIMEOUT="${PROBE_TIMEOUT:-15}"
readonly FAILURES_BEFORE_RESTART="${FAILURES_BEFORE_RESTART:-2}"
readonly MAX_RESTARTS="${MAX_RESTARTS:-3}"
readonly RESTART_WINDOW="${RESTART_WINDOW:-21600}" # 6 hours
readonly SETTLE_SECONDS="${SETTLE_SECONDS:-45}"
readonly FAILURE_FILE="${STATE_DIR}/consecutive_failures"
readonly RESTART_FILE="${STATE_DIR}/restarts"
usage() {
echo "Usage: $SCRIPT_NAME"
echo " Probes signal-cli's connection to Signal and restarts ${CONTAINER}"
echo " when it has been dead for ${FAILURES_BEFORE_RESTART} consecutive checks."
echo " Reads PHONE_NUMBER, API_BASE_URL and BIND_PORT from the environment."
exit 0
}
die() {
echo "Error: $1" >&2
exit 1
}
# journald and the desktop, always both: the broken path IS Signal, so the
# bot cannot tell anybody about this itself.
alarm() {
logger --priority user.warning --tag signal-api-watchdog -- "$1" || true
echo "== $1"
notify-send --urgency=critical --app-name=signal-bot "signal-bot" "$1" 2>/dev/null || true
}
validate_requirements() {
command -v curl >/dev/null || die "curl not found"
command -v docker >/dev/null || die "docker not found"
[[ -n "${PHONE_NUMBER:-}" ]] ||
die "PHONE_NUMBER is unset -- the unit must load the repo's .env"
mkdir -p "$STATE_DIR"
}
read_count() {
local value=0
[[ -f "$FAILURE_FILE" ]] && read -r value <"$FAILURE_FILE"
printf '%s' "${value:-0}"
}
# --max-time on every probe: an unbounded curl would outlive the timer
# interval and overlap the next firing.
http_code() {
curl -s -o /dev/null -m "$2" -w '%{http_code}' "$1" || true
}
# Two tiers. The bot's own /healthz is free and already knows whether it can
# hear; the authenticated probe is what confirms it independently, and what
# still works when the bot process itself is down.
connection_is_alive() {
if [[ "$(http_code "$BOT" 5)" == "200" ]]; then
return 0
fi
local code
code="$(http_code "${API}/v1/devices/${PHONE_NUMBER}" "$PROBE_TIMEOUT")"
if [[ "$code" == "200" ]]; then
return 0
fi
echo "== ${API}/v1/devices answered ${code}"
return 1
}
record_success() {
local previous
previous="$(read_count)"
printf '0\n' >"$FAILURE_FILE"
if ((previous >= FAILURES_BEFORE_RESTART)); then
alarm "signal-api is reachable again after ${previous} failed probe(s)."
fi
}
# Restart history is durable and pruned to the window, so a fault that
# recurs every few hours cannot be papered over by a counter that resets.
recent_restarts() {
local now cutoff stamp count=0 pruned
now="$(date +%s)"
cutoff=$((now - RESTART_WINDOW))
if [[ ! -f "$RESTART_FILE" ]]; then
printf '0'
return 0
fi
pruned="${RESTART_FILE}.pruned"
: >"$pruned"
while read -r stamp; do
[[ "$stamp" =~ ^[0-9]+$ ]] || continue
((stamp > cutoff)) || continue
printf '%s\n' "$stamp" >>"$pruned"
count=$((count + 1))
done <"$RESTART_FILE"
mv "$pruned" "$RESTART_FILE"
printf '%s' "$count"
}
give_up() {
alarm "signal-api has been restarted ${MAX_RESTARTS} time(s) and is still deaf. \
This is probably not transient: the account may be deregistered, or the host \
firewall may be blocking the container. Check 'docker exec ${CONTAINER} head -5 \
/var/log/signal-cli-json-rpc-1/out.log' and 'docker exec ${CONTAINER} getent hosts \
chat.signal.org'. No further restarts until the window passes."
}
restart_container() {
date +%s >>"$RESTART_FILE"
alarm "signal-api cannot reach Signal; restarting ${CONTAINER}."
docker restart "$CONTAINER" >/dev/null || die "docker restart ${CONTAINER} failed"
sleep "$SETTLE_SECONDS"
if connection_is_alive; then
printf '0\n' >"$FAILURE_FILE"
alarm "signal-api is back: the connection to Signal is alive again."
return 0
fi
alarm "signal-api restarted but is still deaf; will retry on the next check."
}
main() {
validate_requirements
if connection_is_alive; then
record_success
exit 0
fi
local failures
failures=$(($(read_count) + 1))
printf '%s\n' "$failures" >"$FAILURE_FILE"
logger --priority user.warning --tag signal-api-watchdog -- \
"signal-api probe failed (${failures}/${FAILURES_BEFORE_RESTART})" || true
echo "== probe failed (${failures}/${FAILURES_BEFORE_RESTART})"
if ((failures < FAILURES_BEFORE_RESTART)); then
exit 0
fi
if (($(recent_restarts) >= MAX_RESTARTS)); then
give_up
exit 0
fi
restart_container
}
while [[ $# -gt 0 ]]; do
case $1 in
-h | --help) usage ;;
*)
echo "Unknown option: $1" >&2
exit 1
;;
esac
done
main

229
scripts/test_watchdog.sh Executable file
View File

@ -0,0 +1,229 @@
#!/bin/bash
# ============================================================================
# Tests for scripts/signal_api_watchdog.sh.
#
# Hermetic: curl and docker are both stubbed on PATH, so nothing here talks to
# a network or a container. The stub docker can "fix" the stub curl's answers,
# which is how the restart-then-recover path is exercised without a restart.
# ============================================================================
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
readonly REPO_ROOT
readonly WATCHDOG="${REPO_ROOT}/scripts/signal_api_watchdog.sh"
WORK=""
FAILURES=0
cleanup() {
if [[ -n "$WORK" && -d "$WORK" ]]; then
rm -rf "$WORK"
fi
}
trap cleanup EXIT
fail() {
echo " FAIL: $1" >&2
FAILURES=$((FAILURES + 1))
}
ok() {
echo " ok: $1"
}
# Rebuild a pristine sandbox: stub binaries, stub answers, empty state.
setup() {
rm -rf "$WORK"
mkdir -p "$WORK/bin" "$WORK/state"
printf '200' >"$WORK/bot_code"
printf '200' >"$WORK/api_code"
printf '0' >"$WORK/fix_on_restart"
cat >"$WORK/bin/curl" <<EOF
#!/bin/bash
url="\${*: -1}"
case "\$url" in
*/healthz) cat "$WORK/bot_code" ;;
*) cat "$WORK/api_code" ;;
esac
EOF
cat >"$WORK/bin/docker" <<EOF
#!/bin/bash
echo "\$@" >> "$WORK/docker.log"
if [[ "\$(cat "$WORK/fix_on_restart")" == "1" ]]; then
printf '200' > "$WORK/bot_code"
printf '200' > "$WORK/api_code"
fi
EOF
chmod +x "$WORK/bin/curl" "$WORK/bin/docker"
}
run_watchdog() {
PATH="$WORK/bin:$PATH" \
PHONE_NUMBER="+15550000000" \
STATE_DIRECTORY="$WORK/state" \
SETTLE_SECONDS=0 \
FAILURES_BEFORE_RESTART=2 \
MAX_RESTARTS=2 \
RESTART_WINDOW=3600 \
"$WATCHDOG" 2>&1
}
expect_contains() {
if [[ "$1" == *"$2"* ]]; then
ok "$3"
else
fail "$3 -- got: $1"
fi
}
expect_missing() {
if [[ "$1" != *"$2"* ]]; then
ok "$3"
else
fail "$3 -- unexpectedly found $2"
fi
}
expect_file() {
local actual
actual="$(cat "$1" 2>/dev/null || echo MISSING)"
if [[ "$actual" == "$2" ]]; then
ok "$3"
else
fail "$3 -- $1 is '$actual', expected '$2'"
fi
}
test_healthy_is_free() {
echo "== a healthy bot needs no restart and no authenticated probe"
setup
run_watchdog >/dev/null
expect_file "$WORK/state/consecutive_failures" "0" "failure counter stays at zero"
if [[ -f "$WORK/docker.log" ]]; then
fail "docker was touched while everything was healthy"
else
ok "docker was never called"
fi
}
test_one_failure_waits() {
echo "== one failed probe is not enough to restart anything"
setup
printf '400' >"$WORK/bot_code"
printf '400' >"$WORK/api_code"
local out
out="$(run_watchdog)"
expect_contains "$out" "probe failed (1/2)" "the failure is counted and logged"
expect_file "$WORK/state/consecutive_failures" "1" "counter persisted for the next firing"
if [[ -f "$WORK/docker.log" ]]; then
fail "docker was restarted after a single failure"
else
ok "docker was not restarted"
fi
}
test_confirmed_failure_restarts_and_recovers() {
echo "== two failures restart the container, and recovery is announced"
setup
printf '400' >"$WORK/bot_code"
printf '400' >"$WORK/api_code"
printf '1' >"$WORK/fix_on_restart"
run_watchdog >/dev/null
local out
out="$(run_watchdog)"
expect_contains "$(cat "$WORK/docker.log")" "restart signal-api" "the container was restarted"
expect_contains "$out" "is back" "the recovery is announced"
expect_file "$WORK/state/consecutive_failures" "0" "the counter was cleared"
}
test_restart_that_does_not_help() {
echo "== a restart that does not help says so instead of claiming success"
setup
printf '400' >"$WORK/bot_code"
printf '400' >"$WORK/api_code"
run_watchdog >/dev/null
local out
out="$(run_watchdog)"
expect_contains "$out" "still deaf" "the failed recovery is reported"
}
test_gives_up_instead_of_looping() {
echo "== it gives up loudly rather than restarting forever"
setup
printf '400' >"$WORK/bot_code"
printf '400' >"$WORK/api_code"
local out="" attempt=0
while ((attempt < 6)); do
out="$(run_watchdog)"
attempt=$((attempt + 1))
done
local restarts
restarts="$(grep -c "restart signal-api" "$WORK/docker.log")"
if [[ "$restarts" == "2" ]]; then
ok "restarts stopped at the cap (2)"
else
fail "expected 2 restarts, got $restarts"
fi
expect_contains "$out" "still deaf" "the give-up message explains what to check"
expect_contains "$out" "out.log" "the give-up message names the log to read"
}
test_requires_a_number() {
echo "== it refuses to run without PHONE_NUMBER"
setup
local out status=0
out="$(PATH="$WORK/bin:$PATH" PHONE_NUMBER="" STATE_DIRECTORY="$WORK/state" \
"$WATCHDOG" 2>&1)" || status=$?
if [[ "$status" == "1" ]]; then
ok "exited non-zero"
else
fail "expected exit 1, got $status"
fi
expect_contains "$out" "PHONE_NUMBER is unset" "it says which value is missing"
}
test_bot_down_but_account_alive() {
echo "== the bot being down is not the container's fault"
setup
printf '000' >"$WORK/bot_code"
local out
out="$(run_watchdog)"
expect_missing "$out" "probe failed" "the authenticated probe carried the check"
if [[ -f "$WORK/docker.log" ]]; then
fail "docker was restarted although the account was reachable"
else
ok "docker was not restarted"
fi
}
main() {
WORK="$(mktemp -d)"
[[ -d "$WORK" ]] || {
echo "Error: failed to create a temporary directory" >&2
exit 1
}
echo "============================================================"
echo "signal_api_watchdog.sh"
echo "============================================================"
test_healthy_is_free
test_bot_down_but_account_alive
test_one_failure_waits
test_confirmed_failure_restarts_and_recovers
test_restart_that_does_not_help
test_gives_up_instead_of_looping
test_requires_a_number
echo "============================================================"
if ((FAILURES > 0)); then
echo "FAILED: $FAILURES check(s)"
exit 1
fi
echo "all checks passed"
}
main "$@"

View File

@ -12,11 +12,10 @@ BIND_HOST/BIND_PORT whenever they live in .env -- which is where they live.
from __future__ import annotations
import logging
import uvicorn
from signal_bot.config import load_config
from signal_bot.config_env import load_config
from signal_bot.logging_setup import configure as configure_logging
from signal_bot.portcheck import PortInUseError, assert_port_free
@ -26,9 +25,7 @@ def main() -> None:
# Before anything else: uvicorn only configures its own loggers, so
# without this the bot's own log lines go to logging.lastResort and
# anything below WARNING is thrown away.
logging.basicConfig(
level=config.log_level, format="%(asctime)s %(levelname)s %(name)s: %(message)s"
)
configure_logging(config.log_level)
try:
assert_port_free(config.bind_host, config.bind_port)
except PortInUseError as exc:

View File

@ -1,11 +1,94 @@
{
"_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"
],
"pope": [
"!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"
],
"help": [
"!pomoc",
"!pomocy",
"!help",
"!komendy",
"!commands"
]
}

View File

@ -4,9 +4,13 @@
from __future__ import annotations
import json
import secrets
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Final
from signal_bot.config import DEFAULT_CAT_API_URL, DEFAULT_DOG_API_URL, DEFAULT_GECKO_API_URL
if TYPE_CHECKING:
from collections.abc import Sequence
@ -14,14 +18,56 @@ if TYPE_CHECKING:
from signal_bot.http_client import ImageFetcher
from signal_bot.registry import CommandContext, CommandRegistry, Handler
CAT_API_URL: Final = "https://api.thecatapi.com/v1/images/search"
CAT_URL_PATH: Final[tuple[str | int, ...]] = (0, "url")
DOG_API_URL: Final = "https://dog.ceo/api/breeds/image/random"
DOG_URL_PATH: Final[tuple[str | int, ...]] = ("message",)
ALIAS_FILE: Final = Path(__file__).with_name("aliases.json")
@dataclass(frozen=True, slots=True)
class ImageSource:
"""Where one image command gets its picture, and how to read the answer."""
api_url: str
url_path: tuple[str | int, ...]
# What !pomoc says this command does, in the group's language.
description: str
rewrite: tuple[str, str] | None = None
page_limit: int | None = None
# iNaturalist's pagination ceiling: page * per_page must stay at or under
# 10 000, and page=10001 comes back empty. Measured, not documented.
INATURALIST_PAGE_LIMIT: Final = 10_000
# Two iNaturalist quirks, kept beside the endpoint because that is what they
# are properties of. It answers with a 75px square thumbnail whose full-size
# sibling is one path segment away; and it accepts `order_by=random` while
# ignoring it -- five requests in a row returned the same gecko -- so the
# randomness has to come from asking for a random page instead.
SOURCES: Final[dict[str, ImageSource]] = {
"cat": ImageSource(DEFAULT_CAT_API_URL, (0, "url"), "losowe zdjęcie kota"),
"dog": ImageSource(DEFAULT_DOG_API_URL, ("message",), "losowe zdjęcie psa"),
"gecko": ImageSource(
DEFAULT_GECKO_API_URL,
("results", 0, "photos", 0, "url"),
"losowe zdjęcie gekona",
("/square.", "/large."),
INATURALIST_PAGE_LIMIT,
),
}
def paged_url(api_url: str, page_limit: int | None) -> str:
"""Return api_url, pointed at a random page when the source needs one.
secrets rather than random: the choice is not security-sensitive, but
ruff's ALL rule set flags random for exactly this shape, and this repo
forbids the noqa that would silence it.
"""
if page_limit is None:
return api_url
separator = "&" if "?" in api_url else "?"
return f"{api_url}{separator}page={secrets.randbelow(page_limit) + 1}"
def load_aliases(path: Path = ALIAS_FILE) -> dict[str, list[str]]:
"""Load the trigger table.
@ -32,12 +78,19 @@ def load_aliases(path: Path = ALIAS_FILE) -> dict[str, list[str]]:
return {name: list(triggers) for name, triggers in document.items() if not name.startswith("_")}
def image_handler(fetcher: ImageFetcher, api_url: str, url_path: Sequence[str | int]) -> Handler:
def image_handler(
fetcher: ImageFetcher,
api_url: str,
url_path: Sequence[str | int],
rewrite: tuple[str, str] | None = None,
page_limit: int | None = None,
) -> Handler:
"""Build a handler that posts one random image from a JSON image API."""
async def handler(ctx: CommandContext) -> None:
encoded = await fetcher.fetch_base64(api_url, url_path)
await ctx.transport.send_image(encoded, ctx.group_id)
url = paged_url(api_url, page_limit)
encoded = await fetcher.fetch_base64(url, url_path, rewrite)
await ctx.reply_image(encoded)
return handler
@ -50,7 +103,7 @@ def register_animal_commands(
aliases: dict[str, list[str]] | None = None,
endpoints: dict[str, str] | None = None,
) -> None:
"""Register the cat and dog commands on a registry.
"""Register every image command on a registry.
Args:
registry: Registry to populate.
@ -62,14 +115,12 @@ def register_animal_commands(
public APIs; the offline environment points these at itself.
"""
table = load_aliases() if aliases is None else aliases
urls = {"cat": CAT_API_URL, "dog": DOG_API_URL} | (endpoints or {})
paths: dict[str, tuple[str | int, ...]] = {
"cat": CAT_URL_PATH,
"dog": DOG_URL_PATH,
}
for name, api_url in urls.items():
url_path = paths[name]
handler = image_handler(fetcher, api_url, url_path)
overrides = endpoints or {}
for name, source in SOURCES.items():
api_url = overrides.get(name, source.api_url)
handler = image_handler(
fetcher, api_url, source.url_path, source.rewrite, source.page_limit
)
if decorate is not None:
handler = decorate(handler)
registry.register(name, table[name], handler)
registry.register(name, table[name], handler, source.description)

130
signal_bot/announce.py Normal file
View File

@ -0,0 +1,130 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Telling a group that the bot has been upgraded.
A group is told about every release it has not seen, and a group that has
never been told anything has not seen any of them -- so the first
announcement starts at 0.0.0 "Petrus" rather than skipping straight to
whatever is current. Watching the ladder start at Peter is the point of
naming releases after popes at all.
That does mean a group added years from now would be handed the whole
backlog, so the message is capped at MAX_RELEASES and says how many older
versions it left out.
The announcement carries the same three things `!papiez` does: the pope's
portrait, his Latin name and his Polish Wikipedia article. Only for the pope
in the header -- ten attachments is the wall MAX_RELEASES exists to avoid.
The version is recorded *before* the message is sent. `Restart=always` with
`RestartSec=5` means a crash between the two would otherwise re-announce on
every restart, and a missed announcement is far cheaper than a looping one.
That is also why a portrait that will not download costs the photo and not
the announcement: the marker is already written, so a Commons outage at boot
would otherwise eat that group's release notes permanently.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Final
from signal_bot.changelog import since
from signal_bot.versioning import article_url, latin_name, pope_line, version_for
if TYPE_CHECKING:
from collections.abc import Iterable
from signal_bot.changelog import Release
from signal_bot.portraits import PortraitCache
from signal_bot.store import Store
from signal_bot.transport_base import Transport
from signal_bot.versioning import Pope
logger = logging.getLogger(__name__)
ANNOUNCED_KEY: Final = "announced_version"
# How many releases one announcement may list before it becomes a wall.
MAX_RELEASES: Final = 10
def render(pope: Pope, releases: Iterable[Release]) -> str:
"""Return the message announcing a new version, in Polish.
One release is rendered flat, because the header already names it. Several
get a block each, so the group can see the ladder it is climbing. Pure on
purpose: whether this text travels as a caption or as a plain message is
announce_to's call, not this function's.
"""
shown = list(releases)
header = f"Wersja {version_for(pope.ordinal)} \u00ab{latin_name(pope)}\u00bb wydana"
header = f"{header}\n{pope_line(pope)}\n{article_url(pope)}"
omitted = max(0, len(shown) - MAX_RELEASES)
shown = shown[-MAX_RELEASES:]
if len(shown) == 1:
body = "\n".join(f"- {line}" for line in shown[0].lines)
return f"{header}\nChangelog:\n{body}"
blocks = [
"\n".join(
[
f"{release.version} \u00ab{latin_name(release.pope_entry)}\u00bb",
pope_line(release.pope_entry),
*(f"- {x}" for x in release.lines),
]
)
for release in shown
]
tail = f"\n\n(pominieto {omitted} starszych wersji)" if omitted else ""
return f"{header}\nChangelog:\n\n" + "\n\n".join(blocks) + tail
async def announce_to(
transport: Transport,
store: Store,
group_id: str,
releases: tuple[Release, ...],
pope: Pope,
portraits: PortraitCache,
) -> None:
"""Announce the current version to one group, if it has not seen it."""
version = version_for(pope.ordinal)
previous = store.meta(group_id, ANNOUNCED_KEY)
if previous == version:
return
# No record at all means the group has seen nothing, not that it should be
# skipped: that is how Petrus gets announced rather than silently assumed.
pending = releases if previous is None else since(releases, previous)
store.set_meta(group_id, ANNOUNCED_KEY, version)
if not pending:
logger.info("group %s recorded at %s with nothing to announce", group_id, version)
return
text = render(pope, pending)
try:
image = await portraits.get_base64(pope)
await transport.send_image(image, group_id, caption=text)
except Exception:
# Both the download and the send are inside this: the marker is
# already written, so either failing would otherwise cost the group
# its release notes permanently. The attachment turns a 2 KB text
# post into a megabyte of base64, which signal-cli can refuse on its
# own terms while it is perfectly able to take the text -- and a
# duplicate post, if the send failed after delivery, is far cheaper
# than release notes nobody ever sees.
logger.exception("photo announcement of %s failed for %s; sending text", version, group_id)
await transport.send_text(text, group_id)
async def announce_all(
transport: Transport,
store: Store,
group_ids: Iterable[str],
releases: tuple[Release, ...],
pope: Pope,
portraits: PortraitCache,
) -> None:
"""Announce to every watched group; one failure must not silence the rest."""
for group_id in group_ids:
try:
await announce_to(transport, store, group_id, releases, pope, portraits)
except Exception:
logger.exception("release announcement failed for group %s", group_id)

View File

@ -1,199 +1,132 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Application wiring and the ASGI entrypoint."""
"""The ASGI entrypoint, and the one endpoint that says whether the bot works.
Wiring lives in bot.py and the startup sequence in startup.py. What is left
here is the part uvicorn imports: an app that begins serving immediately, so
that "the bot is still connecting" is a state you can ask about rather than a
process that is not there.
"""
from __future__ import annotations
import asyncio
import contextlib
import datetime as dt
import logging
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
import httpx
from fastapi import FastAPI, Response, status
from pydantic import BaseModel
from signal_bot.config_env import load_config
from signal_bot.selftest import SelfTestError
from signal_bot.selftest import run as run_selftest
from signal_bot.startup_retry import Starter
from signal_bot.store import Store
from signal_bot.versioning import POPE, __version__, latin_name, pope_line
if TYPE_CHECKING:
from collections.abc import AsyncIterator
from signal_bot.transport_base import Transport
import httpx
from fastapi import FastAPI
from signal_bot.animals import register_animal_commands
from signal_bot.config import Config, load_config
from signal_bot.counting import format_tally
from signal_bot.decorators import cooldown
from signal_bot.discovery import GroupDirectory
from signal_bot.dispatcher import Dispatcher
from signal_bot.http_client import ImageFetcher
from signal_bot.registry import CommandRegistry
from signal_bot.scheduler import DailyScheduler
from signal_bot.store import Store
from signal_bot.transport_rest import RestTransport
logger = logging.getLogger(__name__)
COOLDOWN_MESSAGE = "BEEP BOOP POCZEKAJ {seconds} SEKUND."
HTTP_TIMEOUT_SECONDS = 30.0
def now_local() -> dt.datetime:
"""Current local time, timezone-aware."""
return dt.datetime.now().astimezone()
@dataclass
class Bot:
"""The wired-up bot and its two long-running loops."""
config: Config
store: Store
transport: Transport
directory: GroupDirectory
dispatcher: Dispatcher
async def publish_report(self) -> None:
"""Post each group's own tally into that group, and reset it.
Each group is isolated on purpose. One group refusing the report --
the bot removed from it, a transient send failure -- must not cost
every other group its report, and a tally is cleared only after its
report has actually gone out, so a failed send loses nothing. A
group where nobody spoke is skipped entirely.
"""
for group_id in self.directory.groups:
rows = [(t.display_name or t.uuid, t.count) for t in self.store.tallies(group_id)]
if not rows:
# Logged, not posted. The bot is in every group it was ever
# added to, so posting "nobody spoke" would mean a nightly
# ping into every quiet group, forever.
logger.info("no messages in %s today; not posting a report", group_id)
continue
try:
await self.transport.send_text(format_tally(rows), group_id)
except Exception:
logger.exception("daily report failed for group %s", group_id)
continue
self.store.reset_tallies(group_id)
async def listen(self) -> None:
"""Consume frames forever, handing each to the dispatcher."""
async for frame in self.transport.receive():
await self.dispatcher.handle(frame)
def build_bot(
config: Config,
client: httpx.AsyncClient,
store: Store,
transport: Transport,
directory: GroupDirectory,
) -> Bot:
"""Assemble the object graph from its injected dependencies."""
registry = CommandRegistry()
register_animal_commands(
registry,
ImageFetcher(client),
decorate=cooldown(config.cooldown_seconds, COOLDOWN_MESSAGE),
endpoints={"cat": config.cat_api_url, "dog": config.dog_api_url},
)
dispatcher = Dispatcher(
config=config,
directory=directory,
registry=registry,
store=store,
transport=transport,
clock=now_local,
)
return Bot(
config=config,
store=store,
transport=transport,
directory=directory,
dispatcher=dispatcher,
)
@dataclass
class Runtime:
"""Owns everything that must be torn down when the app stops."""
bot: Bot
client: httpx.AsyncClient
store: Store
tasks: list[asyncio.Task[None]] = field(default_factory=list)
def start(self) -> None:
"""Spawn the listener and the daily scheduler as background tasks."""
scheduler = DailyScheduler(
self.bot.config.report_hour,
self.bot.config.report_minute,
self.bot.publish_report,
now_local,
asyncio.sleep,
)
self.tasks = [
asyncio.create_task(self.bot.listen()),
asyncio.create_task(scheduler.run()),
# Third loop: without it, a group added later is only noticed
# when somebody happens to speak in it.
asyncio.create_task(self.bot.directory.run()),
]
async def stop(self) -> None:
"""Cancel the background tasks and close every resource."""
for task in self.tasks:
task.cancel()
for task in self.tasks:
with contextlib.suppress(asyncio.CancelledError):
await task
await self.client.aclose()
self.store.close()
async def create_runtime(config: Config, client: httpx.AsyncClient) -> Runtime:
"""Build a Runtime, verifying the container exposes a WebSocket first."""
store = Store(config.database_path)
transport = RestTransport(config, client)
await transport.verify_mode()
directory = GroupDirectory(config, client, store)
await directory.refresh()
await directory.verify_allowlist()
return Runtime(
bot=build_bot(config, client, store, transport, directory),
client=client,
store=store,
)
# iNaturalist asks automated clients to identify themselves, and Wikimedia's
# policy outright refuses the default "python-httpx/x.y" this used to send.
USER_AGENT = f"signal-bot/{__version__} (+https://github.com/kuhyx/signal-bot)"
@contextlib.asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
"""Start the background tasks without blocking ASGI startup.
"""Serve first, connect to Signal afterwards.
The previous version awaited asyncio.gather() on two infinite tasks inside
an on_event("startup") handler, so uvicorn never finished starting up and
the HTTP app never began serving.
Two earlier versions of this got it wrong in opposite directions. The
first awaited asyncio.gather() on two infinite tasks, so uvicorn never
finished starting and never served at all. The second connected to
signal-cli inline, so a container that was not ready yet failed startup
outright and burned the unit's restart limit in 25 seconds.
Config errors still fail here and exit non-zero: load_config() raising is
an answer, not an outage, and no amount of waiting fixes a missing
PHONE_NUMBER. Everything that needs the network is handed to Starter.
"""
config = load_config()
client = httpx.AsyncClient(timeout=HTTP_TIMEOUT_SECONDS)
runtime = await create_runtime(config, client)
runtime.start()
logger.info(
"listening as %s, watching %d group(s): %r",
config.phone_number,
len(runtime.bot.directory.groups),
list(runtime.bot.directory.groups),
)
app.state.runtime = runtime
client = httpx.AsyncClient(timeout=HTTP_TIMEOUT_SECONDS, headers={"User-Agent": USER_AGENT})
# Opened once, here, rather than inside the retried connection attempt:
# a Store per attempt would leak one SQLite handle per failed try, for
# as long as the container stayed down.
store = Store(config.database_path)
starter = Starter(config, client, store)
app.state.starter = starter
app.state.client = client
connecting = asyncio.create_task(starter.run())
logger.info("serving on %s:%d while connecting to Signal", config.bind_host, config.bind_port)
try:
yield
finally:
await runtime.stop()
connecting.cancel()
with contextlib.suppress(asyncio.CancelledError):
await connecting
if starter.runtime is not None:
await starter.runtime.stop()
await client.aclose()
store.close()
class SelfTestRequest(BaseModel):
"""One command to type at the bot, and where."""
group: str
text: str
app = FastAPI(lifespan=lifespan)
@app.get("/healthz")
async def healthz() -> dict[str, str]:
"""Liveness probe. The old app defined no routes at all."""
return {"status": "ok"}
async def healthz(response: Response) -> dict[str, str]:
"""Liveness probe, and the only place the bot admits it is not working.
Answering 200 while nothing can reach Signal is what let a three-hour
outage look like a quiet evening, so this must go red before anybody
thinks to look at the logs. It has three answers, not two: a bot that has
not connected yet is "connecting", which is what a booting machine looks
like, and is not the same thing as one that has gone deaf.
"""
starter: Starter = app.state.starter
build = {
"version": __version__,
"pope": latin_name(POPE),
# The same sentence the group is shown, so "which release is this?"
# has one answer whether it is asked here or in Signal.
"papacy": pope_line(POPE),
}
runtime = starter.runtime
if runtime is None:
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
return {"status": "connecting", "reason": starter.reason, **build}
liveness = runtime.bot.liveness
if liveness.healthy:
return {"status": "ok", **build}
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
return {"status": "deaf", "reason": liveness.reason, **build}
@app.post("/_selftest")
async def selftest(request: SelfTestRequest, response: Response) -> dict[str, str]:
"""Type a command at the bot on its own behalf, for verification.
Bound to loopback with the rest of the app, and refuses any group not
named in SELFTEST_GROUPS. See signal_bot/selftest.py for why this exists.
"""
starter: Starter = app.state.starter
runtime = starter.runtime
if runtime is None:
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
return {"status": "connecting", "reason": starter.reason}
try:
group_id = await run_selftest(runtime.bot, app.state.client, request.group, request.text)
except SelfTestError as refusal:
response.status_code = status.HTTP_403_FORBIDDEN
return {"status": "refused", "reason": str(refusal)}
return {"status": "delivered", "group": group_id, "text": request.text}

205
signal_bot/bot.py Normal file
View File

@ -0,0 +1,205 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The bot object itself: the command wiring and the two loops it owns.
Split out of app.py, which had grown to the 250-line cap with the ASGI
entrypoint, the object graph and the startup sequence all in one file. This
half is "what the bot does"; startup.py is "how it comes up".
"""
from __future__ import annotations
import datetime as dt
import logging
from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING
from signal_bot.animals import register_animal_commands
from signal_bot.announce import announce_all
from signal_bot.changelog import load as load_changelog
from signal_bot.decorators import cooldown
from signal_bot.dispatcher import Dispatcher
from signal_bot.help_command import register_help_command
from signal_bot.http_client import ImageFetcher
from signal_bot.pack_command import register_pack_commands
from signal_bot.pack_load import load as load_pack
from signal_bot.popes_command import register_pope_command
from signal_bot.portraits import PortraitCache
from signal_bot.registry import CommandRegistry
from signal_bot.reporting import compose
from signal_bot.stats import periods
from signal_bot.stats.commands import register_stats_commands
from signal_bot.stats.nightly import days_to_report, mark_reported
from signal_bot.versioning import POPE
if TYPE_CHECKING:
import httpx
from signal_bot.config import Config
from signal_bot.discovery import GroupDirectory
from signal_bot.liveness import Liveness
from signal_bot.store import Store
from signal_bot.transport_base import Transport
logger = logging.getLogger(__name__)
Clock = Callable[[], dt.datetime]
COOLDOWN_MESSAGE = "BEEP BOOP POCZEKAJ {seconds} {unit}."
def now_local() -> dt.datetime:
"""Current Warsaw time -- the group's day, not the host's.
One definition of "day" for the whole bot. The daily scheduler fires
against this, ``CommandContext.day`` keys the daily limits off it, and
every event is filed under it, so a host in another timezone (or a
container on UTC) cannot make those three disagree.
"""
return periods.now()
@dataclass
class Bot:
"""The wired-up bot and its two long-running loops."""
config: Config
store: Store
transport: Transport
directory: GroupDirectory
dispatcher: Dispatcher
liveness: Liveness
# The same cache !papiez draws from, so a release announcement and the
# command never download the same portrait twice.
portraits: PortraitCache
# The same clock the dispatcher files events against. One clock, so
# "which day is it" cannot differ between writing an event and reporting
# on it -- which is precisely the drift the old reset-after-post had.
clock: Clock = now_local
async def publish_report(self) -> None:
"""Post each group **one** message: today, plus anything still owed.
Today, because 21:37 is when the group expects to read its own
numbers; a post at 21:37 about yesterday is a day late to everyone
looking at it. The count therefore closes at the report time and the
rest of the evening lands in tomorrow's day -- render_day says so,
because a total that quietly omits three hours is worse than one that
admits to it.
One message, always. A run can have several things to say -- a day
the bot was down for, the day it is on now, and the week or month
that ended inside them -- and saying each in its own post turns one
evening into four notifications. They are blocks in one message
instead, which is also what makes the send atomic: either the group
got the lot, or nothing is marked and the next run says it all again.
Nothing is deleted afterwards. Each group is isolated on purpose: one
group refusing the report -- the bot removed from it, a transient send
failure -- must not cost every other group its report.
"""
latest = periods.today(self.clock())
for group_id in self.directory.groups:
await self._report_group(group_id, latest)
async def _report_group(self, group_id: str, latest: str) -> None:
"""Say everything one group is owed, in one message or not at all."""
days = days_to_report(self.store, group_id, latest)
if not days:
return
now = self.clock()
text = compose(
self.store,
self.directory,
group_id,
days,
today=periods.today(now),
# Off the clock rather than off REPORT_HOUR: the scheduled run
# fires at the configured minute and so says exactly that, while
# a run started by hand at some other hour tells the truth
# instead of repeating a time nobody waited for.
closed_at=now.strftime("%H:%M"),
)
if text:
try:
await self.transport.send_text(text, group_id)
except Exception:
# Nothing is marked, so the next run repeats the whole thing
# rather than losing the days that were inside this message.
logger.exception("report failed for group %s", group_id)
return
# Marked even when there was nothing to say: a day nobody spoke on is
# settled, not pending, and leaving it unmarked would make the bot
# reconsider it every night forever.
for day in days:
mark_reported(self.store, group_id, day)
async def announce_release(self) -> None:
"""Tell every watched group about a version it has not seen yet."""
await announce_all(
self.transport,
self.store,
list(self.directory.groups),
load_changelog(),
POPE,
self.portraits,
)
async def listen(self) -> None:
"""Consume frames forever, handing each to the dispatcher."""
async for frame in self.transport.receive():
# Every frame counts, including receipts and typing indicators:
# the question this answers is "can anything still reach us?",
# not "did anybody address the bot?".
self.liveness.note_envelope()
await self.dispatcher.handle(frame)
def build_bot(
config: Config,
client: httpx.AsyncClient,
store: Store,
transport: Transport,
directory: GroupDirectory,
liveness: Liveness,
clock: Clock = now_local,
) -> Bot:
"""Assemble the object graph from its injected dependencies."""
registry = CommandRegistry()
fetcher = ImageFetcher(client)
portraits = PortraitCache(fetcher, config.commons_api_url)
rate_limit = cooldown(config.cooldown_seconds, COOLDOWN_MESSAGE)
register_animal_commands(
registry,
fetcher,
decorate=rate_limit,
endpoints=config.image_api_urls,
)
register_pope_command(registry, portraits, decorate=rate_limit)
register_stats_commands(registry, decorate=rate_limit)
# Absent unless this installation has an album, and scoped to that
# album's own groups when it does -- so on every other machine, and in
# every other group, these commands simply do not exist.
if config.photo_pack_dir is not None:
register_pack_commands(registry, load_pack(config.photo_pack_dir), decorate=rate_limit)
# Last, so !pomoc trails the list it prints; it reads the registry
# when it runs, so the order is presentation only.
register_help_command(registry, decorate=rate_limit)
dispatcher = Dispatcher(
config=config,
directory=directory,
registry=registry,
store=store,
transport=transport,
clock=clock,
)
return Bot(
config=config,
store=store,
transport=transport,
directory=directory,
dispatcher=dispatcher,
liveness=liveness,
portraits=portraits,
clock=clock,
)

102
signal_bot/changelog.py Normal file
View File

@ -0,0 +1,102 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The changelog the bot announces, read from DOCS-changelog.md.
That file is the single source: there is no second machine-readable copy to
drift out of sync with it. Only two shapes are recognised -- a `## <version> —
<pope>` heading and a `- ` bullet beneath one -- so prose around them is free.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Final
from signal_bot.versioning import Pope, ordinal_for, pope_for
# Repo root, since the changelog is documentation rather than package data.
DEFAULT_PATH: Final = Path(__file__).resolve().parent.parent / "DOCS-changelog.md"
_HEADING: Final = re.compile(r"^##\s+(\d+\.\d+\.\d+)\s*[—-]\s*(.+?)\s*$")
_BULLET: Final = re.compile(r"^-\s+(.+?)\s*$")
# A wrapped bullet: indented, directly under one. Without this a bullet
# that runs past the line width is announced truncated mid-sentence.
_CONTINUATION: Final = re.compile(r"^\s+(\S.*?)\s*$")
@dataclass(frozen=True, slots=True)
class Release:
"""One released version and the lines describing it."""
version: str
pope: str
lines: tuple[str, ...]
@property
def ordinal(self) -> int:
"""The papal ordinal this release carries."""
return ordinal_for(self.version)
@property
def pope_entry(self) -> Pope:
"""The pope this release is named after, from popes.json.
Display reads this, never the ``pope`` field parsed off the heading:
the name is derived from the version, so a typo in the document
cannot make the bot announce the wrong pope into a group.
"""
return pope_for(self.ordinal)
def parse(text: str) -> tuple[Release, ...]:
"""Return every release in the document, oldest first."""
releases: list[Release] = []
version = pope = ""
lines: list[str] = []
open_bullet = False
for raw in text.splitlines():
heading = _HEADING.match(raw)
if heading is not None:
if version:
releases.append(Release(version, pope, tuple(lines)))
version, pope, lines = heading.group(1), heading.group(2), []
open_bullet = False
continue
bullet = _BULLET.match(raw)
if bullet is not None and version:
lines.append(bullet.group(1))
open_bullet = True
continue
continuation = _CONTINUATION.match(raw)
if continuation is not None and open_bullet:
lines[-1] = f"{lines[-1]} {continuation.group(1)}"
continue
open_bullet = False
if version:
releases.append(Release(version, pope, tuple(lines)))
return tuple(sorted(releases, key=lambda release: release.ordinal))
def load(path: Path | None = None) -> tuple[Release, ...]:
"""Return every release, or nothing if the changelog is not on disk.
A missing changelog must not stop the bot: it is documentation that lives
outside the package, so an odd install layout should cost an announcement
rather than the whole process.
"""
source = DEFAULT_PATH if path is None else path
try:
text = source.read_text(encoding="utf-8")
except OSError:
return ()
return parse(text)
def since(releases: tuple[Release, ...], previous: str) -> tuple[Release, ...]:
"""Return the releases newer than ``previous``, oldest first."""
try:
floor = ordinal_for(previous)
except ValueError:
return ()
return tuple(release for release in releases if release.ordinal > floor)

View File

@ -3,13 +3,19 @@
from __future__ import annotations
import logging
import os
from dataclasses import dataclass
from typing import Final
from typing import TYPE_CHECKING, Final
from urllib.parse import urlsplit, urlunsplit
from dotenv import load_dotenv
if TYPE_CHECKING:
from pathlib import Path
from signal_bot.endpoints import (
DEFAULT_CAT_API_URL,
DEFAULT_COMMONS_API_URL,
DEFAULT_DOG_API_URL,
DEFAULT_GECKO_API_URL,
)
# Re-exported: every caller has always imported these from config, and the
# split is a filing change, not an interface change.
@ -18,15 +24,19 @@ from signal_bot.groups import (
build_alias_map,
canonical_group_id,
group_id_aliases,
parse_group_ids,
)
from signal_bot.trust import parse_trusted_inviters
__all__ = [
"DEFAULT_CAT_API_URL",
"DEFAULT_COMMONS_API_URL",
"DEFAULT_DOG_API_URL",
"DEFAULT_GECKO_API_URL",
"Config",
"ConfigError",
"canonical_group_id",
"group_id_aliases",
"load_config",
"parse_trusted_inviters",
]
DEFAULT_API_BASE_URL: Final = "http://localhost:9922"
@ -34,8 +44,6 @@ DEFAULT_DATABASE_PATH: Final = "signal_bot.sqlite3"
DEFAULT_REPORT_HOUR: Final = 21
DEFAULT_REPORT_MINUTE: Final = 37
DEFAULT_COOLDOWN_SECONDS: Final = 10
DEFAULT_CAT_API_URL: Final = "https://api.thecatapi.com/v1/images/search"
DEFAULT_DOG_API_URL: Final = "https://dog.ceo/api/breeds/image/random"
DEFAULT_BIND_HOST: Final = "127.0.0.1"
# Not 8000: that port is a magnet for unrelated dev servers and was already
# taken here by a long-running enforcer. 8137 sits below the ephemeral range
@ -46,6 +54,10 @@ MAX_HOUR: Final = 23
MAX_MINUTE: Final = 59
MAX_PORT: Final = 65535
DEFAULT_LOG_LEVEL: Final = "INFO"
# How long the bot may hear nothing at all before it stops believing its own
# health. Silence is normal -- a group can be quiet all evening -- so this is
# only the point at which silence becomes worth *asking* about.
DEFAULT_SILENCE_SECONDS: Final = 120
_WS_SCHEMES: Final = {"http": "ws", "https": "wss"}
@ -67,6 +79,8 @@ class Config:
# without the bot knowing it is not talking to the real APIs.
cat_api_url: str = DEFAULT_CAT_API_URL
dog_api_url: str = DEFAULT_DOG_API_URL
gecko_api_url: str = DEFAULT_GECKO_API_URL
commons_api_url: str = DEFAULT_COMMONS_API_URL
# Where the /healthz readiness probe binds. Read here rather than in
# __main__ so that .env governs it: __main__ runs before anything has
# loaded a .env file, so an os.getenv() there would silently ignore it.
@ -77,6 +91,15 @@ class Config:
# unreachable in production, which is how a scoping mismatch turns
# into a bot that looks healthy and answers nothing.
log_level: str = DEFAULT_LOG_LEVEL
# Who may add this bot to a group. Empty means anyone. See signal_bot.trust.
trusted_inviters: tuple[str, ...] = ()
# Lowered in the e2e run so the deafness gate can be proven against the
# real process rather than only in unit tests.
silence_seconds: int = DEFAULT_SILENCE_SECONDS
# The private photo album, or None for an installation without one. Only
# the path is config; everything inside it -- who the people are, what
# fires their photos -- is data this repository never sees.
photo_pack_dir: Path | None = None
@property
def is_pinned(self) -> bool:
@ -125,79 +148,25 @@ class Config:
"""REST endpoint reporting the container build and its mode."""
return f"{self.api_base_url}/v1/about"
@property
def devices_url(self) -> str:
"""The one endpoint that fails when signal-cli cannot reach Signal.
Verified on 2026-08-29, in both directions: 200 with a device list
while healthy, and 400 "Failed to get linked devices: Closed
unexpectedly" during the outage -- while /v1/groups and /v1/about
kept answering 200 from local state and the container's own
healthcheck stayed green. Local state is why the bot could look
perfectly healthy for three hours with a dead connection.
"""
return f"{self.api_base_url}/v1/devices/{self.phone_number}"
@property
def groups_url(self) -> str:
"""REST endpoint listing the groups this account knows about."""
return f"{self.api_base_url}/v1/groups/{self.phone_number}"
def _require(env: dict[str, str], key: str) -> str:
"""Return a non-empty environment value or raise ConfigError."""
value = env.get(key, "").strip()
if not value:
msg = f"{key} is required and must not be empty."
raise ConfigError(msg)
return value
def _positive_int(env: dict[str, str], key: str, default: int) -> int:
"""Return an int environment value, falling back to default when unset."""
raw = env.get(key, "").strip()
if not raw:
return default
try:
value = int(raw)
except ValueError:
msg = f"{key} must be an integer, got {raw!r}"
raise ConfigError(msg) from None
if value < 0:
msg = f"{key} must not be negative, got {value}"
raise ConfigError(msg)
return value
def load_config(env: dict[str, str] | None = None, *, use_dotenv: bool = True) -> Config:
"""Build a Config from the environment, failing loudly on anything missing.
Args:
env: Mapping to read instead of os.environ. Used by the tests.
use_dotenv: Load a local .env file first. Disabled in tests.
Returns:
A validated, immutable Config.
"""
if env is None:
if use_dotenv:
load_dotenv()
env = dict(os.environ)
hour = _positive_int(env, "REPORT_HOUR", DEFAULT_REPORT_HOUR)
minute = _positive_int(env, "REPORT_MINUTE", DEFAULT_REPORT_MINUTE)
if hour > MAX_HOUR or minute > MAX_MINUTE:
msg = f"REPORT_HOUR/REPORT_MINUTE out of range: {hour:02d}:{minute:02d}"
raise ConfigError(msg)
log_level = env.get("LOG_LEVEL", "").strip().upper() or DEFAULT_LOG_LEVEL
if log_level not in logging.getLevelNamesMapping():
msg = f"LOG_LEVEL must be a logging level name, got {log_level!r}"
raise ConfigError(msg)
bind_port = _positive_int(env, "BIND_PORT", DEFAULT_BIND_PORT)
if not 1 <= bind_port <= MAX_PORT:
msg = f"BIND_PORT must be between 1 and {MAX_PORT}, got {bind_port}"
raise ConfigError(msg)
return Config(
phone_number=_require(env, "PHONE_NUMBER"),
group_ids=parse_group_ids(env),
api_base_url=env.get("API_BASE_URL", "").strip() or DEFAULT_API_BASE_URL,
database_path=env.get("DATABASE_PATH", "").strip() or DEFAULT_DATABASE_PATH,
report_hour=hour,
report_minute=minute,
cooldown_seconds=_positive_int(env, "COOLDOWN_SECONDS", DEFAULT_COOLDOWN_SECONDS),
cat_api_url=env.get("CAT_API_URL", "").strip() or DEFAULT_CAT_API_URL,
dog_api_url=env.get("DOG_API_URL", "").strip() or DEFAULT_DOG_API_URL,
bind_host=env.get("BIND_HOST", "").strip() or DEFAULT_BIND_HOST,
bind_port=bind_port,
log_level=log_level,
)
@property
def image_api_urls(self) -> dict[str, str]:
"""Image-API endpoint per command name, as the commands want it."""
return {"cat": self.cat_api_url, "dog": self.dog_api_url, "gecko": self.gecko_api_url}

173
signal_bot/config_env.py Normal file
View File

@ -0,0 +1,173 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Reading a :class:`~signal_bot.config.Config` out of the environment.
Split out of ``config.py`` so both stay under the 250-line cap. "What the
settings are" and "how they are parsed and validated" are two things, and only
the first is imported by the rest of the bot.
The dependency runs one way -- this module imports ``config``, never the
reverse -- so ``load_config`` is imported from here rather than re-exported
from ``config``. A re-export would need an import at the bottom of ``config``
and would break depending on which module was imported first.
"""
from __future__ import annotations
import logging
import os
from typing import TYPE_CHECKING
from dotenv import load_dotenv
from signal_bot.config import (
DEFAULT_API_BASE_URL,
DEFAULT_BIND_HOST,
DEFAULT_BIND_PORT,
DEFAULT_COOLDOWN_SECONDS,
DEFAULT_DATABASE_PATH,
DEFAULT_LOG_LEVEL,
DEFAULT_REPORT_HOUR,
DEFAULT_REPORT_MINUTE,
DEFAULT_SILENCE_SECONDS,
MAX_HOUR,
MAX_MINUTE,
MAX_PORT,
Config,
)
from signal_bot.endpoints import (
DEFAULT_CAT_API_URL,
DEFAULT_COMMONS_API_URL,
DEFAULT_DOG_API_URL,
DEFAULT_GECKO_API_URL,
)
from signal_bot.groups import ConfigError, parse_group_ids
from signal_bot.pack import PEOPLE_FILE, default_dir
from signal_bot.pack_load import load as load_pack
from signal_bot.trust import parse_trusted_inviters
if TYPE_CHECKING:
from collections.abc import Mapping
from pathlib import Path
__all__ = ["load_config"]
def _require(env: Mapping[str, str], key: str) -> str:
"""Return a non-empty environment value or raise ConfigError."""
value = env.get(key, "").strip()
if not value:
msg = f"{key} is required and must not be empty."
raise ConfigError(msg)
return value
def _positive_int(env: Mapping[str, str], key: str, default: int) -> int:
"""Return an int environment value, falling back to default when unset."""
raw = env.get(key, "").strip()
if not raw:
return default
try:
value = int(raw)
except ValueError:
msg = f"{key} must be an integer, got {raw!r}"
raise ConfigError(msg) from None
if value < 0:
msg = f"{key} must not be negative, got {value}"
raise ConfigError(msg)
return value
def _report_time(env: Mapping[str, str]) -> tuple[int, int]:
"""Return the validated (hour, minute) the daily report fires at."""
hour = _positive_int(env, "REPORT_HOUR", DEFAULT_REPORT_HOUR)
minute = _positive_int(env, "REPORT_MINUTE", DEFAULT_REPORT_MINUTE)
if hour > MAX_HOUR or minute > MAX_MINUTE:
msg = f"REPORT_HOUR/REPORT_MINUTE out of range: {hour:02d}:{minute:02d}"
raise ConfigError(msg)
return hour, minute
def _log_level(env: Mapping[str, str]) -> str:
"""Return the validated logging level name."""
log_level = env.get("LOG_LEVEL", "").strip().upper() or DEFAULT_LOG_LEVEL
if log_level not in logging.getLevelNamesMapping():
msg = f"LOG_LEVEL must be a logging level name, got {log_level!r}"
raise ConfigError(msg)
return log_level
def _bind_port(env: Mapping[str, str]) -> int:
"""Return the validated port the readiness probe binds to."""
bind_port = _positive_int(env, "BIND_PORT", DEFAULT_BIND_PORT)
if not 1 <= bind_port <= MAX_PORT:
msg = f"BIND_PORT must be between 1 and {MAX_PORT}, got {bind_port}"
raise ConfigError(msg)
return bind_port
def _photo_pack_dir() -> Path | None:
"""The album directory, loaded once here to prove it can be served.
Two different absences, on purpose. A directory the operator *named* and
that is not there is a typo, and startup says so. A directory nobody
named and that is not there is simply an installation with no album, and
the commands do not exist -- which is also what every test gets.
The pack is parsed and thrown away rather than trusted: a manifest that
cannot be honoured should fail here, where load_config raising is an
answer, and not later inside a retry loop that would hide it.
"""
directory, explicit = default_dir()
if not directory.is_dir():
if explicit:
msg = f"PHOTO_PACK_DIR={directory} is not a directory"
raise ConfigError(msg)
return None
if not (directory / PEOPLE_FILE).is_file():
# A directory the tagger has created but not filled in yet. Only an
# explicitly named pack may fail here: the implicit path is a place a
# pack *would* live, and failing on it would put the unit into a
# restart loop the moment somebody made the directory.
if explicit:
msg = f"PHOTO_PACK_DIR={directory} has no {PEOPLE_FILE}"
raise ConfigError(msg)
return None
load_pack(directory)
return directory
def load_config(env: dict[str, str] | None = None, *, use_dotenv: bool = True) -> Config:
"""Build a Config from the environment, failing loudly on anything missing.
Args:
env: Mapping to read instead of os.environ. Used by the tests.
use_dotenv: Load a local .env file first. Disabled in tests.
Returns:
A validated, immutable Config.
"""
if env is None:
if use_dotenv:
load_dotenv()
env = dict(os.environ)
hour, minute = _report_time(env)
return Config(
phone_number=_require(env, "PHONE_NUMBER"),
group_ids=parse_group_ids(env),
api_base_url=env.get("API_BASE_URL", "").strip() or DEFAULT_API_BASE_URL,
database_path=env.get("DATABASE_PATH", "").strip() or DEFAULT_DATABASE_PATH,
report_hour=hour,
report_minute=minute,
cooldown_seconds=_positive_int(env, "COOLDOWN_SECONDS", DEFAULT_COOLDOWN_SECONDS),
cat_api_url=env.get("CAT_API_URL", "").strip() or DEFAULT_CAT_API_URL,
dog_api_url=env.get("DOG_API_URL", "").strip() or DEFAULT_DOG_API_URL,
gecko_api_url=env.get("GECKO_API_URL", "").strip() or DEFAULT_GECKO_API_URL,
commons_api_url=env.get("COMMONS_API_URL", "").strip() or DEFAULT_COMMONS_API_URL,
bind_host=env.get("BIND_HOST", "").strip() or DEFAULT_BIND_HOST,
bind_port=_bind_port(env),
log_level=_log_level(env),
trusted_inviters=parse_trusted_inviters(env),
silence_seconds=_positive_int(env, "SILENCE_SECONDS", DEFAULT_SILENCE_SECONDS),
photo_pack_dir=_photo_pack_dir(),
)

View File

@ -37,20 +37,43 @@ def watched_group(message: IncomingMessage, directory: GroupDirectory) -> str |
def should_count(message: IncomingMessage) -> bool:
"""True when a message should add to its sender's tally.
"""True when a message should be recorded against its sender.
Reactions and stickers are not messages for tally purposes, and a frame
with no text body carries nothing to count.
A reaction is not a message -- it is an annotation on someone else's --
so it stays out. Everything a person actually sent counts, including a
sticker and including a photo posted with no caption. Until 0.1.0 the
last clause was ``bool(message.text)``, which silently valued a
photo-only message at zero.
The bot's own messages never count. ``is_own`` comes from the envelope
branch rather than from comparing identities, which is what makes it
hold on the frames that carry only one spelling of the account.
"""
if message.is_reaction or message.has_sticker:
if message.is_reaction or message.is_own:
return False
return bool(message.text)
return bool(message.text) or bool(message.attachment_types) or message.has_sticker
def format_tally(rows: list[tuple[str, int]]) -> str:
"""Render the daily report, or a placeholder when nobody spoke."""
if not rows:
return "Brak wiadomosci dzisiaj."
width = max(len(name) for name, _ in rows)
lines = [f"{name.ljust(width)} {count}" for name, count in rows]
return "\n".join(lines)
def media_kind(message: IncomingMessage) -> str:
"""Name the kind of media a message carries, or "" for plain text.
Several different kinds in one message collapse to "mixed": the group
reads a count of photos, not a taxonomy, and a message carrying a photo
and a video is neither.
"""
if message.has_sticker and not message.attachment_types:
return "sticker"
kinds = {_kind_of(content_type) for content_type in message.attachment_types}
if not kinds:
return ""
if len(kinds) > 1:
return "mixed"
return kinds.pop()
def _kind_of(content_type: str) -> str:
"""Map one MIME type onto the coarse kind the group cares about."""
major, _, _ = content_type.partition("/")
if major in {"image", "video", "audio"}:
return major
return "file"

View File

@ -2,20 +2,44 @@
"""Reusable gates that wrap a command handler.
These are the mechanisms salvaged from the unmerged vote and rate-limit
branches, detached from the NSFW command they were originally written for.
branches, detached from the command they were originally written for.
They only decide whether a handler may run; recording a successful use is the
dispatcher's job, so stacking two gates cannot double-count one invocation.
A gate that refuses raises ``CommandRefusedError`` rather than returning, which
is what tells the dispatcher no use took place. Returning quietly used to look
identical to a successful run.
"""
from __future__ import annotations
import functools
import logging
import math
from collections.abc import Callable
from signal_bot.registry import CommandContext, Handler
from signal_bot.registry import CommandContext, CommandRefusedError, Handler
from signal_bot.stats.text import plural
logger = logging.getLogger(__name__)
Decorator = Callable[[Handler], Handler]
# Padding on the *displayed* wait only, never on the gate itself. A number that
# is a second short sends somebody back for another refusal, which reads as the
# bot lying; a number that is a second long costs nothing.
DISPLAY_MARGIN_SECONDS = 2
def wait_display(remaining: float) -> tuple[int, str]:
"""Round a remaining wait up (plus margin) and pick its Polish noun form.
Three forms, not two: 1 sekundę, 2-4 sekundy, 5+ sekund -- and the rule
reads the last two digits, so 12-14 take the many-form and 22-24 do not.
"""
seconds = math.ceil(remaining) + DISPLAY_MARGIN_SECONDS
return seconds, plural(seconds, "SEKUNDĘ", "SEKUNDY", "SEKUND")
def cooldown(seconds: float, message: str) -> Decorator:
"""Refuse a command until `seconds` have passed since that user's last use.
@ -29,9 +53,18 @@ def cooldown(seconds: float, message: str) -> Decorator:
async def wrapper(ctx: CommandContext) -> None:
last = ctx.store.last_used(ctx.group_id, ctx.message.source_uuid, ctx.command_name)
if last is not None and ctx.now - last < seconds:
remaining = seconds - (ctx.now - last)
await ctx.reply(message.format(seconds=int(remaining) + 1))
return
shown, unit = wait_display(seconds - (ctx.now - last))
# Logged with the number the group was given: when this said
# one thing and the gate did another, nothing recorded either.
logger.info(
"cooldown refused %s for %s: told them %d %s",
ctx.command_name,
ctx.message.source_name,
shown,
unit,
)
await ctx.reply(message.format(seconds=shown, unit=unit))
raise CommandRefusedError
await handler(ctx)
return wrapper
@ -50,7 +83,7 @@ def daily_limit(max_uses: int, message: str) -> Decorator:
)
if used >= max_uses:
await ctx.reply(message.format(max_uses=max_uses, used=used))
return
raise CommandRefusedError
await handler(ctx)
return wrapper
@ -72,7 +105,7 @@ def vote_gated(required: int, window_seconds: float, message: str) -> Decorator:
votes = ctx.store.count_votes(ctx.group_id, ctx.command_name, ctx.now - window_seconds)
if votes < required:
await ctx.reply(message.format(votes=votes, required=required))
return
raise CommandRefusedError
ctx.store.clear_votes(ctx.group_id, ctx.command_name)
await handler(ctx)

View File

@ -23,11 +23,14 @@ from typing import TYPE_CHECKING, Any, Final
import httpx
from signal_bot.groups import build_alias_map, canonical_group_id
from signal_bot.membership import JoinAttempts, MembershipError, attempt_join
from signal_bot.membership import JoinAttempts, join_pending, verify_allowlist
from signal_bot.roster import RosterCache
if TYPE_CHECKING:
from signal_bot.config import Config
from signal_bot.models import IncomingMessage
from signal_bot.store import Store
from signal_bot.trust import InviteTrust
logger = logging.getLogger(__name__)
@ -44,6 +47,7 @@ class GroupDirectory:
config: Config,
client: httpx.AsyncClient,
store: Store,
trust: InviteTrust,
*,
sleeper: Sleeper | None = None,
) -> None:
@ -54,11 +58,14 @@ class GroupDirectory:
client: HTTP client for the REST API.
store: Where per-group state lives, so a group the bot is
removed from can have its rows dropped.
trust: Decides whether a discovered group is one the operator
asked for.
sleeper: Async sleep used by run(). Injected by the tests.
"""
self._config = config
self._client = client
self._store = store
self._trust = trust
self._sleep = sleeper if sleeper is not None else asyncio.sleep
self._aliases: dict[str, str] = {}
self._groups: tuple[str, ...] = ()
@ -68,6 +75,7 @@ class GroupDirectory:
# make a stranger's message a second earlier swallow the first
# command in a group that was just added.
self._refreshed_for: set[str] = set()
self._members = RosterCache(config.phone_number)
@property
def groups(self) -> tuple[str, ...]:
@ -92,21 +100,46 @@ class GroupDirectory:
return None
return self._aliases.get(group_id)
async def refresh(self) -> None:
def note_group_update(self, message: IncomingMessage) -> None:
"""Record who changed a group's membership.
Called before the scoping gate on purpose: the frame that names the
inviter arrives while the group it describes is still unknown, and
it is the only authoritative answer to "who added this bot?".
Args:
message: Any parsed inbound message.
"""
if message.group_id is None or not message.is_group_update:
return
self._trust.note_update(message.group_id, message.source_number, message.source_uuid)
async def refresh(self) -> bool:
"""Rebuild the watched set from the account's own group listing.
Joins anything the bot was merely invited to, then re-reads the
listing so membership is decided by the API rather than by the join
endpoint's own optimistic answer.
Returns:
True when a listing was actually read. False means the API could
not be reached and the previous set still stands -- on which no
caller may conclude the bot is missing from a pinned group.
"""
entries = await self._fetch()
if entries is None:
return
if await self._join_pending(entries):
return False
if await join_pending(self._client, self._config, entries, self._joins, self._permitted):
entries = await self._fetch()
if entries is None:
return
return False
# Before _adopt, deliberately. _adopt returns early once the watched
# set stops changing -- which is the steady state -- so a roster
# stashed inside it would freeze at whatever the first sweep saw and
# never notice anybody joining or leaving again.
self._members.remember(entries, self._permitted)
self._adopt(entries)
return True
async def refresh_for(self, group_id: str) -> str | None:
"""Refresh once because a message arrived from an unknown group.
@ -125,28 +158,8 @@ class GroupDirectory:
return self.resolve(group_id)
async def verify_allowlist(self) -> None:
"""Refuse to start when GROUP_IDS names a group the bot cannot use.
Only applies when the operator pinned the bot to specific groups. An
unpinned bot watches whatever it has been added to, including
nothing at all, and that is not an error -- it is a bot waiting to
be added.
Raises:
MembershipError: A pinned group is missing or unjoinable.
"""
if not self._config.is_pinned:
logger.info("watching every group this account is a member of")
return
missing = [group_id for group_id in self._config.group_ids if group_id not in self._groups]
if missing:
details = ", ".join(f"{gid} ({self._joins.reason(gid)})" for gid in missing)
msg = (
f"GROUP_IDS pins the bot to {len(self._config.group_ids)} group(s) but it is "
f"not a joined member of: {details}. Have an admin add the bot again now that "
"it has a profile, or drop the id from GROUP_IDS."
)
raise MembershipError(msg)
"""Refuse to start when GROUP_IDS names a group the bot cannot use."""
verify_allowlist(self._config, self._groups, self._joins)
async def run(self, iterations: int | None = None) -> None:
"""Refresh forever, so a group added later needs no restart.
@ -183,34 +196,27 @@ class GroupDirectory:
return None
return [entry for entry in body if isinstance(entry, dict)]
def member_identities(self, group_id: str) -> frozenset[str]:
"""The listing's spelling of every full member of one group."""
return self._members.identities(group_id)
def _permitted(self, entry: dict[str, Any]) -> str | None:
"""Return the canonical id of a listing row the bot may watch."""
raw = entry.get("id") or entry.get("internal_id")
if not isinstance(raw, str) or not raw:
return None
group_id = canonical_group_id(raw)
return group_id if self._config.allows(group_id) else None
async def _join_pending(self, entries: list[dict[str, Any]]) -> bool:
"""Try to accept every invitation worth retrying.
Args:
entries: The current group listing.
Returns:
True when at least one join was attempted, so the caller knows
the listing needs re-reading.
"""
attempted = False
for entry in entries:
group_id = self._permitted(entry)
if group_id is None or entry.get("member") or self._joins.has_failed(group_id):
continue
logger.warning("invited to %r but not a member; trying to join", entry.get("name"))
detail = await attempt_join(self._client, self._config, group_id)
self._joins.record_failure(group_id, detail)
attempted = True
return attempted
if not self._config.allows(group_id):
return None
# Two things that are already vouched for. A pinned id was named by
# the operator in .env; a group already being watched was vouched
# when it was adopted. Re-testing an adopted group every sweep would
# let one listing that spells a member as a uuid -- or omits members
# entirely -- un-watch it and drop its tally, which is the narrowing
# this module exists to prevent.
if self._config.is_pinned or group_id in self._groups:
return group_id
return group_id if self._trust.allows(group_id, entry) else None
def _adopt(self, entries: list[dict[str, Any]]) -> None:
"""Replace the watched set from a listing known to be good."""

View File

@ -10,8 +10,10 @@ from dataclasses import dataclass
from typing import TYPE_CHECKING
from signal_bot.counting import should_count, watched_group
from signal_bot.envelope_shape import shape_of
from signal_bot.models import parse_envelope
from signal_bot.registry import CommandContext, CommandRegistry
from signal_bot.registry import CommandContext, CommandRefusedError, CommandRegistry
from signal_bot.stats.recorder import record_message
if TYPE_CHECKING:
from signal_bot.config import Config
@ -37,10 +39,18 @@ class Dispatcher:
async def handle(self, frame: str) -> None:
"""Process one raw websocket frame end to end."""
# Keys and types only, never values -- see envelope_shape. This is
# how "what does a frame with an attachment look like?" gets answered
# without a code change and a lucky moment.
logger.debug("envelope shape: %s", shape_of(frame))
message = parse_envelope(frame)
if message is None:
return
# Before the scoping gate: a group-update frame arrives while its
# group is still unknown, and it is what vouches for that group.
self.directory.note_group_update(message)
# The scoping gate. Direct messages and every other group the account
# belongs to stop here, before counting and before any handler runs.
# The canonical id it yields is the reply address and the key for
@ -61,10 +71,25 @@ class Dispatcher:
)
return
# Resolved before recording, not after: is_command is part of the
# row, so "was this a command" has to be known at write time. It is
# the same lookup the handler below uses, not a second one.
#
# Scoped to this group, and that is the whole enforcement: a command
# a group is not allowed comes back as None here, so it is not
# answered, not recorded as a command and never named in a log line
# outside the groups it belongs to.
resolved = self.registry.resolve_with_args(message.text, group)
command = resolved.command if resolved is not None else None
if should_count(message):
self.store.increment(group, message.source_uuid, message.source_name)
record_message(
self.store.events,
group,
message,
self.clock(),
is_command=command is not None,
)
command = self.registry.resolve(message.text)
if command is None:
return
@ -79,9 +104,16 @@ class Dispatcher:
command_name=command.name,
now=now.timestamp(),
day=now.date().isoformat(),
args=resolved.args if resolved is not None else (),
)
try:
await command.handler(ctx)
except CommandRefusedError:
# A gate said no and already answered. Nothing ran, so nothing is
# recorded -- otherwise every "wait N seconds" reply would push the
# cooldown window N seconds further away and the wait never ended.
logger.debug("command %s refused by a gate", command.name)
return
except Exception:
logger.exception("command %s failed", command.name)
return

32
signal_bot/endpoints.py Normal file
View File

@ -0,0 +1,32 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Default upstream endpoints for the image commands.
Split out of config.py, which had reached the 250-line cap. Like the groups.py
and trust.py splits before it this is a filing change, not an interface change:
config re-exports every name here, so nothing that imported them has to move.
"""
from __future__ import annotations
from typing import Final
DEFAULT_CAT_API_URL: Final = "https://api.thecatapi.com/v1/images/search"
DEFAULT_DOG_API_URL: Final = "https://dog.ceo/api/breeds/image/random"
# taxon_id 371057 is Gekkota, the gecko infraorder. The licence filter is not
# decoration: without it the API happily returns all-rights-reserved photos,
# and this bot reposts whatever it is handed into a group chat.
# Deliberately no order_by=random -- see animals.paged_url for why it does
# not work and what supplies the randomness instead.
DEFAULT_GECKO_API_URL: Final = (
"https://api.inaturalist.org/v1/observations"
"?taxon_id=371057&photos=true&quality_grade=research"
"&photo_license=cc-by,cc-by-sa,cc0&per_page=1"
)
# Commons resolves a portrait *filename* to a real upload.wikimedia.org URL.
# Special:FilePath would be shorter but answers 302, and this repo's httpx
# client does not follow redirects; imageinfo hands back the final URL and a
# thumbnail in one hop, which is also what keeps a 4000px original off Signal.
DEFAULT_COMMONS_API_URL: Final = "https://commons.wikimedia.org/w/api.php"
# Wide enough to look like a photograph rather than an avatar, small enough
# that the whole 267-portrait cache stays well under 100 MB.
PORTRAIT_WIDTH: Final = 640

View File

@ -0,0 +1,60 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Describing an envelope's *shape* without logging what anybody wrote.
`DOCS-signal-envelopes.md` exists because the wire format is not obvious and
guessing at it has cost this repo real bugs -- the sticker read off the wrong
nesting level, and 0.0.3's `!gekon` shipping green on an assumption nobody had
checked against the live API. The recurring problem is that answering "what
does a frame with an attachment actually look like?" needed a code change, a
restart, and somebody sending one at the right moment.
So the bot can now say it itself, at DEBUG. What it emits is keys and value
*types*, never values -- with a small allowlist for the handful of fields that
are format, not content: a MIME type and a groupInfo type say nothing about
anybody. Message bodies, names, numbers, uuids, quoted text and sticker ids
are all reduced to their type.
LOG_LEVEL=DEBUG, then: journalctl --user -u signal-bot | grep 'envelope shape'
"""
from __future__ import annotations
import json
from typing import Final
# Fields whose value is a wire-format fact rather than anything a person said.
SAFE_VALUES: Final = frozenset({"contentType", "type"})
def _describe(value: object, key: str = "") -> str:
"""Render one value as its shape."""
if isinstance(value, dict):
inner = ", ".join(f"{k}: {_describe(v, k)}" for k, v in sorted(value.items()))
return "{" + inner + "}"
if isinstance(value, list):
if not value:
return "[]"
# One entry is enough to show the element shape; a photo album would
# otherwise print the same dict twenty times.
return f"[{_describe(value[0])} x{len(value)}]"
if key in SAFE_VALUES and isinstance(value, str):
return repr(value)
if value is None:
return "null"
return type(value).__name__
def shape_of(raw: str | bytes) -> str:
"""Describe a raw frame as keys and types, or say why it could not be.
Args:
raw: The JSON frame exactly as received.
Returns:
A one-line description safe to write to a log.
"""
try:
decoded = json.loads(raw)
except json.JSONDecodeError, UnicodeDecodeError:
return "<unparseable>"
return _describe(decoded)

118
signal_bot/folding.py Normal file
View File

@ -0,0 +1,118 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
r"""Fold a typed command down to a comparable skeleton.
A Signal group is full of phone keyboards, and a phone keyboard decides
which alphabet you are in. On 2026-08-29 a member typed `!gecko` on a
Russian layout: the `e` was U+0435 CYRILLIC SMALL LETTER IE and the `o` was
U+043E CYRILLIC SMALL LETTER O. Both are pixel-identical to the Latin
letters, both compare unequal to them, so the command resolved to nothing
and the bot stayed silent -- no error, no cooldown line, nothing to see.
The same trap covers Greek omicron, small capitals, fullwidth forms,
zero-width joiners pasted in from elsewhere, and plain leetspeak.
The fix is to compare *skeletons* rather than codepoints, and to fold both
sides -- the registered trigger and the incoming text -- through the same
function. Folding both sides is what makes it safe: any alias that already
worked still folds to whatever it folded to before, so this can widen what
matches but can never narrow it.
Every mapping below is written as an explicit `\\uXXXX` escape. A table of
confusables whose whole point is that you cannot tell the characters apart
must not be reviewed by eye.
"""
from __future__ import annotations
import unicodedata
from typing import Final
# Cyrillic letters that are visually identical to a Latin one. This is the
# set that actually bit us; Russian and Ukrainian layouts reach all of it.
_CYRILLIC: Final = (
"\u0430\u0432\u0435\u0455\u0456\u0458"
"\u043a\u043c\u043d\u043e\u0440\u0441"
"\u0442\u0443\u0445\u0501\u051b\u051d"
)
_CYRILLIC_LATIN: Final = "abesijkmhopctyxdqw"
# Greek. Less likely from a keyboard, more likely from a copy-paste.
_GREEK: Final = (
"\u03b1\u03b2\u03b3\u03b5\u03b6\u03b7"
"\u03b9\u03ba\u03bc\u03bd\u03bf\u03c1"
"\u03c4\u03c5\u03c7\u03c9"
)
_GREEK_LATIN: Final = "abyeznikmvoptuxw"
# Latin small capitals. NFKC leaves these alone -- they are letters in their
# own right, not compatibility forms -- so aliases.json had to spell out
# "!ᴋᴏᴛ" by hand. With this table it no longer has to.
_SMALL_CAPS: Final = (
"\u1d00\u0299\u1d04\u1d05\u1d07\u0262"
"\u029c\u026a\u1d0a\u1d0b\u029f\u1d0d"
"\u0274\u1d0f\u1d18\u0280\ua731\u1d1b"
"\u1d1c\u1d20\u1d21\u028f\u1d22"
)
_SMALL_CAPS_LATIN: Final = "abcdeghijklmnoprstuvwyz"
# Latin letters outside ASCII that read as an ASCII one. Diacritics are
# handled by decomposition instead; these carry their difference in the
# letterform itself, so no amount of normalising removes it.
_LATIN_LOOKALIKE: Final = "\u0131\u0237\u0142\u00f8\u0111\u00f0"
_LATIN_LOOKALIKE_ASCII: Final = "ijlodd"
# Leetspeak. Deliberately conservative: 1 is read as i (which is what
# "!p1es" wants) and not as l, and 6/9 are left alone because they are
# genuinely ambiguous. The cost of this table is that a command name can
# never contain a digit -- there are none today, and `!ping` is the only
# planned one, so that is a trade worth making.
_LEET: Final = "0134578"
_LEET_LATIN: Final = "oieastb"
# Invisible characters. They survive NFKC, they are impossible to see in a
# chat client, and they arrive whenever text has been copied out of a web
# page or another messenger.
_INVISIBLE: Final = frozenset("\u00ad\u180e\u200b\u200c\u200d\u200e\u200f\u2060\ufeff")
def _table() -> dict[int, str]:
"""Build the single translation table, once, at import.
Raises:
ValueError: a mapping and its replacements have different lengths,
which would silently mis-map every character after the gap.
"""
mapping: dict[str, str] = {}
for source, target in (
(_CYRILLIC, _CYRILLIC_LATIN),
(_GREEK, _GREEK_LATIN),
(_SMALL_CAPS, _SMALL_CAPS_LATIN),
(_LATIN_LOOKALIKE, _LATIN_LOOKALIKE_ASCII),
(_LEET, _LEET_LATIN),
):
mapping.update(dict(zip(source, target, strict=True)))
return str.maketrans(mapping)
TABLE: Final = _table()
def fold(text: str) -> str:
"""Reduce text to the skeleton the registry compares against.
Applied to registered triggers and to incoming messages alike, so the
two can only ever disagree about characters this function does not
touch.
"""
# NFKC first: it collapses the mathematical alphabets, fullwidth forms
# and non-breaking spaces that aliases.json used to enumerate by hand.
compatible = unicodedata.normalize("NFKC", text)
# Then decompose, so an accent becomes a combining mark of its own and
# can be dropped -- this is what turns "papież" into "papiez" and
# what defuses the zalgo-styled alias.
decomposed = unicodedata.normalize("NFD", compatible)
stripped = "".join(
character
for character in decomposed
if not unicodedata.combining(character) and character not in _INVISIBLE
)
return stripped.casefold().translate(TABLE).strip()

139
signal_bot/help_command.py Normal file
View File

@ -0,0 +1,139 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The !pomoc command: every command the bot has, and what each one does.
Nothing in the chat used to say the commands existed. The README's table was
the only list, it was stale within two releases, and nobody in a Signal group
reads a README anyway -- so the list is built from the registry itself. A
command cannot be registered without a description (``CommandRegistry.register``
requires one), and any command this module's ``GROUPS`` does not mention is
printed anyway, under no heading. Between those two, a new command cannot
quietly fail to appear here.
The trigger printed is ``Command.primary``, the first *raw* alias, because
``Command.triggers`` holds folded skeletons in an unordered set: "!papież"
survives there only as "!papiez", and the styled Unicode aliases would come
out as the zalgo they are.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Final
from signal_bot.animals import load_aliases
from signal_bot.pack_command import NAME_PREFIX
if TYPE_CHECKING:
from collections.abc import Sequence
from signal_bot.decorators import Decorator
from signal_bot.registry import Command, CommandContext, CommandRegistry
COMMAND_NAME: Final = "help"
DESCRIPTION: Final = "ta lista"
HEADING: Final = "Komendy"
# Which commands sit under which heading, in the order they are printed.
# Anything missing from here still gets printed, in a block of its own -- see
# the module docstring.
GROUPS: Final[tuple[tuple[str, tuple[str, ...]], ...]] = (
("Obrazki", ("cat", "dog", "gecko")),
("Papież", ("pope",)),
(
"Statystyki",
(
"stats_today",
"stats_yesterday",
"stats_week",
"stats_month",
"stats_year",
"stats_records",
"stats_crown",
"stats_weekdays",
"stats_me",
),
),
)
# Only the canonical spelling is listed above, but half the group types the
# English one. Without this line "!cat" looks broken to somebody holding a
# list that says "!kot".
SPELLINGS: Final = "Każda komenda ma też inne pisownie, np. !cat, !stats, !week."
# The private album, when a group has one. Its heading is here and its
# commands are not: they come from a file this repository never sees, so
# GROUPS could not name them even if it wanted to -- and naming an optional
# command there would make !pomoc fail in every group that has no pack.
PACK_HEADING: Final = "Zdjęcia"
PACK_HINT: Final = "Kilka naraz ({first} {second}) = zdjęcie, na którym są wszyscy."
def _line(command: Command) -> str:
"""One command as !pomoc prints it."""
return f"{command.primary} — {command.description}"
def _pack_block(commands: Sequence[Command]) -> str:
"""The album's own block, or "" for a group that has no album.
Built from whatever is registered rather than from a table, because the
entries are private data: this file cannot know how many there are or
what they are called, and must not need to.
"""
entries = [c for c in commands if c.name.startswith(NAME_PREFIX)]
if not entries:
return ""
lines = [PACK_HEADING, *(_line(command) for command in entries)]
if len(entries) > 1:
lines.append(PACK_HINT.format(first=entries[0].primary, second=entries[1].primary))
return "\n".join(lines)
def render_help(commands: Sequence[Command], group_id: str) -> str:
"""Render the command list for one group, grouped, in registration order.
Per group, because a command can be scoped to one: the private album
exists in its own groups and nowhere else, and a help text that listed it
everywhere would announce it to every group the bot is in.
"""
visible = [command for command in commands if command.allowed_in(group_id)]
by_name = {command.name: command for command in visible}
# Indexed, not .get(): a name in GROUPS that no command answers to is a
# typo in this file, and it should fail loudly the first time the command
# is used rather than silently drop a line.
grouped = {name for _, names in GROUPS for name in names}
blocks = [HEADING]
for title, names in GROUPS:
blocks.append("\n".join([title, *(_line(by_name[name]) for name in names)]))
pack = _pack_block(visible)
if pack:
blocks.append(pack)
blocks.append(
"\n".join(
_line(c)
for c in visible
if c.name not in grouped and not c.name.startswith(NAME_PREFIX)
)
)
blocks.append(SPELLINGS)
return "\n\n".join(blocks)
def register_help_command(
registry: CommandRegistry,
*,
decorate: Decorator | None = None,
aliases: dict[str, list[str]] | None = None,
) -> None:
"""Register !pomoc, which reads the registry it is registered on.
The registry is read when the command *runs*, not when it is registered,
so this may be wired up in any order and still list everything.
"""
table = load_aliases() if aliases is None else aliases
async def handler(ctx: CommandContext) -> None:
await ctx.reply(render_help(registry.commands, ctx.group_id))
wrapped = decorate(handler) if decorate is not None else handler
registry.register(COMMAND_NAME, table[COMMAND_NAME], wrapped, DESCRIPTION)

View File

@ -27,28 +27,58 @@ class ImageFetcher:
"""Store the injected HTTP client."""
self._client = client
async def fetch_base64(self, api_url: str, url_path: Sequence[str | int]) -> str:
"""Fetch an image and return it as base64.
async def fetch_base64(
self,
api_url: str,
url_path: Sequence[str | int],
rewrite: tuple[str, str] | None = None,
) -> str:
"""Fetch an image and return it base64-encoded, ready for Signal."""
return base64.b64encode(await self.fetch_bytes(api_url, url_path, rewrite)).decode("ascii")
async def fetch_bytes(
self,
api_url: str,
url_path: Sequence[str | int],
rewrite: tuple[str, str] | None = None,
params: dict[str, str] | None = None,
) -> bytes:
"""Fetch an image and return its raw bytes.
Args:
api_url: JSON endpoint that names an image.
url_path: Keys/indices to walk in the JSON to reach the image URL.
rewrite: Optional (find, replace) pair applied to the URL found
there. Some APIs name a thumbnail and leave the full-size
photo one substitution away -- iNaturalist's observation JSON
gives a 75px `/square.` URL whose `/large.` sibling is the
real photo -- and a substitution keeps that upstream quirk as
data next to the endpoint rather than as a branch in here.
params: Query string for the JSON endpoint, when it is easier to
pass than to embed -- the Commons API takes a title that has
to be percent-encoded, the animal APIs are fixed URLs.
Returns:
The image bytes, base64-encoded.
The image bytes.
Raises:
ImageFetchError: The JSON did not contain a usable URL.
"""
response = await self._client.get(api_url)
response = await self._client.get(api_url, params=params)
response.raise_for_status()
image_url = _walk(response.json(), url_path)
if rewrite is not None:
image_url = image_url.replace(*rewrite)
# Never written to disk: the original bot named a local file after the
# remote URL's last path segment and wrote it into the process CWD.
# These bytes are never written to a path built from the remote URL:
# the original bot named a local file after the URL's last path
# segment and wrote it into the process CWD, which is both path
# traversal and unbounded. portraits.py does cache to disk, but under
# a name it derives from the pope's ordinal, never from upstream.
image = await self._client.get(image_url)
image.raise_for_status()
return base64.b64encode(image.content).decode("ascii")
return image.content
_MISSING: Final = object()

172
signal_bot/liveness.py Normal file
View File

@ -0,0 +1,172 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Whether the bot can still hear, and the gate that stops it saying yes anyway.
On 2026-08-29 signal-cli's connection to Signal died and reconnected in a
loop for three hours. Every surface said the bot was fine: the container's
own healthcheck answered 204, ``/v1/groups`` answered 200 out of local
state, ``/healthz`` answered 200, and the bot's WebSocket to the container
stayed *open* -- the container keeps client sockets alive even when its own
upstream is dead, so the transport's reconnect logic never fired. The only
symptom was silence, and silence is also what a quiet evening looks like.
So this module answers "is the silence real?" with a question nobody can
answer from a cache: ``/v1/devices``, which needs a live round trip to
Signal. It is asked only after the silence has gone on long enough to be
worth asking about, so a busy group costs nothing and an idle one costs one
request per silence window.
"""
from __future__ import annotations
import asyncio
import logging
import time
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Final
import httpx
if TYPE_CHECKING:
from signal_bot.config import Config
logger = logging.getLogger(__name__)
TICK_SECONDS: Final = 30.0
# Measured against the real failure: the broken endpoint answered in 3.9s
# once and hung past 20s another time. 15s is above the observed failure
# latency and below TICK_SECONDS, so probes can never pile up.
PROBE_TIMEOUT_SECONDS: Final = 15.0
# signal-cli's own reconnect loop backs off in 100..3200ms, so the failure is
# stable within a second. Three probes 30s apart is not "waiting it out", it
# is refusing to trip on one bad round trip.
FAILURES_BEFORE_DEAF: Final = 3
Ticker = Callable[[], float]
Sleeper = Callable[[float], Awaitable[None]]
class Liveness:
"""Tracks proof that messages can still arrive, and reports when they cannot."""
def __init__(
self,
config: Config,
client: httpx.AsyncClient,
*,
ticker: Ticker | None = None,
sleeper: Sleeper | None = None,
failures_before_deaf: int = FAILURES_BEFORE_DEAF,
) -> None:
"""Wire the gate to its config and its injectable I/O.
Args:
config: Resolved runtime configuration.
client: HTTP client used for the probe.
ticker: Monotonic clock. Injected by the tests.
sleeper: Async sleep used by run(). Injected by the tests.
failures_before_deaf: Consecutive failed probes before the bot
stops calling itself healthy.
"""
self._config = config
self._client = client
self._now = ticker if ticker is not None else time.monotonic
self._sleep = sleeper if sleeper is not None else asyncio.sleep
self._limit = failures_before_deaf
# Healthy until proven otherwise: the installer waits on /healthz
# with a 60s budget, and a cold "unknown means 503" would fail the
# install and burn the unit's restart limit for no reason.
self._last_alive = self._now()
self._failures = 0
self._detail = ""
@property
def healthy(self) -> bool:
"""True while the bot has no evidence that it has gone deaf."""
return self._failures < self._limit
@property
def silent_for(self) -> float:
"""Seconds since the last envelope or successful probe."""
return self._now() - self._last_alive
@property
def reason(self) -> str:
"""Why the bot believes it is deaf, in one line for /healthz."""
return (
f"nothing received for {self.silent_for:.0f}s and {self._failures} "
f"consecutive failed probes of {self._config.devices_url}: {self._detail}"
)
def note_envelope(self) -> None:
"""Record proof of life: any frame at all, or a successful probe."""
self._last_alive = self._now()
if self._failures:
logger.warning("receive path recovered after %d failed probe(s)", self._failures)
self._failures = 0
self._detail = ""
async def probe(self) -> bool:
"""Ask signal-cli something it cannot answer from local state.
Returns:
True when the account's connection to Signal is alive.
"""
try:
response = await self._client.get(
self._config.devices_url, timeout=PROBE_TIMEOUT_SECONDS
)
except httpx.HTTPError as exc:
self._detail = f"{type(exc).__name__}: {exc}"
return False
if response.status_code != httpx.codes.OK:
self._detail = f"HTTP {response.status_code}: {response.text.strip()[:200]}"
return False
return True
async def run(self, iterations: int | None = None) -> None:
"""Check for deafness forever.
Args:
iterations: Stop after this many ticks. None means forever.
"""
completed = 0
while iterations is None or completed < iterations:
await self._sleep(TICK_SECONDS)
await self.check()
completed += 1
async def check(self) -> None:
"""Probe once, but only when the silence has lasted long enough.
Public because it is the whole gate in one call: the tests, and any
future hand-run diagnostic, must be able to ask the same question
the loop asks without reaching into private state.
"""
silent = self.silent_for
if silent < self._config.silence_seconds:
return
if await self.probe():
# A live probe is proof of life exactly like an envelope, and
# resetting the clock here is what bounds the cost: an idle
# account probes once per silence window, not once per tick.
self.note_envelope()
return
self._failures += 1
if self._failures <= self._limit:
logger.warning(
"signal-cli cannot reach Signal (failure %d of %d) after %.0fs of silence: %s",
self._failures,
self._limit,
silent,
self._detail,
)
return
# Past the limit the verdict is already in, and "failure 8 of 3"
# reads like a bug in the counter rather than a bot that is still
# deaf. Keep saying it, but say it truthfully.
logger.warning(
"still deaf: %d failed probe(s) and %.0fs of silence: %s",
self._failures,
silent,
self._detail,
)

View File

@ -0,0 +1,41 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Logging configuration, with the noisy libraries kept out of DEBUG.
``LOG_LEVEL=DEBUG`` exists to answer questions about the bot -- which frame
was ignored and why, what shape an envelope actually has. Setting the root
logger to DEBUG also turns on httpx, httpcore and asyncio, which between them
emit several lines per HTTP request. The bot polls a group listing every 30
seconds, so the one line worth reading arrives buried in hundreds that are
not, and journald rate-limiting then starts dropping messages.
So the libraries are held at WARNING whatever the bot is set to. A warning
from httpx is worth seeing; its per-request bookkeeping is not, at any level
-- at INFO it was already emitting a "HTTP Request: GET ... 200 OK" line
every thirty seconds, forever.
"""
from __future__ import annotations
import logging
from typing import Final
FORMAT: Final = "%(asctime)s %(levelname)s %(name)s: %(message)s"
# Every third-party logger that is chatty at DEBUG. httpcore is the worst
# offender by an order of magnitude: it logs both ends of every connection.
NOISY: Final = ("httpx", "httpcore", "asyncio", "websockets", "urllib3")
NOISY_FLOOR: Final = logging.WARNING
def configure(level: str) -> None:
"""Send the bot's logs to stderr at ``level``, muting the noisy libraries.
Args:
level: A logging level name, already validated by config_env.
"""
logging.basicConfig(level=level, format=FORMAT)
# Explicitly too: basicConfig is a documented no-op once the root logger
# already has a handler, which is the case under pytest and under some
# uvicorn arrangements. Without this the level silently does not apply.
logging.getLogger().setLevel(level)
for name in NOISY:
logging.getLogger(name).setLevel(NOISY_FLOOR)

View File

@ -20,6 +20,8 @@ import httpx
from signal_bot.groups import group_id_aliases
if TYPE_CHECKING:
from collections.abc import Callable
from signal_bot.config import Config
logger = logging.getLogger(__name__)
@ -104,3 +106,65 @@ async def attempt_join(client: httpx.AsyncClient, config: Config, group_id: str)
except httpx.HTTPError as exc:
return f"join request failed: {exc}"
return f"join returned HTTP {response.status_code}: {response.text.strip()[:200]}"
async def join_pending(
client: httpx.AsyncClient,
config: Config,
entries: list[dict[str, Any]],
joins: JoinAttempts,
permitted: Callable[[dict[str, Any]], str | None],
) -> bool:
"""Try to accept every invitation worth retrying.
Args:
client: HTTP client for the REST API.
config: Resolved runtime configuration.
entries: The current group listing.
joins: Where a refused join is remembered, so it is tried once.
permitted: Decides whether a listing row is one the bot may watch,
returning its canonical id.
Returns:
True when at least one join was attempted, so the caller knows the
listing needs re-reading.
"""
attempted = False
for entry in entries:
group_id = permitted(entry)
if group_id is None or entry.get("member") or joins.has_failed(group_id):
continue
logger.warning("invited to %r but not a member; trying to join", entry.get("name"))
detail = await attempt_join(client, config, group_id)
joins.record_failure(group_id, detail)
attempted = True
return attempted
def verify_allowlist(config: Config, groups: tuple[str, ...], joins: JoinAttempts) -> None:
"""Refuse to start when GROUP_IDS names a group the bot is not in.
Only applies when the operator pinned the bot to specific groups. An
unpinned bot watches whatever it has been added to, including nothing at
all, and that is not an error -- it is a bot waiting to be added.
Args:
config: Resolved runtime configuration.
groups: The groups the bot actually discovered.
joins: Why a join failed, for the error message.
Raises:
MembershipError: A pinned group is missing or unjoinable.
"""
if not config.is_pinned:
logger.info("watching every group this account is a member of")
return
missing = [group_id for group_id in config.group_ids if group_id not in groups]
if missing:
details = ", ".join(f"{gid} ({joins.reason(gid)})" for gid in missing)
msg = (
f"GROUP_IDS pins the bot to {len(config.group_ids)} group(s) but it is "
f"not a joined member of: {details}. Have an admin add the bot again now that "
"it has a profile, or drop the id from GROUP_IDS."
)
raise MembershipError(msg)

View File

@ -24,6 +24,27 @@ class IncomingMessage:
text: str | None
has_sticker: bool
is_reaction: bool
# The sender's +E.164 number. "source" carries it too, but only
# sometimes: live envelopes have shown a display name there and the
# number here, so this is the field a trust decision may rely on.
source_number: str = ""
# A group membership change rather than a message: this is the only
# frame that names who added the bot to a group.
is_group_update: bool = False
# The sent timestamp, which is the id Signal quotes a message by.
# Without it a reply can only be addressed to the room.
timestamp: int = 0
# contentType of each attachment, in the order Signal listed them.
# Empty for a text-only message.
attachment_types: tuple[str, ...] = ()
# True when this message quotes another one.
is_reply: bool = False
# True when the bot's own account sent this. Taken from *which* envelope
# branch carried the payload, not from comparing identities: the account
# is spelled as a uuid on some frames and a +E.164 number on others, so
# any comparison misses one of them. syncMessage.sentMessage means "this
# account sent it", exactly, on every frame shape.
is_own: bool = False
@property
def is_direct_message(self) -> bool:
@ -35,19 +56,46 @@ class IncomingMessage:
return self.group_id is None
def _payload(envelope: dict[str, Any]) -> dict[str, Any] | None:
"""Return the dataMessage or sentMessage body, whichever is present."""
def _timestamp(payload: dict[str, Any], envelope: dict[str, Any]) -> int:
"""The sent timestamp, preferring the payload's own over the envelope's.
They agree on every frame seen so far, but a quote must point at the
message, so the message's own value wins where they ever differ.
"""
for source in (payload, envelope):
value = source.get("timestamp")
if isinstance(value, int):
return value
return 0
def _payload(envelope: dict[str, Any]) -> tuple[dict[str, Any], bool] | None:
"""Return the message body and whether the bot's own account sent it.
signal-cli reports other people under ``dataMessage`` and this account's
own outgoing messages under ``syncMessage.sentMessage``. Which branch
matched is the only reliable "did we send this" signal, so it is returned
rather than re-derived downstream.
"""
data = envelope.get("dataMessage")
if isinstance(data, dict):
return data
return data, False
sync = envelope.get("syncMessage")
if isinstance(sync, dict):
sent = sync.get("sentMessage")
if isinstance(sent, dict):
return sent
return sent, True
return None
def _attachments(payload: dict[str, Any]) -> tuple[str, ...]:
"""Return each attachment's contentType, in the order Signal listed them."""
items = payload.get("attachments")
if not isinstance(items, list):
return ()
return tuple(str(item.get("contentType", "")) for item in items if isinstance(item, dict))
def _group_id(payload: dict[str, Any]) -> str | None:
"""Return the group id, or None for a direct message."""
info = payload.get("groupInfo")
@ -59,6 +107,15 @@ def _group_id(payload: dict[str, Any]) -> str | None:
return group_id
def _group_type(payload: dict[str, Any]) -> str:
"""Return the groupInfo type ("DELIVER", "UPDATE", ...), or ""."""
info = payload.get("groupInfo")
if not isinstance(info, dict):
return ""
group_type = info.get("type")
return group_type if isinstance(group_type, str) else ""
def _text(payload: dict[str, Any]) -> str | None:
"""Return the message body, or None when there is no text."""
message = payload.get("message")
@ -88,9 +145,10 @@ def parse_envelope(raw: str | bytes) -> IncomingMessage | None:
if not isinstance(envelope, dict):
return None
payload = _payload(envelope)
if payload is None:
resolved = _payload(envelope)
if resolved is None:
return None
payload, is_own = resolved
return IncomingMessage(
source_uuid=str(envelope.get("sourceUuid", "")),
@ -102,4 +160,10 @@ def parse_envelope(raw: str | bytes) -> IncomingMessage | None:
# filtered. Reading it off the resolved payload fixes both shapes.
has_sticker=isinstance(payload.get("sticker"), dict),
is_reaction=isinstance(payload.get("reaction"), dict),
source_number=str(envelope.get("sourceNumber", "")),
is_group_update=_group_type(payload) == "UPDATE",
timestamp=_timestamp(payload, envelope),
attachment_types=_attachments(payload),
is_reply=isinstance(payload.get("quote"), dict),
is_own=is_own,
)

155
signal_bot/pack.py Normal file
View File

@ -0,0 +1,155 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""A private album, and the shape of the commands that post from it.
Nothing here knows a single name. Who the people are, what somebody types to
get their photo, and which file shows whom are all read at run time from a
directory outside this repository -- so the mechanism can be public, tested
and committed while the album stays private. An installation without a pack
directory simply has no such commands.
The pack refers to people by opaque keys (``p1``, ``p2``). Those keys, never
the triggers, are what reach a log line or the rate-limit table: a name that
never leaves that directory cannot leak out of one.
The entry shape is deliberately one type rather than three. A person is an
entry with a single option; "a photo with both of them" is an entry with one
two-key option; "either of them" is an entry with two one-key options. The
handler then has exactly one job -- pick an option that actually has photos
-- and the difference between the three cases is data, not code.
Loading and validating a pack is pack_load.py, the way config_env.py is to
config.py: this half is the shape, that half is how it is read.
"""
from __future__ import annotations
import itertools
import os
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Final
from signal_bot.folding import fold
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
PEOPLE_FILE: Final = "people.json"
TAGS_FILE: Final = "tags.json"
MEDIA_DIR: Final = "media"
# What Signal is told an attachment is. Closed, and checked at load time: the
# suffix is the only thing that tells Signal how to render the file, so an
# unknown one is refused rather than guessed. Mirrors portraits._SUFFIXES.
MEDIA_TYPES: Final[dict[str, str]] = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".mp4": "video/mp4",
}
# How many names one message may combine, the head included. A ceiling
# rather than a judgement: the option sets multiply, and nobody is asking
# for a photo of nine people at once.
MAX_NAMES: Final = 6
@dataclass(frozen=True, slots=True)
class Entry:
"""One command the pack defines, and the people it stands for."""
# The pseudonym. The only identifier this program logs or stores.
key: str
# Raw triggers, canonical spelling first -- that is what !pomoc prints.
triggers: tuple[str, ...]
# Each element is one set of person keys that satisfies the request. One
# option means there is nothing to choose; several mean the handler picks
# between them, preferring one that has photos.
options: tuple[frozenset[str], ...]
@dataclass(frozen=True, slots=True)
class Pack:
"""A loaded album: its commands, its tags, and where its files are."""
directory: Path
# The only groups these commands exist in. Everywhere else they are not
# commands at all -- not refused, not answered, not logged.
groups: frozenset[str]
entries: tuple[Entry, ...]
# Filename to the person keys tagged in it.
tags: Mapping[str, frozenset[str]]
# Folded trigger to entry, so a tail token resolves exactly the way the
# command in front of it did.
by_trigger: Mapping[str, Entry]
def media_path(self, filename: str) -> Path:
"""Where one tagged file lives."""
return self.directory / MEDIA_DIR / filename
def matching(self, keys: frozenset[str]) -> tuple[str, ...]:
"""Every file tagged with all of ``keys``, in a stable order."""
return tuple(sorted(name for name, tagged in self.tags.items() if keys <= tagged))
def media_type(filename: str) -> str:
"""The MIME type for a tagged file, by suffix."""
return MEDIA_TYPES[Path(filename).suffix.lower()]
def default_dir() -> tuple[Path, bool]:
"""Where the pack lives, and whether the operator named it explicitly.
Explicit means a missing directory is an error worth failing startup for.
The implicit paths are the opposite: they are where a pack *would* live,
so their absence is simply an installation with no album.
Read straight off os.environ rather than from a passed mapping, exactly
as portraits.default_cache_dir is: .env has already been loaded into the
environment by then, and it is what lets one autouse fixture keep the
whole test suite away from a real album. STATE_DIRECTORY comes before
anything under $HOME because that is the directory systemd creates and
exposes regardless of ProtectHome.
"""
explicit = os.environ.get("PHOTO_PACK_DIR", "").strip()
if explicit:
return Path(explicit), True
state = os.environ.get("STATE_DIRECTORY", "").strip()
if state:
return Path(state) / "pack", False
home = os.environ.get("XDG_DATA_HOME", "").strip() or str(Path.home() / ".local" / "share")
return Path(home) / "signal-bot" / "pack", False
def options_for(pack: Pack, token: str) -> tuple[frozenset[str], ...] | None:
"""What one typed name could mean, or None when it means nothing.
Accepts the bare spelling as well as the "!" one, because "!celina marek"
is how people actually write it, and refusing the second half over a
missing punctuation mark would be a rule nobody can see.
"""
folded = fold(token)
entry = pack.by_trigger.get(folded) or pack.by_trigger.get(f"!{folded}")
return entry.options if entry is not None else None
def candidate_keysets(
pack: Pack, entry: Entry, tail: Sequence[str]
) -> tuple[frozenset[str], ...] | None:
"""Every set of people the request could be asking for.
None when the message names more people than MAX_NAMES, or when a word in
the tail is not a name at all -- which is answered rather than ignored:
silently dropping it would post a photo of the wrong subset and look
exactly like the tags being wrong.
"""
if len(tail) >= MAX_NAMES:
return None
choices = [entry.options]
for token in tail:
options = options_for(pack, token)
if options is None:
return None
choices.append(options)
return tuple(frozenset().union(*combination) for combination in itertools.product(*choices))

111
signal_bot/pack_command.py Normal file
View File

@ -0,0 +1,111 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The photo commands a private pack defines, and how one message is answered.
One command per entry, so the cooldown, the log line and the rate-limit row
are per person -- and every one of them is named by the entry's pseudonym
(``pack:p1``), never by what was typed. Reading the journal or the database
tells you somebody asked for a photo, and nothing about whose.
Several names in one message mean "a photo with all of them": the trigger
takes the rest of the line as further names, each resolved through the same
table the trigger came from, and the sets are intersected. Where an entry
offers a choice, the choice is made among the options that actually have a
photo -- picking blindly and then reporting failure would be a "no" the
album could have answered.
"""
from __future__ import annotations
import base64
import secrets
from typing import TYPE_CHECKING, Final
from signal_bot.pack import candidate_keysets, media_type
if TYPE_CHECKING:
from collections.abc import Sequence
from signal_bot.decorators import Decorator
from signal_bot.pack import Entry, Pack
from signal_bot.registry import CommandContext, CommandRegistry, Handler
# The prefix every pack command's name carries, so one glance at a log line
# or a command_uses row says where it came from without saying who.
NAME_PREFIX: Final = "pack:"
NO_PHOTO: Final = "BEEP BOOP NIE MAM TAKIEGO ZDJĘCIA."
# Deliberately says nothing about who the entry is: !pomoc prints this next
# to the trigger, and the trigger is the only place a name may appear.
ONE_PERSON: Final = "losowe zdjęcie tej osoby"
EVERYBODY: Final = "losowe zdjęcie, na którym są oni wszyscy"
EITHER: Final = "losowe zdjęcie jednego z nich"
def description_for(entry: Entry) -> str:
"""What !pomoc says an entry does, without naming anybody."""
if len(entry.options) > 1:
return EITHER
return ONE_PERSON if len(entry.options[0]) == 1 else EVERYBODY
def pick(items: Sequence[str]) -> str:
"""One item, uniformly at random.
secrets rather than random for the reason animals.paged_url gives: the
choice is not security-sensitive, but ruff's ALL rule set flags `random`
and this repo forbids the noqa that would silence it.
"""
return items[secrets.randbelow(len(items))]
def pack_handler(pack: Pack, entry: Entry) -> Handler:
"""Build the handler that answers one entry's trigger."""
async def handler(ctx: CommandContext) -> None:
wanted = candidate_keysets(pack, entry, ctx.args)
viable = [keys for keys in wanted or () if pack.matching(keys)]
if not viable:
# One line and no photo, for a name nobody has, a combination
# nobody photographed, and a tail of six names alike: from the
# group's side those are the same question with the same answer.
await ctx.reply(NO_PHOTO)
return
filename = pick(pack.matching(pick_keys(viable)))
payload = base64.b64encode(pack.media_path(filename).read_bytes()).decode("ascii")
await ctx.reply_media(payload, media_type(filename), filename)
return handler
def pick_keys(viable: Sequence[frozenset[str]]) -> frozenset[str]:
"""One of the readings that has photos, chosen at random."""
return viable[secrets.randbelow(len(viable))]
def register_pack_commands(
registry: CommandRegistry,
pack: Pack,
*,
decorate: Decorator | None = None,
) -> None:
"""Register one command per pack entry, scoped to the pack's groups.
Args:
registry: Registry to populate.
pack: The loaded album.
decorate: Optional callable applied to each handler, used to attach
the cooldown gate without hard-wiring policy into the commands.
"""
for entry in pack.entries:
handler = pack_handler(pack, entry)
if decorate is not None:
handler = decorate(handler)
registry.register(
f"{NAME_PREFIX}{entry.key}",
entry.triggers,
handler,
description_for(entry),
groups=pack.groups,
takes_args=True,
)

243
signal_bot/pack_load.py Normal file
View File

@ -0,0 +1,243 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Reading a photo pack off disk, and refusing one it cannot serve.
Every check here fails startup rather than a command, for the reason
config_env.py gives: a manifest that names a person who does not exist, a
trigger the folder can never match, or a file that has since been renamed is
an answer, not an outage, and no amount of waiting fixes it. The one thing
that is *not* an error is a pack that has not been tagged yet -- that is an
album waiting for the tagger, and it says so in the log.
"""
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING, Any, Final
from signal_bot.folding import fold
from signal_bot.groups import ConfigError
from signal_bot.pack import (
MEDIA_DIR,
MEDIA_TYPES,
PEOPLE_FILE,
TAGS_FILE,
Entry,
Pack,
)
if TYPE_CHECKING:
from pathlib import Path
logger = logging.getLogger(__name__)
# "!" plus at least one character to fold.
MIN_TRIGGER_LENGTH: Final = 2
def load(directory: Path) -> Pack:
"""Read a pack, or say precisely what is wrong with it.
Raises:
ConfigError: The manifest is missing, malformed, or names a person, a
trigger or a file the pack cannot honour.
"""
document = _document(directory / PEOPLE_FILE)
entries = _entries(document)
known = {entry.key for entry in entries}
named = {key for entry in entries for option in entry.options for key in option}
unknown = named - known
if unknown:
msg = f"{PEOPLE_FILE} refers to unknown people: {sorted(unknown)}"
raise ConfigError(msg)
return Pack(
directory=directory,
groups=_groups(document),
entries=entries,
tags=_tags(directory, named),
by_trigger={fold(t): entry for entry in entries for t in entry.triggers},
)
def _document(path: Path) -> dict[str, Any]:
"""One JSON manifest, read strictly."""
try:
text = path.read_text(encoding="utf-8")
except OSError as error:
msg = f"photo pack manifest {path} cannot be read: {error}"
raise ConfigError(msg) from error
try:
document = json.loads(text)
except json.JSONDecodeError as error:
msg = f"photo pack manifest {path} is not valid JSON: {error}"
raise ConfigError(msg) from error
if not isinstance(document, dict):
msg = f"photo pack manifest {path} must be an object"
raise ConfigError(msg)
return document
def _groups(document: dict[str, Any]) -> frozenset[str]:
"""The groups the album may be posted into, which may not be empty.
Fail-closed on purpose: the failure mode of defaulting to "every group
the bot is in" is somebody's private photos in a stranger's chat.
"""
groups = document.get("groups")
if not isinstance(groups, list) or not groups:
msg = f"{PEOPLE_FILE} needs a non-empty 'groups' list"
raise ConfigError(msg)
named = {str(group).strip() for group in groups}
if "" in named:
msg = f"{PEOPLE_FILE} has a blank group id"
raise ConfigError(msg)
return frozenset(named)
def _entries(document: dict[str, Any]) -> tuple[Entry, ...]:
"""One entry per person and per combination, validated as it is built."""
entries = [
Entry(
key=_key(person, "people"),
triggers=_triggers(person, "people"),
options=(frozenset({_key(person, "people")}),),
)
for person in _listing(document, "people")
]
entries.extend(
Entry(
key=_key(combo, "combos"), triggers=_triggers(combo, "combos"), options=_options(combo)
)
for combo in _listing(document, "combos")
)
if not entries:
msg = f"{PEOPLE_FILE} defines no commands"
raise ConfigError(msg)
_unique_keys(entries)
_unique_triggers(entries)
return tuple(entries)
def _listing(document: dict[str, Any], field: str) -> list[dict[str, Any]]:
"""One list of manifest objects, defaulting to none at all."""
entries = document.get(field, [])
if not isinstance(entries, list) or any(not isinstance(entry, dict) for entry in entries):
msg = f"{PEOPLE_FILE} field '{field}' must be a list of objects"
raise ConfigError(msg)
return entries
def _key(entry: dict[str, Any], field: str) -> str:
"""The pseudonym for one entry.
Rejected when it looks like a name rather than a key, because this is the
string that ends up in the log and in command_uses: the whole point is
that reading either tells you nothing about who was asked for.
"""
key = str(entry.get("key", "")).strip()
if not key or not key.replace("_", "").isalnum() or not key.isascii():
msg = f"{PEOPLE_FILE} {field} entry needs an ascii alphanumeric 'key', got {key!r}"
raise ConfigError(msg)
return key
def _triggers(entry: dict[str, Any], field: str) -> tuple[str, ...]:
"""Every spelling that fires one entry, canonical first."""
triggers = entry.get("triggers")
if not isinstance(triggers, list) or not triggers:
msg = f"{PEOPLE_FILE} {field} entry {entry.get('key')!r} needs a non-empty 'triggers' list"
raise ConfigError(msg)
return tuple(_trigger(str(trigger), field) for trigger in triggers)
def _trigger(trigger: str, field: str) -> str:
"""One trigger, checked against what the registry can actually match."""
reason = ""
if not trigger.startswith("!") or len(trigger) < MIN_TRIGGER_LENGTH:
reason = 'must start with "!" and have something after it'
elif any(character.isdigit() for character in trigger):
# folding maps 0134578 onto letters, so "!7dni" would resolve as
# "!tdni" -- a trigger with a digit is a trigger you cannot type.
reason = "must not contain a digit, which folding turns into a letter"
elif not fold(trigger).strip("!"):
reason = "folds away to nothing, so no message could ever match it"
if reason:
msg = f"{PEOPLE_FILE} {field} trigger {trigger!r} {reason}"
raise ConfigError(msg)
return trigger
def _options(combo: dict[str, Any]) -> tuple[frozenset[str], ...]:
"""What a combination stands for: everyone at once, or any one of them."""
every = combo.get("all_of")
either = combo.get("any_of")
if isinstance(every, list) and every and either is None:
return (frozenset(str(key) for key in every),)
if isinstance(either, list) and either and every is None:
return tuple(frozenset({str(key)}) for key in either)
msg = f"{PEOPLE_FILE} combo {combo.get('key')!r} needs exactly one of 'all_of' or 'any_of'"
raise ConfigError(msg)
def _unique_keys(entries: list[Entry]) -> None:
"""Two entries sharing a key would share a cooldown and a log line."""
seen: set[str] = set()
for entry in entries:
if entry.key in seen:
msg = f"{PEOPLE_FILE} uses the key {entry.key!r} twice"
raise ConfigError(msg)
seen.add(entry.key)
def _unique_triggers(entries: list[Entry]) -> None:
"""Caught here rather than by the registry, which cannot name the file.
Skeletons, not spellings: two triggers can look different and fold the
same, because folding strips diacritics. Within one entry that is normal
and wanted -- "!celina" and "!celiną" are one person written two ways,
and the registry collapses them into one frozenset. Across two entries it
is a manifest that cannot work, and the registry would only be able to
say which skeleton collided, not which entry to fix.
"""
claimed: dict[str, str] = {}
for entry in entries:
for trigger in entry.triggers:
owner = claimed.setdefault(fold(trigger), entry.key)
if owner != entry.key:
msg = f"{PEOPLE_FILE} trigger {trigger!r} is claimed by {owner!r} and {entry.key!r}"
raise ConfigError(msg)
def _tags(directory: Path, people: set[str]) -> dict[str, frozenset[str]]:
"""Which file shows whom, checked against the album and the manifest.
A missing tags.json is not an error: that is a pack the tagger has not
been run on yet, and the commands answer "no such photo" until it has.
A tag naming a file that is not there *is* an error -- a renamed file
would otherwise drop out of the album silently.
"""
path = directory / TAGS_FILE
if not path.exists():
logger.warning("photo pack %s has no %s yet; run tool/tagger.py", directory, TAGS_FILE)
return {}
document = _document(path)
tags: dict[str, frozenset[str]] = {}
for filename, keys in document.items():
_media_file(directory, str(filename))
if not isinstance(keys, list) or any(str(key) not in people for key in keys):
msg = f"{TAGS_FILE} entry {filename!r} names somebody who is not in {PEOPLE_FILE}"
raise ConfigError(msg)
if keys:
tags[str(filename)] = frozenset(str(key) for key in keys)
return tags
def _media_file(directory: Path, filename: str) -> None:
"""The tagged file has to exist, and be something Signal can render."""
path = directory / MEDIA_DIR / filename
if path.name != filename or not path.is_file():
msg = f"{TAGS_FILE} names {filename!r}, which is not a file in {MEDIA_DIR}/"
raise ConfigError(msg)
if path.suffix.lower() not in MEDIA_TYPES:
msg = f"{TAGS_FILE} names {filename!r}, whose type is not one Signal is told about"
raise ConfigError(msg)

2141
signal_bot/popes.json Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,64 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The !papież command: a random pope, his portrait, his Latin name, his article.
The list this draws from is the same signal_bot/popes.json the version ladder
is built on, so the bot posts the popes it is named after.
"""
from __future__ import annotations
import secrets
from typing import TYPE_CHECKING, Final
from signal_bot.animals import load_aliases
from signal_bot.versioning import POPES, article_url, pope_line
if TYPE_CHECKING:
from signal_bot.decorators import Decorator
from signal_bot.portraits import PortraitCache
from signal_bot.registry import CommandContext, CommandRegistry, Handler
from signal_bot.versioning import Pope
COMMAND_NAME: Final = "pope"
DESCRIPTION: Final = "losowy papież z portretem i imieniem po łacinie"
def random_pope() -> Pope:
"""Return one pope, uniformly at random.
secrets rather than random for the reason animals.paged_url gives: the
choice is not security-sensitive, but ruff's ALL rule set flags `random`
and this repo forbids the noqa that would silence it.
"""
return POPES[secrets.randbelow(len(POPES))]
def caption_for(pope: Pope) -> str:
"""Return the message that rides along with the portrait."""
return f"{pope.name} — {pope.latin}\n{pope_line(pope)}\n{article_url(pope)}"
def pope_handler(cache: PortraitCache) -> Handler:
"""Build the handler that posts a random pope."""
async def handler(ctx: CommandContext) -> None:
pope = random_pope()
image = await cache.get_base64(pope)
await ctx.reply_image(image, caption_for(pope))
return handler
def register_pope_command(
registry: CommandRegistry,
cache: PortraitCache,
*,
decorate: Decorator | None = None,
aliases: dict[str, list[str]] | None = None,
) -> None:
"""Register !papież under every trigger aliases.json gives it."""
table = load_aliases() if aliases is None else aliases
handler = pope_handler(cache)
if decorate is not None:
handler = decorate(handler)
registry.register(COMMAND_NAME, table[COMMAND_NAME], handler, DESCRIPTION)

130
signal_bot/portraits.py Normal file
View File

@ -0,0 +1,130 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""On-disk cache of papal portraits, keyed by ordinal.
The set is closed: 267 popes, one portrait each, so this cache is bounded by
construction and never evicts. That is what makes writing images to disk safe
here when http_client refuses to -- the filename comes from the ordinal, so
nothing upstream controls a path, and the directory belongs to systemd.
"""
from __future__ import annotations
import base64
import os
from pathlib import Path
from typing import TYPE_CHECKING, Final
from signal_bot.endpoints import PORTRAIT_WIDTH
from signal_bot.http_client import ImageFetchError
if TYPE_CHECKING:
from signal_bot.http_client import ImageFetcher
from signal_bot.versioning import Pope
# Where imageinfo puts the thumbnail URL in its reply.
_THUMB_PATH: Final = ("query", "pages", 0, "imageinfo", 0, "thumburl")
# Commons hosts these four for the 267 portraits: 245 jpg, 15 png, 6 gif,
# 1 jpeg. An unknown suffix is refused rather than guessed, because the
# extension is what tells Signal how to render the attachment.
_SUFFIXES: Final = frozenset({".jpg", ".jpeg", ".png", ".gif"})
def default_cache_dir() -> Path:
"""Return the portrait directory, preferring the one systemd hands us.
Under the unit CACHE_DIRECTORY is set and writable even though
ProtectHome=read-only makes the rest of $HOME immutable; outside it -- a
test run, a shell -- XDG applies. Mirrors scripts/signal_api_watchdog.sh.
"""
explicit = os.environ.get("PORTRAIT_CACHE_DIR", "").strip()
if explicit:
return Path(explicit)
cache = os.environ.get("CACHE_DIRECTORY", "").strip()
if cache:
return Path(cache) / "portraits"
home = os.environ.get("XDG_CACHE_HOME", "").strip() or str(Path.home() / ".cache")
return Path(home) / "signal-bot" / "portraits"
class PortraitCache:
"""Fetches a pope's portrait once, then serves it from disk forever."""
def __init__(
self,
fetcher: ImageFetcher,
api_url: str,
cache_dir: Path | None = None,
) -> None:
"""Store the fetcher, the Commons endpoint and where files land."""
self._fetcher = fetcher
self._api_url = api_url
self._dir = default_cache_dir() if cache_dir is None else cache_dir
def path_for(self, pope: Pope) -> Path:
"""Return the cache path for one pope.
Named from the ordinal, never from the Commons filename: those carry
spaces, parentheses, commas and non-ASCII, and are attacker-adjacent
data in a way an integer is not.
"""
suffix = Path(pope.portrait).suffix.lower()
if suffix not in _SUFFIXES:
msg = f"portrait for #{pope.ordinal} has an unusable suffix: {pope.portrait!r}"
raise ImageFetchError(msg)
return self._dir / f"{pope.ordinal:03d}{suffix}"
async def get_base64(self, pope: Pope) -> str:
"""Return the portrait base64-encoded, as the transport wants it."""
return base64.b64encode(await self.get_bytes(pope)).decode("ascii")
async def get_bytes(self, pope: Pope) -> bytes:
"""Return the portrait bytes, downloading them only on a miss."""
path = self.path_for(pope)
cached = _read(path)
if cached is not None:
return cached
image = await self._fetcher.fetch_bytes(
self._api_url,
_THUMB_PATH,
params={
"action": "query",
"format": "json",
"formatversion": "2",
"prop": "imageinfo",
"iiprop": "url",
"iiurlwidth": str(PORTRAIT_WIDTH),
"titles": f"File:{pope.portrait}",
},
)
_write(path, image)
return image
def _read(path: Path) -> bytes | None:
"""Return cached bytes, or None when there is nothing usable there.
An empty file is a miss, not a hit: that is what a crash between create
and write leaves behind, and serving it would post a broken attachment
into the group forever.
"""
try:
data = path.read_bytes()
except OSError:
return None
return data or None
def _write(path: Path, image: bytes) -> None:
"""Write the portrait atomically, ignoring a cache that will not take it.
A read-only or missing cache directory must not cost the group its photo
-- the bytes are already in hand. The next call simply misses again.
"""
try:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_bytes(image)
temporary.replace(path)
except OSError:
return

48
signal_bot/quoting.py Normal file
View File

@ -0,0 +1,48 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Answering a specific message rather than the room.
The container advertises this: /v1/about reports
``capabilities: {"v2/send": ["quotes", "mentions"]}`` and /v2/send accepts
``quote_timestamp``, ``quote_author`` and ``quote_message``.
A quote needs the *sent timestamp of the message being answered*, which is why
``IncomingMessage`` had to start carrying one -- parse_envelope threw it away,
so until now nothing downstream could have built a quote even in principle.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from signal_bot.models import IncomingMessage
@dataclass(frozen=True, slots=True)
class Quote:
"""The message a reply points at."""
timestamp: int
author: str
text: str
def payload(self) -> dict[str, str | int]:
"""The three keys /v2/send wants for a quoted reply."""
return {
"quote_timestamp": self.timestamp,
"quote_author": self.author,
"quote_message": self.text,
}
def quote_of(message: IncomingMessage) -> Quote | None:
"""Return the quote that answers this message, or None if it has none.
Both fields are required by the API, and an envelope missing either is a
shape this bot has not seen -- worth replying without a quote rather than
sending something the container will reject.
"""
if not message.timestamp or not message.source_uuid:
return None
return Quote(message.timestamp, message.source_uuid, message.text or "")

View File

@ -12,6 +12,9 @@ from collections.abc import Awaitable, Callable, Iterable
from dataclasses import dataclass
from typing import TYPE_CHECKING
from signal_bot.folding import fold
from signal_bot.quoting import quote_of
if TYPE_CHECKING:
from signal_bot.config import Config
from signal_bot.models import IncomingMessage
@ -33,15 +36,40 @@ class CommandContext:
command_name: str
now: float
day: str
# Whatever followed the trigger, split on whitespace. Empty for every
# command that does not opt into taking any -- see Command.takes_args.
args: tuple[str, ...] = ()
async def reply(self, text: str) -> None:
"""Send a text reply into the group the command came from.
"""Answer the message that triggered this command, in its group.
There is no configurable reply target. A command answers where it
was asked, which is the only routing that stays correct once the
bot watches a test group and a production group at once.
bot watches a test group and a production group at once -- and it
quotes the asker, so a busy group can tell which "!cat" this is.
"""
await self.transport.send_text(text, self.group_id)
await self.transport.send_text(text, self.group_id, quote_of(self.message))
async def reply_image(self, image_base64: str, caption: str = "") -> None:
"""Answer the triggering message with an image, quoting it."""
await self.transport.send_image(
image_base64, self.group_id, quote_of(self.message), caption
)
async def reply_media(self, payload_base64: str, media_type: str, filename: str) -> None:
"""Answer with an attachment that is not necessarily a photo.
Separate from reply_image because Signal decides how to render an
attachment from what it is told it is, and "a jpeg" is a lie that
makes a video arrive as a file nobody can play.
"""
await self.transport.send_media(
payload_base64,
self.group_id,
quote_of(self.message),
media_type=media_type,
filename=filename,
)
Handler = Callable[[CommandContext], Awaitable[None]]
@ -49,17 +77,58 @@ Handler = Callable[[CommandContext], Awaitable[None]]
@dataclass(frozen=True, slots=True)
class Command:
"""A named command and every phrase that triggers it."""
"""A named command, every phrase that triggers it, and how to explain it."""
name: str
triggers: frozenset[str]
handler: Handler
# Group-facing Polish, one line, for !pomoc. Required at registration so
# that a command cannot exist without one -- a parallel help table would
# go stale exactly the way the README's command list did.
description: str
# The spelling !pomoc shows. It cannot come from `triggers`: those are
# folded skeletons in an unordered set, so "!papiez" is all that survives
# of "!papież". This is the first raw trigger instead, which is the
# canonical Polish one for every entry in aliases.json.
primary: str
# The only groups this command exists in, or None for everywhere. Not a
# gate inside the handler: the dispatcher treats a command that is not
# allowed here as no command at all, so it is never answered, never
# counted as a command and never logged by name in a group it does not
# belong to. A silent handler would still leak all three.
groups: frozenset[str] | None = None
# Whether words after the trigger are arguments rather than nonsense.
# Off by default, so "!cat blah" keeps resolving to nothing exactly as
# it does today.
takes_args: bool = False
def allowed_in(self, group_id: str) -> bool:
"""Whether this command exists in one group."""
return self.groups is None or group_id in self.groups
class DuplicateTriggerError(ValueError):
"""Raised when two commands claim the same trigger word."""
class CommandRefusedError(Exception):
"""A gate declined the command, so nothing happened and nothing is recorded.
The dispatcher records one use per invocation, and it cannot see inside a
handler. Without this signal a *refused* run looked exactly like a
successful one, which slid the cooldown window forward every time somebody
was told to wait -- so waiting the stated time never helped.
"""
@dataclass(frozen=True, slots=True)
class Resolved:
"""A command a message fired, and the words that followed it."""
command: Command
args: tuple[str, ...]
class CommandRegistry:
"""Maps trigger words to commands."""
@ -68,18 +137,36 @@ class CommandRegistry:
self._by_trigger: dict[str, Command] = {}
self._commands: list[Command] = []
def register(self, name: str, triggers: Iterable[str], handler: Handler) -> Command:
def register(
self,
name: str,
triggers: Iterable[str],
handler: Handler,
description: str,
*,
groups: frozenset[str] | None = None,
takes_args: bool = False,
) -> Command:
"""Register one command under every one of its triggers.
Raises:
DuplicateTriggerError: A trigger is already claimed.
"""
normalised = frozenset(t.strip().lower() for t in triggers)
raw = list(triggers)
normalised = frozenset(fold(t) for t in raw)
for trigger in sorted(normalised):
if trigger in self._by_trigger:
msg = f"trigger {trigger!r} is already registered"
raise DuplicateTriggerError(msg)
command = Command(name=name, triggers=normalised, handler=handler)
command = Command(
name=name,
triggers=normalised,
handler=handler,
description=description,
primary=raw[0],
groups=groups,
takes_args=takes_args,
)
for trigger in normalised:
self._by_trigger[trigger] = command
self._commands.append(command)
@ -89,11 +176,37 @@ class CommandRegistry:
"""Return the command a message body triggers, or None."""
if not text:
return None
candidate = text.strip().lower()
# Folded, not just lowercased: a Cyrillic "o" is a different
# codepoint from a Latin one and used to resolve to nothing at all.
candidate = fold(text)
if not candidate.startswith(COMMAND_PREFIX):
return None
return self._by_trigger.get(candidate)
def resolve_with_args(self, text: str | None, group_id: str) -> Resolved | None:
"""Resolve a message in one group, with anything that followed it.
Two lookups, in this order. The whole text first, which is what every
command has always been matched by and stays byte-for-byte the same
rule -- so "!cat blah" still resolves to nothing. Only then the first
word, and only for a command that says it takes arguments.
A command the group is not allowed is not a near miss: it comes back
as None, indistinguishable from a word nobody registered.
"""
if not text:
return None
command = self.resolve(text)
if command is not None:
return Resolved(command, ()) if command.allowed_in(group_id) else None
words = text.split()
if not words:
return None
head = self._by_trigger.get(fold(words[0]))
if head is None or not head.takes_args or not head.allowed_in(group_id):
return None
return Resolved(head, tuple(words[1:]))
@property
def commands(self) -> list[Command]:
"""Every registered command, in registration order."""

133
signal_bot/reporting.py Normal file
View File

@ -0,0 +1,133 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Composing the evening report: what it says, but never the sending of it.
Split out of bot.py at the 250-line cap, and the seam is worth having on its
own terms -- everything here is pure, so "what would the group be told?" is a
question that can be answered without a transport, a group, or a send.
One run can have several things to say: a day the bot was down for, the day
it is on now, and the week or month that ended inside them. They are blocks
in one message rather than a post each, because four notifications in one
evening is how a daily tally becomes something people mute.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Final
from signal_bot.stats import curiosities, periods
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.nightly import closing_periods
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
if TYPE_CHECKING:
from collections.abc import Sequence
from signal_bot.discovery import GroupDirectory
from signal_bot.store import Store
logger = logging.getLogger(__name__)
# What separates the day, the week and any caught-up day inside one report.
# A blank line and a rule, because Signal renders no markdown and two blocks
# run straight into each other without one.
BLOCK_SEPARATOR: Final = "\n\n———\n\n"
def compose(
store: Store,
directory: GroupDirectory,
group_id: str,
days: Sequence[str],
today: str,
closed_at: str | None,
) -> str:
"""The whole message for one group, or "" when there is nothing to say.
Args:
store: The open database.
directory: Used for the member roster, so people who said nothing are
still named.
group_id: The group being reported on.
days: Days to cover, oldest first.
today: The day that is still running, from the caller's clock. Passed
rather than read here: one injected clock decides what "today"
means for the whole bot, and a second reading of the real one
could disagree with it across midnight.
closed_at: "HH:MM" that still-running day was counted up to.
"""
blocks: list[str] = []
for day in days:
block = day_block(store, directory, group_id, day, closed_at if day == today else None)
if block:
blocks.append(block)
blocks.extend(closing_blocks(store, group_id, day))
return BLOCK_SEPARATOR.join(blocks)
def day_block(
store: Store,
directory: GroupDirectory,
group_id: str,
day: str,
closed_at: str | None,
) -> str | None:
"""One day as the group reads it, or None if nobody spoke that day."""
rows = day_rows(store.events, group_id, day)
if not rows:
# The bot is in every group it was ever added to, so "nobody spoke"
# would be a nightly ping into every quiet group, forever.
logger.info("no messages in %s on %s; not reporting on it", group_id, day)
return None
named = store.events.roster(group_id, directory.member_identities(group_id))
with_zeros = with_silent(rows, [(person.uuid, person.display_name) for person in named])
backfilled = backfilled_day(store, group_id)
facts = gather(store.events, group_id, day, with_zeros, exclude=backfilled)
picks = select(curiosities.for_day(facts), SLOTS)
return render_day(
day,
with_zeros,
day_totals(with_zeros),
DayView(
since=store.events.first_day(group_id),
approximate=backfilled == day,
highlights=tuple(pick.text for pick in picks),
# Only for a day that is still running: telling the group a
# finished day's count "stopped at 21:37" would be a lie.
closed_at=closed_at,
),
)
def closing_blocks(store: Store, group_id: str, day: str) -> list[str]:
"""The week, month or year that ended with this day, if any.
Rendered rather than posted: they join the day in one message, so a
Sunday evening is one notification and not two.
"""
blocks: list[str] = []
for period in closing_periods(day):
rows = period_rows(store.events, group_id, period)
if not rows:
continue
before = periods.previous(period)
trend = Trend(
now=total_for(store.events, group_id, period.start, period.end),
before=total_for(store.events, group_id, before.start, before.end),
)
blocks.append(
render_period(
period,
rows,
trend,
since=store.events.first_day(group_id),
podium=period.kind != "week",
)
)
return blocks

61
signal_bot/roster.py Normal file
View File

@ -0,0 +1,61 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Who is in a group, according to the last listing that actually arrived.
The nightly report shows a 0 next to people who said nothing, and the event
log cannot supply them: somebody who has never written has no events. Only the
group listing knows, and it is fetched, not stored -- so this is a cache of a
live answer, deliberately held in memory. A roster persisted to the database
would outlive the truth, and the failure mode of a stale roster is naming
somebody who left.
Kept out of ``discovery`` because that module was two lines under the 250-line
cap, and because "who may the bot watch" and "who is in the room" are separate
questions that happen to be answered by the same HTTP response.
"""
from __future__ import annotations
from collections.abc import Callable
from typing import Any
from signal_bot.trust import identities
Permitted = Callable[[dict[str, Any]], "str | None"]
class RosterCache:
"""Each watched group's membership, from the last good listing."""
def __init__(self, own_number: str) -> None:
"""Wire the cache to the bot's own number, which it excludes.
Args:
own_number: The account's +E.164 number. The bot is a member of
every group it watches, and counting itself as a silent
participant would put the bot in its own report.
"""
self._own = own_number
self._members: dict[str, frozenset[str]] = {}
def remember(self, entries: list[dict[str, Any]], permitted: Permitted) -> None:
"""Stash the membership of every permitted group in a listing.
Pending invitees are excluded: they cannot have written anything, so
listing them as silent members would be wrong rather than merely
noisy.
"""
for entry in entries:
group_id = permitted(entry)
if group_id is None:
continue
members = identities(entry, "members") - identities(entry, "pending_invites")
self._members[group_id] = frozenset(members - {self._own})
def identities(self, group_id: str) -> frozenset[str]:
"""One group's members, or empty for a group no listing has covered.
A mix of ACI uuids and +E.164 numbers -- the listing uses whichever
spelling it has for a given person, which is why the event store
matches on both.
"""
return self._members.get(group_id, frozenset())

99
signal_bot/schema.py Normal file
View File

@ -0,0 +1,99 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The database shape, kept apart from the code that queries it.
Split out of ``store.py`` so both stay under the 250-line cap, and because
"what the tables are" and "how the bot reads them" are two things.
"""
from __future__ import annotations
from typing import Final
# Bumped whenever the shape below changes. See Store._apply_schema for why
# a version number is the only safe way to notice.
#
# Deliberately NOT bumped when a whole new table is added: CREATE TABLE IF
# NOT EXISTS is additive and harmless, whereas a bump drops every table and
# would throw away the live tallies to gain nothing.
SCHEMA_VERSION: Final = 2
# Every table is keyed by group first. The bot watches several groups, and a
# tally, a cooldown or a vote that leaked between them would mean a test
# message throttling the production group -- so the scope is in the primary
# key rather than in the callers' discipline.
SCHEMA: Final = """
CREATE TABLE IF NOT EXISTS command_uses (
group_id TEXT NOT NULL,
user_uuid TEXT NOT NULL,
command TEXT NOT NULL,
used_at REAL NOT NULL,
PRIMARY KEY (group_id, user_uuid, command)
);
CREATE TABLE IF NOT EXISTS daily_uses (
group_id TEXT NOT NULL,
user_uuid TEXT NOT NULL,
command TEXT NOT NULL,
day TEXT NOT NULL,
uses INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (group_id, user_uuid, command, day)
);
CREATE TABLE IF NOT EXISTS votes (
group_id TEXT NOT NULL,
command TEXT NOT NULL,
voter_uuid TEXT NOT NULL,
voted_at REAL NOT NULL,
PRIMARY KEY (group_id, command, voter_uuid)
);
CREATE TABLE IF NOT EXISTS group_meta (
group_id TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (group_id, key)
);
CREATE TABLE IF NOT EXISTS message_events (
group_id TEXT NOT NULL,
uuid TEXT NOT NULL,
display_name TEXT NOT NULL,
sent_at_ms INTEGER NOT NULL,
day TEXT NOT NULL,
local_hour INTEGER NOT NULL,
media_kind TEXT NOT NULL DEFAULT '',
media_count INTEGER NOT NULL DEFAULT 0,
char_len INTEGER NOT NULL DEFAULT 0,
is_command INTEGER NOT NULL DEFAULT 0,
is_reply INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (group_id, uuid, sent_at_ms)
);
CREATE INDEX IF NOT EXISTS idx_events_group_day
ON message_events (group_id, day);
CREATE INDEX IF NOT EXISTS idx_events_group_uuid_day
ON message_events (group_id, uuid, day);
CREATE TABLE IF NOT EXISTS group_people (
group_id TEXT NOT NULL,
uuid TEXT NOT NULL,
display_name TEXT NOT NULL,
number TEXT NOT NULL DEFAULT '',
first_seen TEXT NOT NULL,
last_seen TEXT NOT NULL,
PRIMARY KEY (group_id, uuid)
);
"""
# Cleared when the bot leaves a group, and rebuilt on a schema-version bump.
# Losing any of these costs a cooldown or a vote in progress.
EPHEMERAL_TABLES: Final = (
"command_uses",
"daily_uses",
"votes",
"group_meta",
)
# Never dropped, by either path. These hold the whole statistical history,
# which cannot be recomputed from anything -- so a transient group listing
# that omits a member (the exact failure discovery._permitted guards against)
# must not be able to delete years of it, and neither must a future schema
# bump that only meant to reshape a cooldown table.
PERMANENT_TABLES: Final = (
"message_events",
"group_people",
)
TABLES: Final = EPHEMERAL_TABLES + PERMANENT_TABLES

109
signal_bot/selftest.py Normal file
View File

@ -0,0 +1,109 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Let the bot exercise its own commands without a second Signal account.
Signal never delivers an account its own sends, so the bot cannot type
`!papież` at itself, and every command shipped so far was verified either by
asking a human to type it or by reconstructing the object graph in a scratch
script. Both are weaker than they look: the scratch script is not the wiring
that runs in production, and a human typing it proves nothing about the path
between the websocket and the handler.
This injects a real envelope frame into the *live* dispatcher, so everything
downstream of the websocket read is the code that actually serves the group:
parsing, the scoping gate, the tally, trigger resolution, the cooldown, the
handler and the real transport. Only the socket read itself is skipped.
Fail-closed: SELFTEST_GROUPS names the groups this may post into, and is
empty by default. Without it the endpoint refuses, so a loopback caller
cannot make the bot post into the real group.
"""
from __future__ import annotations
import json
import os
import time
from typing import TYPE_CHECKING, Any, Final
if TYPE_CHECKING:
from collections.abc import Mapping
import httpx
from signal_bot.bot import Bot
from signal_bot.config import Config
GROUPS_ENV: Final = "SELFTEST_GROUPS"
class SelfTestError(RuntimeError):
"""Raised when a self-test cannot be run as asked."""
def allowed_groups(env: Mapping[str, str]) -> frozenset[str]:
"""Return the group names the self-test may post into.
Empty unless SELFTEST_GROUPS says otherwise. A bot that would replay
arbitrary text into the production group on a loopback POST is a worse
problem than the one this module solves.
"""
raw = env.get(GROUPS_ENV, "")
return frozenset(name.strip() for name in raw.split(",") if name.strip())
async def resolve_group(client: httpx.AsyncClient, config: Config, name: str) -> tuple[str, str]:
"""Return (internal group id, an author to attribute the message to).
The author must be somebody Signal can resolve, because the reply quotes
them: a made-up uuid comes back as "user ... is not registered" and the
send fails. Any real member other than the bot will do.
"""
response = await client.get(config.groups_url)
response.raise_for_status()
for entry in response.json():
if entry.get("name") != name:
continue
group_id = str(entry.get("internal_id") or entry.get("id") or "")
members = [m for m in entry.get("members", []) if m != config.phone_number]
if not group_id or not members:
msg = f"group {name!r} has no usable id or no other member"
raise SelfTestError(msg)
return group_id, str(members[0])
msg = f"no group named {name!r}"
raise SelfTestError(msg)
def build_frame(group_id: str, author: str, text: str) -> str:
"""Build the websocket frame signal-cli would emit for this message."""
stamp = int(time.time() * 1000)
payload: dict[str, Any] = {
"timestamp": stamp,
"message": text,
"groupInfo": {"groupId": group_id, "type": "DELIVER"},
}
envelope: dict[str, Any] = {
"source": author,
"sourceNumber": author,
"sourceUuid": author,
"sourceName": "self-test",
"sourceDevice": 1,
"timestamp": stamp,
"dataMessage": payload,
}
return json.dumps({"envelope": envelope, "account": author})
async def run(
bot: Bot,
client: httpx.AsyncClient,
group: str,
text: str,
env: Mapping[str, str] | None = None,
) -> str:
"""Feed one synthetic message through the live dispatcher."""
if group not in allowed_groups(os.environ if env is None else env):
msg = f"{group!r} is not in {GROUPS_ENV}; refusing to post there"
raise SelfTestError(msg)
group_id, author = await resolve_group(client, bot.config, group)
await bot.dispatcher.handle(build_frame(group_id, author, text))
return group_id

116
signal_bot/startup.py Normal file
View File

@ -0,0 +1,116 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Coming up, including when signal-cli is not there yet.
On 2026-08-30 the machine rebooted, the bot started before the signal-api
container was ready, and its very first HTTP call raised. uvicorn reported
"Application startup failed", the unit burned its five restarts in 25
seconds, and it sat in `failed` for eight hours while the container had been
healthy for almost all of them. Nobody noticed, because a unit nobody is
watching is indistinguishable from a quiet group.
So the connection to Signal is no longer part of starting up. uvicorn serves
first, /healthz answers 503 with the reason, and this module keeps trying in
the background until the container answers. A bot that is still connecting is
then *visibly* unhealthy rather than absent.
This module owns what a running bot *is*. The retry loop that gets there,
and the rule about which errors are worth retrying, live in
``signal_bot.startup_retry``.
"""
from __future__ import annotations
import asyncio
import contextlib
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
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.scheduler import DailyScheduler
from signal_bot.transport_rest import RestTransport
from signal_bot.trust import InviteTrust
if TYPE_CHECKING:
import httpx
from signal_bot.config import Config
from signal_bot.store import Store
class NotReadyError(RuntimeError):
"""Raised when signal-cli answers but cannot yet say what it knows."""
@dataclass
class Runtime:
"""The running bot and the background tasks it owns."""
bot: Bot
tasks: list[asyncio.Task[None]] = field(default_factory=list)
def start(self) -> None:
"""Spawn the listener and the daily scheduler as background tasks."""
scheduler = DailyScheduler(
self.bot.config.report_hour,
self.bot.config.report_minute,
self.bot.publish_report,
now_local,
asyncio.sleep,
)
self.tasks = [
asyncio.create_task(self.bot.listen()),
asyncio.create_task(scheduler.run()),
# Third loop: without it, a group added later is only noticed
# when somebody happens to speak in it.
asyncio.create_task(self.bot.directory.run()),
# Fourth loop: without it, a dead connection to Signal is
# indistinguishable from a quiet evening, for hours.
asyncio.create_task(self.bot.liveness.run()),
# Fifth, and one-shot: says hello with a changelog when the
# running version is newer than what a group was last told.
asyncio.create_task(self.bot.announce_release()),
]
async def stop(self) -> None:
"""Cancel the background tasks. The caller owns the client and store."""
for task in self.tasks:
task.cancel()
for task in self.tasks:
with contextlib.suppress(asyncio.CancelledError):
await task
async def create_runtime(config: Config, client: httpx.AsyncClient, store: Store) -> Runtime:
"""Build a Runtime, verifying the container exposes a WebSocket first.
Args:
config: Resolved runtime configuration.
client: HTTP client shared by every component.
store: The already-open tally database. Owned by the caller, because
this function is retried and must not leak a connection per try.
Returns:
A Runtime whose loops have not been started yet.
Raises:
MembershipError: GROUP_IDS names a group the bot is not a member of,
established against a listing that was actually read.
"""
transport = RestTransport(config, client)
await transport.verify_mode()
directory = GroupDirectory(config, client, store, InviteTrust(config.trusted_inviters))
# Only a listing that really arrived can convict the allowlist. A refresh
# that failed leaves the watched set empty, and judging GROUP_IDS on that
# would turn "the container is not up yet" into "you are not in your own
# group" -- fatal, and wrong.
if not await directory.refresh():
msg = f"group listing at {config.groups_url} could not be read"
raise NotReadyError(msg)
await directory.verify_allowlist()
# No probe here: /v1/devices has been seen to hang past 20s, and a
# startup that can hang is a startup that can burn the unit's restart
# limit. The gate starts healthy and earns its verdict at runtime.
liveness = Liveness(config, client)
return Runtime(bot=build_bot(config, client, store, transport, directory, liveness))

161
signal_bot/startup_retry.py Normal file
View File

@ -0,0 +1,161 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Retrying the connection to signal-cli until it works, in the background.
Split out of ``startup.py`` so both stay under the 250-line cap. ``startup``
owns *what a running bot is* (:class:`~signal_bot.startup.Runtime` and how it
is built); this module owns *getting there* -- the retry loop, its backoff, and
the one distinction that keeps the systemd start limit meaningful: only errors
that another attempt might fix are retried. A container in the wrong mode, or a
GROUP_IDS entry naming a group the bot is genuinely not in, are answers.
Retrying them forever would replace a visible failure with an invisible one.
"""
from __future__ import annotations
import asyncio
import logging
import signal
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Final
import httpx
from signal_bot.membership import MembershipError
from signal_bot.startup import NotReadyError, Runtime, create_runtime
from signal_bot.transport_rest import TransportError
if TYPE_CHECKING:
from signal_bot.config import Config
from signal_bot.store import Store
logger = logging.getLogger(__name__)
FIRST_RETRY_SECONDS: Final = 5.0
# Docker's own restart of signal-api plus signal-cli's account load took
# minutes on the reboot this exists for, so the ceiling is what the bot
# spends most of that wait at. A minute is short enough that recovery is
# still prompt and long enough that a long outage is not a busy loop.
MAX_RETRY_SECONDS: Final = 60.0
BACKOFF_FACTOR: Final = 2.0
# Another attempt might fix these: the container is still booting, its HTTP
# server is up but answering 502, or it is returning a holding page that is
# not JSON. ValueError covers the last one -- json.JSONDecodeError is one.
#
# Note what else ValueError covers: registry.DuplicateTriggerError. A command
# alias claimed twice is a programming error that no retry can fix, but it is
# raised while build_bot runs inside create_runtime, so it lands here and the
# bot retries forever reporting "signal-cli not reachable yet" -- the wrong
# diagnosis entirely. tests/test_stats_commands.py builds the whole registry
# so that collision is caught at test time instead.
RETRYABLE: Final = (httpx.HTTPError, ValueError, NotReadyError)
# No further attempt will fix these. They are verdicts, not outages.
FATAL: Final = (TransportError, MembershipError)
Sleeper = Callable[[float], Awaitable[None]]
Stopper = Callable[[], None]
# Quoted: Config and Store are imported for type checking only, and this
# alias is evaluated at import time.
Factory = Callable[["Config", httpx.AsyncClient, "Store"], Awaitable[Runtime]]
def terminate() -> None:
"""Ask uvicorn to shut down, from inside a background task.
A background task cannot exit the process: SystemExit raised in one only
kills that task, is logged as "Task exception was never retrieved", and
uvicorn keeps serving a bot that will never connect. SIGTERM is the
signal uvicorn already handles, and the unit's start limit then turns the
resulting restart loop into a `failed` unit somebody can see.
"""
signal.raise_signal(signal.SIGTERM)
class Starter:
"""Connects to signal-cli in the background, retrying until it works."""
def __init__(
self,
config: Config,
client: httpx.AsyncClient,
store: Store,
*,
sleeper: Sleeper | None = None,
stopper: Stopper | None = None,
factory: Factory = create_runtime,
) -> None:
"""Wire the retry loop to its config and its injectable I/O.
Args:
config: Resolved runtime configuration.
client: HTTP client shared by every component.
store: The already-open event database.
sleeper: Async sleep between attempts. Injected by the tests.
stopper: How to end the process on a fatal error. Injected by
the tests, which must not signal the pytest process.
factory: Builds the runtime. Injected by the tests.
"""
self._config = config
self._client = client
self._store = store
self._sleep = sleeper if sleeper is not None else asyncio.sleep
self._stop = stopper if stopper is not None else terminate
self._factory = factory
self.runtime: Runtime | None = None
self._attempts = 0
self._detail = "not attempted yet"
self._fatal = False
@property
def reason(self) -> str:
"""Why the bot is not connected yet, in one line for /healthz."""
return (
f"connecting to {self._config.api_base_url}, attempt {self._attempts}: {self._detail}"
)
async def attempt(self) -> bool:
"""Try once to build and start the runtime.
Returns:
True once the bot is connected and its loops are running.
"""
self._attempts += 1
try:
runtime = await self._factory(self._config, self._client, self._store)
except FATAL as exc:
self._detail = f"{type(exc).__name__}: {exc}"
self._fatal = True
logger.exception("cannot start, and no retry will help")
self._stop()
return False
except RETRYABLE as exc:
self._detail = f"{type(exc).__name__}: {exc}"
logger.warning("signal-cli not reachable yet (attempt %d): %s", self._attempts, exc)
return False
runtime.start()
self.runtime = runtime
logger.info(
"listening as %s after %d attempt(s), watching %d group(s): %r",
self._config.phone_number,
self._attempts,
len(runtime.bot.directory.groups),
list(runtime.bot.directory.groups),
)
return True
async def run(self, iterations: int | None = None) -> None:
"""Attempt to connect until it works, or until it provably cannot.
Args:
iterations: Stop after this many failed attempts. None means
keep trying forever, which is what production wants.
"""
completed = 0
delay = FIRST_RETRY_SECONDS
while iterations is None or completed < iterations:
if await self.attempt() or self._fatal:
return
await self._sleep(delay)
delay = min(delay * BACKOFF_FACTOR, MAX_RETRY_SECONDS)
completed += 1

View File

@ -0,0 +1,8 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Message statistics: the event log, the queries over it, and the renderers.
Deliberately empty of re-exports. The renderers import the queries, the
queries import the event store, and a convenience re-export here would drag
the whole subpackage into every module that wanted one calendar helper.
Import from the module that owns the thing.
"""

View File

@ -0,0 +1,94 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Carrying the pre-0.1.0 counter into the event log, once.
Before 0.1.0 the bot kept one integer per person and deleted it after each
nightly post. When the event log arrived there were 319 messages sitting in
that counter, accumulated since the last successful post. Throwing them away
would have been tidier, but they are real messages and they are the group's
only pre-history.
What the counter cannot say is *when*. It has no timestamp column, and its
window straddles two calendar days -- from the previous night's post to
whenever the migration runs. So a backfilled day is filed under the day that
holds most of that window, and marked, because a merged 22-hour day pretending
to be a normal one would hand somebody a personal record they never set and
would drag every "average day" figure with it.
Marked days keep their totals and stay out of records and per-hour statistics.
``group_meta`` carries the mark, so this needs no schema change.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Final
from signal_bot.stats.events import MessageEvent
if TYPE_CHECKING:
from signal_bot.store import Store
BACKFILL_KEY: Final = "backfill_day"
# -1, because a backfilled event has no hour at all and any value in 0..23 is
# a lie that reads as data. This started as 12, on the reasoning that the day
# is marked so "nothing that cares about hours will read these" -- and then
# favourite_hour did, and told all seven people their favourite hour was
# 12:00, because 319 synthetic noons outweighed every real evening.
#
# The lesson is in the type, not in a comment: an absent value must not be
# spellable as a present one. Hour queries filter `local_hour >= 0`, so
# forgetting to exclude the backfilled day can no longer invent an answer.
UNKNOWN_HOUR: Final = -1
def has_legacy_counter(store: Store) -> bool:
"""True when this database predates 0.1.0 and still holds the old table."""
row = store.events.connection.execute(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'message_counts'"
).fetchone()
return row is not None
def backfilled_day(store: Store, group_id: str) -> str | None:
"""The one day whose totals came from the old counter, if any."""
return store.meta(group_id, BACKFILL_KEY)
def seed_from_counter(store: Store, day: str) -> dict[str, int]:
"""Copy every surviving tally into the event log as one marked day.
Args:
store: The open database, which must still hold ``message_counts``.
day: The Warsaw day to file the counts under. Choose the day covering
most of the counter's window.
Returns:
Messages seeded per group id, for reporting.
"""
rows = store.events.connection.execute(
"SELECT group_id, uuid, display_name, count FROM message_counts WHERE count > 0"
).fetchall()
seeded: dict[str, int] = {}
for row in rows:
group_id = row["group_id"]
for index in range(row["count"]):
# Synthetic, strictly increasing, and unique per person per group,
# because (group, uuid, sent_at_ms) is the primary key. They are
# not timestamps anybody should read as one, which is what the
# day marking is for.
store.events.record(
MessageEvent(
group_id=group_id,
uuid=row["uuid"],
display_name=row["display_name"],
sent_at_ms=index + 1,
day=day,
local_hour=UNKNOWN_HOUR,
)
)
store.events.note_person(group_id, row["uuid"], row["display_name"], "", day)
seeded[group_id] = seeded.get(group_id, 0) + row["count"]
for group_id in seeded:
store.set_meta(group_id, BACKFILL_KEY, day)
return seeded

View File

@ -0,0 +1,223 @@
# 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 ala` resolves to nothing; teaching
it to split on whitespace would silently make `!kot pls` fire where today it
does nothing, which is a behaviour change with its own blast radius. Each
question gets its own trigger instead.
`!wczoraj` renders through exactly the same path as the nightly post. That is
not a convenience: the bot cannot trigger its own 21:37 report on demand, so
without a command that produces byte-identical text there would be no way to
check the headline output of this release short of waiting for the evening.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from signal_bot.animals import load_aliases
from signal_bot.stats import curiosities, periods, records, streaks
from signal_bot.stats.backfill import backfilled_day
from signal_bot.stats.facts import gather
from signal_bot.stats.highlights import SLOTS, select
from signal_bot.stats.queries_day import day_rows, day_totals, with_silent
from signal_bot.stats.queries_period import (
Trend,
every_day,
period_rows,
total_for,
weekday_buckets,
)
from signal_bot.stats.render_day import DayView, render_day
from signal_bot.stats.render_extra import (
ME_TITLE,
favourite_hour,
render_crown,
render_me,
render_records,
render_weekdays,
)
from signal_bot.stats.render_period import render_period
if TYPE_CHECKING:
from signal_bot.decorators import Decorator
from signal_bot.registry import CommandContext, CommandRegistry, Handler
from signal_bot.stats.periods import Period
def _day_block(ctx: CommandContext, day: str, heading: str | None = None) -> str:
"""Render one day exactly as the nightly report does."""
store = ctx.store
rows = with_silent(
day_rows(store.events, ctx.group_id, day),
[(p.uuid, p.display_name) for p in store.events.people(ctx.group_id)],
)
if not any(not row.is_silent for row in rows):
return "Nikt jeszcze nic nie napisał tego dnia."
backfilled = backfilled_day(store, ctx.group_id)
facts = gather(store.events, ctx.group_id, day, rows, exclude=backfilled)
picks = select(curiosities.for_day(facts), SLOTS)
return render_day(
day,
rows,
day_totals(rows),
DayView(
since=store.events.first_day(ctx.group_id),
approximate=backfilled == day,
highlights=tuple(pick.text for pick in picks),
heading=heading,
),
)
def _period_block(ctx: CommandContext, period: Period, *, podium: bool = False) -> str:
"""Render one period against the one before it."""
store = ctx.store
before = periods.previous(period)
trend = Trend(
now=total_for(store.events, ctx.group_id, period.start, period.end),
before=total_for(store.events, ctx.group_id, before.start, before.end),
)
return render_period(
period,
period_rows(store.events, ctx.group_id, period),
trend,
since=store.events.first_day(ctx.group_id),
podium=podium,
)
async def today(ctx: CommandContext) -> None:
"""`!staty` -- the day so far."""
await ctx.reply(_day_block(ctx, periods.today(), heading="Dziś, na razie:"))
async def yesterday(ctx: CommandContext) -> None:
"""`!wczoraj` -- byte-identical to what the nightly post said."""
await ctx.reply(_day_block(ctx, periods.previous_day()))
async def week(ctx: CommandContext) -> None:
"""`!tydzień` -- this week against last week."""
await ctx.reply(_period_block(ctx, periods.week_of(periods.today())))
async def month(ctx: CommandContext) -> None:
"""`!miesiąc` -- this month, with a podium."""
await ctx.reply(_period_block(ctx, periods.month_of(periods.today()), podium=True))
async def year(ctx: CommandContext) -> None:
"""`!rok` -- this year against last year."""
await ctx.reply(_period_block(ctx, periods.year_of(periods.today())))
async def all_records(ctx: CommandContext) -> None:
"""`!rekordy` -- every all-time record the group has set."""
store = ctx.store
exclude = backfilled_day(store, ctx.group_id)
history = every_day(store.events, ctx.group_id, exclude=exclude)
personal = []
for person in store.events.people(ctx.group_id):
best = records.personal_best(store.events, ctx.group_id, person.uuid, exclude=exclude)
if best is not None:
personal.append((person.display_name, best))
personal.sort(key=lambda pair: (-pair[1].value, pair[0]))
await ctx.reply(
render_records(
history,
records.most_media_day(store.events, ctx.group_id, exclude=exclude),
records.longest_silence(history, periods.today()) if history else None,
personal,
store.events.first_day(ctx.group_id),
)
)
async def crown(ctx: CommandContext) -> None:
"""`!korona` -- who holds it, who held it longest, who has held it most."""
store = ctx.store
winners = streaks.daily_winners(
store.events, ctx.group_id, exclude=backfilled_day(store, ctx.group_id)
)
await ctx.reply(
render_crown(
winners,
store.events.people(ctx.group_id),
store.events.first_day(ctx.group_id),
)
)
async def weekdays(ctx: CommandContext) -> None:
"""`!dni` -- the Monday-to-Sunday picture."""
store = ctx.store
history = every_day(store.events, ctx.group_id, exclude=backfilled_day(store, ctx.group_id))
await ctx.reply(
render_weekdays(
weekday_buckets(history),
periods.weekday_of(periods.today()),
store.events.first_day(ctx.group_id),
)
)
async def me(ctx: CommandContext) -> None:
"""`!ja` -- the asker's own numbers."""
store = ctx.store
uuid = ctx.message.source_uuid
exclude = backfilled_day(store, ctx.group_id)
everyone = period_rows(
store.events,
ctx.group_id,
periods.Period("all", "0000-01-01", "9999-12-31", "wszystko"),
)
mine = next((row for row in everyone if row.uuid == uuid), None)
if mine is None:
await ctx.reply(f"{ME_TITLE}\n\nNie mam jeszcze od ciebie ani jednej wiadomości.")
return
total = sum(row.messages for row in everyone)
winners = streaks.daily_winners(store.events, ctx.group_id, exclude=exclude)
running = [s for s in streaks.current_streaks(winners) if s.uuid == uuid]
await ctx.reply(
render_me(
mine.display_name,
mine.messages,
records.personal_best(store.events, ctx.group_id, uuid, exclude=exclude),
round(mine.messages / total * 100) if total else 0,
favourite_hour(store.events, ctx.group_id, uuid),
running[0].length if running else 0,
)
)
# Handler plus the one line !pomoc prints for it, in the group's language.
# Paired here rather than in the help module so that adding a command and
# explaining it are the same edit.
HANDLERS: dict[str, tuple[Handler, str]] = {
"stats_today": (today, "ile kto dziś napisał, na razie"),
"stats_yesterday": (yesterday, "wczorajszy raport, ten sam, który wpada o 21:37"),
"stats_week": (week, "ten tydzień na tle poprzedniego"),
"stats_month": (month, "ten miesiąc, z podium"),
"stats_year": (year, "ten rok na tle poprzedniego"),
"stats_records": (all_records, "rekordy grupy: najgłośniejszy dzień, najdłuższa cisza"),
"stats_crown": (crown, "kto danego dnia pisze najwięcej i kto trzymał koronę najdłużej"),
"stats_weekdays": (weekdays, "od poniedziałku do niedzieli, który dzień jest najgadatliwszy"),
"stats_me": (me, "twoje własne liczby w tej grupie"),
}
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, description) in HANDLERS.items():
registry.register(
name, table[name], decorate(handler) if decorate else handler, description
)

View File

@ -0,0 +1,232 @@
# 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 ?
AND local_hour >= 0
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]

158
signal_bot/stats/events.py Normal file
View File

@ -0,0 +1,158 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The append-only message log, and the people who wrote it.
One row per counted message, holding metadata only. There is deliberately no
column for the message body: the group's statistics need to know that someone
wrote 140 characters at 23:41, never what they wrote. ``test_events`` pins the
column set exactly so a later edit cannot quietly add one.
Two tables, because they answer two different questions. ``message_events``
answers "who said how much, when". ``group_people`` answers "who is in this
group", which the event log cannot: somebody who has never spoken has no
events, and the group listing spells its members inconsistently -- an ACI uuid
for most people but a +E.164 number for anyone the account has as a contact.
Carrying both spellings is what lets a roster entry find its events.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import sqlite3
from collections.abc import Iterable
@dataclass(frozen=True, slots=True)
class MessageEvent:
"""One counted message, reduced to the metadata the statistics need."""
group_id: str
uuid: str
display_name: str
sent_at_ms: int
day: str
local_hour: int
media_kind: str = ""
media_count: int = 0
char_len: int = 0
is_command: bool = False
is_reply: bool = False
@dataclass(frozen=True, slots=True)
class Person:
"""Somebody who has written at least one message in a group."""
uuid: str
display_name: str
number: str
class EventStore:
"""Reads and writes the message history. Shares the Store's connection."""
def __init__(self, conn: sqlite3.Connection) -> None:
"""Wrap an open connection whose schema has already been applied."""
self._conn = conn
@property
def connection(self) -> sqlite3.Connection:
"""The shared connection, for the query modules in this package."""
return self._conn
def record(self, event: MessageEvent) -> None:
"""Append one message, ignoring a frame that has already been seen.
``ON CONFLICT DO NOTHING`` against the (group, sender, timestamp)
primary key is what makes a websocket redelivery harmless. signal-cli
replays undelivered frames when the bot reconnects, so without this
every restart would silently inflate the counts it just published.
"""
self._conn.execute(
"""
INSERT INTO message_events (
group_id, uuid, display_name, sent_at_ms, day, local_hour,
media_kind, media_count, char_len, is_command, is_reply
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(group_id, uuid, sent_at_ms) DO NOTHING
""",
(
event.group_id,
event.uuid,
event.display_name,
event.sent_at_ms,
event.day,
event.local_hour,
event.media_kind,
event.media_count,
event.char_len,
int(event.is_command),
int(event.is_reply),
),
)
self._conn.commit()
def note_person(
self, group_id: str, uuid: str, display_name: str, number: str, day: str
) -> None:
"""Record that somebody wrote in a group today, under the name they used.
``display_name`` is last-write-wins here on purpose: this table
answers "what do we call them now". The name they had at the time is
preserved per row in ``message_events``, so a rename cannot rewrite
past attribution.
``number`` only updates when a non-empty one arrives. Envelopes carry
it inconsistently, and an empty string overwriting a known number
would break the roster join for exactly the people it exists for.
"""
self._conn.execute(
"""
INSERT INTO group_people (
group_id, uuid, display_name, number, first_seen, last_seen
) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(group_id, uuid) DO UPDATE SET
display_name = excluded.display_name,
number = CASE
WHEN excluded.number <> '' THEN excluded.number
ELSE group_people.number
END,
last_seen = excluded.last_seen
""",
(group_id, uuid, display_name, number, day, day),
)
self._conn.commit()
def people(self, group_id: str) -> list[Person]:
"""Everyone who has ever written in a group, by display name."""
rows = self._conn.execute(
"SELECT uuid, display_name, number FROM group_people "
"WHERE group_id = ? ORDER BY display_name ASC",
(group_id,),
).fetchall()
return [Person(r["uuid"], r["display_name"], r["number"]) for r in rows]
def roster(self, group_id: str, identities: Iterable[str]) -> list[Person]:
"""The named people among a set of listing identities.
The group listing spells a member as either an ACI uuid or a +E.164
number, so both columns are candidates. Anyone it cannot match has
never written here and has no name we could print -- the caller
counts them rather than naming them, because printing a raw uuid or
somebody's phone number into a group chat is a leak.
"""
wanted = {i for i in identities if i}
if not wanted:
return []
return [p for p in self.people(group_id) if p.uuid in wanted or p.number in wanted]
def first_day(self, group_id: str) -> str | None:
"""The earliest day with an event, or None when there is no history."""
row = self._conn.execute(
"SELECT MIN(day) AS first FROM message_events WHERE group_id = ?",
(group_id,),
).fetchone()
first: str | None = row["first"]
return first

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.** "Ala set a personal record", "Ala had 60% of the
day" and "Ala 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)

100
signal_bot/stats/nightly.py Normal file
View File

@ -0,0 +1,100 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Which days still owe the group a report, and posting them.
The event log already survives an outage: a message carries Signal's own send
timestamp, signal-cli keeps receiving while the bot is down, and the replay on
reconnect is absorbed by the primary key. So the *counts* come back on their
own, filed under the day they were actually sent.
The *report* did not. A bot that was down at 21:37 simply never posted that
day, and nothing ever went back for it -- the old counter merged the day into
the next one instead, which is the bug this release exists to remove. So the
last day reported is written down per group, and every day since then gets
posted when the bot comes back.
Bounded, because coming back from a fortnight offline should not open with a
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 Period, month_of, shift, week_of, year_of
if TYPE_CHECKING:
from signal_bot.store import Store
logger = logging.getLogger(__name__)
LAST_REPORTED_KEY: Final = "last_reported_day"
# At most a week of catch-up in one go. Long enough to cover a weekend
# outage nobody noticed, short enough that a month offline is not a wall.
CATCHUP_LIMIT: Final = 7
def days_to_report(store: Store, group_id: str, latest: str) -> list[str]:
"""Every day up to ``latest`` that has not been reported yet, oldest first.
Args:
store: The open database, which holds the per-group marker.
group_id: The group being reported on.
latest: The most recent day eligible for a report, normally today.
Returns:
The days to post, oldest first. A group with no marker gets only
``latest``: the marker is absent on a brand-new group and on the first
run after this release, and neither should trigger a backlog.
"""
last = store.meta(group_id, LAST_REPORTED_KEY)
if last is None:
return [latest]
if last >= latest:
return []
days = []
day = shift(last, 1)
while day <= latest:
days.append(day)
day = shift(day, 1)
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*, never off the calendar. The nightly
post covers the day it runs on, so a week is complete exactly when that
day is a Sunday -- and the same reading stays correct when the bot has
been offline and is catching up on a week-old day, which is why the
predicate takes the day rather than reading a clock.
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.
Called for a day that was posted *and* for a day nobody spoke on -- an
empty day is settled, not pending, and leaving it unmarked would make the
bot reconsider it every night forever.
"""
store.set_meta(group_id, LAST_REPORTED_KEY, day)

197
signal_bot/stats/periods.py Normal file
View File

@ -0,0 +1,197 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""What a "day" is, and the periods built out of days.
Every statistic in this package is grouped by a ``YYYY-MM-DD`` string in
Europe/Warsaw, never by a range of epoch milliseconds. SQLite has no idea what
Europe/Warsaw is, so the day is computed here at insert time and stored beside
the event; grouping on a stored string is the only arrangement where a
daylight-saving change cannot leak into a period boundary.
Warsaw days are not all 24 hours -- 2026-03-29 is 23 and 2026-10-25 is 25,
both verified against the installed tzdata. Two consequences the rest of the
package depends on:
* "Yesterday" is ``date - timedelta(days=1)`` on the *date*. Subtracting 86400
seconds from a timestamp lands at 23:00 the previous evening on a short day.
* Any 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 entirely.
Not named ``calendar``: ruff's A005 forbids shadowing a standard-library
module name, and this package would shadow ``calendar`` for its own imports.
"""
from __future__ import annotations
import datetime as dt
from dataclasses import dataclass
from typing import Final
from zoneinfo import ZoneInfo
WARSAW: Final = ZoneInfo("Europe/Warsaw")
MS_PER_SECOND: Final = 1000
# Nominative, for "Poniedziałek, 1 września". Index 0 is Monday, matching
# date.weekday() so the two never need translating between each other.
WEEKDAY_NAMES: Final = (
"Poniedziałek",
"Wtorek",
"Środa",
"Czwartek",
"Piątek",
"Sobota",
"Niedziela",
)
# Locative-ish plural, for "wtorki mają średnio 74 wiadomości".
WEEKDAY_PLURAL: Final = (
"poniedziałki",
"wtorki",
"środy",
"czwartki",
"piątki",
"soboty",
"niedziele",
)
# Genitive, because a Polish date reads "1 września", never "1 wrzesień".
MONTH_GENITIVE: Final = (
"stycznia",
"lutego",
"marca",
"kwietnia",
"maja",
"czerwca",
"lipca",
"sierpnia",
"września",
"października",
"listopada",
"grudnia",
)
MONTH_NOMINATIVE: Final = (
"styczeń",
"luty",
"marzec",
"kwiecień",
"maj",
"czerwiec",
"lipiec",
"sierpień",
"wrzesień",
"październik",
"listopad",
"grudzień",
)
def now() -> dt.datetime:
"""Current Warsaw time. The group's day, not the host's."""
return dt.datetime.now(WARSAW)
def moment(sent_at_ms: int) -> dt.datetime:
"""A Signal millisecond timestamp as Warsaw wall-clock time."""
return dt.datetime.fromtimestamp(sent_at_ms / MS_PER_SECOND, tz=WARSAW)
def day_of(sent_at_ms: int) -> str:
"""The Warsaw calendar day a timestamp belongs to, as YYYY-MM-DD."""
return moment(sent_at_ms).date().isoformat()
def hour_of(sent_at_ms: int) -> int:
"""The Warsaw wall-clock hour, 0-23.
On the 25-hour day two real hours share the value 2, and on the 23-hour
day nothing has it. Callers must not assume 24 buckets summing to a day.
"""
return moment(sent_at_ms).hour
def today(at: dt.datetime | None = None) -> str:
"""The current Warsaw day as YYYY-MM-DD."""
return (at or now()).astimezone(WARSAW).date().isoformat()
def shift(day: str, days: int) -> str:
"""A day offset by whole calendar days, never by seconds."""
return (dt.date.fromisoformat(day) + dt.timedelta(days=days)).isoformat()
def previous_day(at: dt.datetime | None = None) -> str:
"""The last full Warsaw day -- what the nightly report is about."""
return shift(today(at), -1)
def weekday_of(day: str) -> int:
"""0 for Monday through 6 for Sunday."""
return dt.date.fromisoformat(day).weekday()
def pl_date(day: str) -> str:
"""A day as the group reads it: "Wtorek, 1 września"."""
date = dt.date.fromisoformat(day)
return f"{WEEKDAY_NAMES[date.weekday()]}, {date.day} {MONTH_GENITIVE[date.month - 1]}"
def pl_day_month(day: str) -> str:
"""Just the date: "1 września".
Used after a preposition, where the weekday would have to decline too --
"od wtorek" is wrong and "od wtorku" needs a whole second name table for
one line of output.
"""
date = dt.date.fromisoformat(day)
return f"{date.day} {MONTH_GENITIVE[date.month - 1]}"
@dataclass(frozen=True, slots=True)
class Period:
"""An inclusive span of Warsaw days, with a name the group would use."""
kind: str
start: str
end: str
label: str
@property
def days(self) -> int:
"""How many calendar days the span covers, both ends included."""
return (dt.date.fromisoformat(self.end) - dt.date.fromisoformat(self.start)).days + 1
def week_of(day: str) -> Period:
"""The ISO week (Monday-Sunday) containing a day."""
date = dt.date.fromisoformat(day)
start = date - dt.timedelta(days=date.weekday())
end = start + dt.timedelta(days=6)
return Period("week", start.isoformat(), end.isoformat(), f"tydzień {start.isocalendar().week}")
def month_of(day: str) -> Period:
"""The calendar month containing a day."""
date = dt.date.fromisoformat(day)
start = date.replace(day=1)
end = (start + dt.timedelta(days=32)).replace(day=1) - dt.timedelta(days=1)
label = f"{MONTH_NOMINATIVE[date.month - 1]} {date.year}"
return Period("month", start.isoformat(), end.isoformat(), label)
def year_of(day: str) -> Period:
"""The calendar year containing a day."""
year = dt.date.fromisoformat(day).year
return Period("year", f"{year}-01-01", f"{year}-12-31", str(year))
def previous(period: Period) -> Period:
"""The period of the same kind immediately before this one.
Used for every trend arrow, so it has to be exact rather than "minus
seven days": the month before a 31-day month is not 31 days long.
"""
before = shift(period.start, -1)
if period.kind == "week":
return week_of(before)
if period.kind == "month":
return month_of(before)
return year_of(before)

View File

@ -0,0 +1,113 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""What happened on one Warsaw day.
Every query here groups on the stored ``day`` string rather than on a range of
timestamps. That is what makes the 23-hour and 25-hour days come out right --
see ``signal_bot.stats.periods`` for why the alternative silently does not.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from signal_bot.stats.events import EventStore
@dataclass(frozen=True, slots=True)
class DayRow:
"""One person's day."""
uuid: str
display_name: str
messages: int
media: int
commands: int
chars: int
@property
def is_silent(self) -> bool:
"""True when this person did not write at all."""
return self.messages == 0
@dataclass(frozen=True, slots=True)
class DayTotals:
"""The group's day, as one line of summary."""
messages: int
media: int
commands: int
chars: int
speakers: int
@property
def average_length(self) -> int:
"""Mean characters per message, rounded, or 0 on an empty day."""
if not self.messages:
return 0
return round(self.chars / self.messages)
def day_rows(events: EventStore, group_id: str, day: str) -> list[DayRow]:
"""Everyone who wrote on a day, most talkative first.
Ties break on display name so the order is stable between two renders of
the same day -- a leaderboard that reshuffles itself reads as a bug.
"""
rows = events.connection.execute(
"""
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 = ?
GROUP BY uuid
ORDER BY messages DESC, display_name ASC
""",
(group_id, day),
).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 day_totals(rows: list[DayRow]) -> DayTotals:
"""Sum a day's rows. Derived from the rows so the two can never disagree."""
return DayTotals(
messages=sum(r.messages for r in rows),
media=sum(r.media for r in rows),
commands=sum(r.commands for r in rows),
chars=sum(r.chars for r in rows),
speakers=sum(1 for r in rows if r.messages),
)
def with_silent(rows: list[DayRow], roster: list[tuple[str, str]]) -> list[DayRow]:
"""Append a zero row for every named group member who did not write.
``roster`` is (uuid, display_name) for the people whose names are known.
Anyone in the group whose name we have never seen is deliberately absent:
they exist in the listing only as a raw uuid or a phone number, and
printing either into a group chat would leak it.
"""
spoke = {r.uuid for r in rows}
silent = [
DayRow(uuid=uuid, display_name=name, messages=0, media=0, commands=0, chars=0)
for uuid, name in roster
if uuid not in spoke
]
silent.sort(key=lambda r: r.display_name)
return rows + silent

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]

View File

@ -0,0 +1,67 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Turning one parsed message into one row of history."""
from __future__ import annotations
from typing import TYPE_CHECKING
from signal_bot.counting import media_kind
from signal_bot.stats.events import MessageEvent
from signal_bot.stats.periods import MS_PER_SECOND, day_of, hour_of
if TYPE_CHECKING:
import datetime as dt
from signal_bot.models import IncomingMessage
from signal_bot.stats.events import EventStore
def to_event(
group_id: str,
message: IncomingMessage,
now: dt.datetime,
*,
is_command: bool,
) -> MessageEvent:
"""Reduce a message to the metadata the statistics keep.
The timestamp falls back to the clock because ``models._timestamp``
returns 0 when neither the payload nor the envelope carried one. Zero is
not merely inaccurate: it is part of the primary key, so every
zero-timestamp frame from one sender would collide and the whole run
would be recorded as a single message.
"""
sent_at_ms = message.timestamp or int(now.timestamp() * MS_PER_SECOND)
return MessageEvent(
group_id=group_id,
uuid=message.source_uuid,
display_name=message.source_name or message.source_uuid,
sent_at_ms=sent_at_ms,
day=day_of(sent_at_ms),
local_hour=hour_of(sent_at_ms),
media_kind=media_kind(message),
media_count=len(message.attachment_types) or int(message.has_sticker),
char_len=len(message.text or ""),
is_command=is_command,
is_reply=message.is_reply,
)
def record_message(
events: EventStore,
group_id: str,
message: IncomingMessage,
now: dt.datetime,
*,
is_command: bool,
) -> None:
"""Append a message to the history and refresh who its sender is."""
event = to_event(group_id, message, now, is_command=is_command)
events.record(event)
events.note_person(
group_id,
event.uuid,
event.display_name,
message.source_number,
event.day,
)

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,139 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Rendering one day as the block the group reads.
Plain text, because that is all Signal renders. No markdown, and no column
padding: Signal uses a proportional font, so ``ljust`` lines up in a terminal
and on nobody's phone. A separator that does not depend on glyph widths is the
only spelling that looks the same in both places.
The block is capped at MAX_LINES so the nightly post stays something people
read rather than scroll past. When it has to give something up it gives up
speakers, never the highlight -- a leaderboard with the interesting part cut
off is worse than a shorter leaderboard.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Final
from signal_bot.stats import text
from signal_bot.stats.periods import pl_date, pl_day_month
if TYPE_CHECKING:
from signal_bot.stats.queries_day import DayRow, DayTotals
MAX_LINES: Final = 12
CROWN: Final = "\U0001f451"
CAMERA: Final = "\U0001f4f7"
CHART: Final = "\U0001f4ca"
def _media(count: int) -> str:
"""The camera marker, outside any padded column so it cannot misalign."""
return f" ({count} {CAMERA})" if count else ""
def person_line(row: DayRow, place: int) -> str:
"""One person's line: a crown for first place, otherwise a rank."""
lead = CROWN if place == 1 else f"{place}."
return f"{lead} {row.display_name} — {row.messages}{_media(row.media)}"
def silence_line(rows: list[DayRow], unnamed: int) -> str:
"""Everyone who said nothing, in one line, or "" when everybody spoke.
``unnamed`` are group members who have never written here at all. They are
counted rather than named on purpose: the listing knows them only as a raw
uuid or a phone number, and printing either into a group chat is a leak.
"""
names = [row.display_name for row in rows if row.is_silent]
if unnamed:
names.append(f"i {text.people(unnamed)} bez ani jednej wiadomości tutaj")
return "Cisza: " + ", ".join(names) if names else ""
def summary_line(totals: DayTotals, *, approximate: bool = False) -> str:
"""Commands and average length -- the two facts that qualify the count.
``approximate`` drops the length claim. It is set for the one day carried
over from the pre-0.1.0 counter, whose messages have a count but no
lengths: reporting "średnio 0 znaków" would be a measurement nobody took.
"""
if not totals.messages:
return ""
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:
return ""
return parts[0].capitalize() + (f", {parts[1]}." if len(parts) > 1 else ".")
@dataclass(frozen=True, slots=True)
class DayView:
"""How one day is presented, apart from its numbers.
A value object rather than a widening keyword list: this renderer is
shared by the nightly post and several commands, each wanting a different
combination of these, and they keep accumulating.
"""
since: str | None = None
unnamed: int = 0
highlights: tuple[str, ...] = ()
heading: str | None = None
# The day's messages have counts but no lengths -- see stats.backfill.
approximate: bool = False
# "21:37" when the day is still running and the count stopped there, so
# the block never presents a partial day as a whole one. None for a
# finished day, which needs no caveat.
closed_at: str | None = None
def render_day(
day: str,
rows: list[DayRow],
totals: DayTotals,
view: DayView | None = None,
) -> str:
"""Compose the day block, trimmed to MAX_LINES."""
view = view or DayView()
header = (
view.heading
or f"{CHART} {pl_date(day)} — {text.messages(totals.messages)}{_media(totals.media)}"
)
tail = [
line
for line in (
silence_line(rows, view.unnamed),
summary_line(totals, approximate=view.approximate),
)
if line
]
picks = list(view.highlights)
if view.closed_at:
tail.append(f"(licznik zamknięty o {view.closed_at}; reszta wieczoru wpada do jutra)")
if view.since:
tail.append(f"(liczymy od {pl_day_month(view.since)})")
# Everything except the speakers is mandatory, and at least one highlight
# slot is reserved before any speaker is allowed a line.
reserved = len(tail) + min(len(picks), 1)
spoke = [row for row in rows if not row.is_silent]
# At least one, so the truncation line below always has a line to occupy.
# The tail cannot realistically reach eleven lines, but a floor here is
# cheaper than a defensive branch nothing can ever exercise.
room = max(1, MAX_LINES - 1 - reserved)
people = [person_line(row, i + 1) for i, row in enumerate(spoke[:room])]
if room < len(spoke):
hidden = spoke[room - 1 :]
total = sum(r.messages for r in hidden)
people[-1] = f"…i {text.people(len(hidden))} więcej (razem {text.messages(total)})"
lines = [header, *people]
lines.extend(picks[: max(0, MAX_LINES - len(lines) - len(tail))])
lines.extend(tail)
return "\n".join(lines)

View File

@ -0,0 +1,194 @@
# 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"
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:
"""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]],
since: str | None = None,
) -> str:
"""Every all-time record the group has set."""
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"),
_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("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("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.
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 = [
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)} "
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, since: str | None = None) -> str:
"""The Monday-to-Sunday picture, with today's weekday called out."""
if not buckets:
return nothing_yet("weekdays", since)
lines = [TITLES["weekdays"]]
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)
ME_TITLE: Final = "Twoje liczby w tej grupie"
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 = [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 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)
def favourite_hour(events: EventStore, group_id: str, uuid: str) -> int | None:
"""The hour somebody writes most in, or None when nothing is known.
Skips rows whose hour is UNKNOWN_HOUR. Those are backfilled from a counter
that had no timestamps, and counting them told every member of the group
that they write most at noon.
"""
row = events.connection.execute(
"""
SELECT local_hour, COUNT(*) AS messages
FROM message_events
WHERE group_id = ? AND uuid = ? AND local_hour >= 0
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)

63
signal_bot/stats/text.py Normal file
View File

@ -0,0 +1,63 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Polish number agreement, and the small text pieces the renderers share.
Polish nouns take three forms after a numeral, not two. "1 znak", "2 znaki",
"5 znaków" -- and the rule is on the last *two* digits, so 12, 13 and 14 take
the many-form while 22, 23 and 24 do not. Getting this wrong is the kind of
thing the group notices immediately and mentions every time.
"""
from __future__ import annotations
from typing import Final
TEEN_START: Final = 12
TEEN_END: Final = 14
FEW_START: Final = 2
FEW_END: Final = 4
def plural(count: int, one: str, few: str, many: str) -> str:
"""Pick the Polish form that agrees with a count.
Args:
count: The number the noun follows.
one: The form for exactly 1 ("znak").
few: The form for 2-4 and most numbers ending 2-4 ("znaki").
many: Every other case, including the 12-14 teens ("znaków").
Returns:
The bare noun, without the number.
"""
if count == 1:
return one
if TEEN_START <= count % 100 <= TEEN_END:
return many
if FEW_START <= count % 10 <= FEW_END:
return few
return many
def messages(count: int) -> str:
"""The count and its noun, agreeing: e.g. 3 wiadomości."""
return f"{count} {plural(count, 'wiadomość', 'wiadomości', 'wiadomości')}"
def characters(count: int) -> str:
"""The count and its noun, agreeing: e.g. 44 znaki."""
return f"{count} {plural(count, 'znak', 'znaki', 'znaków')}"
def commands(count: int) -> str:
"""The count and its noun, agreeing: e.g. 4 komendy."""
return f"{count} {plural(count, 'komenda', 'komendy', 'komend')}"
def people(count: int) -> str:
"""The count and its noun, agreeing: e.g. 2 osoby."""
return f"{count} {plural(count, 'osoba', 'osoby', 'osób')}"
def days(count: int) -> str:
"""The count and its noun, agreeing: e.g. 3 dni."""
return f"{count} {plural(count, 'dzień', 'dni', 'dni')}"

View File

@ -1,72 +1,27 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""SQLite persistence for tallies, cooldowns, daily limits and votes.
"""SQLite persistence for cooldowns, daily limits, votes and group state.
Everything the bot remembers lives here so a restart before the daily report
does not lose the day. The original bot kept all of it in module globals.
The message history itself is reached through ``store.events`` -- see
``signal_bot.stats.events``. It is kept apart because it is the one thing here
that is append-only and never discarded.
"""
from __future__ import annotations
import contextlib
import sqlite3
from dataclasses import dataclass
from typing import TYPE_CHECKING, Self
from signal_bot.schema import EPHEMERAL_TABLES, SCHEMA, SCHEMA_VERSION
from signal_bot.stats.events import EventStore
if TYPE_CHECKING:
from collections.abc import Iterator
from types import TracebackType
# Bumped whenever the shape below changes. See Store._apply_schema for why
# a version number is the only safe way to notice.
SCHEMA_VERSION = 2
# Every table is keyed by group first. The bot watches several groups, and a
# tally, a cooldown or a vote that leaked between them would mean a test
# message throttling the production group -- so the scope is in the primary
# key rather than in the callers' discipline.
_SCHEMA = """
CREATE TABLE IF NOT EXISTS message_counts (
group_id TEXT NOT NULL,
uuid TEXT NOT NULL,
display_name TEXT NOT NULL,
count INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (group_id, uuid)
);
CREATE TABLE IF NOT EXISTS command_uses (
group_id TEXT NOT NULL,
user_uuid TEXT NOT NULL,
command TEXT NOT NULL,
used_at REAL NOT NULL,
PRIMARY KEY (group_id, user_uuid, command)
);
CREATE TABLE IF NOT EXISTS daily_uses (
group_id TEXT NOT NULL,
user_uuid TEXT NOT NULL,
command TEXT NOT NULL,
day TEXT NOT NULL,
uses INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (group_id, user_uuid, command, day)
);
CREATE TABLE IF NOT EXISTS votes (
group_id TEXT NOT NULL,
command TEXT NOT NULL,
voter_uuid TEXT NOT NULL,
voted_at REAL NOT NULL,
PRIMARY KEY (group_id, command, voter_uuid)
);
"""
_TABLES = ("message_counts", "command_uses", "daily_uses", "votes")
@dataclass(frozen=True, slots=True)
class Tally:
"""One person's message count for the current reporting period."""
uuid: str
display_name: str
count: int
class Store:
"""Thin, synchronous SQLite wrapper. All state the bot keeps lives here."""
@ -76,6 +31,7 @@ class Store:
self._conn = sqlite3.connect(path)
self._conn.row_factory = sqlite3.Row
self._apply_schema()
self.events = EventStore(self._conn)
def _apply_schema(self) -> None:
"""Create the tables, rebuilding them when the file predates them.
@ -93,9 +49,12 @@ class Store:
"""
version = int(self._conn.execute("PRAGMA user_version").fetchone()[0])
if version < SCHEMA_VERSION:
for table in _TABLES:
# EPHEMERAL_TABLES, not TABLES. Rebuilding a cooldown table is
# free; rebuilding message_events would throw away the entire
# statistical history, which nothing can recompute.
for table in EPHEMERAL_TABLES:
self._conn.execute(f"DROP TABLE IF EXISTS {table}")
self._conn.executescript(_SCHEMA)
self._conn.executescript(SCHEMA)
self._conn.execute(f"PRAGMA user_version = {SCHEMA_VERSION}")
self._conn.commit()
@ -117,52 +76,47 @@ class Store:
self._conn.close()
def forget_group(self, group_id: str) -> None:
"""Drop every row belonging to one group.
"""Drop one group's *ephemeral* rows: cooldowns, limits, votes, meta.
Called when the bot is removed from a group, so that being added
back starts a fresh tally and a clean cooldown rather than
resurrecting whatever was true whenever it was last in there.
Called when the bot is removed from a group, so that being added back
starts with a clean cooldown rather than resurrecting whatever was
true whenever it was last in there.
What it deliberately no longer touches is the message history. A group
listing that transiently omits members -- the exact failure the
comment in discovery._permitted warns about -- would otherwise delete
years of statistics on the strength of one bad HTTP response. History
is permanent; only the live scaffolding is disposable.
"""
# Spelled out rather than looped over _TABLES: an f-string here is a
# SQL-injection shape even when the input is a module constant, and
# the repo does not take lint suppressions. test_forget_group_clears
# _every_table is what keeps this list in step with the schema.
self._conn.execute("DELETE FROM message_counts WHERE group_id = ?", (group_id,))
self._conn.execute("DELETE FROM command_uses WHERE group_id = ?", (group_id,))
self._conn.execute("DELETE FROM daily_uses WHERE group_id = ?", (group_id,))
self._conn.execute("DELETE FROM votes WHERE group_id = ?", (group_id,))
self._conn.execute("DELETE FROM group_meta WHERE group_id = ?", (group_id,))
self._conn.commit()
# -- message tallies ---------------------------------------------------
# -- per-group key/value state -----------------------------------------
def increment(self, group_id: str, uuid: str, display_name: str) -> None:
"""Add one to a person's tally in one group, creating the row when new."""
def meta(self, group_id: str, key: str) -> str | None:
"""Return a stored value for one group, or None if never set."""
row = self._conn.execute(
"SELECT value FROM group_meta WHERE group_id = ? AND key = ?",
(group_id, key),
).fetchone()
return None if row is None else str(row["value"])
def set_meta(self, group_id: str, key: str, value: str) -> None:
"""Store a value for one group, replacing any previous one."""
self._conn.execute(
"""
INSERT INTO message_counts (group_id, uuid, display_name, count)
VALUES (?, ?, ?, 1)
ON CONFLICT(group_id, uuid) DO UPDATE SET
count = count + 1,
display_name = excluded.display_name
""",
(group_id, uuid, display_name),
"INSERT INTO group_meta (group_id, key, value) VALUES (?, ?, ?) "
"ON CONFLICT(group_id, key) DO UPDATE SET value = excluded.value",
(group_id, key, value),
)
self._conn.commit()
def tallies(self, group_id: str) -> list[Tally]:
"""Return one group's tallies, highest count first."""
rows = self._conn.execute(
"SELECT uuid, display_name, count FROM message_counts "
"WHERE group_id = ? ORDER BY count DESC, display_name ASC",
(group_id,),
).fetchall()
return [Tally(r["uuid"], r["display_name"], r["count"]) for r in rows]
def reset_tallies(self, group_id: str) -> None:
"""Clear one group's tallies, as its daily report does after publishing."""
self._conn.execute("DELETE FROM message_counts WHERE group_id = ?", (group_id,))
self._conn.commit()
# -- per-group, per-user, per-command rate limiting --------------------
def record_use(self, group_id: str, user_uuid: str, command: str, now: float, day: str) -> None:

View File

@ -13,6 +13,8 @@ from typing import TYPE_CHECKING, Protocol, runtime_checkable
if TYPE_CHECKING:
from collections.abc import AsyncIterator
from signal_bot.quoting import Quote
@runtime_checkable
class Transport(Protocol):
@ -21,11 +23,37 @@ class Transport(Protocol):
def receive(self) -> AsyncIterator[str]:
"""Yield raw envelope frames until the transport is closed."""
async def send_text(self, text: str, recipient: str) -> None:
"""Send a plain-text message to a group id or phone number."""
async def send_text(self, text: str, recipient: str, quote: Quote | None = None) -> None:
"""Send a plain-text message, optionally quoting one message."""
async def send_image(self, image_base64: str, recipient: str) -> None:
"""Send a base64-encoded image attachment to a recipient."""
async def send_image(
self,
image_base64: str,
recipient: str,
quote: Quote | None = None,
caption: str = "",
) -> None:
"""Send an image attachment, optionally captioned and quoting a message.
/v2/send carries the caption in the same payload as the attachment, so
a captioned photo is one message in the group rather than two.
"""
async def send_media(
self,
payload_base64: str,
recipient: str,
quote: Quote | None = None,
caption: str = "",
media_type: str = "",
filename: str = "",
) -> None:
"""Send an attachment of a stated type, optionally captioned.
send_image is the case where the type can be left to signal-cli.
Anything Signal renders differently -- a video, above all -- has to
say what it is, or it arrives as an unplayable blob.
"""
async def list_attachments(self) -> list[str]:
"""Return the ids of attachments stored server-side."""

View File

@ -14,6 +14,8 @@ from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import AsyncIterator, Iterable
from signal_bot.quoting import Quote
@dataclass(frozen=True, slots=True)
class SentMessage:
@ -22,6 +24,10 @@ class SentMessage:
recipient: str
text: str | None = None
image_base64: str | None = None
caption: str = ""
quote: Quote | None = None
media_type: str = ""
filename: str = ""
@dataclass
@ -42,13 +48,40 @@ class FakeTransport:
for frame in list(self.frames):
yield frame
async def send_text(self, text: str, recipient: str) -> None:
async def send_text(self, text: str, recipient: str, quote: Quote | None = None) -> None:
"""Record a text send."""
self.sent.append(SentMessage(recipient=recipient, text=text))
self.sent.append(SentMessage(recipient=recipient, text=text, quote=quote))
async def send_image(self, image_base64: str, recipient: str) -> None:
async def send_image(
self,
image_base64: str,
recipient: str,
quote: Quote | None = None,
caption: str = "",
) -> None:
"""Record an image send."""
self.sent.append(SentMessage(recipient=recipient, image_base64=image_base64))
await self.send_media(image_base64, recipient, quote, caption)
async def send_media(
self,
payload_base64: str,
recipient: str,
quote: Quote | None = None,
caption: str = "",
media_type: str = "",
filename: str = "",
) -> None:
"""Record an attachment send, type and filename included."""
self.sent.append(
SentMessage(
recipient=recipient,
image_base64=payload_base64,
quote=quote,
caption=caption,
media_type=media_type,
filename=filename,
)
)
async def list_attachments(self) -> list[str]:
"""Return the configured attachment ids."""

View File

@ -20,6 +20,7 @@ if TYPE_CHECKING:
import httpx
from signal_bot.config import Config
from signal_bot.quoting import Quote
logger = logging.getLogger(__name__)
@ -112,26 +113,63 @@ class RestTransport:
msg = f"send failed with HTTP {response.status_code}: {response.text}"
raise TransportError(msg)
async def send_text(self, text: str, recipient: str) -> None:
"""Send a plain-text message to a group id or phone number."""
await self._post_send(
{
"message": text,
"number": self._config.phone_number,
"recipients": [recipient],
}
)
async def send_text(self, text: str, recipient: str, quote: Quote | None = None) -> None:
"""Send a plain-text message, optionally quoting one message."""
payload: dict[str, Any] = {
"message": text,
"number": self._config.phone_number,
"recipients": [recipient],
}
if quote is not None:
payload.update(quote.payload())
await self._post_send(payload)
async def send_image(self, image_base64: str, recipient: str) -> None:
"""Send a base64-encoded image attachment to a recipient."""
await self._post_send(
{
"message": "",
"base64_attachments": [image_base64],
"number": self._config.phone_number,
"recipients": [recipient],
}
)
async def send_image(
self,
image_base64: str,
recipient: str,
quote: Quote | None = None,
caption: str = "",
) -> None:
"""Send an image attachment, captioned in the same payload.
Verified against the container on 2026-08-30: a non-empty "message"
alongside base64_attachments comes back as one timestamp, so Signal
renders it as a single captioned photo rather than two messages.
"""
await self.send_media(image_base64, recipient, quote, caption)
async def send_media(
self,
payload_base64: str,
recipient: str,
quote: Quote | None = None,
caption: str = "",
media_type: str = "",
filename: str = "",
) -> None:
"""Send one attachment, naming its type when the caller knows it.
The data-URI spelling is the container's own, read off its
/swagger/doc.json rather than remembered: api.SendMessageV2 documents
base64_attachments as accepting bare base64,
"data:<MIME-TYPE>;base64,<DATA>" or
"data:<MIME-TYPE>;filename=<FILENAME>;base64,<DATA>". With no type
the bare form goes out, byte for byte what send_image always sent.
"""
attachment = payload_base64
if media_type:
named = f"filename={filename};" if filename else ""
attachment = f"data:{media_type};{named}base64,{payload_base64}"
payload: dict[str, Any] = {
"message": caption,
"base64_attachments": [attachment],
"number": self._config.phone_number,
"recipients": [recipient],
}
if quote is not None:
payload.update(quote.payload())
await self._post_send(payload)
async def list_attachments(self) -> list[str]:
"""Return the ids of attachments stored server-side."""

Some files were not shown because too many files have changed in this diff Show More