mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-28 05:59:06 +01:00
An unrecognised "!word" was dropped in silence, which made a typo
indistinguishable from the bot being down and threw away the best available
list of commands worth writing. Three things now happen at the one place in
dispatcher.py that used to be a bare `return`.
A near miss is corrected -- "!cta" asks whether you meant "!kot". The
distance is optimal string alignment rather than difflib's ratio: a
transposition is the typo people actually make, it costs one edit here, and
it shreds the matching blocks a ratio counts ("!cta"/"!cat" scores 0.75 but
"!cta"/"!kot" scores 0.50, so no cutoff separates them on principle).
A word with no near miss points at !zaproponuj, which files an idea from
inside the group. Either way the word and the message are recorded, and the
management page grows an Ideas tab that lists them.
Three things stay silent, each for its own reason. "!kot ladny" is a real
trigger with words after it and always has been silent. "!!" is punctuation.
And a command claimed in some *other* group is neither answered nor recorded
-- the album's triggers are real people's names, and pack_scoping.yaml says
it out loud: a refusal would itself announce that the album exists. The
existence check is therefore global, which is what pack_add already asks.
Measured rather than guessed, against the shipped aliases.json:
- a minimum candidate length, because "!ja" is one edit from ~40 of the 676
two-letter words somebody could type; 69 of them got a suggestion before
the rule and 18 after.
- the two-edit budget starts at six characters, not five. At five it put
four pairs of *different* commands within reach of each other --
!pies/!popes, !days/!cats, !dzis/!dni, !mnie/!dni -- and costs nothing to
give up, because every real typo this was written for is one edit away.
test_no_two_commands_are_within_reach_of_each_other fails if a future
alias reopens the gap.
Both new tables are keyed on the envelope's own sent_at_ms, never the wall
clock: signal-cli replays undelivered frames on reconnect, and a clock-keyed
table collects a duplicate row per reconnect instead of ignoring one.
The branch is gated on should_count -- which excludes the bot's own envelope,
and that is the loop guard, since handle() checks is_own nowhere else -- and
wrapped in its own try/except, because it runs above the one that wraps a
handler and Bot.listen has no exception handling of its own.
Suggestions live in SQLite, not in a tracked file, and the export goes to the
state directory. check_personal_data learns the names it refuses from the
live database, so it catches a name somebody has typed and cannot catch a
misspelling of one -- and an unrecognised-command corpus is made of
misspellings. A group-writable file in a public tree is both a leak and a
wedge. The export therefore carries
deliberate !zaproponuj notes in full and unrecognised words as counts only;
bodies stay on the loopback-only page.
Verified on the live bot: restarted, both tables created with every existing
row count unchanged, !cta and !zaproponuj !pogoda delivered through
/_selftest, both rows read back out of the live database, and the journal
names neither the word nor the body.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01416TegJ3sa8xL5qGGgrygP
163 lines
5.9 KiB
Python
163 lines
5.9 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
|
"""What the group asked for, read back on the management page.
|
|
|
|
Read-only, and connected read-only: ``mode=ro`` rather than a plain connect,
|
|
which is the same URI ``scripts/personal_data_sources.py`` uses. Two reasons.
|
|
The bot has this file open and commits on every inbound message, so a second
|
|
writer is a lock waiting to happen; and ``Store`` applies its schema on open,
|
|
which drops the ephemeral tables whenever the versions disagree -- a
|
|
management page must never be able to do that to a running bot.
|
|
|
|
The export deliberately does **not** write into the repository. See
|
|
``render_export``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import contextlib
|
|
import os
|
|
import sqlite3
|
|
from pathlib import Path
|
|
from typing import TYPE_CHECKING, Any, Final
|
|
|
|
from fastapi import APIRouter
|
|
|
|
from signal_bot.suggestions import SuggestionStore
|
|
|
|
if TYPE_CHECKING:
|
|
from signal_bot.manage.deps import ManageDeps
|
|
|
|
# Named for the repository's markdown convention, so that a copy pasted
|
|
# into the tree is already compliant -- but written outside it. See
|
|
# default_export_path.
|
|
EXPORT_NAME: Final = "DOCS-suggestions.md"
|
|
|
|
|
|
def default_export_path() -> Path:
|
|
"""Where the export goes: the state directory, never the repository.
|
|
|
|
Same order as pack.default_dir, and for the same reason -- systemd
|
|
creates STATE_DIRECTORY and exposes it regardless of ProtectHome, and
|
|
reading os.environ live is what lets one autouse fixture keep the whole
|
|
test suite out of the operator's real data.
|
|
"""
|
|
state = os.environ.get("STATE_DIRECTORY", "").strip()
|
|
if state:
|
|
return Path(state) / EXPORT_NAME
|
|
home = os.environ.get("XDG_DATA_HOME", "").strip() or str(Path.home() / ".local" / "share")
|
|
return Path(home) / "signal-bot" / EXPORT_NAME
|
|
|
|
|
|
# What a body is truncated to in the export. Long enough for a sentence,
|
|
# short enough that a pasted paragraph cannot bury the file.
|
|
EXPORT_BODY_LIMIT = 200
|
|
|
|
HEADER = """# Suggestions
|
|
|
|
Written by the management page, from the bot's own database. Not generated
|
|
at build time and not checked by anything -- read it, act on what is worth
|
|
acting on, and delete it.
|
|
|
|
Bodies are included for deliberate `!zaproponuj` notes only. Unrecognised
|
|
commands are counts, because that half of the table is full of half-typed
|
|
words and a half-typed name is one the personal-data gate cannot recognise.
|
|
"""
|
|
|
|
|
|
def collect(path: Path) -> dict[str, list[dict[str, Any]]]:
|
|
"""Everything the page shows, or empty lists when there is nothing to read.
|
|
|
|
Opening and reading are inside one try because every way this can fail
|
|
is the same answer -- a bot that has never run, a database older than
|
|
these tables, a half-written file -- and none of them is worth breaking
|
|
the page over. The page is most useful exactly when something is wrong.
|
|
|
|
Closed explicitly: the bot holds this file open and commits on every
|
|
inbound message, so a reader left dangling is a lock waiting to happen.
|
|
"""
|
|
if not path.is_file():
|
|
return {"suggestions": [], "unknown": []}
|
|
try:
|
|
with contextlib.closing(sqlite3.connect(f"file:{path}?mode=ro", uri=True)) as conn:
|
|
conn.row_factory = sqlite3.Row
|
|
store = SuggestionStore(conn)
|
|
filed = store.filed()
|
|
unknown = store.unknown()
|
|
except sqlite3.Error:
|
|
return {"suggestions": [], "unknown": []}
|
|
return {
|
|
"suggestions": [
|
|
{
|
|
"command": one.command,
|
|
"body": one.body,
|
|
"sent_at_ms": one.sent_at_ms,
|
|
"group_id": one.group_id,
|
|
}
|
|
for one in filed
|
|
],
|
|
"unknown": [
|
|
{
|
|
"word": one.word,
|
|
"hits": one.hits,
|
|
"last_seen": one.last_seen,
|
|
"group_id": one.group_id,
|
|
"bodies": list(one.bodies),
|
|
}
|
|
for one in unknown
|
|
],
|
|
}
|
|
|
|
|
|
def render_export(data: dict[str, list[dict[str, Any]]]) -> str:
|
|
"""Turn the collected rows into the markdown the export writes.
|
|
|
|
Deliberate notes keep their text; unrecognised words are reduced to a
|
|
count. That asymmetry is the whole point of the file. A body typed into
|
|
a group chat is free text, and this repository is public and has leaked
|
|
real names once already -- the personal-data gate learns the names it
|
|
refuses from the live database, so it catches "anna" and cannot possibly
|
|
catch "!annna". Counts cannot leak a name; sentences can.
|
|
"""
|
|
lines = [HEADER, "## Asked for", ""]
|
|
if not data["suggestions"]:
|
|
lines.append("_Nothing yet._")
|
|
lines.extend(
|
|
f"- `{one['command']}` — {one['body'][:EXPORT_BODY_LIMIT]}" for one in data["suggestions"]
|
|
)
|
|
lines.extend(["", "## Mistyped, or tried and not there", ""])
|
|
if not data["unknown"]:
|
|
lines.append("_Nothing yet._")
|
|
lines.extend(f"- `{one['word']}` x {one['hits']}" for one in data["unknown"])
|
|
return "\n".join(lines) + "\n"
|
|
|
|
|
|
def router(deps: ManageDeps) -> APIRouter:
|
|
"""The suggestions endpoints.
|
|
|
|
Args:
|
|
deps: The running app's configuration and paths.
|
|
|
|
Returns:
|
|
A router to include in the management app.
|
|
"""
|
|
api = APIRouter(prefix="/api")
|
|
|
|
@api.get("/suggestions")
|
|
async def suggestions() -> dict[str, list[dict[str, Any]]]:
|
|
"""Every filed idea and every unrecognised word, newest first."""
|
|
return collect(deps.database_path)
|
|
|
|
@api.post("/suggestions/export")
|
|
async def export() -> dict[str, Any]:
|
|
"""Write the export and say where it went."""
|
|
data = collect(deps.database_path)
|
|
deps.export_path.parent.mkdir(parents=True, exist_ok=True)
|
|
deps.export_path.write_text(render_export(data), encoding="utf-8")
|
|
return {
|
|
"path": str(deps.export_path),
|
|
"suggestions": len(data["suggestions"]),
|
|
"unknown": len(data["unknown"]),
|
|
}
|
|
|
|
return api
|