Compare commits

...

51 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
a1053c49fc feat: discover groups from the account, so adding the bot is the whole setup
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 15:30:08 +02:00
a6101ecd7e fix: make prime_profile.sh fail loudly instead of exiting 0 or dying silently
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 15:09:21 +02:00
0178b77c0c fix: commit the five modules the last commit only referenced
The wrap-up script stages dirty *tracked* files, so every newly created
file in the multi-group change -- the group-id module, the membership
verifier, their tests, the isolation scenario and prime_profile.sh --
was listed as untracked and then left behind. The tree compiled locally
because the files exist on disk; CI checked out a repo where config.py
imported signal_bot.groups and nothing provided it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013yaBT45KhHqxTKVCTA87iy
2026-08-29 15:05:18 +02:00
4b457da8f3 feat: watch several groups, and answer only where you were asked
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 15:03:24 +02:00
c35e382cd6 feat: make the bot actually reply on Signal, and gate every way it went silent
First live reply, as its own registered account. `!cat` and `!dog` from the
phone return images -- verified in the production shape (the bot *invited to
an already-existing group*) and under a systemd user unit.

Four failures, each of which left the bot looking perfectly healthy:

- Invited is not joined. Signal only adds an account outright if the adder
  holds its profile key; with no profile the add becomes a pending invite,
  and signal-cli cannot accept one addressed to a phone number ("Cannot find
  service ID for self"). Group listed, websocket up, /healthz OK, zero
  messages. register_bot.sh now sets the profile *before* the add, and
  startup refuses on `member: false`.
- MODE=json-rpc-native is a GraalVM build with no AWT: text sends work,
  every attachment 400s with "Can't load library: awt". Both mode guards now
  demand exactly json-rpc, and start_container replaces a wrong-mode
  container instead of reusing it.
- The API spells one group two ways -- /v1/groups returns `group.<base64>`,
  envelopes carry what that decodes to -- so the scoping gate rejected the
  bot's own group. e2e.sh now models both spellings; reverting the fix fails
  4 scenarios, which is why the offline suite missed it before.
- BIND_PORT in .env was dead: __main__ read os.getenv before anything loaded
  a .env. The bind address comes from Config now.

A taken port used to be uvicorn logging the collision and exiting 0, which
every supervisor reads as success. portcheck.py refuses to start, exits
non-zero, and names the holder by reading /proc directly -- no subprocess, no
PATH assumptions, testable against a fake proc tree. Default port is 8137:
not 8000, and below the ephemeral range so the kernel cannot take it.

The bot now runs as signal-bot.service (Restart=always, linger checked rather
than assumed, StartLimitBurst so a config error fails visibly instead of
looping). Verified by SIGKILL and by re-running a command under the unit.

100% branch coverage, 230 tests, all gates green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013yaBT45KhHqxTKVCTA87iy
2026-08-29 14:37:27 +02:00
185 changed files with 19945 additions and 848 deletions

View File

@ -4,17 +4,25 @@
# REQUIRED. The account signal-cli is linked to, in +E.164 form.
PHONE_NUMBER=
# REQUIRED. The group the bot listens to.
# OPTIONAL, and normally left empty. Comma-separated group ids.
#
# A linked Signal device receives every direct message and every group on the
# account. This value is the ONLY thing scoping the bot to one conversation,
# which is why it has no default and startup fails without it.
# Find it with: curl -s localhost:9922/v1/groups/$PHONE_NUMBER | jq
GROUP_ID=
# REQUIRED. Where replies and the daily report are posted. Set it to the same
# value as GROUP_ID to reply in the group that triggered the command.
GROUP_ID_SEND=
# Empty means "every group this account is a member of", discovered at
# runtime: adding the bot to a group is then the whole procedure, with no
# edit here and no restart. That is safe when the bot has its OWN number,
# because such an account has no other chats.
#
# Set it when the bot runs as a LINKED DEVICE on a personal account, where
# it would otherwise see every group on that account. scripts/live_smoke.sh
# writes it for you in that case; scripts/register_bot.sh deliberately does
# not. Startup fails if a listed group is not one the bot has joined.
#
# Find the ids with: curl -s localhost:9922/v1/groups/$PHONE_NUMBER | jq
#
# Replies, rate limits and the daily tally are per group either way: a
# command is answered in the group that asked and nowhere else, so there is
# no send target to configure. GROUP_ID is still accepted as the one-group
# spelling; GROUP_ID_SEND was removed and now fails startup if set.
GROUP_IDS=
# Optional. The signal-cli-rest-api container. Point this at the fake server
# to run entirely offline. Default: http://localhost:9922
@ -30,10 +38,52 @@ 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 the /healthz probe binds. Default: 127.0.0.1:8000
# 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
# servers grab, and below the ephemeral range so the kernel cannot take it.
BIND_HOST=
BIND_PORT=

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

25
.gitignore vendored
View File

@ -60,6 +60,9 @@ cover/
local_settings.py
db.sqlite3
db.sqlite3-journal
# The bot's live tally database, created next to the code by default.
signal_bot.sqlite3
signal_bot.sqlite3-journal
# Flask stuff:
instance/
@ -161,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.is_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.

157
README.md
View File

@ -1,17 +1,25 @@
# 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 as a **linked device** on an existing Signal account via
Runs on its **own registered Signal number** (or, if you prefer, as a linked
device on an existing account) via
[signal-cli-rest-api](https://github.com/bbernhard/signal-cli-rest-api).
## Scoping, first
A linked device receives **every direct message and every group** on the
account it is linked to. `GROUP_ID` is the only thing that keeps this bot
inside one conversation, so:
How wide the bot's reach is depends entirely on **whose account it runs as**,
and the setup scripts pick the safe answer for you rather than leaving it to
be remembered:
| Run as | Written to `.env` | Reach |
|---|---|---|
| its own number (`register_bot.sh`) | no `GROUP_IDS` | every group somebody adds it to — and nothing else, because that account has no other chats |
| a linked device (`live_smoke.sh`) | `GROUP_IDS=<one group>` | only that group. A linked device receives every DM and group on the **personal** account it rides, so it is pinned |
In both cases:
- the bot **refuses to start** without `GROUP_ID` and `GROUP_ID_SEND`;
- direct messages are dropped explicitly, never by a falsy check;
- the `scoping` scenario asserts that DMs and other groups produce **zero**
outbound messages, and `scripts/e2e.sh` fails the build if that stops holding.
@ -79,10 +87,74 @@ ratchet mandatory and **de-registered every account whose client lacked it**,
so a stale client is how a bot dies silently months later. The script checks
the bundled version and refuses rather than warning.
The container runs `MODE=json-rpc`, not `json-rpc-native`. Both expose the
receive WebSocket, but `-native` is a GraalVM native-image build with no AWT,
so every attachment send fails with `Can't load library: awt` — text replies
work and `!cat` returns nothing, which reads as a bug in this repo and is not.
The script solves everything except two steps only a human can do: pasting a
captcha token (the captcha exists to stop exactly this automation) and reading
the SMS code. Then add the bot's number to your private group from your
personal Signal, and it picks the group and starts.
personal Signal, and it picks the group, verifies it really joined, installs
the service and tails the log.
#### Adding the bot to a group: invited is not joined
Signal adds an account to a group outright **only if the person adding it
already holds that account's profile key**. With no profile there is no key,
so the add silently becomes a pending *invitation* — and signal-cli cannot
accept one addressed to a phone number:
```
POST /v1/groups/<number>/<group>/join → 400
{"error":"Cannot find service ID for self to accept invite"}
```
This is why `register_bot.sh` sets the bot's profile **before** telling you to
add it. A group in that state is indistinguishable from a working one from the
outside — `/v1/groups` lists it, the WebSocket connects, `/healthz` answers,
and not one message arrives — so the bot checks `member` at startup and
refuses to run rather than looking healthy and staying deaf:
```
TransportError: the account is invited to 'testbot' but has not joined it,
so it will receive nothing.
```
If you hit it on an existing group: add the bot's number again from Signal.
Verified on 2026-08-29 against a group that already held an unacceptable
invite — re-adding turned `member: false` into `member: true, members: 2`,
and the bot answered `!cat` in that same group. (Signal keeps the dead
invite listed in `pending_invites`; `member` is the field that matters,
which is what the startup gate reads.)
### It runs as a service, not in a terminal
`register_bot.sh` finishes by installing a **user** systemd unit, so the bot
outlives the terminal that started it:
```sh
./scripts/install_service.sh # install, start, verify
./scripts/install_service.sh --verify-only # re-check without reinstalling
systemctl --user status signal-bot.service
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. 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
the kernel cannot hand it out. If it is taken anyway the bot names the
offender and exits non-zero, because uvicorn logs the collision and exits
**0**, which every supervisor reads as success:
```
cannot bind 127.0.0.1:8000 -- held by pid 82385: /usr/bin/python -m ...
```
### A linked device on your own account
@ -92,9 +164,9 @@ personal Signal, and it picks the group and starts.
Starts the container, opens the QR code, waits for the link, then picks a
group. **Caveat:** a linked device rides your account — it sends *as you* and
receives every DM and group you are in. `GROUP_ID` is the only thing scoping
it, which is why that scoping is a tested, CI-enforced invariant rather than a
convention.
receives every DM and group you are in, so `signal_write_env` pins it to the
single group you picked. Prefer `scripts/register_bot.sh`, which gives the bot
its own number and no access to your chats at all.
### Why not Shelter / a second Signal app on the phone
@ -111,38 +183,67 @@ 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.
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.
`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
## Daily tally
`GROUP_IDS` takes a comma-separated list, so one process can serve a test
group and the production group at once:
Every non-sticker, non-reaction message in the watched group increments its
sender's count. At `REPORT_HOUR:REPORT_MINUTE` (default 21:37) the tally is
posted to `GROUP_ID_SEND` and reset. Counts live in SQLite and survive a
restart.
```sh
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 —
`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.
## Statistics
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

@ -1,17 +1,34 @@
# Security Policy
## Scope of a linked device
## Scope depends on whose account it runs as
This bot runs as a **linked device** on an existing Signal account. That means
it can read every direct message and every group on that account, and anything
it sends is sent **as the account owner**. It is not a separate identity.
Two deployments, two very different blast radii:
`GROUP_ID` is the only thing that narrows this. The bot therefore:
- **Its own registered number** (`scripts/register_bot.sh`). A separate
identity with no DMs and no history of its own. The groups it can see are
exactly the groups somebody added it to, so it watches all of them and
discovers new ones by itself. `.env` gets no `GROUP_IDS`.
- **A linked device** (`scripts/live_smoke.sh`). It rides a **personal**
account: it can read every DM and every group on it, and anything it sends
is sent as the account owner. `.env` therefore gets `GROUP_IDS` pinned to
the single group chosen during setup, and `signal_write_env` writes that
automatically — the mode decides, not the operator's memory.
- refuses to start when `GROUP_ID` or `GROUP_ID_SEND` is missing or blank,
rather than defaulting to an empty string that matches nothing predictably;
Anyone who can add the bot's number to a group can make it active there. That
is the intended trade for zero-step setup on a dedicated account; pin
`GROUP_IDS` if you want the old behaviour back.
The bot therefore:
- writes the pinning decision at setup time, from the mode, so an unpinned
linked device is not something you can arrive at by forgetting a step;
- refuses to start when `GROUP_IDS` names a group it is not a joined member
of, naming the group;
- drops messages with no `groupInfo` (direct messages) explicitly, in
`counting.is_watched_group`, rather than relying on a falsy comparison;
`counting.watched_group`, rather than relying on a falsy comparison;
- resolves a message's group **once**, and uses that one answer as the reply
address and the key for all per-group state, so the scoping gate and the
reply router cannot disagree and answer in the wrong group;
- ships a `scoping` scenario asserting that direct messages and other groups
produce zero outbound messages, run by `scripts/e2e.sh` in CI.

View File

@ -24,9 +24,31 @@ def _emit(line: str) -> None:
sys.stdout.write(f"{line}\n")
def _groups(args: argparse.Namespace) -> dict[str, str]:
"""Map the scenario's symbolic group names onto real ids."""
return {"watched": args.group_id, "reply": args.group_id_send, "other": args.other_group}
def resolve_groups(args: argparse.Namespace) -> dict[str, str]:
"""Map the scenario's symbolic group names onto real ids.
Names are supplied as repeated ``--group NAME=ID`` pairs rather than one
flag per group, because the bot now watches an arbitrary number of them
and a scenario has to be able to say "this reply belongs in the *other*
watched group".
Args:
args: Parsed command line.
Returns:
Scenario alias to real group id.
Raises:
SystemExit: A --group argument is not NAME=ID.
"""
groups: dict[str, str] = {}
for pair in args.group:
name, separator, value = pair.partition("=")
if not separator or not name or not value:
msg = f"--group expects NAME=ID, got {pair!r}"
raise SystemExit(msg)
groups[name] = value
return groups
async def run_scenario(
@ -35,6 +57,13 @@ async def run_scenario(
"""Inject every frame, wait for the bot to react, then compare."""
async with httpx.AsyncClient(base_url=base_url, timeout=10.0) as client:
await client.post("/_control/reset")
if scenario.arrive:
# Additive: the groups already on the account stay, exactly as
# they would when somebody adds the bot to one more.
await client.post(
"/_control/groups/add",
json=[arrival.to_entry(groups) for arrival in scenario.arrive],
)
for injection in scenario.inject:
await client.post("/_control/inject", json={"raw": injection.to_frame(groups)})
await asyncio.sleep(settle)
@ -48,16 +77,14 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Replay a scenario against the bot.")
parser.add_argument("scenarios", nargs="+", type=Path)
parser.add_argument("--base-url", default="http://127.0.0.1:8099")
parser.add_argument("--group-id", required=True)
parser.add_argument("--group-id-send", required=True)
parser.add_argument("--other-group", default="group-other==")
parser.add_argument("--group", action="append", default=[], metavar="NAME=ID")
parser.add_argument("--settle", type=float, default=SETTLE_SECONDS)
return parser.parse_args(argv)
async def _main_async(args: argparse.Namespace) -> int:
"""Run every scenario, reporting failures as they happen."""
groups = _groups(args)
groups = resolve_groups(args)
failed = 0
for path in args.scenarios:
scenario = load_scenario(path)

View File

@ -70,11 +70,4 @@ def build_account_router() -> APIRouter:
state.accounts.append(number)
return JSONResponse({}, status_code=201)
@router.get("/v1/groups/{number}")
async def groups(request: Request, number: str) -> JSONResponse:
state = _state(request)
if number not in state.accounts:
return JSONResponse({"error": f"{number} is not registered"}, status_code=400)
return JSONResponse(state.groups, status_code=200)
return router

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,14 +29,43 @@ 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, str]]) -> dict[str, int]:
"""Seed the group list, so the group picker can be rehearsed offline."""
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."""
state = _state(request)
state.groups.clear()
state.groups.extend(groups)
return {"groups": len(state.groups)}
@router.post("/groups/add")
async def add_groups(request: Request, groups: list[dict[str, Any]]) -> dict[str, int]:
"""Add groups without disturbing the existing ones.
Additive on purpose. A scenario that declares only the group it
cares about would otherwise silently remove the others -- and with
the bot dropping a departed group's rows, that would delete state
every later scenario in the same process depends on.
"""
state = _state(request)
known = {group.get("id") for group in state.groups}
state.groups.extend(group for group in groups if group.get("id") not in known)
return {"groups": len(state.groups)}
@router.post("/accounts")
async def set_accounts(request: Request, accounts: list[str]) -> dict[str, int]:
"""Seed the registered accounts, so /v1/groups answers at all."""
state = _state(request)
state.accounts.clear()
state.accounts.extend(accounts)
return {"accounts": len(state.accounts)}
@router.get("/sent")
async def captured(request: Request) -> list[dict[str, Any]]:
return list(_state(request).sent)

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

@ -0,0 +1,49 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The group endpoints, including the join the bot self-heals with."""
from __future__ import annotations
from typing import TYPE_CHECKING
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
if TYPE_CHECKING:
from fake_signal.state import State
def _state(request: Request) -> State:
"""Return the State attached to the running app."""
state: State = request.app.state.fake
return state
def build_group_router() -> APIRouter:
"""Build the router covering group listing and joining."""
router = APIRouter()
@router.get("/v1/groups/{number}")
async def groups(request: Request, number: str) -> JSONResponse:
state = _state(request)
if number not in state.accounts:
return JSONResponse({"error": f"{number} is not registered"}, status_code=400)
return JSONResponse(state.groups, status_code=200)
@router.post("/v1/groups/{number}/{group_id}/join")
async def join(request: Request, number: str, group_id: str) -> JSONResponse:
"""Accept a pending invitation, the way signal-cli sometimes can.
The real endpoint answers 201 whether or not the account ended up a
member, which is why the bot re-reads the listing instead of
trusting this. Modelling that faithfully is the point: a fake that
only ever succeeds would hide the re-check.
"""
state = _state(request)
if number not in state.accounts:
return JSONResponse({"error": f"{number} is not registered"}, status_code=400)
for group in state.groups:
if group_id in {group.get("id"), group.get("internal_id")} and group.get("joinable"):
group["member"] = True
return JSONResponse({}, status_code=201)
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
@ -52,6 +52,47 @@ class Injection:
return json.dumps({"envelope": body, "account": "+15550000000"})
@dataclass(frozen=True, slots=True)
class GroupArrival:
"""A group that appears on the account partway through a scenario.
This is what makes "somebody added the bot to a group" expressible
offline. ``id`` and ``internal_id`` are scenario alias names, resolved
through the same table the injections use, so a scenario never contains
a real group id.
"""
id: str
internal_id: str
name: str = "added-later"
member: bool = True
joinable: bool = True
def to_entry(self, groups: dict[str, str]) -> dict[str, Any]:
"""Render this as a /v1/groups row.
Args:
groups: Scenario alias to real group id.
Returns:
The listing row the fake server should start returning.
Raises:
ScenarioError: An alias is not in the table.
"""
for alias in (self.id, self.internal_id):
if alias not in groups:
msg = f"unknown group alias {alias!r}; known: {sorted(groups)}"
raise ScenarioError(msg)
return {
"id": groups[self.id],
"internal_id": groups[self.internal_id],
"name": self.name,
"member": self.member,
"joinable": self.joinable,
}
@dataclass(frozen=True, slots=True)
class Expectation:
"""One message the bot is expected to have sent."""
@ -59,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)
@ -66,6 +110,7 @@ class Scenario:
"""A named list of injections and the sends they must produce."""
name: str
arrive: list[GroupArrival] = field(default_factory=list)
inject: list[Injection] = field(default_factory=list)
expect: list[Expectation] = field(default_factory=list)
@ -98,18 +143,37 @@ def load_scenario(path: Path) -> Scenario:
raise ScenarioError(msg)
return Scenario(
name=str(document["name"]),
arrive=[_build(GroupArrival, e, "arrive") for e in document.get("arrive", [])],
inject=[_build(Injection, e, "inject") for e in document.get("inject", [])],
expect=[_build(Expectation, e, "expect") for e in document.get("expect", [])],
)
# 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] = []
@ -127,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,11 @@
# The whole feature, in one file: a group appears on the account while the
# bot is running, and the very next message in it is answered. No entry in
# .env, no restart, and not even a wait for the 30-second sweep -- the
# dispatcher refreshes the moment it sees an id it does not recognise.
name: "a group added while the bot is running is answered immediately"
arrive:
- { id: third_reply, internal_id: third, name: added-later }
inject:
- { text: "!cat", group: third, uuid: uuid-hana, name: Hana }
expect:
- { kind: image, to: third_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,10 @@
# Invited is not joined. The bot must accept the invitation itself rather
# than sitting in the group receiving nothing until a human notices; a
# non-member looks perfectly healthy from outside.
name: "a pending invitation is joined, then answered in"
arrive:
- { id: fourth_reply, internal_id: fourth, name: invited-later, member: false, joinable: true }
inject:
- { text: "!cat", group: fourth, uuid: uuid-ivan, name: Ivan }
expect:
- { kind: image, to: fourth_reply }

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,12 @@
# The whole point of watching more than one group: a command is answered in
# the group that asked and nowhere else, and one group's rate limiting does
# not reach into another. Gina asks in both groups inside one cooldown
# window; a shared cooldown would turn the second image into "BEEP BOOP",
# and a fixed reply target would post both into the same group.
name: "a command is answered only in the group that asked"
inject:
- { text: "!cat", group: watched, uuid: uuid-gina, name: Gina }
- { text: "!cat", group: second, uuid: uuid-gina, name: Gina }
expect:
- { kind: image, to: reply }
- { kind: image, to: second_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

@ -1,6 +1,8 @@
# The security invariant. A linked Signal device receives every direct
# conversation and every group on the account; GROUP_ID is the only thing
# scoping the bot. Nothing here may produce a single outbound message.
# The security invariant that survives discovery: the bot answers in groups
# it is a MEMBER of, and in nothing else. A direct message must never reach a
# handler, and a group the account is not in must not be adopted just because
# a frame claiming it arrived. Nothing here may produce a single outbound
# message.
name: "direct messages and other groups are never answered"
inject:
- { text: "!cat", group: null, uuid: uuid-stranger, name: Stranger }

View File

@ -18,6 +18,7 @@ from fake_signal.routes_account import build_account_router
from fake_signal.routes_api import build_api_router
from fake_signal.routes_control import build_control_router
from fake_signal.routes_fixtures import build_fixture_router
from fake_signal.routes_groups import build_group_router
from fake_signal.state import State
@ -27,6 +28,7 @@ def create_app(state: State | None = None) -> FastAPI:
app.state.fake = state if state is not None else State()
app.include_router(build_api_router())
app.include_router(build_account_router())
app.include_router(build_group_router())
app.include_router(build_fixture_router())
app.include_router(build_control_router())
return app

View File

@ -24,13 +24,16 @@ class State:
sockets: list[WebSocket] = field(default_factory=list)
sent: list[dict[str, Any]] = field(default_factory=list)
attachments: list[str] = field(default_factory=list)
mode: str = "json-rpc-native"
mode: str = "json-rpc"
base_url: str = "http://127.0.0.1:8099"
# Registration and group state, so the registration runbook can be
# rehearsed offline instead of first executing against real Signal.
accounts: list[str] = field(default_factory=list)
pending: dict[str, str] = field(default_factory=dict)
groups: list[dict[str, str]] = field(default_factory=list)
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

@ -19,8 +19,22 @@ readonly FAKE_PORT="${FAKE_PORT:-8099}"
readonly BOT_PORT="${BOT_PORT:-8098}"
readonly FAKE_URL="http://127.0.0.1:${FAKE_PORT}"
readonly WATCHED_GROUP="group.e2e.watched=="
readonly REPLY_GROUP="group.e2e.reply=="
# Both spellings of one group, exactly as the real API reports them:
# /v1/groups returns the `group.<base64>` form (what .env holds), while an
# incoming envelope carries the id that base64 decodes to. Modelling only
# one is why the offline suite once passed against a bot that ignored every
# message in its own group.
readonly WATCHED_GROUP="group.WlRKbExYZGhkR05vWldRdFozSnZkWEF0YVdRdE16SXRZbmwwWlhNaElTRT0="
readonly WATCHED_GROUP_INTERNAL="ZTJlLXdhdGNoZWQtZ3JvdXAtaWQtMzItYnl0ZXMhISE="
# A second watched group, so the suite proves replies and rate limits stay
# in the group that asked instead of leaking into the other one.
readonly SECOND_GROUP="group.WlRKbExYTmxZMjl1WkMxbmNtOTFjQzFwWkMwek1pMWllWFJsY3lFaElTRT0="
readonly SECOND_GROUP_INTERNAL="ZTJlLXNlY29uZC1ncm91cC1pZC0zMi1ieXRlcyEhISE="
# Not seeded at boot: these arrive mid-run, which is the point.
readonly THIRD_GROUP="group.WlRKbExYUm9hWEprTFdkeWIzVndMV2xrTFRNeUxXSjVkR1Z6SVNFaElRPT0="
readonly THIRD_GROUP_INTERNAL="ZTJlLXRoaXJkLWdyb3VwLWlkLTMyLWJ5dGVzISEhIQ=="
readonly FOURTH_GROUP="group.WlRKbExXWnZkWEowYUMxbmNtOTFjQzFwWkMwek1pMWllWFJsY3lFaElTRT0="
readonly FOURTH_GROUP_INTERNAL="ZTJlLWZvdXJ0aC1ncm91cC1pZC0zMi1ieXRlcyEhISE="
readonly OTHER_GROUP="group.e2e.other=="
FAKE_PID=""
@ -44,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
@ -87,16 +106,42 @@ main() {
FAKE_PID=$!
wait_for_url "${FAKE_URL}/v1/about" "fake signal server"
echo "== seeding the fake with a registered, joined account"
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 "[{\"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 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_ID="$WATCHED_GROUP" \
GROUP_ID_SEND="$REPLY_GROUP" \
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"
@ -106,9 +151,52 @@ main() {
"$PYTHON" -m fake_signal.cli \
"$REPO_ROOT"/fake_signal/scenarios/*.yaml \
--base-url "$FAKE_URL" \
--group-id "$WATCHED_GROUP" \
--group-id-send "$REPLY_GROUP" \
--other-group "$OTHER_GROUP"
--group "watched=${WATCHED_GROUP_INTERNAL}" \
--group "reply=${WATCHED_GROUP}" \
--group "second=${SECOND_GROUP_INTERNAL}" \
--group "second_reply=${SECOND_GROUP}" \
--group "third=${THIRD_GROUP_INTERNAL}" \
--group "third_reply=${THIRD_GROUP}" \
--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 "$@"

150
scripts/install_service.sh Executable file
View File

@ -0,0 +1,150 @@
#!/bin/bash
# ============================================================================
# Install, start and verify the signal-bot user service.
#
# A *user* unit, not a system one: the bot runs as whoever registered the
# Signal account and reads that user's .env. Lingering is what makes it start
# at boot with nobody logged in -- without it, "survives reboots" is a lie the
# unit file cannot tell you about, so this script checks and fails loudly.
# ============================================================================
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
readonly REPO_ROOT
SCRIPT_NAME="$(basename "$0")"
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"
# shellcheck source=scripts/lib_signal.sh
source "${REPO_ROOT}/scripts/lib_signal.sh"
usage() {
echo "Usage: $SCRIPT_NAME [--verify-only]"
echo " --verify-only Check the running service without reinstalling it."
exit 0
}
die() {
echo "Error: $1" >&2
exit 1
}
# The port the bot will actually bind: .env wins, code default otherwise.
bot_port() {
local port=""
if [[ -f "${REPO_ROOT}/.env" ]]; then
port="$(sed -n 's/^BIND_PORT=[[:space:]]*//p' "${REPO_ROOT}/.env" | tail -1)"
fi
printf '%s' "${port:-$DEFAULT_PORT}"
}
validate_requirements() {
command -v systemctl >/dev/null || die "systemctl not found; this needs systemd"
[[ -f "${REPO_ROOT}/.env" ]] ||
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.
require_linger() {
if [[ "$(loginctl show-user "$USER" --property=Linger --value)" == "yes" ]]; then
echo "== linger enabled: the bot starts at boot with nobody logged in"
return 0
fi
echo "== enabling linger for $USER"
if ! sudo -n loginctl enable-linger "$USER" 2>/dev/null; then
echo "Error: linger is off and sudo needs a password here." >&2
echo " Without it the bot will NOT come back after a reboot." >&2
echo " Run this, then re-run with --verify-only:" >&2
echo >&2
echo " sudo loginctl enable-linger $USER" >&2
return 1
fi
}
install_unit() {
mkdir -p "$UNIT_DIR"
sed "s|@REPO_ROOT@|${REPO_ROOT}|g" "$TEMPLATE" > "${UNIT_DIR}/${UNIT_NAME}"
systemctl --user daemon-reload
systemctl --user enable "$UNIT_NAME" >/dev/null
systemctl --user restart "$UNIT_NAME"
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"
if ! systemctl --user is-active --quiet "$UNIT_NAME"; then
echo "Error: ${UNIT_NAME} is not active." >&2
systemctl --user --no-pager --lines=20 status "$UNIT_NAME" >&2 || true
return 1
fi
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() {
validate_requirements
local port
port="$(bot_port)"
if [[ "$VERIFY_ONLY" != "true" ]]; then
require_linger
install_unit
install_watchdog
fi
verify "$port"
echo "== logs: journalctl --user -u ${UNIT_NAME} -f"
}
while [[ $# -gt 0 ]]; do
case $1 in
--verify-only)
VERIFY_ONLY="true"
shift
;;
-h | --help) usage ;;
*)
echo "Unknown option: $1" >&2
exit 1
;;
esac
done
main "$@"

View File

@ -27,13 +27,18 @@ signal_wait_for_url() {
done
}
# Refuse to continue unless the container exposes a receive WebSocket.
# Refuse to continue unless the container is in exactly the right mode.
#
# Not a *json-rpc* glob: 'json-rpc-native' also matches one, exposes the
# same WebSocket, and is a GraalVM build with no AWT -- so every attachment
# send fails with "Can't load library: awt" while text replies work, which
# looks like a bug in the bot. Accepting it is how that returns.
signal_verify_mode() {
local mode
mode="$(curl -sf "${API}/v1/about" | jq -r '.mode // "unknown"')"
if [[ "$mode" != *json-rpc* ]]; then
echo "Error: container mode is '$mode'." >&2
echo " /v1/receive is only a WebSocket in a json-rpc mode." >&2
if [[ "$mode" != "json-rpc" ]]; then
echo "Error: container mode is '$mode', not 'json-rpc'." >&2
echo " Recreate the container with -e MODE=json-rpc." >&2
return 1
fi
echo "== container mode: $mode"
@ -72,16 +77,98 @@ signal_choose_group() {
printf '%s' "$id"
}
# Write .env for the bot. GROUP_ID == GROUP_ID_SEND so replies land in the
# same group that triggered them.
# Give the account a profile before anyone adds it to a group.
#
# Signal only adds an account to a group outright when the inviter already
# holds its profile key; with no profile there is no key to hold, so the
# add silently degrades into a pending *invitation* -- and signal-cli
# cannot accept one addressed to a phone number ("Cannot find service ID
# for self to accept invite"). That dead end cost a whole session on
# 2026-08-29: the bot looked healthy and received nothing, for hours.
signal_set_profile() {
local number="$1" name="$2" status
status="$(curl -sS -o /dev/null -w '%{http_code}' -X PUT \
"${API}/v1/profiles/${number}" \
-H 'Content-Type: application/json' \
-d "{\"name\":\"${name}\"}")"
if [[ "$status" != "2"* ]]; then
echo "Error: could not set the bot's profile (HTTP $status)." >&2
echo " Without a profile, adding the bot to a group creates an" >&2
echo " invitation it can never accept." >&2
return 1
fi
echo "== profile set to '${name}' (required before joining a group)"
}
# Refuse to finish on a group the bot was only *invited* to.
signal_require_membership() {
local number="$1" group="$2" detail
detail="$(curl -sf "${API}/v1/groups/${number}/${group}")"
if [[ "$(printf '%s' "$detail" | jq -r '.member')" == "true" ]]; then
echo "== the bot is a full member of $(printf '%s' "$detail" | jq -r '.name')"
return 0
fi
echo "Error: the bot is only INVITED to this group, not a member." >&2
echo " It would receive nothing. signal-cli cannot accept an" >&2
echo " invite addressed to a phone number." >&2
echo " Fix: in Signal, remove the pending invite for ${number}," >&2
echo " then add it again -- now that it has a profile, Signal" >&2
echo " adds it as a real member instead of inviting it." >&2
return 1
}
# Print the first free TCP port at or after $1.
#
# The bot's default is 8137, but writing whatever is actually free means a
# machine that already runs something there gets a working .env instead of
# a bot that refuses to start.
signal_free_port() {
local port="$1" limit=$(($1 + 50))
while [[ $port -lt $limit ]]; do
if ! ss -ltn "sport = :${port}" 2>/dev/null | grep -q LISTEN; then
printf '%s' "$port"
return 0
fi
port=$((port + 1))
done
echo "Error: no free port between $1 and ${limit}" >&2
return 1
}
# Write .env for the bot.
#
# The third argument decides whether GROUP_IDS is written at all, and it is
# not a style choice:
#
# own account (register_bot.sh) -> no GROUP_IDS. The bot is its own Signal
# identity, so "every group it is in" is exactly the groups somebody
# added it to. Adding it to a group is then the entire procedure.
# linked device (live_smoke.sh) -> GROUP_IDS pinned to the chosen group.
# A linked device rides a PERSONAL account and receives every group on
# it, so an unpinned bot there would read and answer in all of them.
#
# Getting this backwards is the one way discovery becomes a privacy problem,
# which is why the mode picks the value rather than the operator remembering.
signal_write_env() {
local repo_root="$1" number="$2" group="$3"
local repo_root="$1" number="$2" group="$3" mode="${4:-linked}" port
port="$(signal_free_port "${BOT_PORT_BASE:-8137}")"
cat > "${repo_root}/.env" <<ENV
PHONE_NUMBER=${number}
GROUP_ID=${group}
GROUP_ID_SEND=${group}
API_BASE_URL=${API}
DATABASE_PATH=${repo_root}/signal_bot.sqlite3
BIND_PORT=${port}
ENV
if [[ "$mode" == "linked" ]]; then
cat >> "${repo_root}/.env" <<ENV
# A linked device sees every group on the account it is linked to, so this
# bot is pinned. Remove this line only if the account is the bot's own.
GROUP_IDS=${group}
ENV
else
cat >> "${repo_root}/.env" <<ENV
# No GROUP_IDS: the bot answers in every group this account is added to, and
# discovers new ones by itself. Set it to a comma-separated list to pin it.
ENV
fi
echo "== wrote ${repo_root}/.env"
}

View File

@ -54,10 +54,16 @@ start_container() {
local image="$1"
docker rm -f "$CONTAINER" >/dev/null 2>&1 || true
mkdir -p "$DATA_DIR"
echo "== starting $image on :${PORT} (MODE=json-rpc-native)"
# MODE=json-rpc, not json-rpc-native. Both expose the receive
# WebSocket, but the -native mode runs a GraalVM native-image build
# with no AWT, so every attachment send fails with
# "Can't load library: awt (UnsatisfiedLinkError)" -- meaning !cat
# and !dog return nothing while text replies work. Verified live on
# 2026-08-29: identical request, HTTP 400 native vs 201 on the JVM.
echo "== starting $image on :${PORT} (MODE=json-rpc)"
docker run -d --name "$CONTAINER" --restart=always -p "${PORT}:8080" \
-v "${DATA_DIR}:/home/.local/share/signal-cli" \
-e 'MODE=json-rpc-native' "$image" >/dev/null
-e 'MODE=json-rpc' "$image" >/dev/null
if ! signal_wait_for_url "${API}/v1/about" "signal-cli-rest-api"; then
docker logs --tail 30 "$CONTAINER" >&2
@ -106,7 +112,9 @@ main() {
echo "== linked as ${number}"
group="$(signal_choose_group "$number")"
[[ -n "$group" && "$group" != "null" ]] || { echo "Error: no group chosen" >&2; exit 1; }
signal_write_env "$REPO_ROOT" "$number" "$group"
# "linked": this is somebody's personal account, so the bot stays pinned
# to the one group instead of discovering every chat on it.
signal_write_env "$REPO_ROOT" "$number" "$group" linked
echo "== starting the bot. Send '!cat' in that group; you should get a cat."
exec "$REPO_ROOT/run.sh"

135
scripts/prime_profile.sh Executable file
View File

@ -0,0 +1,135 @@
#!/bin/bash
# ============================================================================
# Hand the bot's profile key to somebody who is about to add it to a group.
#
# Signal only adds an account to a group outright when whoever adds it
# already holds that account's profile key. Otherwise the add silently
# becomes a pending invitation -- and signal-cli cannot accept an invite
# addressed to a phone number, so the bot sits in the group forever,
# looking healthy and receiving nothing.
#
# Sending one direct message from the bot to that person hands their client
# the profile key, so the add that follows lands as a real join. Run this
# BEFORE asking anyone to add the bot to an existing group.
#
# Usage: scripts/prime_profile.sh +48123456789 [+48987654321 ...]
# ============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
readonly REPO_ROOT
SCRIPT_NAME="$(basename "$0")"
readonly SCRIPT_NAME
readonly PORT="${PORT:-9922}"
readonly API="${API:-http://localhost:${PORT}}"
readonly BOT_NAME="${BOT_NAME:-signal-bot}"
readonly MESSAGE="${MESSAGE:-Hi, I am ${BOT_NAME}. Adding me to a group now works: this message gave your phone my profile, so the add becomes a real join instead of an invite I cannot accept.}"
RECIPIENTS=()
# shellcheck source-path=SCRIPTDIR source=scripts/lib_signal.sh
. "${SCRIPT_DIR}/lib_signal.sh"
# Prints only. The caller decides the exit code, so a usage *error* cannot
# exit 0 and be read as success by whatever ran this.
usage() {
echo "Usage: ${SCRIPT_NAME} +<E164 number> [+<E164 number> ...]"
echo "Sends one DM from the bot so the recipient's client learns its"
echo "profile key, which makes a later group add land as a real join."
}
validate_requirements() {
command -v curl >/dev/null || { echo "Error: curl is required" >&2; exit 1; }
command -v jq >/dev/null || { echo "Error: jq is required" >&2; exit 1; }
if [[ ${#RECIPIENTS[@]} -eq 0 ]]; then
echo "Error: at least one recipient number is required" >&2
usage >&2
exit 1
fi
local number
for number in "${RECIPIENTS[@]}"; do
if [[ ! "$number" =~ ^\+[0-9]{6,15}$ ]]; then
echo "Error: '${number}' is not an E.164 number like +48123456789" >&2
exit 1
fi
done
if [[ ! -f "${REPO_ROOT}/.env" ]]; then
echo "Error: no ${REPO_ROOT}/.env -- run scripts/register_bot.sh first" >&2
exit 1
fi
}
# Read the bot's own number out of .env rather than asking for it: a number
# typed twice is a number that can be typed differently the second time.
bot_number() {
local number
# `|| true`: under `set -e` a grep that matches nothing kills the whole
# subshell, so the error message below would never print and the script
# would exit 1 silently -- the failure mode this repo exists to gate.
number="$(grep -E '^PHONE_NUMBER=' "${REPO_ROOT}/.env" || true)"
number="$(printf '%s' "$number" | head -1 | cut -d= -f2-)"
if [[ -z "$number" ]]; then
echo "Error: PHONE_NUMBER is not set in ${REPO_ROOT}/.env" >&2
return 1
fi
printf '%s' "$number"
}
send_dm() {
local from="$1" to="$2" status
status="$(curl -sS -o /dev/null -w '%{http_code}' -X POST "${API}/v2/send" \
-H 'Content-Type: application/json' \
-d "$(jq -n --arg msg "$MESSAGE" --arg from "$from" --arg to "$to" \
'{message: $msg, number: $from, recipients: [$to]}')")"
if [[ "$status" != "2"* ]]; then
echo "Error: could not message ${to} (HTTP ${status})." >&2
return 1
fi
echo "== ${to} now has the bot's profile key"
}
main() {
validate_requirements
local number
number="$(bot_number)"
signal_wait_for_url "${API}/v1/about" "signal-cli-rest-api" 25
signal_verify_mode
# The profile is re-asserted rather than assumed: an account with no
# profile hands over nothing, so the DM would leave the recipient in
# exactly the state this script exists to prevent.
signal_set_profile "$number" "$BOT_NAME"
local recipient
for recipient in "${RECIPIENTS[@]}"; do
send_dm "$number" "$recipient"
done
echo "== done. Ask them to add ${number} to the group now."
echo " Then add the group id to GROUP_IDS in .env and restart:"
echo " systemctl --user restart signal-bot.service"
}
while [[ $# -gt 0 ]]; do
case $1 in
-h | --help)
usage
exit 0
;;
-*)
echo "Unknown option: $1" >&2
exit 1
;;
*)
RECIPIENTS+=("$1")
shift
;;
esac
done
main "$@"

View File

@ -34,6 +34,7 @@ readonly CAPTCHA_URL="https://signalcaptchas.org/registration/generate.html"
# carries "Update to new registration/provisioning API". The stable
# container tag lags, so this is checked rather than hoped for.
readonly MIN_SIGNAL_CLI="0.14.7"
readonly BOT_NAME="${BOT_NAME:-signal-bot}"
readonly CI_IMAGE="bbernhard/signal-cli-rest-api:1787779383-ci"
NUMBER=""
@ -66,16 +67,28 @@ validate_requirements() {
}
start_container() {
# Only reuse a container that is in the mode we need. A leftover
# json-rpc-native container answers /v1/about perfectly well and then
# fails every image send, so reusing it silently undoes the fix below.
if curl -sf "${API}/v1/about" >/dev/null 2>&1; then
echo "== reusing the container already listening on :${PORT}"
return 0
if signal_verify_mode >/dev/null 2>&1; then
echo "== reusing the container already listening on :${PORT}"
return 0
fi
echo "== replacing the container on :${PORT}: wrong mode for attachments"
fi
mkdir -p "$DATA_DIR"
docker rm -f "$CONTAINER" >/dev/null 2>&1 || true
echo "== starting $IMAGE on :${PORT} (MODE=json-rpc-native)"
# MODE=json-rpc, not json-rpc-native. Both expose the receive
# WebSocket, but the -native mode runs a GraalVM native-image build
# with no AWT, so every attachment send fails with
# "Can't load library: awt (UnsatisfiedLinkError)" -- meaning !cat
# and !dog return nothing while text replies work. Verified live on
# 2026-08-29: identical request, HTTP 400 native vs 201 on the JVM.
echo "== starting $IMAGE on :${PORT} (MODE=json-rpc)"
docker run -d --name "$CONTAINER" --restart=always -p "${PORT}:8080" \
-v "${DATA_DIR}:/home/.local/share/signal-cli" \
-e 'MODE=json-rpc-native' "$IMAGE" >/dev/null
-e 'MODE=json-rpc' "$IMAGE" >/dev/null
signal_wait_for_url "${API}/v1/about" "signal-cli-rest-api"
}
@ -180,6 +193,8 @@ main() {
confirm_registered
fi
signal_set_profile "$NUMBER" "$BOT_NAME"
echo
echo "== NEXT: from your personal Signal, add ${NUMBER} to the private group,"
echo " then press Enter. The bot must be a member before it can post."
@ -187,10 +202,19 @@ main() {
local group
group="$(signal_choose_group "$NUMBER")"
signal_write_env "$REPO_ROOT" "$NUMBER" "$group"
signal_require_membership "$NUMBER" "$group"
# "own": this number is the bot's own account, so it may watch every
# group it is added to. See signal_write_env for why the mode decides.
signal_write_env "$REPO_ROOT" "$NUMBER" "$group" own
echo "== starting the bot. Send '!cat' in that group."
exec "$REPO_ROOT/run.sh"
# Install the service rather than running in the foreground: a bot that
# only lives as long as this terminal is a demo, not a bot.
"$REPO_ROOT/scripts/install_service.sh"
echo
echo "== running. Send '!cat' in that group."
echo "== to use it in another group later, just add ${NUMBER} to it."
echo "== following the log; Ctrl-C stops watching, not the bot."
exec journalctl --user -u signal-bot.service -f
}
while [[ $# -gt 0 ]]; do

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

@ -0,0 +1,52 @@
# Installed to ~/.config/systemd/user/ by scripts/install_service.sh, which
# substitutes @REPO_ROOT@. Edit this template, never the installed copy.
[Unit]
Description=Signal group bot
Documentation=file://@REPO_ROOT@/README.md
# 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
# 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]
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`: 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=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
ProtectHome=read-only
ReadWritePaths=@REPO_ROOT@
ProtectKernelTunables=true
ProtectControlGroups=true
RestrictSUIDSGID=true
[Install]
WantedBy=default.target

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

@ -3,27 +3,34 @@
The old readme told people to run `python main.py`, which had no __main__
block and no uvicorn.run() call, so it silently did nothing at all.
The bind address comes from Config rather than os.getenv() here: this module
runs *before* uvicorn imports the app, and therefore before anything has
called load_dotenv(), so reading the environment directly would ignore
BIND_HOST/BIND_PORT whenever they live in .env -- which is where they live.
"""
from __future__ import annotations
import os
import uvicorn
# Loopback by default: the only inbound surface is /healthz, and the link to
# signal-cli-rest-api is outbound. Override with BIND_HOST when containerised.
DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 8000
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
def main() -> None:
"""Run the ASGI app under uvicorn."""
uvicorn.run(
"signal_bot.app:app",
host=os.getenv("BIND_HOST", DEFAULT_HOST),
port=int(os.getenv("BIND_PORT", str(DEFAULT_PORT))),
)
"""Run the ASGI app under uvicorn, refusing to start on a taken port."""
config = load_config()
# 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.
configure_logging(config.log_level)
try:
assert_port_free(config.bind_host, config.bind_port)
except PortInUseError as exc:
raise SystemExit(str(exc)) from exc
uvicorn.run("signal_bot.app:app", host=config.bind_host, port=config.bind_port)
if __name__ == "__main__":

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.recipient)
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,150 +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.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
dispatcher: Dispatcher
async def publish_report(self) -> None:
"""Post the tally to the reply group and reset it."""
rows = [(t.display_name or t.uuid, t.count) for t in self.store.tallies()]
await self.transport.send_text(format_tally(rows), self.config.group_id_send)
self.store.reset_tallies()
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) -> 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,
registry=registry,
store=store,
transport=transport,
clock=now_local,
)
return Bot(config=config, store=store, transport=transport, 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()),
]
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()
return Runtime(bot=build_bot(config, client, store, transport), 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()
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,37 +3,73 @@
from __future__ import annotations
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.
from signal_bot.groups import (
ConfigError,
build_alias_map,
canonical_group_id,
group_id_aliases,
)
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",
"parse_trusted_inviters",
]
DEFAULT_API_BASE_URL: Final = "http://localhost:9922"
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
# (/proc/sys/net/ipv4/ip_local_port_range, 32768-60999 on Arch), so the kernel
# will never hand it out to an outbound connection and steal it back.
DEFAULT_BIND_PORT: Final = 8137
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"}
class ConfigError(RuntimeError):
"""Raised when the environment does not describe a runnable bot."""
@dataclass(frozen=True, slots=True)
class Config:
"""Everything the bot needs to know, resolved and validated."""
phone_number: str
group_id: str
group_id_send: str
# The optional allowlist. Empty means every group the account is a
# full member of, discovered at runtime -- see signal_bot.discovery.
group_ids: tuple[str, ...] = ()
api_base_url: str = DEFAULT_API_BASE_URL
database_path: str = DEFAULT_DATABASE_PATH
report_hour: int = DEFAULT_REPORT_HOUR
@ -43,6 +79,50 @@ 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.
bind_host: str = DEFAULT_BIND_HOST
bind_port: int = DEFAULT_BIND_PORT
# Set LOG_LEVEL=DEBUG to see why a frame was ignored. Without a knob,
# the one log line that explains a silently-dropped message is
# 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:
"""True when GROUP_IDS restricts the bot to a fixed set of groups."""
return bool(self.group_ids)
def allows(self, group_id: str) -> bool:
"""True when a discovered group is permitted by the allowlist.
An empty allowlist permits everything: the bot answers wherever it
has been added. This is only the *permission* check -- whether the
account is actually a member is decided by the live listing, in
signal_bot.discovery.
Args:
group_id: A canonical group id from the group listing.
Returns:
True when the group may be watched.
"""
if not self.group_ids:
return True
return group_id in build_alias_map(self.group_ids)
@property
def receive_url(self) -> str:
@ -68,66 +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.
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. "
"A linked Signal device sees every chat on the account, so the bot "
"refuses to start without an explicit group to scope itself to."
)
raise ConfigError(msg)
return value
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 _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)
return Config(
phone_number=_require(env, "PHONE_NUMBER"),
group_id=_require(env, "GROUP_ID"),
group_id_send=_require(env, "GROUP_ID_SEND"),
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,
)
@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

@ -6,39 +6,74 @@ from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from signal_bot.config import Config
from signal_bot.discovery import GroupDirectory
from signal_bot.models import IncomingMessage
def is_watched_group(message: IncomingMessage, config: Config) -> bool:
"""True only for messages from the one group the bot is scoped to.
def watched_group(message: IncomingMessage, directory: GroupDirectory) -> str | None:
"""Return the canonical id of the watched group a message came from.
A linked Signal device receives every direct conversation and every group
on the account. This predicate is the entire boundary between "a bot in
one group" and "a bot reading all of your chats", so it is deliberately
written as an explicit group-id equality rather than a falsy check: a
direct message has no group id at all and must never reach a handler.
The bot answers in every group it has been added to, and in nothing
else. Direct messages are rejected here by an explicit lookup rather
than a falsy check: a DM carries no group id at all, and one must never
reach a handler no matter how the surrounding code is later rearranged.
It returns the id rather than a bool so that the gate and the reply
router are the same decision. Answering "may this run?" and "where does
the answer go?" separately is how a bot ends up replying to the wrong
group.
Args:
message: The parsed inbound message.
directory: The live set of groups the bot is a member of.
Returns:
The canonical group id, or None for a direct message or any group
the bot is not scoped to.
"""
if message.group_id is None:
return False
return message.group_id == config.group_id
return None
return directory.resolve(message.group_id)
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.
@ -27,11 +51,20 @@ def cooldown(seconds: float, message: str) -> Decorator:
def decorate(handler: Handler) -> Handler:
@functools.wraps(handler)
async def wrapper(ctx: CommandContext) -> None:
last = ctx.store.last_used(ctx.message.source_uuid, ctx.command_name)
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
@ -45,10 +78,12 @@ def daily_limit(max_uses: int, message: str) -> Decorator:
def decorate(handler: Handler) -> Handler:
@functools.wraps(handler)
async def wrapper(ctx: CommandContext) -> None:
used = ctx.store.uses_today(ctx.message.source_uuid, ctx.command_name, ctx.day)
used = ctx.store.uses_today(
ctx.group_id, ctx.message.source_uuid, ctx.command_name, ctx.day
)
if used >= max_uses:
await ctx.reply(message.format(max_uses=max_uses, used=used))
return
raise CommandRefusedError
await handler(ctx)
return wrapper
@ -66,12 +101,12 @@ def vote_gated(required: int, window_seconds: float, message: str) -> Decorator:
def decorate(handler: Handler) -> Handler:
@functools.wraps(handler)
async def wrapper(ctx: CommandContext) -> None:
ctx.store.add_vote(ctx.command_name, ctx.message.source_uuid, ctx.now)
votes = ctx.store.count_votes(ctx.command_name, ctx.now - window_seconds)
ctx.store.add_vote(ctx.group_id, ctx.command_name, ctx.message.source_uuid, ctx.now)
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
ctx.store.clear_votes(ctx.command_name)
raise CommandRefusedError
ctx.store.clear_votes(ctx.group_id, ctx.command_name)
await handler(ctx)
return wrapper

244
signal_bot/discovery.py Normal file
View File

@ -0,0 +1,244 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Which groups the bot is in, decided at runtime rather than in .env.
The bot is its own registered Signal account, so the groups it can see are
exactly the groups somebody put it in. Making the operator also write those
ids into .env and restart added a second step to "add the bot" that could
only ever be forgotten. This module keeps the watched set in sync with the
account itself.
The one rule that matters: a *failed* refresh never narrows the set. If the
listing cannot be fetched, or comes back malformed, the previous set stands.
Rebuilding from a partial answer would make the bot conclude it had been
removed from everything -- deaf, and with every group's counts purged.
"""
from __future__ import annotations
import asyncio
import logging
from collections.abc import Awaitable, Callable
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, 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__)
REFRESH_SECONDS: Final = 30.0
Sleeper = Callable[[float], Awaitable[None]]
class GroupDirectory:
"""The live set of groups the bot answers in."""
def __init__(
self,
config: Config,
client: httpx.AsyncClient,
store: Store,
trust: InviteTrust,
*,
sleeper: Sleeper | None = None,
) -> None:
"""Wire the directory to its config, HTTP client and store.
Args:
config: Resolved runtime configuration.
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, ...] = ()
self._joins = JoinAttempts()
# Group ids seen in an envelope that were not in the listing yet. One
# refresh per *id*, not per unit of time: a global cooldown would
# 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, ...]:
"""Every group currently watched, canonical and in listing order."""
return self._groups
def resolve(self, group_id: str | None) -> str | None:
"""Return the canonical id of a watched group, or None.
This is the single place an envelope's group id becomes a group the
bot acts on: the scoping gate, the reply address and the per-group
state key all come from this one answer.
Args:
group_id: The id as it arrived, or None for a direct message.
Returns:
The canonical id, or None for a direct message or a group the
bot does not watch.
"""
if group_id is None:
return None
return self._aliases.get(group_id)
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 False
if await join_pending(self._client, self._config, entries, self._joins, self._permitted):
entries = await self._fetch()
if entries is None:
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.
Args:
group_id: The unrecognised id from the envelope.
Returns:
The canonical id if the refresh adopted that group, else None.
"""
if group_id in self._refreshed_for:
return None
self._refreshed_for.add(group_id)
logger.info("message from unknown group %r; refreshing the listing", group_id)
await self.refresh()
return self.resolve(group_id)
async def verify_allowlist(self) -> None:
"""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.
Args:
iterations: Stop after this many refreshes. None means forever.
"""
completed = 0
while iterations is None or completed < iterations:
await self._sleep(REFRESH_SECONDS)
await self.refresh()
completed += 1
async def _fetch(self) -> list[dict[str, Any]] | None:
"""Return the group listing, or None when it could not be read.
None is the "keep what we have" signal. Every failure mode of this
call -- timeout, 500, a body that is not a list -- must leave the
watched set alone rather than emptying it.
"""
try:
response = await self._client.get(self._config.groups_url)
response.raise_for_status()
body = response.json()
except (httpx.HTTPError, ValueError) as exc:
logger.warning(
"group listing unavailable, keeping the %d group(s) already known: %s",
len(self._groups),
exc,
)
return None
if not isinstance(body, list):
logger.warning("group listing was %s, not a list; keeping what we have", type(body))
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)
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."""
groups = tuple(
group_id
for entry in entries
if entry.get("member") and (group_id := self._permitted(entry)) is not None
)
if groups == self._groups:
return
added = [group_id for group_id in groups if group_id not in self._groups]
removed = [group_id for group_id in self._groups if group_id not in groups]
# Built whole and assigned in one statement: the dispatcher reads
# this map between awaits, and must never see it half-built.
self._aliases = build_alias_map(groups)
self._groups = groups
for group_id in added:
self._joins.forget(group_id)
self._refreshed_for.discard(group_id)
logger.info("now watching %s", group_id)
for group_id in removed:
# Dropped, not kept: a re-add should start a fresh tally rather
# than resurrect counts from whenever the bot was last in there.
self._store.forget_group(group_id)
logger.info("no longer a member of %s; its counts were dropped", group_id)

View File

@ -9,12 +9,15 @@ from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING
from signal_bot.counting import is_watched_group, should_count
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
from signal_bot.discovery import GroupDirectory
from signal_bot.store import Store
from signal_bot.transport_base import Transport
@ -28,6 +31,7 @@ class Dispatcher:
"""Applies the scoping rules and dispatches commands."""
config: Config
directory: GroupDirectory
registry: CommandRegistry
store: Store
transport: Transport
@ -35,38 +39,83 @@ 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.
if not is_watched_group(message, self.config):
logger.debug("ignoring message outside the watched group")
# The canonical id it yields is the reply address and the key for
# every piece of per-group state, so a message can only ever be
# counted, rate-limited and answered in the group it came from.
group = watched_group(message, self.directory)
if group is None and message.group_id is not None:
# The bot was probably just added: Signal is already delivering
# this group's messages while our listing still predates it.
# Refreshing here is what makes the *first* command after an add
# work, instead of the one after the next 30-second sweep.
group = await self.directory.refresh_for(message.group_id)
if group is None:
logger.debug(
"ignoring message from group %r; watching %r",
message.group_id,
list(self.directory.groups),
)
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(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
logger.info("running command %s for %s", command.name, message.source_name)
now = self.clock()
ctx = CommandContext(
message=message,
recipient=self.config.group_id_send,
group_id=group,
transport=self.transport,
store=self.store,
config=self.config,
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
# Recorded once, here, so stacked gates cannot double-count a use.
self.store.record_use(message.source_uuid, command.name, ctx.now, ctx.day)
self.store.record_use(group, message.source_uuid, command.name, ctx.now, ctx.day)

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()

158
signal_bot/groups.py Normal file
View File

@ -0,0 +1,158 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Group ids: the three spellings, and the one that wins.
Split out of config.py because it is the whole reason the bot can watch more
than one group without answering in the wrong one. The REST API reports a
group as ``group.<base64>``, an envelope carries what that decodes to, and
only the first form can be sent to -- so every id is normalised here, once,
before anything downstream compares or addresses one.
"""
from __future__ import annotations
import base64
import binascii
from typing import TYPE_CHECKING, Final
if TYPE_CHECKING:
from collections.abc import Iterable
GROUP_ID_PREFIX: Final = "group."
class ConfigError(RuntimeError):
"""Raised when the environment does not describe a runnable bot."""
def group_id_aliases(group_id: str) -> frozenset[str]:
"""Every spelling of one group id that can arrive in an envelope.
The REST API reports group ids two different ways and never says so:
``/v1/groups`` returns ``group.<base64>`` (what the setup script writes
into .env), while an incoming envelope's ``groupInfo.groupId`` carries
the *internal* id -- which is exactly what that base64 decodes to. The
two never compare equal, so a bot configured from the API's own output
silently ignores every message in its own group. Verified live on
2026-08-29: ``group.Ni9nRXdS...`` decodes to ``6/gEwRkqs/...``, the id
the same endpoint reports as ``internal_id``.
Args:
group_id: The configured group id, in either spelling.
Returns:
The configured id plus its decoded internal form, when it has one.
"""
aliases = {group_id}
if group_id.startswith(GROUP_ID_PREFIX):
try:
decoded = base64.b64decode(group_id.removeprefix(GROUP_ID_PREFIX), validate=True)
except binascii.Error, ValueError:
return frozenset(aliases)
aliases.add(decoded.decode("utf-8", errors="replace"))
else:
aliases.add(canonical_group_id(group_id))
return frozenset(aliases)
def canonical_group_id(group_id: str) -> str:
"""Return the ``group.<base64>`` spelling of a group id.
One spelling has to win, because the same string is used for three
different jobs: matching an incoming envelope, addressing a reply, and
keying per-group state. The prefixed form wins because it is the only
one ``/v2/send`` and the group REST paths accept -- the internal form
contains ``/`` and ``+``. The internal id is itself base64 text, so the
conversion is just the inverse of what group_id_aliases decodes.
Args:
group_id: A group id in either spelling.
Returns:
The id in ``group.<base64>`` form, unchanged if it already is one.
"""
if group_id.startswith(GROUP_ID_PREFIX):
return group_id
return GROUP_ID_PREFIX + base64.b64encode(group_id.encode("utf-8")).decode("ascii")
def build_alias_map(group_ids: Iterable[str]) -> dict[str, str]:
"""Map every spelling of every configured group to its canonical id.
Args:
group_ids: Configured group ids, already canonical.
Returns:
A lookup from any spelling an envelope might carry to the one
canonical id that scopes state and addresses replies.
"""
mapping: dict[str, str] = {}
for group_id in group_ids:
for alias in group_id_aliases(group_id):
mapping[alias] = group_id
return mapping
def parse_group_ids(env: dict[str, str]) -> tuple[str, ...]:
"""Return the optional allowlist of groups, canonical and de-duplicated.
Empty is the normal case and means "every group this account is a full
member of". The bot is its own registered Signal account, not a linked
device on a personal one, so the groups it can see are exactly the
groups somebody put it in -- there is nothing to scope it away from,
and requiring a list here is what made adding the bot a two-step
procedure with a restart in the middle.
Set it to pin the bot to specific groups anyway. ``GROUP_IDS`` is the
list form; ``GROUP_ID`` remains accepted as a one-element spelling.
Setting both is an error rather than a precedence rule, because a
precedence rule means silently ignoring one of two values the operator
clearly meant.
Args:
env: The environment mapping to read.
Returns:
Canonical group ids in the order listed, or empty for "all of them".
Raises:
ConfigError: Both keys are set, a removed key is set, or the value
is nothing but separators.
"""
if env.get("GROUP_ID_SEND", "").strip():
msg = (
"GROUP_ID_SEND has been removed. Replies and the daily report now "
"go back to the group the message came from, which a fixed send "
"target cannot express once the bot watches more than one group. "
"Delete the line from .env."
)
raise ConfigError(msg)
listed = env.get("GROUP_IDS", "").strip()
single = env.get("GROUP_ID", "").strip()
if listed and single:
msg = "set GROUP_IDS or GROUP_ID, not both; GROUP_ID is the one-group spelling"
raise ConfigError(msg)
raw = listed or single
if not raw:
return ()
group_ids: list[str] = []
seen: dict[str, str] = {}
for part in raw.split(","):
candidate = part.strip()
if not candidate:
continue
canonical = canonical_group_id(candidate)
aliases = group_id_aliases(canonical)
clash = next((seen[alias] for alias in aliases if alias in seen), None)
if clash is not None:
msg = f"group {candidate!r} is listed twice, once as {clash!r}"
raise ConfigError(msg)
seen.update(dict.fromkeys(aliases, canonical))
group_ids.append(canonical)
if not group_ids:
msg = f"GROUP_IDS lists no group ids, only separators: {raw!r}"
raise ConfigError(msg)
return tuple(group_ids)

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)

170
signal_bot/membership.py Normal file
View File

@ -0,0 +1,170 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Invited is not joined.
Signal only adds an account to a group outright when whoever adds it already
holds its profile key; otherwise the add becomes a pending invitation. A
non-member looks perfectly healthy from outside -- the group is listed, the
websocket is up, /healthz answers -- and not one message ever arrives. This
module is the part that tells the two states apart and tries to fix the
second one.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, Final
from urllib.parse import quote
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__)
MEMBER_KEY: Final = "member"
class MembershipError(RuntimeError):
"""Raised when the account is not a full member of a required group."""
def entry_matches(entry: dict[str, Any], group_id: str) -> bool:
"""True when a /v1/groups row is the group with this id, in any spelling.
Args:
entry: One row of the group listing.
group_id: The canonical id being looked for.
Returns:
True when the row describes that group.
"""
return bool({entry.get("id"), entry.get("internal_id")} & group_id_aliases(group_id))
def find_entry(entries: list[dict[str, Any]], group_id: str) -> dict[str, Any] | None:
"""Return the listing row for one group, or None when it is absent."""
return next((entry for entry in entries if entry_matches(entry, group_id)), None)
class JoinAttempts:
"""Remembers which invitations could not be accepted.
signal-cli cannot accept an invite addressed to a phone number at all
("Cannot find service ID for self"). Without this, the refresh loop would
retry that same impossible join every 30 seconds forever, logging a
warning each time and burying anything worth reading.
"""
def __init__(self) -> None:
"""Start with nothing known to have failed."""
self._failed: dict[str, str] = {}
def has_failed(self, group_id: str) -> bool:
"""True when joining this group has already been tried and refused."""
return group_id in self._failed
def reason(self, group_id: str) -> str:
"""Return why the last join attempt for this group failed."""
return self._failed.get(group_id, "not attempted")
def record_failure(self, group_id: str, detail: str) -> None:
"""Remember that this group could not be joined, and why."""
self._failed[group_id] = detail
def forget(self, group_id: str) -> None:
"""Drop the memory of a failure, once the group is joined."""
self._failed.pop(group_id, None)
async def attempt_join(client: httpx.AsyncClient, config: Config, group_id: str) -> str:
"""Try to accept a pending invitation, reporting what the API said.
This never raises. The join endpoint is a best-effort self-heal, and the
authority on whether it worked is the caller's membership re-check, not
this response -- returning the outcome as text only keeps it available
for the error message when the re-check still says non-member.
Args:
client: HTTP client for the REST API.
config: Resolved runtime configuration.
group_id: The canonical group id to join.
Returns:
A short description of the attempt.
"""
# Percent-encoded: the internal spelling contains '/' and '+', which do
# not survive being a path segment.
quoted = quote(group_id, safe="")
url = f"{config.api_base_url}/v1/groups/{config.phone_number}/{quoted}/join"
try:
response = await client.post(url)
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)

119
signal_bot/portcheck.py Normal file
View File

@ -0,0 +1,119 @@
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Refuse to start on a taken port, and name whatever is already holding it.
uvicorn logs "address already in use" and then shuts down *cleanly*: the
process exits 0, so a supervisor records a successful run and a human reads a
tidy "Application shutdown complete" as if nothing were wrong. That is a
fail-open, and it is exactly how this bot silently failed to start.
Attribution reads /proc directly rather than forking `ss` or `lsof`: no
subprocess, no PATH assumptions, and the whole thing is testable against a
fake proc tree passed in as `proc_root`.
"""
from __future__ import annotations
import socket
from pathlib import Path
from typing import Final
PROC_ROOT: Final = Path("/proc")
_TCP_TABLES: Final = ("net/tcp", "net/tcp6")
_LISTEN_STATE: Final = "0A"
_INODE_FIELD: Final = 9
class PortInUseError(RuntimeError):
"""Raised when the bot's bind address is already taken."""
def _listening_inodes(port: int, proc_root: Path) -> set[str]:
"""Return the socket inodes of every LISTEN socket on the given port."""
inodes: set[str] = set()
for table in _TCP_TABLES:
try:
# Skip the header row; every remaining line is one socket.
lines = (proc_root / table).read_text().splitlines()[1:]
except OSError:
continue
for line in lines:
fields = line.split()
if len(fields) <= _INODE_FIELD or fields[3] != _LISTEN_STATE:
continue
_, _, hex_port = fields[1].rpartition(":")
try:
listening_on = int(hex_port, 16)
except ValueError:
continue
if listening_on == port:
inodes.add(fields[_INODE_FIELD])
return inodes
def _command_of(pid_dir: Path) -> str:
"""Return the full command line of a process, or a placeholder."""
try:
raw = (pid_dir / "cmdline").read_bytes()
except OSError:
return "(command unavailable)"
argv = raw.decode(errors="replace").rstrip("\0").split("\0")
return " ".join(argv).strip() or "(command unavailable)"
def _owner_of(inodes: set[str], proc_root: Path) -> tuple[int, str] | None:
"""Find the pid holding any of these socket inodes, with its command line."""
targets = {f"socket:[{inode}]" for inode in inodes}
for pid_dir in sorted(proc_root.iterdir()):
if not pid_dir.name.isdigit():
continue
try:
descriptors = sorted((pid_dir / "fd").iterdir())
except OSError:
# Another user's process, or one that exited mid-scan.
continue
for descriptor in descriptors:
try:
link = str(descriptor.readlink())
except OSError:
continue
if link in targets:
return int(pid_dir.name), _command_of(pid_dir)
return None
def describe_listener(port: int, proc_root: Path = PROC_ROOT) -> str:
"""Describe whoever is listening on a port, or "" if nobody identifiable is."""
inodes = _listening_inodes(port, proc_root)
if not inodes:
return ""
owner = _owner_of(inodes, proc_root)
if owner is None:
return "held by a process belonging to another user"
pid, command = owner
return f"held by pid {pid}: {command}"
def assert_port_free(host: str, port: int, proc_root: Path = PROC_ROOT) -> None:
"""Raise PortInUseError unless host:port can actually be bound.
Args:
host: Address the server will bind.
port: Port the server will bind.
proc_root: Root of the proc filesystem. Replaced in tests.
Raises:
PortInUseError: The address is already in use.
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
probe.bind((host, port))
except OSError as exc:
holder = describe_listener(port, proc_root)
detail = f" -- {holder}" if holder else ""
msg = (
f"cannot bind {host}:{port}{detail}. "
f"Set BIND_PORT in .env to a free port, or stop that process. "
f"Refusing to start, because uvicorn would log this and exit 0."
)
raise PortInUseError(msg) from exc

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
@ -26,17 +29,47 @@ class CommandContext:
"""Everything a command handler is allowed to touch."""
message: IncomingMessage
recipient: str
group_id: str
transport: Transport
store: Store
config: Config
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 to the configured reply target."""
await self.transport.send_text(text, self.recipient)
"""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 -- and it
quotes the asker, so a busy group can tell which "!cat" this is.
"""
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]]
@ -44,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."""
@ -63,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)
@ -84,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)

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