mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-26 22:37:15 +01:00
Compare commits
53 Commits
6c98917dfa
...
86e174ee49
| Author | SHA1 | Date | |
|---|---|---|---|
| 86e174ee49 | |||
| 37a27c6dff | |||
| a9535f52e4 | |||
| 80c0fa8e45 | |||
| 7f66116cd5 | |||
| 86ea1b3220 | |||
| 3b3a78820a | |||
| 1f4080e75d | |||
| 35102be863 | |||
| 9db3687752 | |||
| 50bd390b00 | |||
| 1bf63b053b | |||
| a79506c18f | |||
| ba54092e0a | |||
| da6e69cd44 | |||
| dc642b8a1f | |||
| 3d6ae0680c | |||
| ca38147576 | |||
| 032284bab3 | |||
| 116671236a | |||
| 0c29583db3 | |||
| 40538b89a1 | |||
| ad93bbfdf7 | |||
| be24243507 | |||
| dedc153cb4 | |||
| 8df2646377 | |||
| bfc2bcb3b8 | |||
| 0e0c9ba619 | |||
| a9ffd02f33 | |||
| 0f824c441e | |||
| 50f6a587c2 | |||
| 63f262bddd | |||
| dc1995b558 | |||
| 558dd297a4 | |||
| 0d7cb99f5c | |||
| 72482629d9 | |||
| a1855a453d | |||
| e102e413ff | |||
| b70730fc7a | |||
| 6f5a703824 | |||
| a413ab59ec | |||
| f4efcd97e2 | |||
| 79dab5cc01 | |||
| a202317072 | |||
| f92502d18b | |||
| 14c17a11b4 | |||
| a9f6875abe | |||
| d5c63b423b | |||
| 0c4b259c17 | |||
| f4f8c32329 | |||
| bb72f0ae93 | |||
| 5d76adf4db | |||
| b48c945d89 |
72
.env.sample
72
.env.sample
@ -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=
|
||||
|
||||
12
.github/workflows/ci.yml
vendored
12
.github/workflows/ci.yml
vendored
@ -36,6 +36,12 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The name half of this check needs the operator's private data and so
|
||||
# can only run locally; the shape half -- phone numbers, uuids, Signal
|
||||
# group ids -- works anywhere and is what CI enforces on every push.
|
||||
- name: no personal data
|
||||
run: ./scripts/check_personal_data.sh --all
|
||||
|
||||
- name: ruff format
|
||||
run: .venv/bin/ruff format --check .
|
||||
|
||||
@ -56,3 +62,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
25
.gitignore
vendored
@ -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/
|
||||
|
||||
87
.personal-data-allowlist
Normal file
87
.personal-data-allowlist
Normal file
@ -0,0 +1,87 @@
|
||||
# Values this public repository is allowed to contain.
|
||||
#
|
||||
# Everything a real person could be identified by is refused by
|
||||
# scripts/check_personal_data.sh, which learns the names from OUTSIDE this
|
||||
# repository (the photo pack, the message database, .env) so that the list of
|
||||
# real names is never in it. What is left is shapes -- phone numbers, uuids,
|
||||
# Signal group ids -- and those need an explicit list of the invented ones the
|
||||
# documents and fixtures are built from. That list is this file.
|
||||
#
|
||||
# One value per line, lower-cased. Add a value here only after checking it
|
||||
# belongs to nobody.
|
||||
|
||||
# Phone numbers. The 555 range is reserved for fiction; the two below are
|
||||
# structurally valid and deliberately not anybody's.
|
||||
+15550000000
|
||||
+48123456789
|
||||
+420111222333
|
||||
+48000000000
|
||||
+48111222333
|
||||
|
||||
# UUIDs used as fixtures.
|
||||
b1c2d3e4-0000-4a00-8a00-000000000001
|
||||
b1c2d3e4-0000-4a00-8a00-000000000002
|
||||
|
||||
# Group ids invented for the offline end-to-end run and the unit tests. Each
|
||||
# one base64-decodes to a sentence saying it is a fixture.
|
||||
group.wlrkbexyzghkr05vzldrdc1ncm91cc1pzc0zmi1ienl0zxmhisfd
|
||||
group.zdjgmfkyagxaqzfuy205mwndmxbaqzb6twkxiwvyumxjeuvositfaelrpt0=
|
||||
group.wtjllxdhdgnozwqtz3jvdxatawqtmzitynl0zxmhisfd
|
||||
|
||||
# The author's own handle, which is the repository owner and appears in the
|
||||
# project URL, the User-Agent and every copyright line.
|
||||
kuhy
|
||||
# The sender name POST /_selftest injects. Not a person.
|
||||
self-test
|
||||
|
||||
# Given names that are also popes. Permitted ONLY in the files that carry the
|
||||
# papal list, so the same name in a test fixture or a document is still
|
||||
# refused -- which is exactly how it leaked the first time.
|
||||
signal_bot/popes.json::marek
|
||||
signal_bot/popes.json::wiktor
|
||||
tests/test_versioning.py::wiktor
|
||||
DOCS-changelog.md::wiktor
|
||||
|
||||
# Invented Signal group ids. Every one of these base64-decodes twice to a
|
||||
# sentence saying what it is, which is how you can tell it belongs to nobody:
|
||||
# group.WlRKbExYZGhkR05vWldRdFozSnZkWEF0YVdRdE16SXRZbmwwWlhNaElTRT0=
|
||||
# -> ZTJlLXdhdGNoZWQtZ3JvdXAtaWQtMzItYnl0ZXMhISE= -> e2e-watched-group-id-32-bytes!!!
|
||||
group.WTI5dVptbG5MV2R5YjNWd0xXbGtMVE15TFdKNWRHVnpJU0VoSVNFaElRPT0=
|
||||
group.WlRKbExYZGhkR05vWldRdFozSnZkWEF0YVdRdE16SXRZbmwwWlhNaElTRT0=
|
||||
group.WlRKbExYTmxZMjl1WkMxbmNtOTFjQzFwWkMwek1pMWllWFJsY3lFaElTRT0=
|
||||
group.WlRKbExYUm9hWEprTFdkeWIzVndMV2xrTFRNeUxXSjVkR1Z6SVNFaElRPT0=
|
||||
group.WlRKbExXWnZkWEowYUMxbmNtOTFjQzFwWkMwek1pMWllWFJsY3lFaElTRT0=
|
||||
group.WTI1c1pDMXZibVV0WjNKdmRYQXRhV1F0TXpJdFlubDBaWE1oSVNFaElTRT0=
|
||||
group.WTI5c1pDMXZibVV0WjNKdmRYQXRhV1F0TXpJdFlubDBaWE1oSVNFaElTRT0=
|
||||
group.WTI5c1pDMTBkMjh0WjNKdmRYQXRhV1F0TXpJdFlubDBaWE1oSVNFaElTRT0=
|
||||
group.WTI5c1pDMTBhSEpsWlMxbmNtOTFjQzFwWkMwek1pMWllWFJsY3lFaElTRT0=
|
||||
group.WTI5c1pDMW1iM1Z5TFdkeWIzVndMV2xrTFRNeUxXSjVkR1Z6SVNFaElTRT0=
|
||||
group.YjNSb1pYSXRaM0p2ZFhBdGFXUXRNekl0WW5sMFpYTWhJU0VoSVNFPQ==
|
||||
group.YzJWamIyNWtMV2R5YjNWd0xXbGtMVE15TFdKNWRHVnpJU0VoSVNFaA==
|
||||
group.ZDJGMFkyaGxaQzFuY205MWNDMXBaQzB6TWkxaWVYUmxjeUVoSVNFaElRPT0=
|
||||
group.WlRKbExYZGhkR05vWldRdA==
|
||||
|
||||
# Invented phone numbers used as fixtures. Reserved / non-allocated ranges.
|
||||
+15550000001
|
||||
+15550000002
|
||||
+15550001111
|
||||
+15550001234
|
||||
+15555550123
|
||||
+15559999999
|
||||
+48987654321
|
||||
signal_bot/versioning.py::wiktor
|
||||
|
||||
# Given names that are also popes, permitted only in the files that carry or
|
||||
# assert the papal list. Anywhere else -- a test fixture, a document, a help
|
||||
# text -- they are still refused, which is the case that leaked.
|
||||
signal_bot/popes.json::jan
|
||||
signal_bot/popes.json::marek
|
||||
signal_bot/popes.json::wiktor
|
||||
signal_bot/versioning.py::jan
|
||||
tool/gen_popes.py::jan
|
||||
tool/gen_popes.py::marek
|
||||
tool/gen_popes.py::wiktor
|
||||
tests/test_versioning.py::jan
|
||||
tests/test_changelog.py::jan
|
||||
tests/test_popes_command.py::jan
|
||||
DOCS-changelog.md::jan
|
||||
@ -45,6 +45,37 @@ 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.
|
||||
# This repository is public and leaked once: real names, two phone
|
||||
# numbers and a member's Signal uuid reached GitHub and only came off
|
||||
# it by deleting the repository. The checker learns what to refuse from
|
||||
# OUTSIDE the repo -- the photo pack, the message database, .env -- so
|
||||
# the list of real names is never in the thing being checked.
|
||||
- id: personal-data
|
||||
name: no personal data
|
||||
entry: scripts/check_personal_data.sh
|
||||
language: system
|
||||
types: [text]
|
||||
|
||||
# The same check on the commit message, because that is where two of
|
||||
# the leaks actually lived.
|
||||
- id: personal-data-message
|
||||
name: no personal data in the commit message
|
||||
entry: scripts/check_personal_data.sh --message
|
||||
language: system
|
||||
stages: [commit-msg]
|
||||
always_run: true
|
||||
pass_filenames: true
|
||||
|
||||
- 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 +129,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
224
DOCS-changelog.md
Normal 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
51
DOCS-commands.md
Normal 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
46
DOCS-latency.md
Normal 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.
|
||||
83
DOCS-liveness-and-trust.md
Normal file
83
DOCS-liveness-and-trust.md
Normal 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
109
DOCS-photo-pack.md
Normal 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.
|
||||
83
DOCS-privacy.md
Normal file
83
DOCS-privacy.md
Normal file
@ -0,0 +1,83 @@
|
||||
# What is private, and what stops it leaking
|
||||
|
||||
This repository is public. The bot it describes reads a private group chat,
|
||||
posts from a private photo album, and keeps a database of who said how much.
|
||||
None of that may be in here, and on 2026-08-30 some of it was.
|
||||
|
||||
## What leaked, and how
|
||||
|
||||
Real first names, one full name, two phone numbers and a group member's
|
||||
Signal uuid were in the tree *and* in the public history. They arrived one
|
||||
way every time: **somebody reached for a real name because it was the example
|
||||
in front of them** — a test fixture built from a live database dump, an
|
||||
envelope pasted verbatim out of a running container, a help text written
|
||||
while looking at the actual group.
|
||||
|
||||
Fixing it needed the tree scrubbed, all 56 commits rewritten with
|
||||
`git filter-repo`, and then the repository **deleted and recreated**, because
|
||||
GitHub keeps orphaned commits fetchable by their SHA after a force-push and
|
||||
only the repository going away takes them with it. The closed pull requests
|
||||
and the star went too.
|
||||
|
||||
## What is private, and where it lives
|
||||
|
||||
| | Where | Never in git because |
|
||||
|---|---|---|
|
||||
| the photos and who is in them | `~/.local/share/signal-bot/pack/` | it is outside the repo, and `.gitignore` also names `people.json`, `tags.json`, `media/`, `pack/` and every media extension |
|
||||
| the message database | `signal_bot.sqlite3` | `*.sqlite3` and its `-wal`/`-shm` siblings are ignored |
|
||||
| the account's number, groups, inviters | `.env` | `.env` is ignored; `.env.sample` carries the shape and no values |
|
||||
| everyone's names | the database and the pack manifest | nothing reads them into the repo; the bot logs `pack:p1`, never a name |
|
||||
|
||||
All of it is `700`/`600` on disk. The repository never needs any of it: the
|
||||
tests, the documents and the offline end-to-end run use invented people —
|
||||
alfa, beta, gamma, ala, basia, celina — and invented ids that base64-decode
|
||||
twice into a sentence saying what they are.
|
||||
|
||||
## The gate
|
||||
|
||||
`scripts/check_personal_data.sh` refuses a commit that carries personal data.
|
||||
It runs on staged files, on the commit message, and over the whole tree in
|
||||
CI. Two halves, because they fail differently:
|
||||
|
||||
- **Names cannot be listed here** — a file of real names kept in the repo to
|
||||
check against *is* the leak. So the checker learns them at run time from
|
||||
outside: the photo pack's manifest, the message database, and `.env`. It
|
||||
never prints the word it matched, because this output reaches CI logs.
|
||||
- **Shapes can be listed** — a phone number, a uuid and a Signal group id
|
||||
look like themselves anywhere, so those are matched by pattern and compared
|
||||
against `.personal-data-allowlist`, which holds only invented values.
|
||||
|
||||
On a machine with none of that private data (CI, a fresh clone) the name half
|
||||
has nothing to compare against and **says so** rather than passing quietly.
|
||||
|
||||
It found a real leak the first time it was run: the live test group's id, in
|
||||
two spellings, in `tests/test_config.py` — which four rounds of grepping by
|
||||
hand had missed, because nobody thinks to grep for base64.
|
||||
|
||||
## When it fires
|
||||
|
||||
```
|
||||
tests/test_thing.py:12: a name from your private data
|
||||
```
|
||||
|
||||
Use an invented name. `ala`, `basia`, `celina`, `darek` are already in use;
|
||||
so are `+15550000000` and ids that decode to `e2e-watched-group-id-32-bytes!!!`.
|
||||
|
||||
```
|
||||
DOCS-thing.md:40: phone number '+48123456789' is not in .personal-data-allowlist
|
||||
```
|
||||
|
||||
Either it belongs to somebody — replace it — or it is invented, in which case
|
||||
add it to `.personal-data-allowlist` **after checking that it is**. A line
|
||||
there may be scoped to one file (`signal_bot/popes.json::hadrian`), which is how
|
||||
a given name that is also a pope stays refused in every test fixture that has
|
||||
no business carrying it.
|
||||
|
||||
## What the gate cannot do
|
||||
|
||||
- It does not scan history. Rewriting that is a deliberate, separate act.
|
||||
- It knows only what is on *this* machine. A name nobody has ever typed into
|
||||
the group is a name it cannot recognise.
|
||||
- It does not stop the bot's own logs holding display names —
|
||||
`journalctl --user -u signal-bot` does, and `--vacuum-time=` is how that is
|
||||
emptied.
|
||||
47
DOCS-selftest.md
Normal file
47
DOCS-selftest.md
Normal 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.
|
||||
@ -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": "Y29uZmlnLWdy…", "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
90
DOCS-statistics.md
Normal 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
157
README.md
@ -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. The group's own data stays out: `DOCS-privacy.md`.
|
||||
|
||||
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
|
||||
|
||||
|
||||
33
SECURITY.md
33
SECURITY.md
@ -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.
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -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)
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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
|
||||
|
||||
49
fake_signal/routes_groups.py
Normal file
49
fake_signal/routes_groups.py
Normal 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
|
||||
@ -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
|
||||
|
||||
5
fake_signal/scenarios/cyrillic_homoglyph.yaml
Normal file
5
fake_signal/scenarios/cyrillic_homoglyph.yaml
Normal 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 }
|
||||
11
fake_signal/scenarios/discovers_a_new_group.yaml
Normal file
11
fake_signal/scenarios/discovers_a_new_group.yaml
Normal 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 }
|
||||
5
fake_signal/scenarios/gecko_command.yaml
Normal file
5
fake_signal/scenarios/gecko_command.yaml
Normal 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 }
|
||||
7
fake_signal/scenarios/help_command.yaml
Normal file
7
fake_signal/scenarios/help_command.yaml
Normal 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" }
|
||||
10
fake_signal/scenarios/joins_a_pending_invitation.yaml
Normal file
10
fake_signal/scenarios/joins_a_pending_invitation.yaml
Normal 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 }
|
||||
7
fake_signal/scenarios/pack_combination.yaml
Normal file
7
fake_signal/scenarios/pack_combination.yaml
Normal 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 }
|
||||
7
fake_signal/scenarios/pack_command.yaml
Normal file
7
fake_signal/scenarios/pack_command.yaml
Normal 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 }
|
||||
7
fake_signal/scenarios/pack_no_photo.yaml
Normal file
7
fake_signal/scenarios/pack_no_photo.yaml
Normal 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" }
|
||||
7
fake_signal/scenarios/pack_scoping.yaml
Normal file
7
fake_signal/scenarios/pack_scoping.yaml
Normal 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: []
|
||||
7
fake_signal/scenarios/pack_video.yaml
Normal file
7
fake_signal/scenarios/pack_video.yaml
Normal 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 }
|
||||
12
fake_signal/scenarios/per_group_isolation.yaml
Normal file
12
fake_signal/scenarios/per_group_isolation.yaml
Normal 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 }
|
||||
5
fake_signal/scenarios/pope_command.yaml
Normal file
5
fake_signal/scenarios/pope_command.yaml
Normal 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 }
|
||||
5
fake_signal/scenarios/quoted_reply.yaml
Normal file
5
fake_signal/scenarios/quoted_reply.yaml
Normal 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 }
|
||||
@ -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 }
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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."""
|
||||
|
||||
@ -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
26
scripts/check_no_binaries.sh
Executable 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 "$@"
|
||||
158
scripts/check_personal_data.py
Executable file
158
scripts/check_personal_data.py
Executable file
@ -0,0 +1,158 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
||||
"""Refuse to commit anything that identifies a real person.
|
||||
|
||||
This repository is public and has already leaked once: real first names, a
|
||||
full name, two phone numbers and a group member's Signal uuid reached GitHub
|
||||
and stayed there until the repository had to be deleted and recreated. Every
|
||||
one of them arrived the same way -- somebody (a human once, this program's
|
||||
author the second time) reached for a real name because it was the example
|
||||
in front of them.
|
||||
|
||||
So it is a gate rather than a rule. Two halves, because they fail differently:
|
||||
|
||||
* **Names**, which cannot be listed here. The forbidden words are read at run
|
||||
time from outside the repository -- the photo pack's manifest, the message
|
||||
database, the local .env -- so the check knows them and the repository
|
||||
never does. On a machine with none of those (CI, a fresh clone) this half
|
||||
simply has nothing to compare against and says so.
|
||||
* **Shapes**, which can. A phone number, a uuid and a Signal group id look
|
||||
like themselves wherever they appear, so those are matched by pattern and
|
||||
compared against the placeholders this repository is allowed to contain.
|
||||
|
||||
Usage:
|
||||
scripts/check_personal_data.sh --all # every tracked file
|
||||
scripts/check_personal_data.sh a.py b.md # named files
|
||||
|
||||
The shell wrapper is the entry point; it knows how to list what git tracks,
|
||||
which keeps this half free of a subprocess call it would need a suppression
|
||||
for.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from personal_data_sources import REPO, forbidden
|
||||
|
||||
ALLOWLIST: Final = REPO / ".personal-data-allowlist"
|
||||
|
||||
# Shapes that identify somebody wherever they turn up.
|
||||
PATTERNS: Final[dict[str, re.Pattern[str]]] = {
|
||||
"phone number": re.compile(r"\+\d{9,15}\b"),
|
||||
"uuid": re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b"),
|
||||
"signal group id": re.compile(r"\bgroup\.[A-Za-z0-9+/]{16,}={0,2}"),
|
||||
}
|
||||
|
||||
SKIP_DIRS: Final = frozenset({".git", ".venv", "__pycache__", ".mypy_cache", ".ruff_cache"})
|
||||
SKIP_SUFFIXES: Final = frozenset({".lock", ".bundle"})
|
||||
|
||||
|
||||
def allowed(path: Path | None = None) -> set[str]:
|
||||
"""Literals this repository may contain, lower-cased.
|
||||
|
||||
A plain line permits a value anywhere. A ``some/path::value`` line
|
||||
permits it only in that file, which is how a name that is also a pope in
|
||||
popes.json stays refused in every test fixture and document that has no
|
||||
business carrying it.
|
||||
"""
|
||||
if not ALLOWLIST.exists():
|
||||
return set()
|
||||
permitted: set[str] = set()
|
||||
where = str(path) if path is not None else ""
|
||||
# The allowlist has to be able to name the values it permits, including
|
||||
# the file-scoped ones, so inside it every listed value counts as
|
||||
# permitted. It is the list of exceptions; it cannot be its own exception.
|
||||
inside = path is not None and path.resolve() == ALLOWLIST
|
||||
for raw in ALLOWLIST.read_text(encoding="utf-8").splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
scope, separator, value = line.partition("::")
|
||||
if not separator:
|
||||
permitted.add(line.lower())
|
||||
elif inside or where.endswith(scope.strip()):
|
||||
permitted.add(value.strip().lower())
|
||||
return permitted
|
||||
|
||||
|
||||
def scan(text: str, words: set[str], path: Path | None = None) -> list[tuple[int, str]]:
|
||||
"""Return (line number, what matched) for every hit in one document."""
|
||||
permitted = allowed(path)
|
||||
words = {word for word in words if word not in permitted}
|
||||
hits: list[tuple[int, str]] = []
|
||||
for number, line in enumerate(text.splitlines(), start=1):
|
||||
lowered = line.lower()
|
||||
for word in words:
|
||||
if re.search(rf"(?<![\w]){re.escape(word)}(?![\w])", lowered):
|
||||
# The word itself is never printed: this output can end up in
|
||||
# a CI log, and naming the name there would be the same leak
|
||||
# by a longer route.
|
||||
hits.append((number, "a name from your private data"))
|
||||
break
|
||||
hits.extend(
|
||||
(number, f"{label} {match!r} is not in .personal-data-allowlist")
|
||||
for label, pattern in PATTERNS.items()
|
||||
for match in pattern.findall(line)
|
||||
if match.lower() not in permitted
|
||||
)
|
||||
return hits
|
||||
|
||||
|
||||
def readable(path: Path) -> str | None:
|
||||
"""The file's text, or None when it is not text at all."""
|
||||
if path.suffix in SKIP_SUFFIXES or any(part in SKIP_DIRS for part in path.parts):
|
||||
return None
|
||||
try:
|
||||
return path.read_text(encoding="utf-8")
|
||||
except OSError, UnicodeDecodeError:
|
||||
return None
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Check whatever was asked for, and explain any refusal."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
||||
)
|
||||
parser.add_argument("--files", nargs="*", type=Path, default=[])
|
||||
parser.add_argument("--message", type=Path, default=None, help="a commit message file")
|
||||
arguments = parser.parse_args()
|
||||
|
||||
words, sources = forbidden(allowed())
|
||||
targets = list(arguments.files)
|
||||
if arguments.message is not None:
|
||||
targets.append(arguments.message)
|
||||
|
||||
failures = 0
|
||||
for path in targets:
|
||||
text = readable(path)
|
||||
if text is None:
|
||||
continue
|
||||
for number, reason in scan(text, words, path):
|
||||
sys.stdout.write(f"{path}:{number}: {reason}\n")
|
||||
failures += 1
|
||||
|
||||
if failures:
|
||||
sys.stdout.write(
|
||||
f"\nRefused: {failures} line(s) carry personal data.\n"
|
||||
"This repository is public. Use an invented name, a placeholder number, or\n"
|
||||
"add the value to .personal-data-allowlist if it is genuinely not anybody's.\n"
|
||||
)
|
||||
return 1
|
||||
if not words:
|
||||
# Said out loud rather than passing quietly: on CI and on a fresh
|
||||
# clone the name half of this check has nothing to compare against,
|
||||
# and a gate that silently checks nothing is worse than no gate.
|
||||
sys.stdout.write("no local private data to compare against; shapes only\n")
|
||||
else:
|
||||
sys.stdout.write(f"clean ({len(words)} name(s) from: {', '.join(sources)})\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
73
scripts/check_personal_data.sh
Executable file
73
scripts/check_personal_data.sh
Executable file
@ -0,0 +1,73 @@
|
||||
#!/bin/bash
|
||||
|
||||
# ============================================================================
|
||||
# Refuse to commit anything that identifies a real person.
|
||||
#
|
||||
# The logic is check_personal_data.py; this half exists to list what git
|
||||
# tracks, which keeps the Python free of a subprocess call it would otherwise
|
||||
# need a lint suppression for.
|
||||
#
|
||||
# scripts/check_personal_data.sh --all every tracked file
|
||||
# scripts/check_personal_data.sh a.py b.md named files
|
||||
# scripts/check_personal_data.sh --message .git/COMMIT_EDITMSG
|
||||
# ============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
readonly SCRIPT_DIR
|
||||
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
readonly REPO_ROOT
|
||||
readonly CHECKER="${SCRIPT_DIR}/check_personal_data.py"
|
||||
|
||||
# The repo's own interpreter when there is one, so the check runs the same
|
||||
# way under pre-commit, in CI and by hand.
|
||||
PYTHON="${PYTHON:-${REPO_ROOT}/.venv/bin/python}"
|
||||
if [[ ! -x "$PYTHON" ]]; then
|
||||
PYTHON="$(command -v python3)"
|
||||
fi
|
||||
readonly PYTHON
|
||||
|
||||
usage() {
|
||||
echo "Usage: $(basename "$0") [--all | --message FILE | FILE...]"
|
||||
exit 0
|
||||
}
|
||||
|
||||
main() {
|
||||
if [[ $# -eq 0 ]]; then
|
||||
usage
|
||||
fi
|
||||
|
||||
case "$1" in
|
||||
-h | --help)
|
||||
usage
|
||||
;;
|
||||
--message)
|
||||
if [[ $# -lt 2 ]]; then
|
||||
echo "Error: --message needs a file" >&2
|
||||
exit 1
|
||||
fi
|
||||
"$PYTHON" "$CHECKER" --message "$2"
|
||||
;;
|
||||
--all)
|
||||
local files=()
|
||||
mapfile -t files < <(git -C "$REPO_ROOT" ls-files)
|
||||
if [[ ${#files[@]} -eq 0 ]]; then
|
||||
echo "Error: git tracks no files here" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Prefixed with the repo root so this works from any directory.
|
||||
local paths=()
|
||||
local file
|
||||
for file in "${files[@]}"; do
|
||||
paths+=("${REPO_ROOT}/${file}")
|
||||
done
|
||||
"$PYTHON" "$CHECKER" --files "${paths[@]}"
|
||||
;;
|
||||
*)
|
||||
"$PYTHON" "$CHECKER" --files "$@"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
main "$@"
|
||||
153
scripts/cold_start.sh
Executable file
153
scripts/cold_start.sh
Executable 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 "$@"
|
||||
102
scripts/e2e.sh
102
scripts/e2e.sh
@ -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
150
scripts/install_service.sh
Executable 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 "$@"
|
||||
@ -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"
|
||||
}
|
||||
|
||||
@ -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"
|
||||
|
||||
164
scripts/personal_data_sources.py
Executable file
164
scripts/personal_data_sources.py
Executable file
@ -0,0 +1,164 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
||||
"""Where the forbidden words come from -- all of it outside this repository.
|
||||
|
||||
Split out of check_personal_data.py at the 250-line cap, and the seam is the
|
||||
honest one: this half knows the private data, that half knows nothing but how
|
||||
to search. A list of real names kept *in* the repository to check against
|
||||
would be the leak the check exists to prevent, so nothing here is ever
|
||||
written down -- it is read at run time from the photo pack, the message
|
||||
database and the local .env, and on a machine with none of those it simply
|
||||
comes back empty.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
REPO: Final = Path(__file__).resolve().parent.parent
|
||||
|
||||
# Three, because real first names are three letters long and one of this
|
||||
# group's is. Two would match inside half the words in the repository; three
|
||||
# needs a handful of allowlist entries for the given names that are also
|
||||
# popes, which is a cost worth paying to catch a real one.
|
||||
MIN_NAME: Final = 3
|
||||
|
||||
# How much of a group id has to appear before it counts as that group. Eight
|
||||
# base64 characters are 48 bits: unique enough that a coincidence is not
|
||||
# worth worrying about, short enough to catch a truncated quotation.
|
||||
PREFIX: Final = 8
|
||||
|
||||
|
||||
def _pack_names(directory: Path) -> set[str]:
|
||||
"""Every trigger word in a photo pack manifest -- i.e. every name."""
|
||||
manifest = directory / "people.json"
|
||||
if not manifest.is_file():
|
||||
return set()
|
||||
try:
|
||||
document = json.loads(manifest.read_text(encoding="utf-8"))
|
||||
except OSError, json.JSONDecodeError:
|
||||
return set()
|
||||
entries = [*document.get("people", []), *document.get("combos", [])]
|
||||
return {
|
||||
str(trigger).lstrip("!").strip()
|
||||
for entry in entries
|
||||
for trigger in entry.get("triggers", [])
|
||||
}
|
||||
|
||||
|
||||
def _database_names(path: Path) -> set[str]:
|
||||
"""Display names of everybody the bot has ever seen speak."""
|
||||
if not path.is_file():
|
||||
return set()
|
||||
try:
|
||||
connection = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
|
||||
except sqlite3.Error:
|
||||
return set()
|
||||
# Literal statements, not a table name interpolated into one: a
|
||||
# formatted query is a SQL-injection shape even when every input is a
|
||||
# constant, and this repository takes no lint suppressions.
|
||||
queries = (
|
||||
"SELECT DISTINCT display_name FROM message_counts",
|
||||
"SELECT DISTINCT display_name FROM group_people",
|
||||
"SELECT DISTINCT display_name FROM message_events",
|
||||
)
|
||||
found: set[str] = set()
|
||||
with connection:
|
||||
for query in queries:
|
||||
try:
|
||||
rows = connection.execute(query)
|
||||
except sqlite3.Error:
|
||||
continue
|
||||
found.update(str(row[0]) for row in rows if row[0])
|
||||
connection.close()
|
||||
return found
|
||||
|
||||
|
||||
def _database_groups(path: Path) -> set[str]:
|
||||
"""Every real group id the bot has seen, in both spellings.
|
||||
|
||||
Both, because they are the same group written two ways: /v1/groups
|
||||
reports "group.<base64>" and an inbound envelope carries the id that
|
||||
base64 decodes to. A check that knew only the first would have missed the
|
||||
one that was sitting in tests/test_config.py.
|
||||
"""
|
||||
if not path.is_file():
|
||||
return set()
|
||||
try:
|
||||
connection = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
|
||||
except sqlite3.Error:
|
||||
return set()
|
||||
queries = (
|
||||
"SELECT DISTINCT group_id FROM group_meta",
|
||||
"SELECT DISTINCT group_id FROM message_events",
|
||||
)
|
||||
found: set[str] = set()
|
||||
with connection:
|
||||
for query in queries:
|
||||
try:
|
||||
rows = connection.execute(query)
|
||||
except sqlite3.Error:
|
||||
continue
|
||||
found.update(str(row[0]) for row in rows if row[0])
|
||||
connection.close()
|
||||
inner: set[str] = set()
|
||||
for group in found:
|
||||
payload = group.removeprefix("group.")
|
||||
# The leading run as well as the whole id: a log line quoted into a
|
||||
# commit message says "group.<first few chars>..." and stops, and
|
||||
# matching only the full id let exactly that through once.
|
||||
inner.add(payload[:PREFIX])
|
||||
try:
|
||||
inner.add(base64.b64decode(payload, validate=True).decode("utf-8"))
|
||||
except ValueError, UnicodeDecodeError:
|
||||
continue
|
||||
return found | inner
|
||||
|
||||
|
||||
def _env_values(path: Path) -> set[str]:
|
||||
"""Phone numbers, group ids and inviters from the deployment's .env."""
|
||||
if not path.is_file():
|
||||
return set()
|
||||
interesting = {"PHONE_NUMBER", "GROUP_IDS", "GROUP_ID", "TRUSTED_INVITERS"}
|
||||
found: set[str] = set()
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
key, _, value = line.partition("=")
|
||||
if key.strip() in interesting:
|
||||
found.update(part.strip() for part in value.split(",") if part.strip())
|
||||
return found
|
||||
|
||||
|
||||
def forbidden(permitted: set[str]) -> tuple[set[str], list[str]]:
|
||||
"""Every literal that must not be committed, and where they came from.
|
||||
|
||||
The sources are all outside the repository on purpose. A list of real
|
||||
names kept *in* the repository to check against would be the leak it is
|
||||
meant to prevent.
|
||||
"""
|
||||
pack = os.environ.get("PHOTO_PACK_DIR", "").strip()
|
||||
directory = (
|
||||
Path(pack)
|
||||
if pack
|
||||
else Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
|
||||
/ "signal-bot"
|
||||
/ "pack"
|
||||
)
|
||||
sources: list[str] = []
|
||||
words: set[str] = set()
|
||||
for label, found in (
|
||||
(f"pack manifest ({directory})", _pack_names(directory)),
|
||||
("message database", _database_names(REPO / "signal_bot.sqlite3")),
|
||||
("group ids", _database_groups(REPO / "signal_bot.sqlite3")),
|
||||
(".env", _env_values(REPO / ".env")),
|
||||
):
|
||||
if found:
|
||||
sources.append(label)
|
||||
words |= found
|
||||
return {
|
||||
word.lower() for word in words if len(word) >= MIN_NAME and word.lower() not in permitted
|
||||
}, sources
|
||||
135
scripts/prime_profile.sh
Executable file
135
scripts/prime_profile.sh
Executable 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 "$@"
|
||||
@ -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
64
scripts/selftest.sh
Executable 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 "$@"
|
||||
22
scripts/signal-api-watchdog.service
Normal file
22
scripts/signal-api-watchdog.service
Normal 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
|
||||
15
scripts/signal-api-watchdog.timer
Normal file
15
scripts/signal-api-watchdog.timer
Normal 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
|
||||
52
scripts/signal-bot.service
Normal file
52
scripts/signal-bot.service
Normal 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
179
scripts/signal_api_watchdog.sh
Executable 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
229
scripts/test_watchdog.sh
Executable 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 "$@"
|
||||
@ -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__":
|
||||
|
||||
@ -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"
|
||||
]
|
||||
}
|
||||
|
||||
@ -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
130
signal_bot/announce.py
Normal 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)
|
||||
@ -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
205
signal_bot/bot.py
Normal 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
102
signal_bot/changelog.py
Normal 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)
|
||||
@ -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
173
signal_bot/config_env.py
Normal 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(),
|
||||
)
|
||||
@ -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"
|
||||
|
||||
@ -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
244
signal_bot/discovery.py
Normal 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)
|
||||
@ -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
32
signal_bot/endpoints.py
Normal 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
|
||||
60
signal_bot/envelope_shape.py
Normal file
60
signal_bot/envelope_shape.py
Normal 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
118
signal_bot/folding.py
Normal 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
158
signal_bot/groups.py
Normal 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.WTI5dVptbG5...`` decodes to ``Y29uZmlnLWdy...``, 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
139
signal_bot/help_command.py
Normal 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)
|
||||
@ -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
172
signal_bot/liveness.py
Normal 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,
|
||||
)
|
||||
41
signal_bot/logging_setup.py
Normal file
41
signal_bot/logging_setup.py
Normal 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
170
signal_bot/membership.py
Normal 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)
|
||||
@ -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
155
signal_bot/pack.py
Normal 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 basia"
|
||||
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
111
signal_bot/pack_command.py
Normal 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
243
signal_bot/pack_load.py
Normal 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
2141
signal_bot/popes.json
Normal file
File diff suppressed because it is too large
Load Diff
64
signal_bot/popes_command.py
Normal file
64
signal_bot/popes_command.py
Normal 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
119
signal_bot/portcheck.py
Normal 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
130
signal_bot/portraits.py
Normal 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
48
signal_bot/quoting.py
Normal 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 "")
|
||||
@ -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
133
signal_bot/reporting.py
Normal 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
61
signal_bot/roster.py
Normal 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
99
signal_bot/schema.py
Normal 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
109
signal_bot/selftest.py
Normal 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
116
signal_bot/startup.py
Normal 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
161
signal_bot/startup_retry.py
Normal 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
|
||||
8
signal_bot/stats/__init__.py
Normal file
8
signal_bot/stats/__init__.py
Normal 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.
|
||||
"""
|
||||
94
signal_bot/stats/backfill.py
Normal file
94
signal_bot/stats/backfill.py
Normal 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
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user