# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """The image commands, and the alias tables people actually type.""" from __future__ import annotations import json from pathlib import Path from typing import TYPE_CHECKING, Final if TYPE_CHECKING: from collections.abc import Sequence from signal_bot.decorators import Decorator 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") 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]) -> Handler: """Build a handler that posts one random image from a JSON image API.""" async def handler(ctx: CommandContext) -> None: encoded = await fetcher.fetch_base64(api_url, url_path) await ctx.transport.send_image(encoded, ctx.group_id) 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 the cat and dog commands 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 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) if decorate is not None: handler = decorate(handler) registry.register(name, table[name], handler)