298 lines
10 KiB
Python
298 lines
10 KiB
Python
"""
|
|
R5: Inline-Befehlserkennung — Command-Registry und Help-Text-Generator.
|
|
|
|
Stellt die ::-Befehlssyntax für erfahrene Nutzer bereit:
|
|
::sethome — Setzt den Heimatraum (Alternative zu /sethome)
|
|
::setfakt — Ändert den FAKT-Speicherort
|
|
::hilfe — Zeigt Hilfeseite mit allen Befehlen
|
|
::status — Zeigt aktuellen Plugin-Status
|
|
::reset — Alternative zu /reset
|
|
|
|
Die Hilfeseite wird auch durch natürliche Sprache ausgelöst:
|
|
'Ich brauche Hilfe zum Rocketchat Plugin'
|
|
'Was kannst du?'
|
|
'Hilfe'
|
|
|
|
Konvention für Command-Handler:
|
|
Handler, die selbst posten (z.B. Buttons, Attachments), MÜSSEN einen
|
|
leeren String ("") zurückgeben. _handle_inline_command sendet den
|
|
Return-Wert sonst doppelt als Textnachricht.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from typing import Dict, List, Optional, Callable, Awaitable, Any
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# ── Natural language help triggers ──────────────────────────────────────
|
|
# Diese Sätze lösen die Hilfeseite aus (case-insensitive, stripped).
|
|
NATURAL_HELP_TRIGGERS: List[str] = [
|
|
"hilfe",
|
|
"help",
|
|
"was kannst du",
|
|
"was kannst du?",
|
|
"ich brauche hilfe zum rocketchat plugin",
|
|
"ich brauche hilfe zum rocketchat-plugin",
|
|
"rocketchat hilfe",
|
|
"rocketchat help",
|
|
"plugin hilfe",
|
|
"plugin help",
|
|
"was kann das plugin",
|
|
"was kann das plugin?",
|
|
"welche befehle",
|
|
"welche befehle?",
|
|
"welche befehle gibt es",
|
|
"welche befehle gibt es?",
|
|
"zeige befehle",
|
|
"zeige hilfe",
|
|
"commands",
|
|
"was geht",
|
|
"was geht?",
|
|
]
|
|
|
|
|
|
def is_natural_help_request(text: str) -> bool:
|
|
"""Prüft ob der Text eine natürliche Hilfeseiten-Anfrage ist.
|
|
|
|
Args:
|
|
text: Der Nachrichtentext (wird gestripped und lowercased).
|
|
|
|
Returns:
|
|
True wenn der Text eine Hilfeseiten-Anfrage ist.
|
|
"""
|
|
stripped = text.strip().lower()
|
|
# Exakte Matches
|
|
if stripped in NATURAL_HELP_TRIGGERS:
|
|
return True
|
|
# Enthält-Matches für längere Sätze
|
|
for trigger in NATURAL_HELP_TRIGGERS:
|
|
if len(trigger) > 10 and trigger in stripped:
|
|
return True
|
|
return False
|
|
|
|
|
|
# ── Inline-Command Registry ────────────────────────────────────────────
|
|
|
|
# Command-Handler-Signatur: async def handler(room_id: str, args: str) -> str
|
|
# Gibt den Antworttext zurück, der im Raum gepostet wird.
|
|
CommandHandler = Callable[[str, str], Awaitable[str]]
|
|
|
|
|
|
class InlineCommandRegistry:
|
|
"""Registry für ::-Befehle mit Handler und Help-Text."""
|
|
|
|
def __init__(self):
|
|
self._commands: Dict[str, Dict[str, Any]] = {}
|
|
|
|
def register(
|
|
self,
|
|
name: str,
|
|
handler: CommandHandler,
|
|
help_text: str,
|
|
description: str = "",
|
|
category: str = "Plugin",
|
|
subcommands: Optional[Dict[str, str]] = None,
|
|
) -> None:
|
|
"""Registriert einen ::-Befehl.
|
|
|
|
Args:
|
|
name: Befehlsname ohne :: (z.B. 'sethome').
|
|
handler: Async callable (room_id, args) -> Antworttext.
|
|
help_text: Kurzer Hilfetext (eine Zeile).
|
|
description: Ausführliche Beschreibung.
|
|
category: Kategorie für die Hilfeseite.
|
|
subcommands: Optionales Dict {subcmd: beschreibung} für Befehle
|
|
mit Subcommands (z.B. {'start': 'Startet...', ...}).
|
|
"""
|
|
self._commands[name] = {
|
|
"handler": handler,
|
|
"help_text": help_text,
|
|
"description": description,
|
|
"category": category,
|
|
"subcommands": subcommands or {},
|
|
}
|
|
|
|
def get_handler(self, name: str) -> Optional[CommandHandler]:
|
|
"""Gibt den Handler für einen Befehl zurück."""
|
|
cmd = self._commands.get(name)
|
|
return cmd["handler"] if cmd else None
|
|
|
|
def get_commands(self) -> Dict[str, Dict[str, Any]]:
|
|
"""Gibt alle registrierten Befehle zurück."""
|
|
return dict(self._commands)
|
|
|
|
def is_registered(self, name: str) -> bool:
|
|
"""Prüft ob ein Befehl registriert ist."""
|
|
return name in self._commands
|
|
|
|
|
|
# ── Help-Text-Generator ─────────────────────────────────────────────────
|
|
|
|
|
|
def build_help_text(registry: InlineCommandRegistry, room_map_summary: str = "") -> str:
|
|
"""Baut die Hilfeseite mit ::-Befehlen und natürlichen Sprach-Befehlen.
|
|
|
|
Args:
|
|
registry: Die InlineCommandRegistry mit allen registrierten Befehlen.
|
|
room_map_summary: Optionale Raum-Map-Übersicht für den Status-Teil.
|
|
|
|
Returns:
|
|
Formatierte Hilfeseite als Markdown-String.
|
|
"""
|
|
lines = [
|
|
"## 🤖 Rocket.Chat Plugin — Hilfe",
|
|
"",
|
|
"Diese Befehle erkennst du am `::` am Satzanfang:",
|
|
"",
|
|
]
|
|
|
|
# ::-Befehle nach Kategorie gruppieren
|
|
by_category: Dict[str, List[Dict[str, Any]]] = {}
|
|
for name, cmd in registry.get_commands().items():
|
|
cat = cmd.get("category", "Plugin")
|
|
by_category.setdefault(cat, []).append({"name": name, **cmd})
|
|
|
|
# ── Sektion 1: Standard-Hermes-Befehle (:: als Variante) ──────────
|
|
standard_categories = {"Standard", "Gateway", "Session", "Info"}
|
|
standard_cmds = []
|
|
for cat in sorted(by_category):
|
|
if cat in standard_categories:
|
|
standard_cmds.extend(by_category[cat])
|
|
|
|
if standard_cmds:
|
|
lines.append("### 🔷 Standard-Hermes-Befehle (:: als Variante)")
|
|
lines.append("")
|
|
lines.append("Diese Befehle sind die ::-Entsprechungen der Hermes-Slash-Commands")
|
|
lines.append("(`/sethome`, `/reset`, `/busy`, …). Da Rocket.Chat kein `/` unterstützt,")
|
|
lines.append("wurden sie auf `::` umgestellt:")
|
|
lines.append("")
|
|
for cmd in standard_cmds:
|
|
lines.append(f"- `::{cmd['name']}` — {cmd['help_text']}")
|
|
subcmds = cmd.get('subcommands', {})
|
|
for sub_name, sub_desc in subcmds.items():
|
|
lines.append(f" - `::{cmd['name']} {sub_name}` — {sub_desc}")
|
|
lines.append("")
|
|
|
|
# ── Sektion 2: RC-Plugin-spezifische Befehle ──────────────────────
|
|
rc_categories = {"Raum", "Konfiguration", "Hilfe", "Plugin"}
|
|
rc_cmds = []
|
|
for cat in sorted(by_category):
|
|
if cat in rc_categories:
|
|
rc_cmds.extend(by_category[cat])
|
|
|
|
if rc_cmds:
|
|
lines.append("### 🔶 RC-Plugin-spezifische Befehle")
|
|
lines.append("")
|
|
lines.append("Diese Befehle steuern das Rocket.Chat-Plugin direkt:")
|
|
lines.append("")
|
|
for cmd in rc_cmds:
|
|
lines.append(f"- `::{cmd['name']}` — {cmd['help_text']}")
|
|
subcmds = cmd.get('subcommands', {})
|
|
for sub_name, sub_desc in subcmds.items():
|
|
lines.append(f" - `::{cmd['name']} {sub_name}` — {sub_desc}")
|
|
lines.append("")
|
|
|
|
# ── Sektion 3: Natürliche Sprach-Befehle ──────────────────────────
|
|
lines.append("### 🗣️ Natürliche Sprach-Befehle")
|
|
lines.append("")
|
|
lines.append("Du kannst auch in natürlicher Sprache mit mir sprechen:")
|
|
lines.append("")
|
|
lines.append("- **Raum wechseln:** 'Lass uns in #Projektraum wechseln'")
|
|
lines.append("- **Thema verschieben:** 'Das gehört in den Plugin-Raum'")
|
|
lines.append("- **Hilfe anfordern:** 'Ich brauche Hilfe zum Rocketchat Plugin'")
|
|
lines.append("- **Status abfragen:** '::status' oder 'Wie ist der Status?'")
|
|
lines.append("- **Auftrag erteilen:** 'Mach mal...', 'Teste...', 'Fix...'")
|
|
lines.append("")
|
|
|
|
# ── Sektion 4: Plugin-Status ──────────────────────────────────────
|
|
lines.append("### 📋 Plugin-Status")
|
|
lines.append("")
|
|
|
|
if room_map_summary:
|
|
lines.append(room_map_summary)
|
|
else:
|
|
lines.append("Keine Raum-Map geladen.")
|
|
|
|
lines.append("")
|
|
lines.append("---")
|
|
lines.append("💡 **Tipp:** `::hilfe` zeigt diese Seite jederzeit an.")
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
def build_status_text(
|
|
room_count: int = 0,
|
|
archivar_active: bool = False,
|
|
butler_mode: str = "unknown",
|
|
onboarding_active: bool = False,
|
|
room_map_summary: str = "",
|
|
) -> str:
|
|
"""Baut die Status-Seite mit aktuellen Plugin-Informationen.
|
|
|
|
Args:
|
|
room_count: Anzahl der Räume in der Map.
|
|
archivar_active: Ob der Archivar aktiv ist.
|
|
butler_mode: Butler-Modus ('cognitive', 'strict', 'off').
|
|
onboarding_active: Ob Onboarding gerade läuft.
|
|
room_map_summary: Raum-Map-Übersicht.
|
|
|
|
Returns:
|
|
Formatierte Status-Seite.
|
|
"""
|
|
butler_labels = {
|
|
"cognitive": "🤖 Kognitiv",
|
|
"strict": "📋 Klassisch",
|
|
"off": "🔇 Aus",
|
|
}
|
|
|
|
lines = [
|
|
"## 📊 Plugin-Status",
|
|
"",
|
|
f"- **Räume in Map:** {room_count}",
|
|
f"- **Archivar:** {'✅ Aktiv' if archivar_active else '❌ Inaktiv'}",
|
|
f"- **Butler-Modus:** {butler_labels.get(butler_mode, butler_mode)}",
|
|
f"- **Onboarding:** {'🔄 Läuft' if onboarding_active else '✅ Abgeschlossen'}",
|
|
]
|
|
|
|
if room_map_summary:
|
|
lines.append("")
|
|
lines.append(room_map_summary)
|
|
|
|
lines.append("")
|
|
lines.append("💡 `::hilfe` für alle Befehle | `::status` für Aktualisierung")
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
# ── Inline-Command-Parser ───────────────────────────────────────────────
|
|
|
|
|
|
def parse_inline_command(text: str) -> Optional[tuple]:
|
|
"""Parst einen ::-Befehl aus dem Nachrichtentext.
|
|
|
|
Args:
|
|
text: Der Nachrichtentext.
|
|
|
|
Returns:
|
|
(command_name, args) wenn ein ::-Befehl erkannt wurde, sonst None.
|
|
command_name ist der Befehl ohne :: (z.B. 'sethome').
|
|
args ist der Rest des Texts nach dem Befehl (kann leer sein).
|
|
"""
|
|
stripped = text.strip()
|
|
if not stripped.startswith("::"):
|
|
return None
|
|
|
|
# Extrahiere Befehl und Argumente
|
|
# Format: ::befehl [args]
|
|
rest = stripped[2:] # Entferne ::
|
|
if not rest:
|
|
return None
|
|
|
|
parts = rest.split(None, 1)
|
|
command = parts[0].lower()
|
|
args = parts[1] if len(parts) > 1 else ""
|
|
|
|
return (command, args)
|