mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-29 20:00:36 +01:00
Compare commits
No commits in common. "bbf18db938b5c9b321fe645869f11e0ce503f95e" and "1c25469f04f716fd2e2aff4a530bc7212a738a90" have entirely different histories.
bbf18db938
...
1c25469f04
@ -16,11 +16,6 @@ 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
|
is not a `##` heading or a `-` bullet under one is ignored, so prose between
|
||||||
releases is free.
|
releases is free.
|
||||||
|
|
||||||
## 0.0.3 — Klemens I
|
|
||||||
|
|
||||||
- nowa komenda `!gekon` — bot wrzuca losowe zdjęcie gekona; działa też
|
|
||||||
`!gecko`, `!geckon`, `!geko`, `!gekony` i `!geckos`
|
|
||||||
|
|
||||||
## 0.0.2 — Anaklet
|
## 0.0.2 — Anaklet
|
||||||
|
|
||||||
- bot odpowiada teraz na konkretną wiadomość, cytując ją — w ruchliwej
|
- bot odpowiada teraz na konkretną wiadomość, cytując ją — w ruchliwej
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
# signal-bot
|
# signal-bot
|
||||||
|
|
||||||
A Signal group bot: `!cat` / `!dog` / `!gekon` image commands and a daily tally.
|
A Signal group bot: `!cat` / `!dog` image commands and a daily message tally.
|
||||||
|
|
||||||
Runs on its **own registered Signal number** (or, if you prefer, as a linked
|
Runs on its **own registered Signal number** (or, if you prefer, as a linked
|
||||||
device on an existing account) via
|
device on an existing account) via
|
||||||
@ -196,10 +196,10 @@ connection to Signal is dead, a two-minute timer restarts the container, and
|
|||||||
|---|---|
|
|---|---|
|
||||||
| cat | `!kot` `!koty` `!kots` `!cat` `!cats` `!meow` `!miau` + styled variants |
|
| cat | `!kot` `!koty` `!kots` `!cat` `!cats` `!meow` `!miau` + styled variants |
|
||||||
| dog | `!pies` `!psy` `!dog` `!dogs` `!woof` `!szczek` + styled variants |
|
| dog | `!pies` `!psy` `!dog` `!dogs` `!woof` `!szczek` + styled variants |
|
||||||
| gecko | `!gekon` `!gekony` `!geko` `!gecko` `!geckon` `!geckos` |
|
|
||||||
|
|
||||||
Aliases live in `signal_bot/aliases.json`, not in source. Each command is rate-limited
|
Aliases live in `signal_bot/aliases.json`, not in source. Each command is
|
||||||
per user, per command — the original bot shared one 10-second window across everybody.
|
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
|
`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;
|
once N distinct people ask, within a window). Both are generic and tested;
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
||||||
"""Local stand-ins for the image APIs, shaped like the real responses."""
|
"""Local stand-ins for thecatapi and dog.ceo, shaped like the real responses."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@ -27,22 +27,8 @@ def build_fixture_router() -> APIRouter:
|
|||||||
async def dog_api(request: Request) -> dict[str, str]:
|
async def dog_api(request: Request) -> dict[str, str]:
|
||||||
return {"message": _image_url(request)}
|
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]}]}
|
|
||||||
|
|
||||||
@router.get("/image.png")
|
@router.get("/image.png")
|
||||||
async def image() -> Response:
|
async def image() -> Response:
|
||||||
return Response(content=PIXEL_PNG, media_type="image/png")
|
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
|
return router
|
||||||
|
|||||||
@ -1,5 +0,0 @@
|
|||||||
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 }
|
|
||||||
@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "signal-bot"
|
name = "signal-bot"
|
||||||
version = "0.0.3"
|
version = "0.0.2"
|
||||||
description = "A Signal group bot: image commands and daily message tallies."
|
description = "A Signal group bot: image commands and daily message tallies."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|||||||
@ -129,7 +129,6 @@ main() {
|
|||||||
DATABASE_PATH="${TEMP_DIR}/e2e.sqlite3" \
|
DATABASE_PATH="${TEMP_DIR}/e2e.sqlite3" \
|
||||||
CAT_API_URL="${FAKE_URL}/_fixtures/cat-api" \
|
CAT_API_URL="${FAKE_URL}/_fixtures/cat-api" \
|
||||||
DOG_API_URL="${FAKE_URL}/_fixtures/dog-api" \
|
DOG_API_URL="${FAKE_URL}/_fixtures/dog-api" \
|
||||||
GECKO_API_URL="${FAKE_URL}/_fixtures/gecko-api" \
|
|
||||||
BIND_PORT="$BOT_PORT" \
|
BIND_PORT="$BOT_PORT" \
|
||||||
SILENCE_SECONDS=0 \
|
SILENCE_SECONDS=0 \
|
||||||
"$PYTHON" -m signal_bot &
|
"$PYTHON" -m signal_bot &
|
||||||
|
|||||||
@ -7,8 +7,5 @@
|
|||||||
"dog": [
|
"dog": [
|
||||||
"!pies", "!psy", "!dog", "!dogs", "!woof", "!szczek",
|
"!pies", "!psy", "!dog", "!dogs", "!woof", "!szczek",
|
||||||
"!𝗽𝗶𝗲𝘀", "!͓̽p͓̽i͓̽e͓̽s͓̽"
|
"!𝗽𝗶𝗲𝘀", "!͓̽p͓̽i͓̽e͓̽s͓̽"
|
||||||
],
|
|
||||||
"gecko": [
|
|
||||||
"!gekon", "!gekony", "!geko", "!gecko", "!geckon", "!geckos"
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,13 +4,9 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import secrets
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import TYPE_CHECKING, Final
|
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:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
|
|
||||||
@ -18,53 +14,14 @@ if TYPE_CHECKING:
|
|||||||
from signal_bot.http_client import ImageFetcher
|
from signal_bot.http_client import ImageFetcher
|
||||||
from signal_bot.registry import CommandContext, CommandRegistry, Handler
|
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")
|
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, ...]
|
|
||||||
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")),
|
|
||||||
"dog": ImageSource(DEFAULT_DOG_API_URL, ("message",)),
|
|
||||||
"gecko": ImageSource(
|
|
||||||
DEFAULT_GECKO_API_URL,
|
|
||||||
("results", 0, "photos", 0, "url"),
|
|
||||||
("/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]]:
|
def load_aliases(path: Path = ALIAS_FILE) -> dict[str, list[str]]:
|
||||||
"""Load the trigger table.
|
"""Load the trigger table.
|
||||||
|
|
||||||
@ -75,18 +32,11 @@ 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("_")}
|
return {name: list(triggers) for name, triggers in document.items() if not name.startswith("_")}
|
||||||
|
|
||||||
|
|
||||||
def image_handler(
|
def image_handler(fetcher: ImageFetcher, api_url: str, url_path: Sequence[str | int]) -> 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."""
|
"""Build a handler that posts one random image from a JSON image API."""
|
||||||
|
|
||||||
async def handler(ctx: CommandContext) -> None:
|
async def handler(ctx: CommandContext) -> None:
|
||||||
url = paged_url(api_url, page_limit)
|
encoded = await fetcher.fetch_base64(api_url, url_path)
|
||||||
encoded = await fetcher.fetch_base64(url, url_path, rewrite)
|
|
||||||
await ctx.reply_image(encoded)
|
await ctx.reply_image(encoded)
|
||||||
|
|
||||||
return handler
|
return handler
|
||||||
@ -100,7 +50,7 @@ def register_animal_commands(
|
|||||||
aliases: dict[str, list[str]] | None = None,
|
aliases: dict[str, list[str]] | None = None,
|
||||||
endpoints: dict[str, str] | None = None,
|
endpoints: dict[str, str] | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Register every image command on a registry.
|
"""Register the cat and dog commands on a registry.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
registry: Registry to populate.
|
registry: Registry to populate.
|
||||||
@ -112,12 +62,14 @@ def register_animal_commands(
|
|||||||
public APIs; the offline environment points these at itself.
|
public APIs; the offline environment points these at itself.
|
||||||
"""
|
"""
|
||||||
table = load_aliases() if aliases is None else aliases
|
table = load_aliases() if aliases is None else aliases
|
||||||
overrides = endpoints or {}
|
urls = {"cat": CAT_API_URL, "dog": DOG_API_URL} | (endpoints or {})
|
||||||
for name, source in SOURCES.items():
|
paths: dict[str, tuple[str | int, ...]] = {
|
||||||
api_url = overrides.get(name, source.api_url)
|
"cat": CAT_URL_PATH,
|
||||||
handler = image_handler(
|
"dog": DOG_URL_PATH,
|
||||||
fetcher, api_url, source.url_path, source.rewrite, source.page_limit
|
}
|
||||||
)
|
for name, api_url in urls.items():
|
||||||
|
url_path = paths[name]
|
||||||
|
handler = image_handler(fetcher, api_url, url_path)
|
||||||
if decorate is not None:
|
if decorate is not None:
|
||||||
handler = decorate(handler)
|
handler = decorate(handler)
|
||||||
registry.register(name, table[name], handler)
|
registry.register(name, table[name], handler)
|
||||||
|
|||||||
@ -39,9 +39,6 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
COOLDOWN_MESSAGE = "BEEP BOOP POCZEKAJ {seconds} SEKUND."
|
COOLDOWN_MESSAGE = "BEEP BOOP POCZEKAJ {seconds} SEKUND."
|
||||||
HTTP_TIMEOUT_SECONDS = 30.0
|
HTTP_TIMEOUT_SECONDS = 30.0
|
||||||
# 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)"
|
|
||||||
|
|
||||||
|
|
||||||
def now_local() -> dt.datetime:
|
def now_local() -> dt.datetime:
|
||||||
@ -119,7 +116,7 @@ def build_bot(
|
|||||||
registry,
|
registry,
|
||||||
ImageFetcher(client),
|
ImageFetcher(client),
|
||||||
decorate=cooldown(config.cooldown_seconds, COOLDOWN_MESSAGE),
|
decorate=cooldown(config.cooldown_seconds, COOLDOWN_MESSAGE),
|
||||||
endpoints=config.image_api_urls,
|
endpoints={"cat": config.cat_api_url, "dog": config.dog_api_url},
|
||||||
)
|
)
|
||||||
dispatcher = Dispatcher(
|
dispatcher = Dispatcher(
|
||||||
config=config,
|
config=config,
|
||||||
@ -210,7 +207,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|||||||
the HTTP app never began serving.
|
the HTTP app never began serving.
|
||||||
"""
|
"""
|
||||||
config = load_config()
|
config = load_config()
|
||||||
client = httpx.AsyncClient(timeout=HTTP_TIMEOUT_SECONDS, headers={"User-Agent": USER_AGENT})
|
client = httpx.AsyncClient(timeout=HTTP_TIMEOUT_SECONDS)
|
||||||
runtime = await create_runtime(config, client)
|
runtime = await create_runtime(config, client)
|
||||||
runtime.start()
|
runtime.start()
|
||||||
logger.info(
|
logger.info(
|
||||||
|
|||||||
@ -38,16 +38,6 @@ DEFAULT_REPORT_MINUTE: Final = 37
|
|||||||
DEFAULT_COOLDOWN_SECONDS: Final = 10
|
DEFAULT_COOLDOWN_SECONDS: Final = 10
|
||||||
DEFAULT_CAT_API_URL: Final = "https://api.thecatapi.com/v1/images/search"
|
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_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"
|
|
||||||
)
|
|
||||||
DEFAULT_BIND_HOST: Final = "127.0.0.1"
|
DEFAULT_BIND_HOST: Final = "127.0.0.1"
|
||||||
# Not 8000: that port is a magnet for unrelated dev servers and was already
|
# 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
|
# taken here by a long-running enforcer. 8137 sits below the ephemeral range
|
||||||
@ -83,7 +73,6 @@ class Config:
|
|||||||
# without the bot knowing it is not talking to the real APIs.
|
# without the bot knowing it is not talking to the real APIs.
|
||||||
cat_api_url: str = DEFAULT_CAT_API_URL
|
cat_api_url: str = DEFAULT_CAT_API_URL
|
||||||
dog_api_url: str = DEFAULT_DOG_API_URL
|
dog_api_url: str = DEFAULT_DOG_API_URL
|
||||||
gecko_api_url: str = DEFAULT_GECKO_API_URL
|
|
||||||
# Where the /healthz readiness probe binds. Read here rather than in
|
# Where the /healthz readiness probe binds. Read here rather than in
|
||||||
# __main__ so that .env governs it: __main__ runs before anything has
|
# __main__ so that .env governs it: __main__ runs before anything has
|
||||||
# loaded a .env file, so an os.getenv() there would silently ignore it.
|
# loaded a .env file, so an os.getenv() there would silently ignore it.
|
||||||
@ -165,11 +154,6 @@ class Config:
|
|||||||
"""REST endpoint listing the groups this account knows about."""
|
"""REST endpoint listing the groups this account knows about."""
|
||||||
return f"{self.api_base_url}/v1/groups/{self.phone_number}"
|
return f"{self.api_base_url}/v1/groups/{self.phone_number}"
|
||||||
|
|
||||||
@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}
|
|
||||||
|
|
||||||
|
|
||||||
def _require(env: dict[str, str], key: str) -> str:
|
def _require(env: dict[str, str], key: str) -> str:
|
||||||
"""Return a non-empty environment value or raise ConfigError."""
|
"""Return a non-empty environment value or raise ConfigError."""
|
||||||
@ -237,7 +221,6 @@ def load_config(env: dict[str, str] | None = None, *, use_dotenv: bool = True) -
|
|||||||
cooldown_seconds=_positive_int(env, "COOLDOWN_SECONDS", DEFAULT_COOLDOWN_SECONDS),
|
cooldown_seconds=_positive_int(env, "COOLDOWN_SECONDS", DEFAULT_COOLDOWN_SECONDS),
|
||||||
cat_api_url=env.get("CAT_API_URL", "").strip() or DEFAULT_CAT_API_URL,
|
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,
|
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,
|
|
||||||
bind_host=env.get("BIND_HOST", "").strip() or DEFAULT_BIND_HOST,
|
bind_host=env.get("BIND_HOST", "").strip() or DEFAULT_BIND_HOST,
|
||||||
bind_port=bind_port,
|
bind_port=bind_port,
|
||||||
log_level=log_level,
|
log_level=log_level,
|
||||||
|
|||||||
@ -27,23 +27,12 @@ class ImageFetcher:
|
|||||||
"""Store the injected HTTP client."""
|
"""Store the injected HTTP client."""
|
||||||
self._client = client
|
self._client = client
|
||||||
|
|
||||||
async def fetch_base64(
|
async def fetch_base64(self, api_url: str, url_path: Sequence[str | int]) -> str:
|
||||||
self,
|
|
||||||
api_url: str,
|
|
||||||
url_path: Sequence[str | int],
|
|
||||||
rewrite: tuple[str, str] | None = None,
|
|
||||||
) -> str:
|
|
||||||
"""Fetch an image and return it as base64.
|
"""Fetch an image and return it as base64.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
api_url: JSON endpoint that names an image.
|
api_url: JSON endpoint that names an image.
|
||||||
url_path: Keys/indices to walk in the JSON to reach the image URL.
|
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.
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The image bytes, base64-encoded.
|
The image bytes, base64-encoded.
|
||||||
@ -54,8 +43,6 @@ class ImageFetcher:
|
|||||||
response = await self._client.get(api_url)
|
response = await self._client.get(api_url)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
image_url = _walk(response.json(), url_path)
|
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
|
# 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.
|
# remote URL's last path segment and wrote it into the process CWD.
|
||||||
|
|||||||
@ -28,7 +28,7 @@ PATCHES_PER_MINOR: Final = 8
|
|||||||
|
|
||||||
# Which release this build is. Bump by one per release; everything else,
|
# Which release this build is. Bump by one per release; everything else,
|
||||||
# including the version string in pyproject.toml, follows from it.
|
# including the version string in pyproject.toml, follows from it.
|
||||||
RELEASE_ORDINAL: Final = 4
|
RELEASE_ORDINAL: Final = 3
|
||||||
|
|
||||||
_POPES_FILE: Final = Path(__file__).with_name("popes.json")
|
_POPES_FILE: Final = Path(__file__).with_name("popes.json")
|
||||||
|
|
||||||
|
|||||||
@ -11,9 +11,7 @@ import pytest
|
|||||||
|
|
||||||
from signal_bot.animals import (
|
from signal_bot.animals import (
|
||||||
ALIAS_FILE,
|
ALIAS_FILE,
|
||||||
INATURALIST_PAGE_LIMIT,
|
|
||||||
load_aliases,
|
load_aliases,
|
||||||
paged_url,
|
|
||||||
register_animal_commands,
|
register_animal_commands,
|
||||||
)
|
)
|
||||||
from signal_bot.decorators import cooldown
|
from signal_bot.decorators import cooldown
|
||||||
@ -32,20 +30,12 @@ if TYPE_CHECKING:
|
|||||||
IMAGE = b"png-bytes"
|
IMAGE = b"png-bytes"
|
||||||
|
|
||||||
|
|
||||||
def _fetcher(seen: list[str] | None = None) -> ImageFetcher:
|
def _fetcher() -> ImageFetcher:
|
||||||
"""Build a fetcher over the three fixture APIs, optionally recording URLs."""
|
|
||||||
|
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
url = str(request.url)
|
if "thecatapi" in str(request.url):
|
||||||
if seen is not None:
|
|
||||||
seen.append(url)
|
|
||||||
if "thecatapi" in url:
|
|
||||||
return httpx.Response(200, json=[{"url": "https://cdn/cat.png"}])
|
return httpx.Response(200, json=[{"url": "https://cdn/cat.png"}])
|
||||||
if "dog.ceo" in url:
|
if "dog.ceo" in str(request.url):
|
||||||
return httpx.Response(200, json={"message": "https://cdn/dog.png"})
|
return httpx.Response(200, json={"message": "https://cdn/dog.png"})
|
||||||
if "inaturalist" in url:
|
|
||||||
photo = {"url": "https://cdn/photos/1/square.jpeg"}
|
|
||||||
return httpx.Response(200, json={"results": [{"photos": [photo]}]})
|
|
||||||
return httpx.Response(200, content=IMAGE)
|
return httpx.Response(200, content=IMAGE)
|
||||||
|
|
||||||
return ImageFetcher(httpx.AsyncClient(transport=httpx.MockTransport(handler)))
|
return ImageFetcher(httpx.AsyncClient(transport=httpx.MockTransport(handler)))
|
||||||
@ -73,7 +63,6 @@ def test_alias_file_ships_with_the_package() -> None:
|
|||||||
aliases = load_aliases()
|
aliases = load_aliases()
|
||||||
assert "!cat" in aliases["cat"]
|
assert "!cat" in aliases["cat"]
|
||||||
assert "!pies" in aliases["dog"]
|
assert "!pies" in aliases["dog"]
|
||||||
assert "!gekon" in aliases["gecko"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_comment_keys_are_skipped(tmp_path: Path) -> None:
|
def test_comment_keys_are_skipped(tmp_path: Path) -> None:
|
||||||
@ -88,12 +77,9 @@ def test_styled_unicode_aliases_resolve() -> None:
|
|||||||
assert registry.resolve("!\U0001d5f8\U0001d5fc\U0001d601") is not None
|
assert registry.resolve("!\U0001d5f8\U0001d5fc\U0001d601") is not None
|
||||||
assert registry.resolve("!miau").name == "cat"
|
assert registry.resolve("!miau").name == "cat"
|
||||||
assert registry.resolve("!szczek").name == "dog"
|
assert registry.resolve("!szczek").name == "dog"
|
||||||
assert registry.resolve("!gekon").name == "gecko"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(("trigger", "name"), [("!cat", "cat"), ("!dog", "dog")])
|
||||||
("trigger", "name"), [("!cat", "cat"), ("!dog", "dog"), ("!gekon", "gecko")]
|
|
||||||
)
|
|
||||||
async def test_commands_post_an_image(
|
async def test_commands_post_an_image(
|
||||||
transport: FakeTransport, store: Store, config: Config, trigger: str, name: str
|
transport: FakeTransport, store: Store, config: Config, trigger: str, name: str
|
||||||
) -> None:
|
) -> None:
|
||||||
@ -120,60 +106,6 @@ async def test_decorator_is_applied_when_given(
|
|||||||
|
|
||||||
def test_custom_alias_table_is_honoured() -> None:
|
def test_custom_alias_table_is_honoured() -> None:
|
||||||
registry = CommandRegistry()
|
registry = CommandRegistry()
|
||||||
table = {"cat": ["!c"], "dog": ["!d"], "gecko": ["!g"]}
|
register_animal_commands(registry, _fetcher(), aliases={"cat": ["!c"], "dog": ["!d"]})
|
||||||
register_animal_commands(registry, _fetcher(), aliases=table)
|
|
||||||
assert registry.resolve("!c").name == "cat"
|
assert registry.resolve("!c").name == "cat"
|
||||||
assert registry.resolve("!cat") is None
|
assert registry.resolve("!cat") is None
|
||||||
|
|
||||||
|
|
||||||
def test_paged_url_leaves_a_source_without_a_page_limit_alone() -> None:
|
|
||||||
assert paged_url("https://api/x?a=1", None) == "https://api/x?a=1"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
("api_url", "separator"), [("https://api/x?a=1", "&"), ("https://api/x", "?")]
|
|
||||||
)
|
|
||||||
def test_paged_url_appends_a_page_with_the_right_separator(api_url: str, separator: str) -> None:
|
|
||||||
url = paged_url(api_url, 10)
|
|
||||||
prefix = f"{api_url}{separator}page="
|
|
||||||
assert url.startswith(prefix)
|
|
||||||
assert 1 <= int(url.removeprefix(prefix)) <= 10
|
|
||||||
|
|
||||||
|
|
||||||
def test_paged_url_actually_varies() -> None:
|
|
||||||
"""The regression: iNaturalist accepts order_by=random and ignores it.
|
|
||||||
|
|
||||||
0.0.3 shipped with that as the only source of variety and posted one
|
|
||||||
identical gecko every time. Twenty draws over a 10 000-page range
|
|
||||||
collide with probability far below any plausible flake budget.
|
|
||||||
"""
|
|
||||||
drawn = {paged_url("https://api/x?a=1", INATURALIST_PAGE_LIMIT) for _ in range(20)}
|
|
||||||
assert len(drawn) > 1
|
|
||||||
|
|
||||||
|
|
||||||
async def test_gecko_asks_for_the_full_size_photo(
|
|
||||||
transport: FakeTransport, store: Store, config: Config
|
|
||||||
) -> None:
|
|
||||||
"""iNaturalist names a 75px thumbnail; the group should get the real photo."""
|
|
||||||
seen: list[str] = []
|
|
||||||
registry = CommandRegistry()
|
|
||||||
register_animal_commands(registry, _fetcher(seen))
|
|
||||||
command = registry.resolve("!gecko")
|
|
||||||
assert command is not None
|
|
||||||
await command.handler(_ctx(transport, store, config, "gecko", "!gecko"))
|
|
||||||
assert "https://cdn/photos/1/large.jpeg" in seen
|
|
||||||
assert "https://cdn/photos/1/square.jpeg" not in seen
|
|
||||||
assert "page=" in seen[0]
|
|
||||||
|
|
||||||
|
|
||||||
async def test_cat_is_asked_for_without_a_page(
|
|
||||||
transport: FakeTransport, store: Store, config: Config
|
|
||||||
) -> None:
|
|
||||||
"""Only the sources that need paging get one; thecatapi is random already."""
|
|
||||||
seen: list[str] = []
|
|
||||||
registry = CommandRegistry()
|
|
||||||
register_animal_commands(registry, _fetcher(seen))
|
|
||||||
command = registry.resolve("!cat")
|
|
||||||
assert command is not None
|
|
||||||
await command.handler(_ctx(transport, store, config, "cat", "!cat"))
|
|
||||||
assert "page=" not in seen[0]
|
|
||||||
|
|||||||
@ -80,14 +80,9 @@ def test_inject_with_no_listeners_delivers_nothing(client: TestClient) -> None:
|
|||||||
def test_fixture_apis_mirror_the_real_response_shapes(client: TestClient) -> None:
|
def test_fixture_apis_mirror_the_real_response_shapes(client: TestClient) -> None:
|
||||||
cat = client.get("/_fixtures/cat-api").json()
|
cat = client.get("/_fixtures/cat-api").json()
|
||||||
dog = client.get("/_fixtures/dog-api").json()
|
dog = client.get("/_fixtures/dog-api").json()
|
||||||
gecko = client.get("/_fixtures/gecko-api").json()
|
|
||||||
assert cat[0]["url"].endswith("/_fixtures/image.png")
|
assert cat[0]["url"].endswith("/_fixtures/image.png")
|
||||||
assert dog["message"].endswith("/_fixtures/image.png")
|
assert dog["message"].endswith("/_fixtures/image.png")
|
||||||
assert gecko["results"][0]["photos"][0]["url"].endswith("/_fixtures/photos/square.png")
|
|
||||||
assert client.get("/_fixtures/image.png").content == PIXEL_PNG
|
assert client.get("/_fixtures/image.png").content == PIXEL_PNG
|
||||||
# The square URL is deliberately absent: the bot must rewrite it.
|
|
||||||
assert client.get("/_fixtures/photos/large.png").content == PIXEL_PNG
|
|
||||||
assert client.get("/_fixtures/photos/square.png").status_code == 404
|
|
||||||
|
|
||||||
|
|
||||||
def test_create_app_makes_its_own_state_when_none_given() -> None:
|
def test_create_app_makes_its_own_state_when_none_given() -> None:
|
||||||
|
|||||||
@ -85,35 +85,3 @@ async def test_image_download_error_propagates() -> None:
|
|||||||
|
|
||||||
with pytest.raises(httpx.HTTPStatusError):
|
with pytest.raises(httpx.HTTPStatusError):
|
||||||
await _fetcher(handler).fetch_base64("https://api/images/search", [0, "url"])
|
await _fetcher(handler).fetch_base64("https://api/images/search", [0, "url"])
|
||||||
|
|
||||||
|
|
||||||
async def test_rewrite_swaps_the_thumbnail_for_the_full_size_photo() -> None:
|
|
||||||
"""The URL actually downloaded is the rewritten one, not the one in the JSON."""
|
|
||||||
seen: list[str] = []
|
|
||||||
|
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
|
||||||
seen.append(str(request.url))
|
|
||||||
if "observations" in str(request.url):
|
|
||||||
return httpx.Response(200, json={"url": "https://cdn/1/square.jpeg"})
|
|
||||||
return httpx.Response(200, content=IMAGE)
|
|
||||||
|
|
||||||
encoded = await _fetcher(handler).fetch_base64(
|
|
||||||
"https://api/observations", ["url"], ("/square.", "/large.")
|
|
||||||
)
|
|
||||||
assert base64.b64decode(encoded) == IMAGE
|
|
||||||
assert seen[-1] == "https://cdn/1/large.jpeg"
|
|
||||||
|
|
||||||
|
|
||||||
async def test_rewrite_that_matches_nothing_leaves_the_url_alone() -> None:
|
|
||||||
seen: list[str] = []
|
|
||||||
|
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
|
||||||
seen.append(str(request.url))
|
|
||||||
if "observations" in str(request.url):
|
|
||||||
return httpx.Response(200, json={"url": "https://cdn/1/original.jpeg"})
|
|
||||||
return httpx.Response(200, content=IMAGE)
|
|
||||||
|
|
||||||
await _fetcher(handler).fetch_base64(
|
|
||||||
"https://api/observations", ["url"], ("/square.", "/large.")
|
|
||||||
)
|
|
||||||
assert seen[-1] == "https://cdn/1/original.jpeg"
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user