mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-10 19:37:03 +01:00
A compliment gets a reaction drawn from a small warm set (❤️ 🥰 😊 👍 🎉 🙏 😸) put on the compliment itself, and nothing in the group -- the one answer that adds no line. Same cooldown as every other command. The transport learns reactions: send_reaction on the Protocol, POST /v1/reactions/<number> on the REST adapter with the four fields api.SendReactionRequest requires (204 back), a recorded list on the fake. CommandContext.react() names the target the way a quote does, and falls back to the emoji as text for an envelope with no timestamp, so a shape this bot has never seen is visible rather than swallowed. The fake container gains the endpoint, strict about the schema, and records reactions in order with the sends; a scenario can now expect {kind: reaction, quotes: true}. First two-word trigger: fold() keeps the inner space and the registry matches whole text first, so "!good bot" resolves and "!good" does not; one-word spellings cover a double space. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
128 lines
5.0 KiB
Python
128 lines
5.0 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
|
"""The endpoints the real signal-cli-rest-api exposes."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any, Final
|
|
|
|
from fastapi import APIRouter, Request, WebSocket, WebSocketDisconnect
|
|
from fastapi.responses import JSONResponse, Response
|
|
|
|
from fake_signal.state import PIXEL_PNG, State
|
|
|
|
# Read off the real container's /swagger/doc.json, not remembered.
|
|
REACTION_FIELDS: Final = frozenset({"reaction", "recipient", "target_author", "timestamp"})
|
|
|
|
|
|
def _state(request: Request) -> State:
|
|
"""Return the State attached to the running app."""
|
|
state: State = request.app.state.fake
|
|
return state
|
|
|
|
|
|
def build_api_router() -> APIRouter:
|
|
"""Build the router mirroring the real container's API."""
|
|
router = APIRouter()
|
|
|
|
@router.get("/v1/about")
|
|
async def about(request: Request) -> dict[str, Any]:
|
|
return {"build": 2, "mode": _state(request).mode, "versions": ["v1", "v2"]}
|
|
|
|
@router.get("/v1/qrcodelink")
|
|
async def qrcodelink(device_name: str = "signal-api") -> Response:
|
|
# The real endpoint returns a PNG, which is why the live runbook has
|
|
# to open an image rather than print a string.
|
|
return Response(
|
|
content=PIXEL_PNG,
|
|
media_type="image/png",
|
|
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)
|
|
return JSONResponse({"timestamp": 1719177917717}, status_code=201)
|
|
|
|
@router.post("/v1/reactions/{number}")
|
|
async def react(request: Request, number: str, payload: dict[str, Any]) -> Response:
|
|
"""The container's api.SendReactionRequest: all four fields required."""
|
|
if REACTION_FIELDS - payload.keys():
|
|
return JSONResponse({"error": "missing reaction fields"}, status_code=400)
|
|
_state(request).record_reaction(number, payload)
|
|
return Response(status_code=204)
|
|
|
|
_add_attachment_routes(router)
|
|
_add_receive_route(router)
|
|
|
|
return router
|
|
|
|
|
|
def _add_attachment_routes(router: APIRouter) -> None:
|
|
"""Attach the attachment store's three endpoints.
|
|
|
|
Split out so the router builder stays under the complexity cap, exactly
|
|
as _add_receive_route already is.
|
|
"""
|
|
|
|
@router.get("/v1/attachments")
|
|
async def list_attachments(request: Request) -> list[str]:
|
|
return list(_state(request).attachments)
|
|
|
|
@router.get("/v1/attachments/{attachment_id}")
|
|
async def fetch_attachment(request: Request, attachment_id: str) -> Response:
|
|
"""Hand over one stored attachment, the way the container does."""
|
|
payload = _state(request).stored.get(attachment_id)
|
|
if payload is None:
|
|
return JSONResponse({"error": "no such attachment"}, status_code=404)
|
|
return Response(content=payload, media_type="application/octet-stream")
|
|
|
|
@router.delete("/v1/attachments/{attachment_id}")
|
|
async def delete_attachment(request: Request, attachment_id: str) -> Response:
|
|
state = _state(request)
|
|
if attachment_id in state.attachments:
|
|
state.attachments.remove(attachment_id)
|
|
# The bytes go too, which is what makes "the second copy is gone"
|
|
# something a scenario can assert rather than assume.
|
|
state.stored.pop(attachment_id, None)
|
|
return Response(status_code=204)
|
|
|
|
|
|
def _add_receive_route(router: APIRouter) -> None:
|
|
"""Attach the WebSocket receive endpoint.
|
|
|
|
Split out so the router builder stays under the complexity cap.
|
|
"""
|
|
|
|
@router.websocket("/v1/receive/{number}")
|
|
async def receive(websocket: WebSocket, number: str) -> None:
|
|
state: State = websocket.app.state.fake
|
|
await websocket.accept()
|
|
await websocket.send_json({"envelope": {"subscribed": number}})
|
|
state.sockets.append(websocket)
|
|
try:
|
|
while True:
|
|
# Blocks until the client goes away. The bot never sends.
|
|
await websocket.receive_text()
|
|
except WebSocketDisconnect:
|
|
pass
|
|
finally:
|
|
# Branchless: a conditional remove leaves an arc no test can reach.
|
|
state.sockets[:] = [s for s in state.sockets if s is not websocket]
|