signal-bot/signal_bot/animals.py
Krzysztof kuhy Rudnicki 48957a105d
Some checks are pending
CI / check (push) Waiting to run
feat: serve several photo albums at once, each scoped to its own groups
You asked for !add_photo in testbot without the real album being reachable
there. One album cannot do that: its people.json "groups" list *is* the
privacy guarantee, so making the commands exist in a second group necessarily
makes the real photos postable there. So the bot now loads several albums.

PHOTO_PACK_DIR takes a comma-separated list, the spelling GROUP_IDS and
TRUSTED_INVITERS already use. Each album carries its own group scope, its own
people, its own tags and its own custom labels; they share nothing but the
process they run in.

That makes trigger collisions between albums legal for the first time, and the
registry had to learn it. Two albums are two different sets of people and both
may reasonably call somebody "!alfa" -- no message can ever mean both, because
a command a group is not scoped to is not a command there at all. So a trigger
may be claimed more than once, and DuplicateTriggerError now fires only where
the group sets *overlap*. Overlapping albums are refused at startup rather than
resolved by registration order: a coin toss about which private album receives
a photo is the outcome this whole design exists to prevent.

Two consequences worth naming:

- registry.resolve() takes an optional group. Without one it still answers
  "does anything claim this word", which is what pack_add's mint check wants;
  with one it answers "what runs here", which is what the dispatcher wants.
  resolve_with_args no longer resolves-then-checks, because with two claimants
  the first one found may be the wrong group's.
- CommandContext moved to signal_bot/context.py to keep registry.py under the
  250-line cap. A filing change: that file is "which word runs what", this one
  is "what the thing that runs may do".

DOCS-add-photo.md is likewise a split, not new prose -- DOCS-photo-pack.md had
grown past the cap and the ingest path is its own subject now.

Verified live: the unit serves both albums, the real group resolves its 13
album commands and testbot its 7, and !losowe / !alfa / !dodaj all fire in
testbot through the live dispatcher. 997 tests, 100% branch coverage, 28 e2e
scenarios.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JqqE22jp94B1ypwxppdr1o
2026-08-31 11:58:50 +02:00

128 lines
4.6 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The image commands, and the alias tables people actually type."""
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
from signal_bot.context import CommandContext
from signal_bot.decorators import Decorator
from signal_bot.http_client import ImageFetcher
from signal_bot.registry import CommandRegistry, Handler
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.
Aliases live in JSON rather than in source so that the styled Unicode
variants are data the linter never has to reason about.
"""
document = json.loads(path.read_text(encoding="utf-8"))
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],
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:
url = paged_url(api_url, page_limit)
encoded = await fetcher.fetch_base64(url, url_path, rewrite)
await ctx.reply_image(encoded)
return handler
def register_animal_commands(
registry: CommandRegistry,
fetcher: ImageFetcher,
*,
decorate: Decorator | None = None,
aliases: dict[str, list[str]] | None = None,
endpoints: dict[str, str] | None = None,
) -> None:
"""Register every image command on a registry.
Args:
registry: Registry to populate.
fetcher: Injected image fetcher.
decorate: Optional callable applied to each handler, used to attach
the cooldown gate without hard-wiring policy into the commands.
aliases: Trigger table. Defaults to the shipped aliases.json.
endpoints: Command name to image-API URL. Defaults to the real
public APIs; the offline environment points these at itself.
"""
table = load_aliases() if aliases is None else aliases
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, source.description)