mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-11 14:17:31 +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
155 lines
6.0 KiB
Python
155 lines
6.0 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
|
"""The !pomoc command: every command the bot has, and what each one does.
|
|
|
|
Nothing in the chat used to say the commands existed. The README's table was
|
|
the only list, it was stale within two releases, and nobody in a Signal group
|
|
reads a README anyway -- so the list is built from the registry itself. A
|
|
command cannot be registered without a description (``CommandRegistry.register``
|
|
requires one), and any command this module's ``GROUPS`` does not mention is
|
|
printed anyway, under no heading. Between those two, a new command cannot
|
|
quietly fail to appear here.
|
|
|
|
The trigger printed is ``Command.primary``, the first *raw* alias, because
|
|
``Command.triggers`` holds folded skeletons in an unordered set: "!papież"
|
|
survives there only as "!papiez", and the styled Unicode aliases would come
|
|
out as the zalgo they are.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import TYPE_CHECKING, Final
|
|
|
|
from signal_bot.animals import load_aliases
|
|
from signal_bot.pack_command import NAME_PREFIX
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Sequence
|
|
|
|
from signal_bot.context import CommandContext
|
|
from signal_bot.decorators import Decorator
|
|
from signal_bot.registry import Command, CommandRegistry
|
|
|
|
COMMAND_NAME: Final = "help"
|
|
DESCRIPTION: Final = "ta lista"
|
|
|
|
HEADING: Final = "Komendy"
|
|
|
|
# Which commands sit under which heading, in the order they are printed.
|
|
# Anything missing from here still gets printed, in a block of its own -- see
|
|
# the module docstring.
|
|
GROUPS: Final[tuple[tuple[str, tuple[str, ...]], ...]] = (
|
|
("Obrazki", ("cat", "dog", "gecko")),
|
|
("Papież", ("pope",)),
|
|
("Propozycje", ("suggest",)),
|
|
(
|
|
"Statystyki",
|
|
(
|
|
"stats_today",
|
|
"stats_yesterday",
|
|
"stats_week",
|
|
"stats_month",
|
|
"stats_year",
|
|
"stats_records",
|
|
"stats_crown",
|
|
"stats_weekdays",
|
|
"stats_me",
|
|
),
|
|
),
|
|
)
|
|
|
|
# Only the canonical spelling is listed above, but half the group types the
|
|
# English one. Without this line "!cat" looks broken to somebody holding a
|
|
# list that says "!kot".
|
|
SPELLINGS: Final = "Każda komenda ma też inne pisownie, np. !cat, !stats, !week."
|
|
|
|
# The private album, when a group has one. Its heading is here and its
|
|
# commands are not: they come from a file this repository never sees, so
|
|
# GROUPS could not name them even if it wanted to -- and naming an optional
|
|
# command there would make !pomoc fail in every group that has no pack.
|
|
PACK_HEADING: Final = "Zdjęcia"
|
|
PACK_HINT: Final = "Kilka naraz ({first} {second}) = zdjęcie, na którym są wszyscy."
|
|
|
|
# The two commands that act on the album rather than posting one person from
|
|
# it. Their own block, so the "kilka naraz" hint above keeps describing the
|
|
# people entries it was written for. Spelled from NAME_PREFIX rather than
|
|
# imported, so !pomoc does not pull the ingest path in just to print a line.
|
|
ALBUM_HEADING: Final = "Album"
|
|
ALBUM_NAMES: Final = (f"{NAME_PREFIX}add", f"{NAME_PREFIX}random")
|
|
|
|
|
|
def _line(command: Command) -> str:
|
|
"""One command as !pomoc prints it."""
|
|
return f"{command.primary} — {command.description}"
|
|
|
|
|
|
def _pack_block(commands: Sequence[Command]) -> str:
|
|
"""The album's own block, or "" for a group that has no album.
|
|
|
|
Built from whatever is registered rather than from a table, because the
|
|
entries are private data: this file cannot know how many there are or
|
|
what they are called, and must not need to.
|
|
"""
|
|
entries = [c for c in commands if c.name.startswith(NAME_PREFIX) and c.name not in ALBUM_NAMES]
|
|
if not entries:
|
|
return ""
|
|
lines = [PACK_HEADING, *(_line(command) for command in entries)]
|
|
if len(entries) > 1:
|
|
lines.append(PACK_HINT.format(first=entries[0].primary, second=entries[1].primary))
|
|
return "\n".join(lines)
|
|
|
|
|
|
def _album_block(commands: Sequence[Command]) -> str:
|
|
"""The !add_photo / !random block, or "" where there is no album."""
|
|
entries = [c for c in commands if c.name in ALBUM_NAMES]
|
|
if not entries:
|
|
return ""
|
|
return "\n".join([ALBUM_HEADING, *(_line(command) for command in entries)])
|
|
|
|
|
|
def render_help(commands: Sequence[Command], group_id: str) -> str:
|
|
"""Render the command list for one group, grouped, in registration order.
|
|
|
|
Per group, because a command can be scoped to one: the private album
|
|
exists in its own groups and nowhere else, and a help text that listed it
|
|
everywhere would announce it to every group the bot is in.
|
|
"""
|
|
visible = [command for command in commands if command.allowed_in(group_id)]
|
|
by_name = {command.name: command for command in visible}
|
|
# Indexed, not .get(): a name in GROUPS that no command answers to is a
|
|
# typo in this file, and it should fail loudly the first time the command
|
|
# is used rather than silently drop a line.
|
|
grouped = {name for _, names in GROUPS for name in names}
|
|
blocks = [HEADING]
|
|
for title, names in GROUPS:
|
|
blocks.append("\n".join([title, *(_line(by_name[name]) for name in names)]))
|
|
blocks.extend(block for block in (_pack_block(visible), _album_block(visible)) if block)
|
|
blocks.append(
|
|
"\n".join(
|
|
_line(c)
|
|
for c in visible
|
|
if c.name not in grouped and not c.name.startswith(NAME_PREFIX)
|
|
)
|
|
)
|
|
blocks.append(SPELLINGS)
|
|
return "\n\n".join(blocks)
|
|
|
|
|
|
def register_help_command(
|
|
registry: CommandRegistry,
|
|
*,
|
|
decorate: Decorator | None = None,
|
|
aliases: dict[str, list[str]] | None = None,
|
|
) -> None:
|
|
"""Register !pomoc, which reads the registry it is registered on.
|
|
|
|
The registry is read when the command *runs*, not when it is registered,
|
|
so this may be wired up in any order and still list everything.
|
|
"""
|
|
table = load_aliases() if aliases is None else aliases
|
|
|
|
async def handler(ctx: CommandContext) -> None:
|
|
await ctx.reply(render_help(registry.commands, ctx.group_id))
|
|
|
|
wrapped = decorate(handler) if decorate is not None else handler
|
|
registry.register(COMMAND_NAME, table[COMMAND_NAME], wrapped, DESCRIPTION)
|