signal-bot/signal_bot/store.py
Krzysztof kuhy Rudnicki 6bde3493a4 feat: rewrite the bot so it runs, and gate it like the other repos
The bot did not work. `run.sh` started a FastAPI app whose
`@app.on_event("startup")` awaited `asyncio.gather()` on two infinite
tasks, so uvicorn never finished starting up and no HTTP was ever served;
the readme's `python main.py` was a no-op with no `__main__` block and no
`uvicorn.run()` call. All three CI workflows were red, one referencing an
`environment.yml` that does not exist.

Rewritten as a package behind an injectable transport seam, which is what
makes the offline environment possible.

Bugs fixed:
- startup deadlock: lifespan spawns the loops instead of awaiting them
- sticker filter read dataMessage.sticker even on syncMessage envelopes, so
  the account's own stickers were never filtered (e038772, 53028cc, 07fa90d,
  2416cef all fought this symptom)
- no websocket reconnect: a container restart killed the bot silently
- blocking `requests` inside async functions stalled the event loop
- every counted message DMed the whole tally to the bot itself
- images were written to CWD under a filename taken from the remote URL
- one global 10s cooldown shared across all users and commands
- dead code: RECEIVE_URL, get_attachments (no call site), USER_MESSAGE_COUNT
- .env.sample declared PRIMARY/SECONDARY_PHONE_NUMBER and MODE, none read

Scoping is now an enforced invariant. A linked device receives every DM and
every group on the account; GROUP_ID was the only thing narrowing that and
defaulted to "". Config refuses to start unscoped, direct messages are
dropped explicitly rather than by a falsy check, and a scenario asserts that
DMs and other groups produce zero outbound messages.

Offline environment: fake_signal/ serves the real protocol surface, so the
unmodified bot connects to it by pointing API_BASE_URL at it. scripts/e2e.sh
boots both, replays 7 scenarios and exits non-zero on mismatch. A local
Signal server is not achievable (signal-cli compiles its endpoints and trust
store in; Signal-Server needs FoundationDB), so faking this boundary is the
only way to test every feature without an account.

Transport pinned to bbernhard/signal-cli-rest-api:0.100 with
MODE=json-rpc-native. The readme pinned 0.167-dev; the dev tag series counts
separately, so that was older than 0.100, not newer. /v1/receive is only a
WebSocket in a json-rpc mode, so the mode is verified at startup.

Repo standards: ruff select=ALL, mypy --strict, 189 tests at 100% branch
coverage, 250-line cap, exact pins at newest stable, shared gates delegated
to ~/utils, one CI workflow replacing three red ones. No noqa, no
type: ignore, no coverage omits anywhere.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013yaBT45KhHqxTKVCTA87iy
2026-08-29 13:05:42 +02:00

180 lines
6.1 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""SQLite persistence for tallies, cooldowns, daily limits and votes.
Everything the bot remembers lives here so a restart before the daily report
does not lose the day. The original bot kept all of it in module globals.
"""
from __future__ import annotations
import contextlib
import sqlite3
from dataclasses import dataclass
from typing import TYPE_CHECKING, Self
if TYPE_CHECKING:
from collections.abc import Iterator
from types import TracebackType
_SCHEMA = """
CREATE TABLE IF NOT EXISTS message_counts (
uuid TEXT PRIMARY KEY,
display_name TEXT NOT NULL,
count INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS command_uses (
user_uuid TEXT NOT NULL,
command TEXT NOT NULL,
used_at REAL NOT NULL,
PRIMARY KEY (user_uuid, command)
);
CREATE TABLE IF NOT EXISTS daily_uses (
user_uuid TEXT NOT NULL,
command TEXT NOT NULL,
day TEXT NOT NULL,
uses INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (user_uuid, command, day)
);
CREATE TABLE IF NOT EXISTS votes (
command TEXT NOT NULL,
voter_uuid TEXT NOT NULL,
voted_at REAL NOT NULL,
PRIMARY KEY (command, voter_uuid)
);
"""
@dataclass(frozen=True, slots=True)
class Tally:
"""One person's message count for the current reporting period."""
uuid: str
display_name: str
count: int
class Store:
"""Thin, synchronous SQLite wrapper. All state the bot keeps lives here."""
def __init__(self, path: str) -> None:
"""Open (or create) the database at path and apply the schema."""
self._conn = sqlite3.connect(path)
self._conn.row_factory = sqlite3.Row
self._conn.executescript(_SCHEMA)
self._conn.commit()
def __enter__(self) -> Self:
"""Enter a context manager that closes the connection on exit."""
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
"""Close the underlying connection."""
self.close()
def close(self) -> None:
"""Close the underlying connection."""
self._conn.close()
# -- message tallies ---------------------------------------------------
def increment(self, uuid: str, display_name: str) -> None:
"""Add one to a person's tally, creating the row when new."""
self._conn.execute(
"""
INSERT INTO message_counts (uuid, display_name, count)
VALUES (?, ?, 1)
ON CONFLICT(uuid) DO UPDATE SET
count = count + 1,
display_name = excluded.display_name
""",
(uuid, display_name),
)
self._conn.commit()
def tallies(self) -> list[Tally]:
"""Return every tally, highest count first."""
rows = self._conn.execute(
"SELECT uuid, display_name, count FROM message_counts "
"ORDER BY count DESC, display_name ASC"
).fetchall()
return [Tally(r["uuid"], r["display_name"], r["count"]) for r in rows]
def reset_tallies(self) -> None:
"""Clear every tally, as the daily report does after publishing."""
self._conn.execute("DELETE FROM message_counts")
self._conn.commit()
# -- per-user, per-command rate limiting -------------------------------
def record_use(self, user_uuid: str, command: str, now: float, day: str) -> None:
"""Record one successful use for both cooldown and daily-limit checks."""
self._conn.execute(
"INSERT INTO command_uses (user_uuid, command, used_at) VALUES (?, ?, ?) "
"ON CONFLICT(user_uuid, command) DO UPDATE SET used_at = excluded.used_at",
(user_uuid, command, now),
)
self._conn.execute(
"""
INSERT INTO daily_uses (user_uuid, command, day, uses)
VALUES (?, ?, ?, 1)
ON CONFLICT(user_uuid, command, day) DO UPDATE SET uses = uses + 1
""",
(user_uuid, command, day),
)
self._conn.commit()
def last_used(self, user_uuid: str, command: str) -> float | None:
"""Return when this user last ran this command, or None."""
row = self._conn.execute(
"SELECT used_at FROM command_uses WHERE user_uuid = ? AND command = ?",
(user_uuid, command),
).fetchone()
return None if row is None else float(row["used_at"])
def uses_today(self, user_uuid: str, command: str, day: str) -> int:
"""Return how many times this user ran this command on the given day."""
row = self._conn.execute(
"SELECT uses FROM daily_uses WHERE user_uuid = ? AND command = ? AND day = ?",
(user_uuid, command, day),
).fetchone()
return 0 if row is None else int(row["uses"])
# -- vote gating -------------------------------------------------------
def add_vote(self, command: str, voter_uuid: str, now: float) -> None:
"""Record one vote, ignoring a repeat vote from the same person."""
self._conn.execute(
"INSERT INTO votes (command, voter_uuid, voted_at) VALUES (?, ?, ?) "
"ON CONFLICT(command, voter_uuid) DO NOTHING",
(command, voter_uuid, now),
)
self._conn.commit()
def count_votes(self, command: str, not_before: float) -> int:
"""Return how many votes for command are still inside the window."""
row = self._conn.execute(
"SELECT COUNT(*) AS n FROM votes WHERE command = ? AND voted_at >= ?",
(command, not_before),
).fetchone()
return int(row["n"])
def clear_votes(self, command: str) -> None:
"""Drop every vote for a command, after it fires or expires."""
self._conn.execute("DELETE FROM votes WHERE command = ?", (command,))
self._conn.commit()
@contextlib.contextmanager
def open_store(path: str) -> Iterator[Store]:
"""Open a Store as a context manager."""
store = Store(path)
try:
yield store
finally:
store.close()