исправлен встроенный разбор справочника: примеры больше не считаются командами (28 -> 13)

This commit is contained in:
root committed 2026-10-15 16:14:00 +03:00
1 parent 14536be3cc
commit 5df4f985ea
1 file changed
+23 -10
+23 -10
View File
@@ -82,6 +82,15 @@ def _simple_parse(text: str) -> dict:
continue
if section == "commands":
if item is None:
continue
# ВАЖНО: сначала проверяем, не является ли строка элементом
# списка (примеры, варианты). Иначе строка «- /status» в
# примерах создавала ЛИШНЮЮ команду без имени — из-за этого
# справочник давал 28 записей вместо 13 и падала подсказка.
if list_key and stripped.startswith("- "):
item[list_key].append(stripped[2:].strip().strip('"\''))
continue
if stripped.startswith("- "):
item = {}
data["commands"].append(item)
@@ -91,15 +100,10 @@ def _simple_parse(text: str) -> dict:
k, v = rest.split(":", 1)
item[k.strip()] = v.strip()
continue
if item is None:
continue
if stripped.endswith(":") and not stripped.startswith("-"):
if stripped.endswith(":"):
list_key = stripped[:-1]
item[list_key] = []
continue
if stripped.startswith("- ") and list_key:
item[list_key].append(stripped[2:].strip().strip('"\''))
continue
if ":" in stripped:
k, v = stripped.split(":", 1)
item[k.strip()] = v.strip().strip('"\'')
@@ -107,10 +111,19 @@ def _simple_parse(text: str) -> dict:
return data
def _named_commands(data: dict) -> list[dict]:
"""Только записи с именем команды.
Разбор может дать служебные записи без поля command — они
пропускаются, чтобы справка не падала.
"""
return [c for c in data.get("commands", []) if c.get("command")]
def commands_for(data: dict, bot: str) -> list[dict]:
"""Команды бота: его собственные плюс общие (bot: all)."""
out = []
for cmd in data.get("commands", []):
for cmd in _named_commands(data):
if cmd.get("bot") in (bot, "all"):
out.append(cmd)
return out
@@ -146,7 +159,7 @@ def help_text(data: dict, bot: str) -> str:
def command_help(data: dict, name: str) -> str | None:
"""Подробная справка по одной команде."""
name = name.lstrip("/!").strip()
for cmd in data.get("commands", []):
for cmd in _named_commands(data):
if cmd.get("command") == name or name in (cmd.get("aliases") or []):
lines = [f"<b>/{cmd['command']}</b> — {cmd.get('title', '')}"]
lines.append(cmd.get("description", ""))
@@ -172,7 +185,7 @@ def suggest(data: dict, wrong: str | None) -> str | None:
"""Подсказка при опечатке: «возможно, вы имели в виду»."""
if not wrong:
return None
names = [c["command"] for c in data.get("commands", [])]
names = [c["command"] for c in _named_commands(data)]
close = difflib.get_close_matches(wrong.lstrip("/!").strip(), names, n=1, cutoff=0.6)
if close:
return f"Команда не распознана. Возможно, вы имели в виду /{close[0]}? Список: /help"
@@ -204,7 +217,7 @@ def markdown(data: dict) -> str:
lines.append("## Общие команды")
lines.append("")
for cmd in data.get("commands", []):
for cmd in _named_commands(data):
if cmd.get("bot") == "all":
lines.append(f"- `{cmd.get('usage')}` — {cmd.get('description', '')}")
lines.append("")