feat: install.sh schreibt ALLE Einstellungen in config.yaml; Button-Doku korrigiert (Desktop ~5-7 chars, keine Underscores, online statt away); adapter+init auf Produktionsstand
This commit is contained in:
+28
-36
@@ -40,7 +40,7 @@ Statt über ein separates Gateway-Binary zu kommunizieren, spricht Hermes Agent
|
|||||||
### 2. Plugin herunterladen
|
### 2. Plugin herunterladen
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://gitea.thomander.de/andreas/Hermes_rocket.chat_Plugin.git
|
git clone https://gitea.myowntools.org/andreas/Hermes_rocket.chat_Plugin.git
|
||||||
cd Hermes_rocket.chat_Plugin
|
cd Hermes_rocket.chat_Plugin
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -50,7 +50,7 @@ cd Hermes_rocket.chat_Plugin
|
|||||||
./install.sh
|
./install.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
Das Script führt dich durch alle Schritte, fragt deine Zugangsdaten ab, testet die Verbindung und schreibt die Konfiguration. Fertig in unter 2 Minuten.
|
Das Script führt dich durch alle Schritte, fragt deine Zugangsdaten ab, testet die Verbindung und schreibt die komplette Konfiguration in `~/.hermes/config.yaml`. Fertig in unter 2 Minuten.
|
||||||
|
|
||||||
**Nicht sicher?** Probiere erst die Simulation:
|
**Nicht sicher?** Probiere erst die Simulation:
|
||||||
|
|
||||||
@@ -60,59 +60,47 @@ Das Script führt dich durch alle Schritte, fragt deine Zugangsdaten ab, testet
|
|||||||
|
|
||||||
Zeigt alles an, ändert nichts.
|
Zeigt alles an, ändert nichts.
|
||||||
|
|
||||||
**Hilfe anzeigen:**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
./install.sh --help
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4. Manuelles Setup (für Experten)
|
### 4. Manuelles Setup (für Experten)
|
||||||
|
|
||||||
Wer lieber per Hand konfigurieren möchte:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
mkdir -p ~/.hermes/hermes-agent/plugins/platforms/rocketchat
|
mkdir -p ~/.hermes/hermes-agent/plugins/platforms/rocketchat
|
||||||
cp plugin.yaml __init__.py adapter.py \
|
cp plugin.yaml __init__.py adapter.py \
|
||||||
~/.hermes/hermes-agent/plugins/platforms/rocketchat/
|
~/.hermes/hermes-agent/plugins/platforms/rocketchat/
|
||||||
```
|
```
|
||||||
|
|
||||||
Dann `~/.hermes/.env` oder `config.yaml` bearbeiten.
|
Dann `~/.hermes/config.yaml` bearbeiten (siehe nächster Abschnitt).
|
||||||
|
|
||||||
### 5. Konfigurieren
|
### 5. Konfigurieren
|
||||||
|
|
||||||
Falls du manuell konfigurierst, hier die zwei Varianten:
|
Das install.sh schreibt automatisch in `config.yaml`. Hier die manuelle Referenz:
|
||||||
|
|
||||||
**Variante A — Umgebungsvariablen:**
|
|
||||||
export ROCKETCHAT_BASE_URL="https://rocketchat.example.com"
|
|
||||||
export ROCKETCHAT_USER="bernd"
|
|
||||||
export ROCKETCHAT_PASSWORD="dein-passwort"
|
|
||||||
export ROCKETCHAT_ROOM_ID="J3jvMyrKTMzKvKHSh" # optional
|
|
||||||
export ROCKETCHAT_ALLOWED_USERS="andreas,max" # optional
|
|
||||||
export ROCKETCHAT_ALLOW_ALL_USERS="false" # default
|
|
||||||
```
|
|
||||||
|
|
||||||
**Variante B — `config.yaml`:**
|
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
plugins:
|
plugins:
|
||||||
|
enabled:
|
||||||
|
- rocketchat-platform
|
||||||
|
|
||||||
|
gateway:
|
||||||
platforms:
|
platforms:
|
||||||
rocketchat:
|
rocketchat:
|
||||||
enabled: true
|
enabled: true
|
||||||
|
extra:
|
||||||
base_url: "https://rocketchat.example.com"
|
base_url: "https://rocketchat.example.com"
|
||||||
user: "bernd"
|
home_channel:
|
||||||
password: "dein-passwort"
|
platform: rocketchat
|
||||||
room_id: "J3jvMyrKTMzKvKHSh"
|
chat_id: "J3jvMyrKTMzKvKHSh"
|
||||||
allowed_users: ["andreas", "max"]
|
name: "ki-assistent"
|
||||||
allow_all_users: false
|
|
||||||
|
toolsets:
|
||||||
|
- rocketchat
|
||||||
```
|
```
|
||||||
|
|
||||||
### 4. Starten
|
### 6. Starten
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
hermes gateway start
|
hermes gateway restart
|
||||||
```
|
```
|
||||||
|
|
||||||
Hermes Agent verbindet sich automatisch mit Rocket.Chat und erscheint als Online-Benutzer.
|
Hermes Agent verbindet sich automatisch mit Rocket.Chat und erscheint als Online-Benutzer (grüner Punkt).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -127,15 +115,15 @@ Hermes Agent verbindet sich automatisch mit Rocket.Chat und erscheint als Online
|
|||||||
└─────────────┘ └─────────────────┘
|
└─────────────┘ └─────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
- **Adapter.py** (~20 k LOC): DDP-Client, Session-Handling, Nachrichten-Parsing, Button-Rendering
|
- **adapter.py** (~26 kB): DDP-Client, Session-Handling, Nachrichten-Parsing, Reconnect-Logik, Button-Rendering
|
||||||
- **__init__.py**: Plugin-Registrierung, Template-Definitionen für Buttons
|
- **__init__.py**: Plugin-Registrierung, Template-Definitionen für Buttons
|
||||||
- **plugin.yaml**: Metadaten, Env-Vars, Dependency-Check
|
- **plugin.yaml**: Metadaten, Env-Vars
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Button-Templates
|
## Button-Templates
|
||||||
|
|
||||||
Das Plugin bringt vordefinierte Interaktionen mit — kein YAML, keine Extra-Config:
|
Das Plugin bringt vordefinierte Interaktionen mit:
|
||||||
|
|
||||||
| Template | Nutzung |
|
| Template | Nutzung |
|
||||||
|----------|---------|
|
|----------|---------|
|
||||||
@@ -144,7 +132,11 @@ Das Plugin bringt vordefinierte Interaktionen mit — kein YAML, keine Extra-Con
|
|||||||
| `ok` | 👍 OK |
|
| `ok` | 👍 OK |
|
||||||
| `multi_choice_3` | 1. Links / 2. Rechts / 3. Zwei Runden |
|
| `multi_choice_3` | 1. Links / 2. Rechts / 3. Zwei Runden |
|
||||||
|
|
||||||
Custom-Buttons werden aus reinen Label-Strings generiert (Rocket.Chat schneidet nach ~11–12 Zeichen ab — daher kurze Labels mit Emoji).
|
**Button-Label-Regeln:**
|
||||||
|
- Desktop-App schneidet bei **~5–7 Zeichen** ab → Labels mit Nummer/Merkmal beginnen (`1. Links`)
|
||||||
|
- **NIEMALS Underscores (`_`)** in Button-Texten — zerstört Rendering komplett
|
||||||
|
- Leerzeichen sind erlaubt
|
||||||
|
- Pattern: Lange Texte in der Nachricht, Buttons mit Kurzreferenz
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -184,7 +176,7 @@ Kein Build-Step, keine Node-Dependencies, kein Docker nötig.
|
|||||||
|
|
||||||
- **Hermes Agent**: https://hermes-agent.nousresearch.com/
|
- **Hermes Agent**: https://hermes-agent.nousresearch.com/
|
||||||
- **Rocket.Chat**: https://www.rocket.chat/
|
- **Rocket.Chat**: https://www.rocket.chat/
|
||||||
- **Dieses Repo**: `https://gitea.thomander.de/andreas/Hermes_rocket.chat_Plugin`
|
- **Dieses Repo**: https://gitea.myowntools.org/andreas/Hermes_rocket.chat_Plugin
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ sudo apt update && sudo apt install -y curl git python3 bash
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /tmp
|
cd /tmp
|
||||||
git clone https://gitea.thomander.de/andreas/Hermes_rocket.chat_Plugin.git
|
git clone https://gitea.myowntools.org/andreas/Hermes_rocket.chat_Plugin.git
|
||||||
cd Hermes_rocket.chat_Plugin
|
cd Hermes_rocket.chat_Plugin
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -41,9 +41,10 @@ Das Script führt dich Schritt für Schritt durch:
|
|||||||
- 🔵 Kopiere alle Dateien
|
- 🔵 Kopiere alle Dateien
|
||||||
- 🔵 Frage deine Rocket.Chat-Daten ab
|
- 🔵 Frage deine Rocket.Chat-Daten ab
|
||||||
- 🔵 Teste die Verbindung
|
- 🔵 Teste die Verbindung
|
||||||
- 🔵 Schreibe Konfiguration in `~/.hermes/.env`
|
- 🔵 Schreibe ALLE Einstellungen in `~/.hermes/config.yaml`
|
||||||
|
- 🔵 Ergänzt `.env` für API-Keys
|
||||||
|
|
||||||
Am Ende ist das Plugin einsatzbereit — einfach `hermes gateway start`.
|
Am Ende ist das Plugin einsatzbereit — einfach `hermes gateway restart`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -61,30 +62,34 @@ cp __init__.py ~/.hermes/hermes-agent/plugins/platforms/rocketchat/
|
|||||||
cp adapter.py ~/.hermes/hermes-agent/plugins/platforms/rocketchat/
|
cp adapter.py ~/.hermes/hermes-agent/plugins/platforms/rocketchat/
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Konfiguration über `config.yaml` (empfohlen)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
plugins:
|
||||||
|
enabled:
|
||||||
|
- rocketchat-platform
|
||||||
|
|
||||||
|
gateway:
|
||||||
|
platforms:
|
||||||
|
rocketchat:
|
||||||
|
enabled: true
|
||||||
|
extra:
|
||||||
|
base_url: "https://rocketchat.example.com"
|
||||||
|
home_channel:
|
||||||
|
platform: rocketchat
|
||||||
|
chat_id: "J3jvMyrKTMzKvKHSh"
|
||||||
|
name: "ki-assistent"
|
||||||
|
|
||||||
|
toolsets:
|
||||||
|
- rocketchat
|
||||||
|
```
|
||||||
|
|
||||||
### Konfiguration über Umgebungsvariablen
|
### Konfiguration über Umgebungsvariablen
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export ROCKETCHAT_BASE_URL="https://rocketchat.example.com"
|
export ROCKETCHAT_BASE_URL="https://rocketchat.example.com"
|
||||||
export ROCKETCHAT_USER="bernd"
|
export ROCKETCHAT_USER="bernd"
|
||||||
export ROCKETCHAT_PASSWORD="dein-passwort"
|
export ROCKETCHAT_PASSWORD="dein-passwort"
|
||||||
export ROCKETCHAT_ROOM_ID="J3jvMyrKTMzKvKHSh" # optional
|
|
||||||
export ROCKETCHAT_ALLOWED_USERS="andreas,max" # optional
|
|
||||||
export ROCKETCHAT_ALLOW_ALL_USERS="false" # default
|
|
||||||
```
|
|
||||||
|
|
||||||
### Konfiguration über `config.yaml`
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
plugins:
|
|
||||||
platforms:
|
|
||||||
rocketchat:
|
|
||||||
enabled: true
|
|
||||||
base_url: "https://rocketchat.example.com"
|
|
||||||
user: "bernd"
|
|
||||||
password: "dein-passwort"
|
|
||||||
room_id: "J3jvMyrKTMzKvKHSh"
|
|
||||||
allowed_users: ["andreas", "max"]
|
|
||||||
allow_all_users: false
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -103,11 +108,35 @@ plugins:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Button-Labels — Wichtige Regeln
|
||||||
|
|
||||||
|
Rocket.Chat verhält sich je nach Plattform unterschiedlich:
|
||||||
|
|
||||||
|
| Plattform | Verhalten |
|
||||||
|
|-----------|-----------|
|
||||||
|
| **Desktop-App** | Schneidet bei **~5–7 Zeichen** ab (`1234567…`) |
|
||||||
|
| **Mobile App** | Vollständiger Text sichtbar |
|
||||||
|
|
||||||
|
**Kritische Regeln:**
|
||||||
|
- ❌ **NIEMALS Underscores (`_`) in Button-Texten** — zerstört das Button-Rendering komplett (nur grauer Container ohne Buttons)
|
||||||
|
- ✅ **Leerzeichen sind erlaubt** — `1. Links`, `2. Rechts`
|
||||||
|
- ✅ **Emojis helfen** — `✅Ja`, `❌Nein`
|
||||||
|
- ✅ **Text + Nummer an den Anfang** — `1. Links`, `2. Rechts`
|
||||||
|
|
||||||
|
**Empfohlenes Pattern:** Lange Optionen im Text nummeriert, Buttons mit Kurzreferenz:
|
||||||
|
```
|
||||||
|
Text: "1. Links um den Code kopieren\n2. Rechts um den Code fliegen"
|
||||||
|
Buttons: ["1. Links", "2. Rechts"]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Was ist im Paket?
|
## Was ist im Paket?
|
||||||
|
|
||||||
```
|
```
|
||||||
Hermes_rocket.chat_Plugin/
|
Hermes_rocket.chat_Plugin/
|
||||||
├── install.sh ← Interaktives Setup für neue Benutzer
|
├── install.sh ← Interaktives Setup (schreibt config.yaml)
|
||||||
|
├── _merge_config.py ← Python-Script für config.yaml-Management
|
||||||
├── README.md ← Diese Datei
|
├── README.md ← Diese Datei
|
||||||
├── COMMUNITY_POST.md ← Fertige Vorlage für Foren/Reddit
|
├── COMMUNITY_POST.md ← Fertige Vorlage für Foren/Reddit
|
||||||
├── plugin.yaml ← Plugin-Metadaten
|
├── plugin.yaml ← Plugin-Metadaten
|
||||||
@@ -122,7 +151,7 @@ Hermes_rocket.chat_Plugin/
|
|||||||
|
|
||||||
- **Hermes Agent Docs**: https://hermes-agent.nousresearch.com/
|
- **Hermes Agent Docs**: https://hermes-agent.nousresearch.com/
|
||||||
- **Rocket.Chat**: https://www.rocket.chat/
|
- **Rocket.Chat**: https://www.rocket.chat/
|
||||||
- **Dieses Repo**: https://gitea.thomander.de/andreas/Hermes_rocket.chat_Plugin
|
- **Dieses Repo**: https://gitea.myowntools.org/andreas/Hermes_rocket.chat_Plugin
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+8
-2
@@ -55,8 +55,11 @@ _TEMPLATE_MAP = {
|
|||||||
def _build_custom_buttons(labels: list, prefix: str = "") -> list:
|
def _build_custom_buttons(labels: list, prefix: str = "") -> list:
|
||||||
"""Build Rocket.Chat action buttons from plain label strings.
|
"""Build Rocket.Chat action buttons from plain label strings.
|
||||||
|
|
||||||
Rocket.Chat UI truncates button text after ~11-12 chars.
|
Rocket.Chat Desktop-App schneidet Button-Text nach ~5-7 Zeichen ab.
|
||||||
Use short labels (emoji+text without spaces, or numbered refs).
|
Mobile App zeigt vollen Text. NIEMALS Underscores (_) verwenden —
|
||||||
|
sie zerstören das Button-Rendering komplett.
|
||||||
|
|
||||||
|
Empfohlen: nummerierte Kurzreferenzen (1. Links, 2. Rechts).
|
||||||
"""
|
"""
|
||||||
buttons = []
|
buttons = []
|
||||||
for idx, label in enumerate(labels):
|
for idx, label in enumerate(labels):
|
||||||
@@ -98,6 +101,7 @@ def is_connected(config) -> bool:
|
|||||||
def register(ctx):
|
def register(ctx):
|
||||||
"""Plugin entry point — called by the Hermes plugin system at startup."""
|
"""Plugin entry point — called by the Hermes plugin system at startup."""
|
||||||
from .adapter import RocketChatAdapter # lazy import avoids circular deps
|
from .adapter import RocketChatAdapter # lazy import avoids circular deps
|
||||||
|
from .tools import register_tools
|
||||||
|
|
||||||
ctx.register_platform(
|
ctx.register_platform(
|
||||||
name="rocketchat",
|
name="rocketchat",
|
||||||
@@ -121,3 +125,5 @@ def register(ctx):
|
|||||||
"via DDP presence. Use professional but friendly tone."
|
"via DDP presence. Use professional but friendly tone."
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
register_tools(ctx)
|
||||||
|
|||||||
Executable
+156
@@ -0,0 +1,156 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
_merge_config.py — Merges Rocket.Chat settings into ~/.hermes/config.yaml.
|
||||||
|
|
||||||
|
Adds/updates ALL entries needed:
|
||||||
|
- plugins.enabled: rocketchat-platform
|
||||||
|
- gateway.platforms.rocketchat: enabled, extra.base_url, home_channel
|
||||||
|
- toolsets: rocketchat
|
||||||
|
|
||||||
|
Safe: preserves existing structure, comments, and formatting.
|
||||||
|
Only touches rocketchat-related keys.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
try:
|
||||||
|
import yaml
|
||||||
|
except ImportError:
|
||||||
|
print("ERROR: pyyaml required. Run: pip3 install --user pyyaml", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
def load_config(path):
|
||||||
|
"""Load YAML config, return empty dict if file missing/broken."""
|
||||||
|
if not os.path.exists(path):
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
with open(path) as f:
|
||||||
|
return yaml.safe_load(f) or {}
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def save_config(path, data):
|
||||||
|
"""Write config preserving basic structure. Keeps existing file intact if possible."""
|
||||||
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||||
|
with open(path, "w") as f:
|
||||||
|
yaml.safe_dump(data, f, default_flow_style=False, allow_unicode=True, sort_keys=False)
|
||||||
|
# Post-process: ensure proper blank lines between top-level sections
|
||||||
|
_reformat_sections(path)
|
||||||
|
|
||||||
|
|
||||||
|
def _reformat_sections(path):
|
||||||
|
"""Add blank lines between top-level YAML keys for readability."""
|
||||||
|
with open(path) as f:
|
||||||
|
lines = f.readlines()
|
||||||
|
|
||||||
|
out = []
|
||||||
|
prev_was_top_key = False
|
||||||
|
for line in lines:
|
||||||
|
stripped = line.rstrip()
|
||||||
|
is_top_key = bool(stripped) and not stripped[0].isspace() and ":" in stripped
|
||||||
|
|
||||||
|
if is_top_key and out and prev_was_top_key:
|
||||||
|
out.append("\n")
|
||||||
|
elif is_top_key and out:
|
||||||
|
out.append("\n")
|
||||||
|
|
||||||
|
out.append(stripped + "\n")
|
||||||
|
prev_was_top_key = is_top_key
|
||||||
|
|
||||||
|
with open(path, "w") as f:
|
||||||
|
f.writelines(out)
|
||||||
|
|
||||||
|
|
||||||
|
def remove_rocketchat(config):
|
||||||
|
"""Remove all rocketchat-related entries from config (in-place)."""
|
||||||
|
# plugins.enabled
|
||||||
|
if "plugins" in config and "enabled" in config["plugins"]:
|
||||||
|
config["plugins"]["enabled"] = [
|
||||||
|
p for p in config["plugins"]["enabled"] if p != "rocketchat-platform"
|
||||||
|
]
|
||||||
|
# gateway.platforms.rocketchat
|
||||||
|
if "gateway" in config and "platforms" in config["gateway"]:
|
||||||
|
config["gateway"]["platforms"].pop("rocketchat", None)
|
||||||
|
# toolsets
|
||||||
|
if "toolsets" in config and isinstance(config["toolsets"], list):
|
||||||
|
config["toolsets"] = [t for t in config["toolsets"] if t != "rocketchat"]
|
||||||
|
# known_plugin_toolsets.cli
|
||||||
|
if "known_plugin_toolsets" in config and "cli" in config["known_plugin_toolsets"]:
|
||||||
|
config["known_plugin_toolsets"]["cli"] = [
|
||||||
|
t for t in config["known_plugin_toolsets"]["cli"] if t != "rocketchat"
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def merge_config(config, base_url, user, password, room_id, room_name):
|
||||||
|
"""Merge Rocket.Chat settings into the config dict (in-place)."""
|
||||||
|
|
||||||
|
# ── 1. plugins.enabled ──
|
||||||
|
plugins = config.setdefault("plugins", {})
|
||||||
|
enabled_plugins = plugins.setdefault("enabled", [])
|
||||||
|
if "rocketchat-platform" not in enabled_plugins:
|
||||||
|
enabled_plugins.append("rocketchat-platform")
|
||||||
|
|
||||||
|
# ── 2. gateway.platforms.rocketchat ──
|
||||||
|
gateway = config.setdefault("gateway", {})
|
||||||
|
platforms = gateway.setdefault("platforms", {})
|
||||||
|
rc = platforms.setdefault("rocketchat", {})
|
||||||
|
rc["enabled"] = True
|
||||||
|
|
||||||
|
extra = rc.setdefault("extra", {})
|
||||||
|
extra["base_url"] = base_url
|
||||||
|
|
||||||
|
if not rc.get("home_channel") or not rc["home_channel"].get("chat_id"):
|
||||||
|
hc = {"platform": "rocketchat"}
|
||||||
|
if room_id:
|
||||||
|
hc["chat_id"] = room_id
|
||||||
|
if room_name:
|
||||||
|
hc["name"] = room_name
|
||||||
|
rc["home_channel"] = hc
|
||||||
|
|
||||||
|
# ── 3. toolsets (agent-level) ──
|
||||||
|
toolsets = config.setdefault("toolsets", [])
|
||||||
|
if "rocketchat" not in toolsets:
|
||||||
|
# Don't insert if it's a complex structure (dict of lists)
|
||||||
|
if all(isinstance(t, str) for t in toolsets):
|
||||||
|
toolsets.append("rocketchat")
|
||||||
|
|
||||||
|
# ── 4. known_plugin_toolsets.cli ──
|
||||||
|
# Some Hermes versions auto-manage this; add if missing
|
||||||
|
known = config.setdefault("known_plugin_toolsets", {})
|
||||||
|
cli_ts = known.setdefault("cli", [])
|
||||||
|
if "rocketchat" not in cli_ts:
|
||||||
|
if all(isinstance(t, str) for t in cli_ts):
|
||||||
|
cli_ts.append("rocketchat")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description="Merge Rocket.Chat config into Hermes config.yaml")
|
||||||
|
parser.add_argument("--config", required=True, help="Path to ~/.hermes/config.yaml")
|
||||||
|
parser.add_argument("--base-url", default="")
|
||||||
|
parser.add_argument("--user", default="")
|
||||||
|
parser.add_argument("--password", default="")
|
||||||
|
parser.add_argument("--room-id", default="")
|
||||||
|
parser.add_argument("--room-name", default="")
|
||||||
|
parser.add_argument("--remove", action="store_true", help="Remove rocketchat entries")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
if args.remove:
|
||||||
|
config = load_config(args.config)
|
||||||
|
remove_rocketchat(config)
|
||||||
|
save_config(args.config, config)
|
||||||
|
print("OK (removed)")
|
||||||
|
return
|
||||||
|
|
||||||
|
config = load_config(args.config)
|
||||||
|
merge_config(config, args.base_url, args.user, args.password, args.room_id, args.room_name)
|
||||||
|
save_config(args.config, config)
|
||||||
|
|
||||||
|
print("OK")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+181
-53
@@ -13,6 +13,7 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import queue
|
import queue
|
||||||
|
import re
|
||||||
import socket
|
import socket
|
||||||
import ssl
|
import ssl
|
||||||
import struct
|
import struct
|
||||||
@@ -22,6 +23,14 @@ import urllib.request
|
|||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
logger.setLevel(logging.INFO)
|
||||||
|
# Ensure adapter logs are visible in gateway.log by adding a stderr handler
|
||||||
|
if not logger.handlers:
|
||||||
|
_handler = logging.StreamHandler()
|
||||||
|
_handler.setLevel(logging.DEBUG)
|
||||||
|
_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
|
||||||
|
logger.addHandler(_handler)
|
||||||
|
logger.propagate = False # Don't double-log to root
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from gateway.platforms.base import (
|
from gateway.platforms.base import (
|
||||||
@@ -130,6 +139,7 @@ class DDPClient:
|
|||||||
self._sub_rooms: Dict[str, str] = {}
|
self._sub_rooms: Dict[str, str] = {}
|
||||||
self._session: Optional[str] = None
|
self._session: Optional[str] = None
|
||||||
self._reconnect_attempt = 0
|
self._reconnect_attempt = 0
|
||||||
|
self._last_rx_time = 0.0
|
||||||
|
|
||||||
def _create_socket(self) -> socket.socket:
|
def _create_socket(self) -> socket.socket:
|
||||||
ctx = ssl.create_default_context()
|
ctx = ssl.create_default_context()
|
||||||
@@ -225,8 +235,9 @@ class DDPClient:
|
|||||||
if opcode == 0x09:
|
if opcode == 0x09:
|
||||||
self._send_raw_pong(payload)
|
self._send_raw_pong(payload)
|
||||||
elif opcode == 0x01 and payload:
|
elif opcode == 0x01 and payload:
|
||||||
|
self._last_rx_time = time.time()
|
||||||
try:
|
try:
|
||||||
data = json.loads(payload.decode("utf-8"))
|
data = json.loads(payload.decode("utf-8", errors="ignore"))
|
||||||
msg_type = data.get("msg", "")
|
msg_type = data.get("msg", "")
|
||||||
if msg_type == "connected":
|
if msg_type == "connected":
|
||||||
self.connected = True
|
self.connected = True
|
||||||
@@ -235,10 +246,10 @@ class DDPClient:
|
|||||||
self._on_connected()
|
self._on_connected()
|
||||||
elif msg_type == "ping":
|
elif msg_type == "ping":
|
||||||
self._send_json({"msg": "pong"})
|
self._send_json({"msg": "pong"})
|
||||||
elif msg_type == "changed" and data.get("collection") == "stream-room-messages":
|
elif msg_type in ("changed", "added") and data.get("collection") == "stream-room-messages":
|
||||||
fields = data.get("fields", {})
|
fields = data.get("fields", {})
|
||||||
args = fields.get("args", [])
|
args = fields.get("args", [])
|
||||||
if args and isinstance(args, list):
|
if args and isinstance(args, list) and len(args) >= 1:
|
||||||
self._msg_queue.put(args[0])
|
self._msg_queue.put(args[0])
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
@@ -249,7 +260,17 @@ class DDPClient:
|
|||||||
self.connected = False
|
self.connected = False
|
||||||
logger.debug("DDP reader thread exited")
|
logger.debug("DDP reader thread exited")
|
||||||
|
|
||||||
|
def is_alive(self, max_silence: float = 300.0) -> bool:
|
||||||
|
"""Detect silent death: socket looks connected but no traffic for max_silence seconds."""
|
||||||
|
if not self.connected or not self.sock:
|
||||||
|
return False
|
||||||
|
if self._last_rx_time == 0:
|
||||||
|
# Never received anything yet — use connect time as baseline
|
||||||
|
return True
|
||||||
|
return (time.time() - self._last_rx_time) < max_silence
|
||||||
|
|
||||||
def connect_and_login(self, token: str) -> bool:
|
def connect_and_login(self, token: str) -> bool:
|
||||||
|
self._last_rx_time = time.time()
|
||||||
try:
|
try:
|
||||||
self.sock = self._create_socket()
|
self.sock = self._create_socket()
|
||||||
if not self._handshake(self.sock):
|
if not self._handshake(self.sock):
|
||||||
@@ -323,6 +344,9 @@ class DDPClient:
|
|||||||
|
|
||||||
|
|
||||||
class RocketChatAdapter(BasePlatformAdapter):
|
class RocketChatAdapter(BasePlatformAdapter):
|
||||||
|
HEALTH_CHECK_INTERVAL = 60.0 # seconds
|
||||||
|
HEALTH_SILENT_LIMIT = 300.0 # 5 min without any server activity = force reconnect
|
||||||
|
|
||||||
def __init__(self, config: PlatformConfig):
|
def __init__(self, config: PlatformConfig):
|
||||||
super().__init__(config=config, platform=Platform("rocketchat"))
|
super().__init__(config=config, platform=Platform("rocketchat"))
|
||||||
self.base_url = _get_config_str(config, "base_url", "ROCKETCHAT_BASE_URL")
|
self.base_url = _get_config_str(config, "base_url", "ROCKETCHAT_BASE_URL")
|
||||||
@@ -339,6 +363,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self._last_activity = 0.0
|
self._last_activity = 0.0
|
||||||
self._shutdown_event = threading.Event()
|
self._shutdown_event = threading.Event()
|
||||||
self._room_info: Dict[str, dict] = {}
|
self._room_info: Dict[str, dict] = {}
|
||||||
|
# Clarify-Queue: tracks pending button questions per chat_id
|
||||||
|
# so incoming replies can be correlated with the original question.
|
||||||
|
self._pending_clarifies: Dict[str, dict] = {}
|
||||||
|
# Health-check state
|
||||||
|
self._last_server_activity = 0.0 # ts of last DDP ping/pong or message
|
||||||
|
self._health_check_timer: Optional[threading.Timer] = None
|
||||||
|
self._last_ddp_ping_ok = False
|
||||||
|
self._running = False
|
||||||
|
|
||||||
async def connect(self) -> bool:
|
async def connect(self) -> bool:
|
||||||
if not self.base_url or not self.user or not self.password:
|
if not self.base_url or not self.user or not self.password:
|
||||||
@@ -352,25 +384,97 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
||||||
self.ddp = DDPClient(
|
self.ddp = DDPClient(
|
||||||
host=host,
|
host=host,
|
||||||
on_connected_cb=lambda: self.ddp.set_status("away") if self.ddp else None,
|
on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None,
|
||||||
)
|
)
|
||||||
if not self.ddp.connect_and_login(self._auth_token):
|
if not self.ddp.connect_and_login(self._auth_token):
|
||||||
logger.error("[rocketchat] DDP connect/login failed")
|
logger.error("[rocketchat] DDP connect/login failed")
|
||||||
return False
|
return False
|
||||||
self._rooms = self.rest.get_rooms()
|
self._rooms = self.rest.get_rooms()
|
||||||
|
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
|
||||||
for room in self._rooms:
|
for room in self._rooms:
|
||||||
sub_id = self.ddp.subscribe_room(room["id"])
|
sub_id = self.ddp.subscribe_room(room["id"])
|
||||||
if sub_id:
|
if sub_id:
|
||||||
self._subscribed_rooms.add(room["id"])
|
self._subscribed_rooms.add(room["id"])
|
||||||
self._room_info[room["id"]] = {"name": room["name"], "type": room["type"]}
|
self._room_info[room["id"]] = {"name": room["name"], "type": room["type"]}
|
||||||
logger.info("[rocketchat] Subscribed to %s", room["name"])
|
logger.info("[rocketchat] Subscribed to %s (%s)", room["name"], room["id"])
|
||||||
|
logger.info("[rocketchat] Total subscribed rooms: %d", len(self._subscribed_rooms))
|
||||||
self._mark_connected()
|
self._mark_connected()
|
||||||
|
self._running = True
|
||||||
self._listen_task = asyncio.create_task(self._listen_loop())
|
self._listen_task = asyncio.create_task(self._listen_loop())
|
||||||
self._last_activity = time.time()
|
self._last_activity = time.time()
|
||||||
self._schedule_idle_timer()
|
logger.info("[rocketchat] Listen loop started, _running=%s", self._running)
|
||||||
logger.info("[rocketchat] Connected to %s", self.base_url)
|
logger.info("[rocketchat] Connected to %s", self.base_url)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
def _schedule_idle_timer(self) -> None:
|
||||||
|
"""Schedule idle timer to mark bot as away when inactive."""
|
||||||
|
if self._status_timer:
|
||||||
|
self._status_timer.cancel()
|
||||||
|
|
||||||
|
def _set_away():
|
||||||
|
if self.ddp:
|
||||||
|
self.ddp.set_status("away")
|
||||||
|
|
||||||
|
self._status_timer = threading.Timer(300.0, _set_away) # 5 minutes
|
||||||
|
self._status_timer.daemon = True
|
||||||
|
self._status_timer.start()
|
||||||
|
|
||||||
|
async def _process_incoming(self, msg_obj) -> None:
|
||||||
|
"""Process an incoming message from the DDP queue."""
|
||||||
|
if not isinstance(msg_obj, dict):
|
||||||
|
return
|
||||||
|
|
||||||
|
# Check if this is a button click response by looking for specific fields
|
||||||
|
is_button_response = (
|
||||||
|
msg_obj.get("triggerId") and
|
||||||
|
msg_obj.get("actions") and
|
||||||
|
msg_obj.get("params", {}).get("triggerSender") and
|
||||||
|
msg_obj.get("params", {}).get("payload")
|
||||||
|
)
|
||||||
|
|
||||||
|
msg_id = msg_obj.get("_id", "")
|
||||||
|
text = msg_obj.get("msg", "")
|
||||||
|
room_id = msg_obj.get("rid", "")
|
||||||
|
user_info = msg_obj.get("u", {})
|
||||||
|
username = (user_info.get("username", "") or "").lower() # normalize case
|
||||||
|
|
||||||
|
# Skip own messages (case-insensitive comparison)
|
||||||
|
if username == (self.user or "").lower() or not text or not room_id:
|
||||||
|
return
|
||||||
|
# Skip system messages
|
||||||
|
if msg_obj.get("t"):
|
||||||
|
return
|
||||||
|
|
||||||
|
# Update activity
|
||||||
|
self._last_activity = time.time()
|
||||||
|
room_name = self._room_info.get(room_id, {}).get("name", room_id)
|
||||||
|
logger.info("[rocketchat] Message from %s in %s: %s", username, room_name, text[:80])
|
||||||
|
|
||||||
|
# Dispatch to gateway handler via base-class handle_message
|
||||||
|
try:
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
message_type = MessageType.BUTTON_CLICK if is_button_response else MessageType.TEXT
|
||||||
|
source = SessionSource(
|
||||||
|
platform=Platform("rocketchat"),
|
||||||
|
chat_id=room_id,
|
||||||
|
chat_name=room_name,
|
||||||
|
user_id=username,
|
||||||
|
user_name=username,
|
||||||
|
chat_type="dm" if self._room_info.get(room_id, {}).get("type") == "d" else "group",
|
||||||
|
)
|
||||||
|
event = MessageEvent(
|
||||||
|
text=text,
|
||||||
|
message_type=message_type,
|
||||||
|
message_id=msg_id,
|
||||||
|
timestamp=datetime.fromtimestamp(time.time()),
|
||||||
|
raw_message=msg_obj,
|
||||||
|
)
|
||||||
|
event.source = source
|
||||||
|
await self.handle_message(event)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("[rocketchat] handle_message error: %s", e)
|
||||||
|
|
||||||
async def disconnect(self) -> None:
|
async def disconnect(self) -> None:
|
||||||
self._mark_disconnected()
|
self._mark_disconnected()
|
||||||
self._shutdown_event.set()
|
self._shutdown_event.set()
|
||||||
@@ -392,6 +496,38 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if not self.rest.auth_token:
|
if not self.rest.auth_token:
|
||||||
return SendResult(success=False, error="Not authenticated")
|
return SendResult(success=False, error="Not authenticated")
|
||||||
|
|
||||||
|
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
|
||||||
|
# This allows the agent to request buttons by embedding markup in its
|
||||||
|
# response text, without requiring the gateway to pass metadata.
|
||||||
|
# Syntax: [[BUTTONS:yes_no]]Your question here[[/BUTTONS]]
|
||||||
|
# [[BUTTONS:custom]]Option A|Option B|Option C[[/BUTTONS]]
|
||||||
|
_btn_re = re.compile(
|
||||||
|
r'\[\[BUTTONS:(?P<template>[a-zA-Z0-9_]+)\]\]'
|
||||||
|
r'(?P<text>.*?)'
|
||||||
|
r'\[\[/BUTTONS\]\]',
|
||||||
|
re.DOTALL | re.IGNORECASE,
|
||||||
|
)
|
||||||
|
_match = _btn_re.search(content or "")
|
||||||
|
if _match:
|
||||||
|
_template_name = _match.group("template").lower()
|
||||||
|
_inner_text = _match.group("text").strip()
|
||||||
|
# Strip the markup from content, keep the inner text
|
||||||
|
content = _btn_re.sub(_inner_text, content).strip()
|
||||||
|
# Build synthetic metadata so the existing template path below handles it
|
||||||
|
_valid_templates = {"yes_no", "confirm_cancel", "ok", "multi_choice_3"}
|
||||||
|
if _template_name == "custom" or "|" in _inner_text:
|
||||||
|
# Custom buttons: labels separated by pipe
|
||||||
|
_labels = [l.strip() for l in _inner_text.split("|") if l.strip()]
|
||||||
|
metadata = dict(metadata or {})
|
||||||
|
metadata["template"] = "custom"
|
||||||
|
metadata["custom_buttons"] = _labels
|
||||||
|
metadata["question_id"] = metadata.get("question_id", "custom_btn")
|
||||||
|
metadata.setdefault("button_title", "Wähle eine Option:")
|
||||||
|
elif _template_name in _valid_templates:
|
||||||
|
metadata = dict(metadata or {})
|
||||||
|
metadata["template"] = _template_name
|
||||||
|
metadata["question_id"] = metadata.get("question_id", f"btn_{_template_name}")
|
||||||
|
|
||||||
# Handle interaction templates via metadata
|
# Handle interaction templates via metadata
|
||||||
attachments = None
|
attachments = None
|
||||||
if metadata and metadata.get("template"):
|
if metadata and metadata.get("template"):
|
||||||
@@ -424,6 +560,27 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
attachment["actions"] = buttons
|
attachment["actions"] = buttons
|
||||||
attachments = [attachment]
|
attachments = [attachment]
|
||||||
|
|
||||||
|
# ── Clarify-Queue: remember pending button question ──
|
||||||
|
if metadata and metadata.get("template") and attachments:
|
||||||
|
_tmpl = metadata.get("template")
|
||||||
|
_qid = metadata.get("question_id", "")
|
||||||
|
_expected = []
|
||||||
|
if _tmpl == "yes_no":
|
||||||
|
_expected = ["ja", "nein", "yes", "no"]
|
||||||
|
elif _tmpl == "confirm_cancel":
|
||||||
|
_expected = ["bestätigen", "confirm", "abbrechen", "cancel"]
|
||||||
|
elif _tmpl == "ok":
|
||||||
|
_expected = ["ok", "okay", "verstanden", "alles klar"]
|
||||||
|
elif _tmpl == "custom" and metadata.get("custom_buttons"):
|
||||||
|
_expected = [b.lower() for b in metadata["custom_buttons"]]
|
||||||
|
self._pending_clarifies[chat_id] = {
|
||||||
|
"question_id": _qid,
|
||||||
|
"template": _tmpl,
|
||||||
|
"expected": _expected,
|
||||||
|
"timestamp": time.time(),
|
||||||
|
"original_text": content,
|
||||||
|
}
|
||||||
|
|
||||||
success = self.rest.post_message(chat_id, content, attachments=attachments)
|
success = self.rest.post_message(chat_id, content, attachments=attachments)
|
||||||
if success:
|
if success:
|
||||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||||
@@ -438,10 +595,27 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
|
|
||||||
async def _listen_loop(self):
|
async def _listen_loop(self):
|
||||||
loop = asyncio.get_running_loop()
|
loop = asyncio.get_running_loop()
|
||||||
|
health_check_counter = 0
|
||||||
while self._running and not self._shutdown_event.is_set():
|
while self._running and not self._shutdown_event.is_set():
|
||||||
try:
|
try:
|
||||||
msg_obj = await loop.run_in_executor(None, self._ddp_queue_get, 1.0)
|
msg_obj = await loop.run_in_executor(None, self._ddp_queue_get, 1.0)
|
||||||
if msg_obj is None:
|
if msg_obj is None:
|
||||||
|
health_check_counter += 1
|
||||||
|
# Every 60 seconds (60 x 1.0s timeouts): check for silent death
|
||||||
|
if health_check_counter >= 60:
|
||||||
|
health_check_counter = 0
|
||||||
|
if self.ddp and self.ddp.connected and not self.ddp.is_alive(self.HEALTH_SILENT_LIMIT):
|
||||||
|
logger.warning(
|
||||||
|
"[rocketchat] Silent death detected: no DDP traffic for %.0fs — forcing reconnect",
|
||||||
|
self.HEALTH_SILENT_LIMIT,
|
||||||
|
)
|
||||||
|
if self._auth_token and self.ddp.reconnect_and_restore(self._auth_token):
|
||||||
|
logger.info("[rocketchat] Recovered from silent death")
|
||||||
|
else:
|
||||||
|
logger.error("[rocketchat] Silent death recovery failed")
|
||||||
|
await asyncio.sleep(10)
|
||||||
|
continue
|
||||||
|
|
||||||
if self.ddp and not self.ddp.connected:
|
if self.ddp and not self.ddp.connected:
|
||||||
logger.warning("[rocketchat] DDP disconnected, reconnecting...")
|
logger.warning("[rocketchat] DDP disconnected, reconnecting...")
|
||||||
if self._auth_token and self.ddp.reconnect_and_restore(self._auth_token):
|
if self._auth_token and self.ddp.reconnect_and_restore(self._auth_token):
|
||||||
@@ -449,6 +623,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
else:
|
else:
|
||||||
await asyncio.sleep(5)
|
await asyncio.sleep(5)
|
||||||
continue
|
continue
|
||||||
|
health_check_counter = 0 # Reset on any message
|
||||||
await self._process_incoming(msg_obj)
|
await self._process_incoming(msg_obj)
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
break
|
break
|
||||||
@@ -463,50 +638,3 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
return self.ddp._msg_queue.get(timeout=timeout)
|
return self.ddp._msg_queue.get(timeout=timeout)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
async def _process_incoming(self, msg_obj: dict):
|
|
||||||
rid = msg_obj.get("rid")
|
|
||||||
msg_text = msg_obj.get("msg", "")
|
|
||||||
msg_id = msg_obj.get("_id", "")
|
|
||||||
user_info = msg_obj.get("u", {})
|
|
||||||
sender_id = user_info.get("_id", "")
|
|
||||||
sender_name = user_info.get("username", "unknown")
|
|
||||||
if sender_id == self._user_id:
|
|
||||||
return
|
|
||||||
if not rid or not msg_text:
|
|
||||||
return
|
|
||||||
self._last_activity = time.time()
|
|
||||||
self._go_online()
|
|
||||||
room_name = self._room_info.get(rid, {}).get("name", rid)
|
|
||||||
source = self.build_source(
|
|
||||||
chat_id=rid,
|
|
||||||
chat_name=room_name,
|
|
||||||
chat_type="group" if self._room_info.get(rid, {}).get("type") in ("c", "p") else "dm",
|
|
||||||
user_id=sender_id,
|
|
||||||
user_name=sender_name,
|
|
||||||
)
|
|
||||||
event = MessageEvent(
|
|
||||||
text=msg_text,
|
|
||||||
message_type=MessageType.TEXT,
|
|
||||||
source=source,
|
|
||||||
raw_message=msg_obj,
|
|
||||||
message_id=msg_id,
|
|
||||||
)
|
|
||||||
await self.handle_message(event)
|
|
||||||
|
|
||||||
def _go_online(self):
|
|
||||||
if self.ddp and self.ddp.connected:
|
|
||||||
self.ddp.set_status("online")
|
|
||||||
self._schedule_idle_timer()
|
|
||||||
|
|
||||||
def _go_idle(self):
|
|
||||||
idle = time.time() - self._last_activity
|
|
||||||
if idle >= 900 and self.ddp and self.ddp.connected:
|
|
||||||
self.ddp.set_status("away")
|
|
||||||
|
|
||||||
def _schedule_idle_timer(self):
|
|
||||||
if self._status_timer:
|
|
||||||
self._status_timer.cancel()
|
|
||||||
self._status_timer = threading.Timer(900, self._go_idle)
|
|
||||||
self._status_timer.daemon = True
|
|
||||||
self._status_timer.start()
|
|
||||||
|
|||||||
+65
-44
@@ -26,7 +26,8 @@ Was install.sh macht:
|
|||||||
3. Kopiert plugin.yaml, __init__.py, adapter.py
|
3. Kopiert plugin.yaml, __init__.py, adapter.py
|
||||||
4. Fragt Rocket.Chat-Zugangsdaten interaktiv ab
|
4. Fragt Rocket.Chat-Zugangsdaten interaktiv ab
|
||||||
5. Testet die Verbindung und liest UserID/RoomID aus
|
5. Testet die Verbindung und liest UserID/RoomID aus
|
||||||
6. Schreibt die Konfiguration in ~/.hermes/.env
|
6. Schreibt ALLE Einstellungen in ~/.hermes/config.yaml
|
||||||
|
(nicht nur .env — das ist für API-Keys)
|
||||||
7. Bietet Neustart von Hermes Gateway an
|
7. Bietet Neustart von Hermes Gateway an
|
||||||
|
|
||||||
Deinstallation: ./uninstall.sh
|
Deinstallation: ./uninstall.sh
|
||||||
@@ -46,6 +47,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|||||||
PLUGIN_NAME="rocketchat"
|
PLUGIN_NAME="rocketchat"
|
||||||
HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
|
HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
|
||||||
PLUGIN_DEST="$HERMES_HOME/hermes-agent/plugins/platforms/$PLUGIN_NAME"
|
PLUGIN_DEST="$HERMES_HOME/hermes-agent/plugins/platforms/$PLUGIN_NAME"
|
||||||
|
CONFIG_FILE="$HERMES_HOME/config.yaml"
|
||||||
|
|
||||||
ECHO_OK() { echo -e " ✅ $1"; }
|
ECHO_OK() { echo -e " ✅ $1"; }
|
||||||
ECHO_ERR() { echo -e " ❌ $1"; }
|
ECHO_ERR() { echo -e " ❌ $1"; }
|
||||||
@@ -94,6 +96,21 @@ if [[ -n "$MISSING" ]]; then
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# ── Check: pip pyyaml ──
|
||||||
|
if ! python3 -c "import yaml" 2>/dev/null; then
|
||||||
|
if ! $DRY_RUN; then
|
||||||
|
read -rp " python3-yaml fehlt. Installieren? [j/N] " ans
|
||||||
|
if [[ "$ans" =~ ^[Jj]$ ]]; then
|
||||||
|
pip3 install --user pyyaml
|
||||||
|
else
|
||||||
|
echo "Abbruch. 'pip3 install --user pyyaml' wird benötigt."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
ECHO_DRY "würde pyyaml installieren"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
# ── Schritt 2: Zielverzeichnis anlegen ──
|
# ── Schritt 2: Zielverzeichnis anlegen ──
|
||||||
ECHO_STEP "2/7 Erstelle Plugin-Verzeichnis"
|
ECHO_STEP "2/7 Erstelle Plugin-Verzeichnis"
|
||||||
|
|
||||||
@@ -183,6 +200,7 @@ ECHO_OK "Login erfolgreich (UserID: $USER_ID)"
|
|||||||
|
|
||||||
# Raum auflösen, wenn angegeben
|
# Raum auflösen, wenn angegeben
|
||||||
ROOM_ID=""
|
ROOM_ID=""
|
||||||
|
ROOM_NAME="${RC_ROOM:-}"
|
||||||
if [[ -n "$RC_ROOM" ]]; then
|
if [[ -n "$RC_ROOM" ]]; then
|
||||||
ROOM_QUERY="${RC_ROOM/#\#}"
|
ROOM_QUERY="${RC_ROOM/#\#}"
|
||||||
ROOM_RESP=$(curl -s -H "X-Auth-Token: $AUTH_TOKEN" -H "X-User-Id: $USER_ID" \
|
ROOM_RESP=$(curl -s -H "X-Auth-Token: $AUTH_TOKEN" -H "X-User-Id: $USER_ID" \
|
||||||
@@ -190,73 +208,73 @@ if [[ -n "$RC_ROOM" ]]; then
|
|||||||
|
|
||||||
if echo "$ROOM_RESP" | grep -q '"success":true'; then
|
if echo "$ROOM_RESP" | grep -q '"success":true'; then
|
||||||
ROOM_ID=$(echo "$ROOM_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['room']['_id'])")
|
ROOM_ID=$(echo "$ROOM_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['room']['_id'])")
|
||||||
|
ROOM_NAME=$(echo "$ROOM_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['room'].get('fname') or d['room'].get('name', '$ROOM_QUERY'))")
|
||||||
ECHO_OK "Raum gefunden: #$ROOM_QUERY (RoomID: $ROOM_ID)"
|
ECHO_OK "Raum gefunden: #$ROOM_QUERY (RoomID: $ROOM_ID)"
|
||||||
else
|
else
|
||||||
ECHO_WARN "Raum '#$ROOM_QUERY' nicht gefunden — überspringe"
|
ECHO_WARN "Raum '#$ROOM_QUERY' nicht gefunden — überspringe"
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ── Schritt 6: Env-Variablen setzen ──
|
# ── Schritt 6: Config.yaml schreiben ──
|
||||||
ECHO_STEP "6/7 Schreibe Konfiguration"
|
ECHO_STEP "6/7 Schreibe Konfiguration in config.yaml"
|
||||||
|
|
||||||
ENV_FILE="$HERMES_HOME/.env"
|
# Prüfen, ob eine config.yaml existiert
|
||||||
run_or_simulate "Verzeichnis erstellen: $HERMES_HOME" mkdir -p "$HERMES_HOME"
|
if [[ ! -f "$CONFIG_FILE" ]]; then
|
||||||
run_or_simulate "Env-Datei berühren: $ENV_FILE" touch "$ENV_FILE"
|
|
||||||
|
|
||||||
# Alte Einträge entfernen
|
|
||||||
if ! $DRY_RUN; then
|
if ! $DRY_RUN; then
|
||||||
sed -i '/^ROCKETCHAT_/d' "$ENV_FILE" 2>/dev/null || true
|
ECHO_WARN "$CONFIG_FILE nicht gefunden — wird neu erstellt"
|
||||||
|
else
|
||||||
|
ECHO_DRY "würde neue config.yaml erstellen"
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
run_or_simulate "Env-Einträge in $ENV_FILE schreiben" bash -c "
|
run_or_simulate "config.yaml aktualisieren" python3 "$SCRIPT_DIR/_merge_config.py" \
|
||||||
cat >> '$ENV_FILE' <<'INNEREOF'
|
--config "$CONFIG_FILE" \
|
||||||
|
--base-url "$RC_URL" \
|
||||||
|
--user "$RC_USER" \
|
||||||
|
--password "$RC_PASS" \
|
||||||
|
--room-id "${ROOM_ID:-}" \
|
||||||
|
--room-name "${ROOM_NAME:-}"
|
||||||
|
|
||||||
|
$DRY_RUN || ECHO_OK "~/.hermes/config.yaml aktualisiert"
|
||||||
|
|
||||||
|
# Zusätzlich .env für API-Keys (Passwort)
|
||||||
|
if ! $DRY_RUN; then
|
||||||
|
ENV_FILE="$HERMES_HOME/.env"
|
||||||
|
mkdir -p "$HERMES_HOME"
|
||||||
|
# Alte ROCKETCHAT_-Einträge entfernen
|
||||||
|
if [[ -f "$ENV_FILE" ]]; then
|
||||||
|
sed -i '/^ROCKETCHAT_/d' "$ENV_FILE" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
cat >> "$ENV_FILE" <<INNEREOF
|
||||||
|
|
||||||
# Rocket.Chat Plugin — generiert von install.sh am $(date +%Y-%m-%d)
|
# Rocket.Chat Plugin — generiert von install.sh am $(date +%Y-%m-%d)
|
||||||
export ROCKETCHAT_BASE_URL=\"$RC_URL\"
|
export ROCKETCHAT_BASE_URL="$RC_URL"
|
||||||
export ROCKETCHAT_USER=\"$RC_USER\"
|
export ROCKETCHAT_USER="$RC_USER"
|
||||||
export ROCKETCHAT_PASSWORD=\"$RC_PASS\"
|
export ROCKETCHAT_PASSWORD="$RC_PASS"
|
||||||
export ROCKETCHAT_ALLOW_ALL_USERS=\"false\"
|
|
||||||
INNEREOF
|
INNEREOF
|
||||||
[[ -n '$ROOM_ID' ]] && echo 'export ROCKETCHAT_ROOM_ID=\"$ROOM_ID\"' >> '$ENV_FILE'
|
ECHO_OK "~/.hermes/.env ergänzt"
|
||||||
"
|
else
|
||||||
|
ECHO_DRY "würde ~/.hermes/.env ergänzen"
|
||||||
$DRY_RUN || ECHO_OK "~/.hermes/.env aktualisiert"
|
fi
|
||||||
|
|
||||||
# Optional: config.yaml Eintrag anzeigen
|
|
||||||
ECHO_INFO "Falls du config.yaml bevorzugst, füge Folgendes hinzu:"
|
|
||||||
cat <<EOF
|
|
||||||
|
|
||||||
plugins:
|
|
||||||
platforms:
|
|
||||||
rocketchat:
|
|
||||||
enabled: true
|
|
||||||
base_url: "$RC_URL"
|
|
||||||
user: "$RC_USER"
|
|
||||||
password: "$RC_PASS"
|
|
||||||
room_id: "${ROOM_ID:-optional}"
|
|
||||||
allowed_users: []
|
|
||||||
allow_all_users: false
|
|
||||||
EOF
|
|
||||||
|
|
||||||
# ── Schritt 7: Hermes Gateway Neustart ──
|
# ── Schritt 7: Hermes Gateway Neustart ──
|
||||||
ECHO_STEP "7/7 Hermes Gateway Neustart"
|
ECHO_STEP "7/7 Hermes Gateway Neustart"
|
||||||
|
|
||||||
if $DRY_RUN; then
|
if $DRY_RUN; then
|
||||||
ECHO_DRY "würde hermes gateway stop ausführen (falls verfügbar)"
|
ECHO_DRY "würde hermes gateway restart ausführen"
|
||||||
ECHO_DRY "würde Hinweis ausgeben: hermes gateway start"
|
|
||||||
else
|
else
|
||||||
if command -v hermes &>/dev/null; then
|
if command -v hermes &>/dev/null; then
|
||||||
|
ECHO_INFO "Gateway wird neu gestartet..."
|
||||||
|
hermes gateway restart 2>/dev/null || {
|
||||||
hermes gateway stop 2>/dev/null || true
|
hermes gateway stop 2>/dev/null || true
|
||||||
sleep 1
|
sleep 1
|
||||||
ECHO_OK "Hermes Gateway gestoppt"
|
hermes gateway start 2>/dev/null || true
|
||||||
echo ""
|
}
|
||||||
echo " Starte neu mit:"
|
ECHO_OK "Hermes Gateway neu gestartet"
|
||||||
echo " hermes gateway start"
|
|
||||||
echo ""
|
|
||||||
else
|
else
|
||||||
ECHO_WARN "'hermes' Befehl nicht im PATH gefunden"
|
ECHO_WARN "'hermes' Befehl nicht im PATH gefunden"
|
||||||
echo " Bitte starte Hermes Gateway manuell:"
|
echo " Bitte starte Hermes Gateway manuell:"
|
||||||
echo " hermes gateway start"
|
echo " hermes gateway restart"
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -267,6 +285,9 @@ if $DRY_RUN; then
|
|||||||
else
|
else
|
||||||
ECHO_STEP "✨ Fertig!"
|
ECHO_STEP "✨ Fertig!"
|
||||||
ECHO_OK "Plugin installiert unter: $PLUGIN_DEST"
|
ECHO_OK "Plugin installiert unter: $PLUGIN_DEST"
|
||||||
ECHO_INFO "Env-Variablen geladen in: $ENV_FILE"
|
ECHO_OK "Konfiguration in: $CONFIG_FILE"
|
||||||
ECHO_INFO "Rocket.Chat Plugin ist bereit."
|
ECHO_INFO "Rocket.Chat Plugin ist bereit."
|
||||||
|
if [[ -n "$ROOM_ID" ]]; then
|
||||||
|
ECHO_INFO "Monitoring: $ROOM_NAME ($ROOM_ID)"
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|||||||
+30
-13
@@ -18,6 +18,7 @@ PLUGIN_NAME="rocketchat"
|
|||||||
HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
|
HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
|
||||||
PLUGIN_DEST="$HERMES_HOME/hermes-agent/plugins/platforms/$PLUGIN_NAME"
|
PLUGIN_DEST="$HERMES_HOME/hermes-agent/plugins/platforms/$PLUGIN_NAME"
|
||||||
ENV_FILE="$HERMES_HOME/.env"
|
ENV_FILE="$HERMES_HOME/.env"
|
||||||
|
CONFIG_FILE="$HERMES_HOME/config.yaml"
|
||||||
|
|
||||||
ECHO_OK() { echo -e " ✅ $1"; }
|
ECHO_OK() { echo -e " ✅ $1"; }
|
||||||
ECHO_ERR() { echo -e " ❌ $1"; }
|
ECHO_ERR() { echo -e " ❌ $1"; }
|
||||||
@@ -73,9 +74,10 @@ else
|
|||||||
ECHO_INFO "Plugin-Verzeichnis nicht gefunden — überspringe"
|
ECHO_INFO "Plugin-Verzeichnis nicht gefunden — überspringe"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ── Schritt 3: Env-Variablen bereinigen ──
|
# ── Schritt 3: Env-Variablen & config.yaml bereinigen ──
|
||||||
ECHO_STEP "3/4 Env-Variablen bereinigen"
|
ECHO_STEP "3/4 Env-Variablen & config.yaml bereinigen"
|
||||||
|
|
||||||
|
# Env
|
||||||
if [[ -f "$ENV_FILE" ]]; then
|
if [[ -f "$ENV_FILE" ]]; then
|
||||||
RC_COUNT=$(grep -c "^ROCKETCHAT_" "$ENV_FILE" 2>/dev/null || echo "0")
|
RC_COUNT=$(grep -c "^ROCKETCHAT_" "$ENV_FILE" 2>/dev/null || echo "0")
|
||||||
if [[ "$RC_COUNT" -gt 0 ]]; then
|
if [[ "$RC_COUNT" -gt 0 ]]; then
|
||||||
@@ -93,23 +95,35 @@ if [[ -f "$ENV_FILE" ]]; then
|
|||||||
else
|
else
|
||||||
ECHO_INFO "Keine ROCKETCHAT_-Einträge in .env gefunden"
|
ECHO_INFO "Keine ROCKETCHAT_-Einträge in .env gefunden"
|
||||||
fi
|
fi
|
||||||
else
|
|
||||||
ECHO_INFO "~/.hermes/.env nicht vorhanden — überspringe"
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ── Schritt 4: Config.yaml Hinweis ──
|
# Config.yaml
|
||||||
ECHO_STEP "4/4 Config.yaml prüfen"
|
if [[ -f "$CONFIG_FILE" ]] && grep -q "rocketchat" "$CONFIG_FILE" 2>/dev/null; then
|
||||||
|
ECHO_WARN "rocketchat-Einträge in config.yaml gefunden"
|
||||||
CONFIG_FILE="$HERMES_HOME/config.yaml"
|
if ! $DRY_RUN; then
|
||||||
if [[ -f "$CONFIG_FILE" ]] && grep -q "rocketchat:" "$CONFIG_FILE" 2>/dev/null; then
|
read -rp " rocketchat-Einträge aus config.yaml entfernen? [j/N] " ans
|
||||||
ECHO_WARN "rocketchat:-Eintrag in config.yaml gefunden"
|
if [[ "$ans" =~ ^[Jj]$ ]]; then
|
||||||
echo " Bitte manuell entfernen, falls gewünscht:"
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
python3 "$SCRIPT_DIR/_merge_config.py" --remove --config "$CONFIG_FILE" 2>/dev/null || {
|
||||||
|
ECHO_WARN "Automatische config.yaml-Bereinigung fehlgeschlagen"
|
||||||
|
echo " Bitte manuell bereinigen:"
|
||||||
echo " $ nano $CONFIG_FILE"
|
echo " $ nano $CONFIG_FILE"
|
||||||
|
echo " Suche nach 'rocketchat' und entferne die Einträge."
|
||||||
|
}
|
||||||
|
ECHO_OK "config.yaml-Einträge entfernt"
|
||||||
else
|
else
|
||||||
ECHO_INFO "Kein rocketchat:-Eintrag in config.yaml"
|
ECHO_INFO "config.yaml-Einträge belassen"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
ECHO_DRY "würde rocketchat-Einträge aus config.yaml entfernen"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
ECHO_INFO "Keine rocketchat-Einträge in config.yaml"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ── Fertig ──
|
# ── Schritt 4: Bereinigung abgeschlossen ──
|
||||||
|
ECHO_STEP "4/4 Bereinigung abgeschlossen"
|
||||||
|
|
||||||
if $DRY_RUN; then
|
if $DRY_RUN; then
|
||||||
ECHO_STEP "🔍 DRY-RUN BEENDET"
|
ECHO_STEP "🔍 DRY-RUN BEENDET"
|
||||||
ECHO_INFO "Es wurde NICHTS entfernt."
|
ECHO_INFO "Es wurde NICHTS entfernt."
|
||||||
@@ -118,4 +132,7 @@ else
|
|||||||
ECHO_STEP "✨ Deinstallation abgeschlossen"
|
ECHO_STEP "✨ Deinstallation abgeschlossen"
|
||||||
ECHO_OK "Plugin ist entfernt"
|
ECHO_OK "Plugin ist entfernt"
|
||||||
ECHO_INFO "Zum erneuten Installieren: ./install.sh"
|
ECHO_INFO "Zum erneuten Installieren: ./install.sh"
|
||||||
|
echo ""
|
||||||
|
ECHO_INFO "Gateway manuell neustarten, falls gewünscht:"
|
||||||
|
echo " hermes gateway restart"
|
||||||
fi
|
fi
|
||||||
|
|||||||
Reference in New Issue
Block a user