v2.0: Gateway-Plugin-Architektur + interaktiver bilingualer install.sh
- Legacy-Standalone-Daemon entfernt (__init__.py, adapter.py, _merge_config.py, uninstall.sh) - Plugin-Dateien in plugin/ strukturiert (von produktiver Susi-Instanz) - Neuer install.sh: --lang en/de, --help, --non-interactive, Bot Username Prompt, Re-Install-Erkennung - tools.py: Rocket.Chat REST-Tools fur Rooms, Users, DMs, Send - BasePlatformAdapter-Vererbung, DDP-added-Events, case-insensitive Filter
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
Rocket.Chat Platform Plugin for Hermes Agent.
|
||||
|
||||
Registers a gateway platform adapter that connects to a self-hosted
|
||||
Rocket.Chat server via DDP/WebSocket (real-time incoming messages + presence)
|
||||
and REST API (outgoing replies).
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── Interaction Templates ──
|
||||
_TEMPLATE_MAP = {
|
||||
"yes_no": {
|
||||
"label": "Ja/Nein",
|
||||
"description": "Binary confirmation",
|
||||
"attachment": {"color": "#1d74f5", "title": "Bitte bestätigen:"},
|
||||
"buttons": [
|
||||
{"text": "✅ Ja", "msg": "ja", "style": "primary"},
|
||||
{"text": "❌ Nein", "msg": "nein", "style": "danger"},
|
||||
],
|
||||
},
|
||||
"confirm_cancel": {
|
||||
"label": "Bestätigen/Abbrechen",
|
||||
"description": "Safe action with abort",
|
||||
"attachment": {"color": "#1d74f5", "title": "Aktion bestätigen:"},
|
||||
"buttons": [
|
||||
{"text": "✅ Bestätigen", "msg": "bestätigen", "style": "primary"},
|
||||
{"text": "🚫 Abbrechen", "msg": "abbrechen", "style": "danger"},
|
||||
],
|
||||
},
|
||||
"ok": {
|
||||
"label": "OK",
|
||||
"description": "Single acknowledgement",
|
||||
"attachment": {"color": "#1d74f5", "title": "Hinweis:"},
|
||||
"buttons": [
|
||||
{"text": "👍 OK", "msg": "ok", "style": "primary"},
|
||||
],
|
||||
},
|
||||
"multi_choice_3": {
|
||||
"label": "3 Optionen",
|
||||
"description": "Three choices",
|
||||
"attachment": {"color": "#1d74f5", "title": "Bitte wählen:"},
|
||||
"buttons": [
|
||||
{"text": "1. Links", "msg": "1. Links"},
|
||||
{"text": "2. Rechts", "msg": "2. Rechts"},
|
||||
{"text": "3. Zwei Runden", "msg": "3. Zwei Runden"},
|
||||
],
|
||||
},
|
||||
"custom": {
|
||||
"label": "Custom",
|
||||
"description": "User-defined buttons",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def check_requirements(config=None):
|
||||
"""Validate that required env vars are set."""
|
||||
required = ["ROCKETCHAT_BASE_URL", "ROCKETCHAT_USER", "ROCKETCHAT_PASSWORD"]
|
||||
missing = [v for v in required if not os.environ.get(v)]
|
||||
return len(missing) == 0, f"Missing env: {', '.join(missing)}" if missing else "Ready"
|
||||
|
||||
|
||||
def validate_config(config):
|
||||
"""Validate platform-specific config."""
|
||||
return True, "OK"
|
||||
|
||||
|
||||
def is_connected(adapter):
|
||||
"""Check if the adapter has an active connection."""
|
||||
if adapter is None:
|
||||
return False
|
||||
return getattr(adapter, "_running", False)
|
||||
|
||||
|
||||
def register(ctx):
|
||||
"""Plugin entry point — called by the Hermes plugin system at startup."""
|
||||
from .adapter import RocketChatAdapter # lazy import avoids circular deps
|
||||
try:
|
||||
from .tools import register_tools
|
||||
except ImportError:
|
||||
register_tools = None
|
||||
|
||||
ctx.register_platform(
|
||||
name="rocketchat",
|
||||
label="Rocket.Chat",
|
||||
adapter_factory=lambda cfg: RocketChatAdapter(cfg),
|
||||
check_fn=check_requirements,
|
||||
validate_config=validate_config,
|
||||
is_connected=is_connected,
|
||||
required_env=["ROCKETCHAT_BASE_URL", "ROCKETCHAT_USER", "ROCKETCHAT_PASSWORD"],
|
||||
install_hint="No extra packages needed (stdlib only)",
|
||||
allowed_users_env="ROCKETCHAT_ALLOWED_USERS",
|
||||
allow_all_env="ROCKETCHAT_ALLOW_ALL_USERS",
|
||||
max_message_length=4000,
|
||||
emoji="🚀",
|
||||
pii_safe=False,
|
||||
allow_update_command=True,
|
||||
platform_hint=(
|
||||
"You are chatting via Rocket.Chat. You support markdown formatting: "
|
||||
"**bold**, *italic*, `inline code`, ```code blocks```, and [links](url). "
|
||||
"Messages can be up to ~4000 characters. You have a green online dot "
|
||||
"via DDP presence. Use professional but friendly tone."
|
||||
),
|
||||
)
|
||||
|
||||
if register_tools is not None:
|
||||
register_tools(ctx)
|
||||
@@ -0,0 +1,640 @@
|
||||
"""
|
||||
Rocket.Chat Platform Adapter for Hermes Agent.
|
||||
|
||||
Plugin-based gateway adapter connecting to a self-hosted Rocket.Chat server.
|
||||
Uses WebSocket/DDP for real-time incoming messages + presence,
|
||||
and REST API for sending replies.
|
||||
|
||||
Zero external dependencies — stdlib only.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import queue
|
||||
import re
|
||||
import socket
|
||||
import ssl
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
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:
|
||||
from gateway.platforms.base import (
|
||||
BasePlatformAdapter,
|
||||
SendResult,
|
||||
MessageEvent,
|
||||
MessageType,
|
||||
)
|
||||
from gateway.session import SessionSource
|
||||
from gateway.config import PlatformConfig, Platform
|
||||
except ImportError:
|
||||
# Fallback for standalone test / development outside gateway
|
||||
BasePlatformAdapter = object
|
||||
SendResult = dict
|
||||
MessageEvent = dict
|
||||
MessageType = object
|
||||
SessionSource = object
|
||||
PlatformConfig = object
|
||||
Platform = str
|
||||
|
||||
|
||||
def _get_config_str(config: PlatformConfig, key: str, env_var: str, default: str = "") -> str:
|
||||
extra = getattr(config, "extra", {}) or {}
|
||||
return os.getenv(env_var) or extra.get(key, default)
|
||||
|
||||
|
||||
class RocketChatREST:
|
||||
def __init__(self, base_url: str):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.auth_token: Optional[str] = None
|
||||
self.user_id: Optional[str] = None
|
||||
|
||||
def _request(self, method: str, endpoint: str, headers: Optional[dict] = None, data: Optional[dict] = None):
|
||||
url = f"{self.base_url}{endpoint}"
|
||||
req_headers = dict(headers) if headers else {}
|
||||
body = json.dumps(data).encode("utf-8") if data else None
|
||||
if body:
|
||||
req_headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(url, data=body, headers=req_headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
except Exception as e:
|
||||
logger.debug("REST %s %s failed: %s", method, endpoint, e)
|
||||
return None
|
||||
|
||||
def login(self, user: str, password: str) -> bool:
|
||||
r = self._request("POST", "/api/v1/login", data={"user": user, "password": password})
|
||||
if r and r.get("status") == "success":
|
||||
self.auth_token = r["data"]["authToken"]
|
||||
self.user_id = r["data"]["userId"]
|
||||
return True
|
||||
return False
|
||||
|
||||
def get_rooms(self) -> List[dict]:
|
||||
if not self.auth_token:
|
||||
return []
|
||||
r = self._request("GET", "/api/v1/rooms.get", headers={
|
||||
"X-Auth-Token": self.auth_token,
|
||||
"X-User-Id": self.user_id,
|
||||
})
|
||||
if not r or not r.get("success"):
|
||||
return []
|
||||
rooms = []
|
||||
for rm in r.get("update", []):
|
||||
t = rm.get("t", "c")
|
||||
rid = rm["_id"]
|
||||
if t == "d":
|
||||
usernames = rm.get("usernames", [])
|
||||
other = [u for u in usernames if u != os.getenv("ROCKETCHAT_USER", "")]
|
||||
name = "DM mit " + (", ".join(other) if other else "unbekannt")
|
||||
else:
|
||||
name = rm.get("name", "unnamed")
|
||||
rooms.append({"id": rid, "name": name, "type": t})
|
||||
return rooms
|
||||
|
||||
def post_message(self, room_id: str, text: str, attachments: Optional[List[dict]] = None) -> bool:
|
||||
if not self.auth_token:
|
||||
return False
|
||||
payload = {"roomId": room_id, "text": text}
|
||||
if attachments:
|
||||
payload["attachments"] = attachments
|
||||
r = self._request("POST", "/api/v1/chat.postMessage", headers={
|
||||
"X-Auth-Token": self.auth_token,
|
||||
"X-User-Id": self.user_id,
|
||||
"Content-Type": "application/json",
|
||||
}, data=payload)
|
||||
return bool(r and r.get("success"))
|
||||
|
||||
|
||||
class DDPClient:
|
||||
PING_INTERVAL = 8.0
|
||||
RECONNECT_BACKOFFS = [5, 10, 20, 30, 60, 120]
|
||||
|
||||
def __init__(self, host: str, on_message_cb=None, on_connected_cb=None):
|
||||
self.host = host
|
||||
self._on_message = on_message_cb
|
||||
self._on_connected = on_connected_cb
|
||||
self.sock: Optional[socket.socket] = None
|
||||
self.connected = False
|
||||
self._running = False
|
||||
self._reader_thread: Optional[threading.Thread] = None
|
||||
self._write_lock = threading.Lock()
|
||||
self._msg_queue: queue.Queue = queue.Queue()
|
||||
self._next_sub_id = 1
|
||||
self._sub_rooms: Dict[str, str] = {}
|
||||
self._session: Optional[str] = None
|
||||
self._reconnect_attempt = 0
|
||||
self._last_rx_time = 0.0
|
||||
|
||||
def _create_socket(self) -> socket.socket:
|
||||
ctx = ssl.create_default_context()
|
||||
raw = socket.create_connection((self.host, 443), timeout=10)
|
||||
return ctx.wrap_socket(raw, server_hostname=self.host)
|
||||
|
||||
def _handshake(self, s: socket.socket) -> bool:
|
||||
import base64
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
hs = (
|
||||
f"GET /websocket HTTP/1.1\r\n"
|
||||
f"Host: {self.host}\r\n"
|
||||
f"Upgrade: websocket\r\n"
|
||||
f"Connection: Upgrade\r\n"
|
||||
f"Sec-WebSocket-Key: {key}\r\n"
|
||||
f"Sec-WebSocket-Version: 13\r\n"
|
||||
f"Origin: https://{self.host}\r\n\r\n"
|
||||
)
|
||||
s.sendall(hs.encode())
|
||||
resp = b""
|
||||
while b"\r\n\r\n" not in resp:
|
||||
chunk = s.recv(1024)
|
||||
if not chunk:
|
||||
break
|
||||
resp += chunk
|
||||
return b"101 Switching Protocols" in resp
|
||||
|
||||
def _send_frame(self, data: bytes, opcode: int = 0x01, mask: bool = True) -> None:
|
||||
if not self.sock:
|
||||
return
|
||||
length = len(data)
|
||||
if length < 126:
|
||||
header = struct.pack("!BB", 0x80 | opcode, (0x80 if mask else 0x00) | length)
|
||||
elif length < 65536:
|
||||
header = struct.pack("!BBH", 0x80 | opcode, (0x80 if mask else 0x00) | 126, length)
|
||||
else:
|
||||
header = struct.pack("!BBQ", 0x80 | opcode, (0x80 if mask else 0x00) | 127, length)
|
||||
frame = header
|
||||
if mask:
|
||||
masking = os.urandom(4)
|
||||
masked = bytes(b ^ masking[i % 4] for i, b in enumerate(data))
|
||||
frame += masking + masked
|
||||
else:
|
||||
frame += data
|
||||
with self._write_lock:
|
||||
self.sock.sendall(frame)
|
||||
|
||||
def _send_json(self, obj: dict) -> None:
|
||||
self._send_frame(json.dumps(obj).encode("utf-8"), opcode=0x01, mask=True)
|
||||
|
||||
def _send_raw_pong(self, payload: bytes) -> None:
|
||||
self._send_frame(payload, opcode=0x0A, mask=True)
|
||||
|
||||
def _reader_loop(self):
|
||||
import select
|
||||
self.sock.settimeout(1.0)
|
||||
last_ping = time.time()
|
||||
while self._running:
|
||||
try:
|
||||
if time.time() - last_ping >= self.PING_INTERVAL:
|
||||
try:
|
||||
self._send_json({"msg": "ping"})
|
||||
last_ping = time.time()
|
||||
except Exception:
|
||||
break
|
||||
readable, _, _ = select.select([self.sock], [], [], 1.0)
|
||||
if not readable:
|
||||
continue
|
||||
hdr = self.sock.recv(2)
|
||||
if not hdr:
|
||||
break
|
||||
fin = (hdr[0] & 0x80) != 0
|
||||
opcode = hdr[0] & 0x0F
|
||||
masked = (hdr[1] & 0x80) != 0
|
||||
length = hdr[1] & 0x7F
|
||||
if length == 126:
|
||||
length = struct.unpack("!H", self.sock.recv(2))[0]
|
||||
elif length == 127:
|
||||
length = struct.unpack("!Q", self.sock.recv(8))[0]
|
||||
payload = b""
|
||||
remaining = length
|
||||
while remaining > 0:
|
||||
chunk = self.sock.recv(min(4096, remaining))
|
||||
if not chunk:
|
||||
break
|
||||
payload += chunk
|
||||
remaining -= len(chunk)
|
||||
if len(payload) < length:
|
||||
break
|
||||
if masked:
|
||||
mask = payload[:4]
|
||||
payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload[4:]))
|
||||
if opcode == 0x09:
|
||||
self._send_raw_pong(payload)
|
||||
elif opcode == 0x01 and payload:
|
||||
self._last_rx_time = time.time()
|
||||
try:
|
||||
data = json.loads(payload.decode("utf-8", errors="ignore"))
|
||||
msg_type = data.get("msg", "")
|
||||
if msg_type == "connected":
|
||||
self.connected = True
|
||||
self._session = data.get("session")
|
||||
if self._on_connected:
|
||||
self._on_connected()
|
||||
elif msg_type == "ping":
|
||||
self._send_json({"msg": "pong"})
|
||||
elif msg_type in ("changed", "added") and data.get("collection") == "stream-room-messages":
|
||||
fields = data.get("fields", {})
|
||||
args = fields.get("args", [])
|
||||
if args and isinstance(args, list) and len(args) >= 1:
|
||||
self._msg_queue.put(args[0])
|
||||
except Exception:
|
||||
pass
|
||||
elif opcode == 0x08:
|
||||
break
|
||||
except Exception:
|
||||
break
|
||||
self.connected = False
|
||||
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:
|
||||
self._last_rx_time = time.time()
|
||||
try:
|
||||
self.sock = self._create_socket()
|
||||
if not self._handshake(self.sock):
|
||||
return False
|
||||
self._running = True
|
||||
self._reader_thread = threading.Thread(target=self._reader_loop, daemon=True)
|
||||
self._reader_thread.start()
|
||||
time.sleep(0.3)
|
||||
self._send_json({"msg": "connect", "version": "1", "support": ["1", "pre2", "pre1"]})
|
||||
for _ in range(50):
|
||||
if self.connected:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
if not self.connected:
|
||||
self.disconnect()
|
||||
return False
|
||||
time.sleep(0.2)
|
||||
self._send_json({"msg": "method", "method": "login",
|
||||
"params": [{"resume": token}], "id": "ddplogin"})
|
||||
time.sleep(0.5)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error("DDP connect failed: %s", e)
|
||||
self.disconnect()
|
||||
return False
|
||||
|
||||
def subscribe_room(self, room_id: str) -> Optional[str]:
|
||||
if not self.connected:
|
||||
return None
|
||||
sub_id = f"sub{self._next_sub_id}"
|
||||
self._next_sub_id += 1
|
||||
# CRITICAL: Rocket.Chat V5+ requires {"token": "true"} as second param,
|
||||
# otherwise subscribe succeeds but NO messages ever stream.
|
||||
self._send_json({
|
||||
"msg": "sub",
|
||||
"name": "stream-room-messages",
|
||||
"params": [room_id, {"token": "true"}],
|
||||
"id": sub_id
|
||||
})
|
||||
self._sub_rooms[room_id] = sub_id
|
||||
return sub_id
|
||||
|
||||
def set_status(self, status: str) -> bool:
|
||||
if not self.connected:
|
||||
return False
|
||||
method = f"UserPresence:{status}"
|
||||
self._send_json({"msg": "method", "method": method, "params": [], "id": f"st{int(time.time()*1000)}"})
|
||||
return True
|
||||
|
||||
def disconnect(self):
|
||||
self._running = False
|
||||
if self.sock:
|
||||
try:
|
||||
self.sock.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.sock = None
|
||||
self.connected = False
|
||||
self._sub_rooms.clear()
|
||||
|
||||
def reconnect_and_restore(self, token: str) -> bool:
|
||||
self.disconnect()
|
||||
time.sleep(1)
|
||||
old_subs = list(self._sub_rooms.keys())
|
||||
self._sub_rooms.clear()
|
||||
if self.connect_and_login(token):
|
||||
for rid in old_subs:
|
||||
self.subscribe_room(rid)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
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):
|
||||
super().__init__(config=config, platform=Platform("rocketchat"))
|
||||
self.base_url = _get_config_str(config, "base_url", "ROCKETCHAT_BASE_URL")
|
||||
self.user = _get_config_str(config, "user", "ROCKETCHAT_USER")
|
||||
self.password = _get_config_str(config, "password", "ROCKETCHAT_PASSWORD")
|
||||
self.rest = RocketChatREST(self.base_url)
|
||||
self.ddp: Optional[DDPClient] = None
|
||||
self._auth_token: Optional[str] = None
|
||||
self._user_id: Optional[str] = None
|
||||
self._rooms: List[dict] = []
|
||||
self._subscribed_rooms: set = set()
|
||||
self._listen_task: Optional[asyncio.Task] = None
|
||||
self._status_timer: Optional[threading.Timer] = None
|
||||
self._last_activity = 0.0
|
||||
self._shutdown_event = threading.Event()
|
||||
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:
|
||||
if not self.base_url or not self.user or not self.password:
|
||||
logger.error("[rocketchat] Missing configuration")
|
||||
return False
|
||||
if not self.rest.login(self.user, self.password):
|
||||
logger.error("[rocketchat] REST login failed")
|
||||
return False
|
||||
self._auth_token = self.rest.auth_token
|
||||
self._user_id = self.rest.user_id
|
||||
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
||||
self.ddp = DDPClient(
|
||||
host=host,
|
||||
on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None,
|
||||
)
|
||||
if not self.ddp.connect_and_login(self._auth_token):
|
||||
logger.error("[rocketchat] DDP connect/login failed")
|
||||
return False
|
||||
self._rooms = self.rest.get_rooms()
|
||||
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
|
||||
for room in self._rooms:
|
||||
sub_id = self.ddp.subscribe_room(room["id"])
|
||||
if sub_id:
|
||||
self._subscribed_rooms.add(room["id"])
|
||||
self._room_info[room["id"]] = {"name": room["name"], "type": room["type"]}
|
||||
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._running = True
|
||||
self._listen_task = asyncio.create_task(self._listen_loop())
|
||||
self._last_activity = time.time()
|
||||
logger.info("[rocketchat] Listen loop started, _running=%s", self._running)
|
||||
logger.info("[rocketchat] Connected to %s", self.base_url)
|
||||
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:
|
||||
self._mark_disconnected()
|
||||
self._shutdown_event.set()
|
||||
if self._status_timer:
|
||||
self._status_timer.cancel()
|
||||
if self._listen_task and not self._listen_task.done():
|
||||
self._listen_task.cancel()
|
||||
try:
|
||||
await self._listen_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
if self.ddp:
|
||||
self.ddp.disconnect()
|
||||
self.ddp = None
|
||||
logger.info("[rocketchat] Disconnected")
|
||||
|
||||
async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None) -> SendResult:
|
||||
if not self.rest.auth_token:
|
||||
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
|
||||
attachments = None
|
||||
if metadata and metadata.get("template"):
|
||||
from . import _TEMPLATE_MAP, _build_custom_buttons
|
||||
template_name = metadata.get("template")
|
||||
question_id = metadata.get("question_id", "")
|
||||
if template_name == "custom" and metadata.get("custom_buttons"):
|
||||
buttons = _build_custom_buttons(metadata["custom_buttons"], prefix=question_id)
|
||||
attachments = [{
|
||||
"color": "#1d74f5",
|
||||
"title": metadata.get("button_title", "Wähle eine Option:"),
|
||||
"actions": buttons,
|
||||
}]
|
||||
elif template_name in _TEMPLATE_MAP:
|
||||
tmpl = _TEMPLATE_MAP[template_name]
|
||||
attachment = dict(tmpl.get("attachment", {}))
|
||||
raw_buttons = tmpl.get("buttons", [])
|
||||
buttons = []
|
||||
for btn in raw_buttons:
|
||||
msg_payload = btn.get("msg", "")
|
||||
if question_id:
|
||||
msg_payload = f"{question_id}::{msg_payload}"
|
||||
buttons.append({
|
||||
"type": "button",
|
||||
"text": btn.get("text", "?"),
|
||||
"msg": msg_payload,
|
||||
"msg_in_chat_window": True,
|
||||
"style": btn.get("style", "default"),
|
||||
})
|
||||
attachment["actions"] = buttons
|
||||
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)
|
||||
if success:
|
||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||
return SendResult(success=False, error="chat.postMessage failed")
|
||||
|
||||
async def send_typing(self, chat_id: str, metadata=None) -> None:
|
||||
pass
|
||||
|
||||
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
|
||||
info = self._room_info.get(chat_id, {})
|
||||
return {"name": info.get("name", chat_id), "type": "group" if info.get("type") in ("c", "p") else "dm"}
|
||||
|
||||
async def _listen_loop(self):
|
||||
loop = asyncio.get_running_loop()
|
||||
health_check_counter = 0
|
||||
while self._running and not self._shutdown_event.is_set():
|
||||
try:
|
||||
msg_obj = await loop.run_in_executor(None, self._ddp_queue_get, 1.0)
|
||||
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:
|
||||
logger.warning("[rocketchat] DDP disconnected, reconnecting...")
|
||||
if self._auth_token and self.ddp.reconnect_and_restore(self._auth_token):
|
||||
logger.info("[rocketchat] Reconnected")
|
||||
else:
|
||||
await asyncio.sleep(5)
|
||||
continue
|
||||
health_check_counter = 0 # Reset on any message
|
||||
await self._process_incoming(msg_obj)
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
except Exception as e:
|
||||
logger.error("[rocketchat] Listener error: %s", e)
|
||||
await asyncio.sleep(1)
|
||||
|
||||
def _ddp_queue_get(self, timeout: float):
|
||||
if not self.ddp:
|
||||
return None
|
||||
try:
|
||||
return self.ddp._msg_queue.get(timeout=timeout)
|
||||
except queue.Empty:
|
||||
return None
|
||||
@@ -0,0 +1,19 @@
|
||||
name: rocketchat-platform
|
||||
kind: platform
|
||||
version: 1.0.0
|
||||
description: >
|
||||
Rocket.Chat gateway adapter for Hermes Agent.
|
||||
Connects to a self-hosted Rocket.Chat server via WebSocket/DDP for
|
||||
real-time message streaming and presence, and REST API for sending replies.
|
||||
Supports channels, private groups, and direct messages.
|
||||
author: Hermes Community
|
||||
requires_env:
|
||||
- ROCKETCHAT_BASE_URL
|
||||
- ROCKETCHAT_USER
|
||||
- ROCKETCHAT_PASSWORD
|
||||
- name: ROCKETCHAT_ALLOW_ALL_USERS
|
||||
description: "Set to 'true' to allow all users (default: false = allowlist)"
|
||||
required: false
|
||||
- name: ROCKETCHAT_ALLOWED_USERS
|
||||
description: "Comma-separated list of allowed Rocket.Chat usernames"
|
||||
required: false
|
||||
+739
@@ -0,0 +1,739 @@
|
||||
"""Rocket.Chat REST API tools for the Hermes Agent.
|
||||
|
||||
Lightweight wrappers calling the Rocket.Chat REST API directly.
|
||||
Uses only stdlib (urllib) — no external dependencies.
|
||||
|
||||
These tools are registered by the rocketchat-platform plugin and are
|
||||
available whenever ROCKETCHAT_BASE_URL, ROCKETCHAT_USER and
|
||||
ROCKETCHAT_PASSWORD are set in the environment.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import urllib.request
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from tools.registry import tool_error, tool_result
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Rocket.Chat REST API client (lightweight, stdlib-only)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class RocketChatAPI:
|
||||
"""Thin REST client for Rocket.Chat stdlib only."""
|
||||
|
||||
def __init__(self, base_url: str, auth_token: str, user_id: str):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.auth_token = auth_token
|
||||
self.user_id = user_id
|
||||
|
||||
# -- internal helpers ----------------------------------------------------
|
||||
|
||||
def _request(self, method: str, endpoint: str, data: Optional[dict] = None) -> Optional[dict]:
|
||||
url = f"{self.base_url}{endpoint}"
|
||||
headers: Dict[str, str] = {
|
||||
"X-Auth-Token": self.auth_token,
|
||||
"X-User-Id": self.user_id,
|
||||
}
|
||||
body: Optional[bytes] = None
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
body = json.dumps(data).encode("utf-8")
|
||||
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as exc:
|
||||
msg = f"HTTP {exc.code} on {method} {endpoint}"
|
||||
try:
|
||||
detail = json.loads(exc.read().decode("utf-8"))
|
||||
msg += f": {detail}"
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("RocketChatAPI %s", msg)
|
||||
return {"success": False, "error": msg}
|
||||
except Exception as exc:
|
||||
logger.debug("RocketChatAPI request failed: %s", exc)
|
||||
return {"success": False, "error": str(exc)}
|
||||
|
||||
# -- rooms ---------------------------------------------------------------
|
||||
|
||||
def get_rooms(self) -> List[dict]:
|
||||
r = self._request("GET", "/api/v1/rooms.get")
|
||||
if r and r.get("success"):
|
||||
return r.get("update", [])
|
||||
return []
|
||||
|
||||
def get_channels(self) -> List[dict]:
|
||||
r = self._request("GET", "/api/v1/channels.list.joined")
|
||||
if r and r.get("success"):
|
||||
return r.get("channels", [])
|
||||
return []
|
||||
|
||||
def get_groups(self) -> List[dict]:
|
||||
r = self._request("GET", "/api/v1/groups.list")
|
||||
if r and r.get("success"):
|
||||
return r.get("groups", [])
|
||||
return []
|
||||
|
||||
def get_dm_rooms(self) -> List[dict]:
|
||||
r = self._request("GET", "/api/v1/im.list")
|
||||
if r and r.get("success"):
|
||||
return r.get("ims", [])
|
||||
return []
|
||||
|
||||
def create_channel(self, name: str, members: Optional[List[str]] = None) -> dict:
|
||||
payload: Dict[str, Any] = {"name": name}
|
||||
if members:
|
||||
payload["members"] = members
|
||||
return self._request("POST", "/api/v1/channels.create", payload) or {}
|
||||
|
||||
def create_group(self, name: str, members: Optional[List[str]] = None) -> dict:
|
||||
payload: Dict[str, Any] = {"name": name}
|
||||
if members:
|
||||
payload["members"] = members
|
||||
return self._request("POST", "/api/v1/groups.create", payload) or {}
|
||||
|
||||
def archive_room(self, room_id: str, room_type: str = "c") -> dict:
|
||||
if room_type == "c":
|
||||
return self._request("POST", "/api/v1/channels.archive", {"roomId": room_id}) or {}
|
||||
return self._request("POST", "/api/v1/groups.archive", {"roomId": room_id}) or {}
|
||||
|
||||
def delete_room(self, room_id: str, room_type: str = "c") -> dict:
|
||||
if room_type == "c":
|
||||
return self._request("POST", "/api/v1/channels.delete", {"roomId": room_id}) or {}
|
||||
return self._request("POST", "/api/v1/groups.delete", {"roomId": room_id}) or {}
|
||||
|
||||
def room_info(self, room_id: str, room_type: str = "c") -> dict:
|
||||
if room_type == "c":
|
||||
return self._request("GET", f"/api/v1/channels.info?roomId={room_id}") or {}
|
||||
if room_type == "p":
|
||||
return self._request("GET", f"/api/v1/groups.info?roomId={room_id}") or {}
|
||||
return self._request("GET", f"/api/v1/rooms.info?roomId={room_id}") or {}
|
||||
|
||||
def room_history(self, room_id: str, count: int = 20) -> List[dict]:
|
||||
r = self._request("GET", f"/api/v1/channels.history?roomId={room_id}&count={count}")
|
||||
if r and r.get("success"):
|
||||
return r.get("messages", [])
|
||||
# Fallback for groups / DMs
|
||||
r2 = self._request("GET", f"/api/v1/groups.history?roomId={room_id}&count={count}")
|
||||
if r2 and r2.get("success"):
|
||||
return r2.get("messages", [])
|
||||
return []
|
||||
|
||||
def invite_user(self, room_id: str, user_id: str, room_type: str = "c") -> dict:
|
||||
if room_type == "c":
|
||||
return self._request("POST", "/api/v1/channels.invite", {"roomId": room_id, "userId": user_id}) or {}
|
||||
return self._request("POST", "/api/v1/groups.invite", {"roomId": room_id, "userId": user_id}) or {}
|
||||
|
||||
def kick_user(self, room_id: str, user_id: str, room_type: str = "c") -> dict:
|
||||
if room_type == "c":
|
||||
return self._request("POST", "/api/v1/channels.kick", {"roomId": room_id, "userId": user_id}) or {}
|
||||
return self._request("POST", "/api/v1/groups.kick", {"roomId": room_id, "userId": user_id}) or {}
|
||||
|
||||
# -- users ---------------------------------------------------------------
|
||||
|
||||
def get_users(self, query: Optional[str] = None, count: int = 50) -> List[dict]:
|
||||
endpoint = f"/api/v1/users.list?count={count}"
|
||||
if query:
|
||||
endpoint += f"&query={{\"name\":{{\"$regex\":\"{query}\",\"$options\":\"i\"}}}}"
|
||||
r = self._request("GET", endpoint)
|
||||
if r and r.get("success"):
|
||||
return r.get("users", [])
|
||||
return []
|
||||
|
||||
def get_user_info(self, user_id: Optional[str] = None, username: Optional[str] = None) -> dict:
|
||||
if user_id:
|
||||
return self._request("GET", f"/api/v1/users.info?userId={user_id}") or {}
|
||||
if username:
|
||||
return self._request("GET", f"/api/v1/users.info?username={username}") or {}
|
||||
return {"success": False, "error": "Either user_id or username is required for users.info"}
|
||||
|
||||
# -- direct messages -----------------------------------------------------
|
||||
|
||||
def create_dm(self, username: str) -> dict:
|
||||
return self._request("POST", "/api/v1/im.create", {"username": username}) or {}
|
||||
|
||||
def send_message(self, room_id: str, text: str, attachments: Optional[List[dict]] = None) -> dict:
|
||||
payload: Dict[str, Any] = {"roomId": room_id, "text": text}
|
||||
if attachments:
|
||||
payload["attachments"] = attachments
|
||||
return self._request("POST", "/api/v1/chat.postMessage", payload) or {}
|
||||
|
||||
@classmethod
|
||||
def login(cls, base_url: str, user: str, password: str) -> Optional["RocketChatAPI"]:
|
||||
"""Authenticate and return an API client, or None if login fails."""
|
||||
url = base_url.rstrip("/")
|
||||
req = urllib.request.Request(
|
||||
f"{url}/api/v1/login",
|
||||
data=json.dumps({"user": user, "password": password}).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
if data.get("status") == "success":
|
||||
return cls(url, data["data"]["authToken"], data["data"]["userId"])
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Module-level cached client (avoids re-auth on every tool call)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_cached_client: Optional[RocketChatAPI] = None
|
||||
_cached_login_ts: float = 0.0
|
||||
_CACHE_TTL: float = 900.0 # 15 minutes
|
||||
|
||||
|
||||
def _rc_client() -> Optional[RocketChatAPI]:
|
||||
"""Return a logged-in RocketChatAPI client, or None if not configured."""
|
||||
global _cached_client, _cached_login_ts
|
||||
base_url = os.getenv("ROCKETCHAT_BASE_URL", "").strip()
|
||||
user = os.getenv("ROCKETCHAT_USER", "").strip()
|
||||
password = os.getenv("ROCKETCHAT_PASSWORD", "").strip()
|
||||
if not base_url or not user or not password:
|
||||
return None
|
||||
if _cached_client and (time.time() - _cached_login_ts) < _CACHE_TTL:
|
||||
return _cached_client
|
||||
client = RocketChatAPI.login(base_url, user, password)
|
||||
if client:
|
||||
_cached_client = client
|
||||
_cached_login_ts = time.time()
|
||||
return client
|
||||
|
||||
|
||||
def _rc_error() -> str:
|
||||
return tool_error(
|
||||
"Rocket.Chat is not configured. Set ROCKETCHAT_BASE_URL, "
|
||||
"ROCKETCHAT_USER and ROCKETCHAT_PASSWORD in your environment."
|
||||
)
|
||||
|
||||
|
||||
def _normalize_room(room_raw: dict) -> dict:
|
||||
"""Normalize heterogeneous Rocket.Chat room objects to a common schema."""
|
||||
t = room_raw.get("t", "c")
|
||||
rid = room_raw.get("_id", "")
|
||||
if t == "d":
|
||||
usernames = room_raw.get("usernames", [])
|
||||
bot_user = os.getenv("ROCKETCHAT_USER", "")
|
||||
other = [u for u in usernames if u != bot_user]
|
||||
name = "DM mit " + (", ".join(other[:3]) if other else "unbekannt")
|
||||
else:
|
||||
name = room_raw.get("name", "")
|
||||
return {
|
||||
"id": rid,
|
||||
"name": name,
|
||||
"type": t,
|
||||
"fname": room_raw.get("fname", ""),
|
||||
"num_msgs": room_raw.get("msgs", 0),
|
||||
"num_users": room_raw.get("usersCount", 0),
|
||||
"readonly": room_raw.get("ro", False),
|
||||
"archived": room_raw.get("archived", False),
|
||||
"is_default": room_raw.get("default", False),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tool handlers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _handle_rocketchat_rooms(args: dict, **kw) -> str:
|
||||
action = str(args.get("action") or "").strip().lower()
|
||||
client = _rc_client()
|
||||
if not client:
|
||||
return _rc_error()
|
||||
|
||||
try:
|
||||
if action == "list":
|
||||
room_type = str(args.get("room_type") or "all").strip().lower()
|
||||
all_rooms: List[dict] = []
|
||||
if room_type in ("all", "channel", "c"):
|
||||
all_rooms.extend(client.get_channels())
|
||||
if room_type in ("all", "group", "p"):
|
||||
all_rooms.extend(client.get_groups())
|
||||
if room_type in ("all", "dm", "d"):
|
||||
all_rooms.extend(client.get_dm_rooms())
|
||||
return tool_result({
|
||||
"success": True,
|
||||
"action": action,
|
||||
"room_type": room_type,
|
||||
"count": len(all_rooms),
|
||||
"rooms": [_normalize_room(r) for r in all_rooms],
|
||||
})
|
||||
|
||||
if action == "create":
|
||||
name = str(args.get("name") or "").strip()
|
||||
if not name:
|
||||
return tool_error("name is required for action='create'")
|
||||
members = args.get("members")
|
||||
if isinstance(members, str):
|
||||
members = [m.strip() for m in members.split(",") if m.strip()]
|
||||
room_type = str(args.get("room_type") or "channel").strip().lower()
|
||||
if room_type in ("group", "p"):
|
||||
result = client.create_group(name, members=members)
|
||||
else:
|
||||
result = client.create_channel(name, members=members)
|
||||
return tool_result({"success": result.get("success", False), "action": action, "result": result})
|
||||
|
||||
if action == "info":
|
||||
room_id = str(args.get("room_id") or "").strip()
|
||||
if not room_id:
|
||||
return tool_error("room_id is required for action='info'")
|
||||
room_type = str(args.get("room_type") or "c").strip().lower()
|
||||
result = client.room_info(room_id, room_type)
|
||||
return tool_result({"success": result.get("success", False), "action": action, "data": result.get("channel") or result.get("group") or result.get("room")})
|
||||
|
||||
if action == "history":
|
||||
room_id = str(args.get("room_id") or "").strip()
|
||||
if not room_id:
|
||||
return tool_error("room_id is required for action='history'")
|
||||
count = int(args.get("count", 20))
|
||||
msgs = client.room_history(room_id, count=count)
|
||||
return tool_result({"success": True, "action": action, "count": len(msgs), "messages": msgs})
|
||||
|
||||
if action == "archive":
|
||||
room_id = str(args.get("room_id") or "").strip()
|
||||
if not room_id:
|
||||
return tool_error("room_id is required for action='archive'")
|
||||
room_type = str(args.get("room_type") or "c").strip().lower()
|
||||
result = client.archive_room(room_id, room_type)
|
||||
return tool_result({"success": result.get("success", False), "action": action})
|
||||
|
||||
if action == "delete":
|
||||
room_id = str(args.get("room_id") or "").strip()
|
||||
if not room_id:
|
||||
return tool_error("room_id is required for action='delete'")
|
||||
room_type = str(args.get("room_type") or "c").strip().lower()
|
||||
result = client.delete_room(room_id, room_type)
|
||||
return tool_result({"success": result.get("success", False), "action": action})
|
||||
|
||||
if action == "invite":
|
||||
room_id = str(args.get("room_id") or "").strip()
|
||||
username = str(args.get("username") or "").strip()
|
||||
if not room_id or not username:
|
||||
return tool_error("room_id and username are required for action='invite'")
|
||||
# Resolve username -> user_id
|
||||
user_info = client.get_user_info(username=username)
|
||||
user_id = user_info.get("user", {}).get("_id") if user_info.get("success") else None
|
||||
if not user_id:
|
||||
return tool_error(f"Could not resolve username '{username}' to a user ID.")
|
||||
room_type = str(args.get("room_type") or "c").strip().lower()
|
||||
result = client.invite_user(room_id, user_id, room_type)
|
||||
return tool_result({"success": result.get("success", False), "action": action})
|
||||
|
||||
if action == "kick":
|
||||
room_id = str(args.get("room_id") or "").strip()
|
||||
username = str(args.get("username") or "").strip()
|
||||
if not room_id or not username:
|
||||
return tool_error("room_id and username are required for action='kick'")
|
||||
user_info = client.get_user_info(username=username)
|
||||
user_id = user_info.get("user", {}).get("_id") if user_info.get("success") else None
|
||||
if not user_id:
|
||||
return tool_error(f"Could not resolve username '{username}' to a user ID.")
|
||||
room_type = str(args.get("room_type") or "c").strip().lower()
|
||||
result = client.kick_user(room_id, user_id, room_type)
|
||||
return tool_result({"success": result.get("success", False), "action": action})
|
||||
|
||||
return tool_error(f"Unknown rocketchat_rooms action: {action}")
|
||||
except Exception as exc:
|
||||
return tool_error(f"rocketchat_rooms failed: {type(exc).__name__}: {exc}")
|
||||
|
||||
|
||||
def _handle_rocketchat_users(args: dict, **kw) -> str:
|
||||
action = str(args.get("action") or "").strip().lower()
|
||||
client = _rc_client()
|
||||
if not client:
|
||||
return _rc_error()
|
||||
|
||||
try:
|
||||
if action == "list":
|
||||
query = str(args.get("query") or "").strip() or None
|
||||
count = int(args.get("count", 50))
|
||||
users = client.get_users(query=query, count=count)
|
||||
return tool_result({
|
||||
"success": True,
|
||||
"action": action,
|
||||
"count": len(users),
|
||||
"users": [
|
||||
{
|
||||
"id": u.get("_id"),
|
||||
"username": u.get("username"),
|
||||
"name": u.get("name"),
|
||||
"status": u.get("status"),
|
||||
"email": (u.get("emails") or [{}])[0].get("address"),
|
||||
"active": u.get("active"),
|
||||
"roles": u.get("roles", []),
|
||||
}
|
||||
for u in users
|
||||
],
|
||||
})
|
||||
|
||||
if action == "info":
|
||||
user_id = str(args.get("user_id") or "").strip() or None
|
||||
username = str(args.get("username") or "").strip() or None
|
||||
if not user_id and not username:
|
||||
return tool_error("user_id or username is required for action='info'")
|
||||
result = client.get_user_info(user_id=user_id, username=username)
|
||||
user = result.get("user", {}) if result.get("success") else {}
|
||||
return tool_result({
|
||||
"success": result.get("success", False),
|
||||
"action": action,
|
||||
"user": {
|
||||
"id": user.get("_id"),
|
||||
"username": user.get("username"),
|
||||
"name": user.get("name"),
|
||||
"status": user.get("status"),
|
||||
"statusConnection": user.get("statusConnection"),
|
||||
"email": (user.get("emails") or [{}])[0].get("address"),
|
||||
"roles": user.get("roles", []),
|
||||
"active": user.get("active"),
|
||||
"utcOffset": user.get("utcOffset"),
|
||||
"avatarUrl": user.get("avatarUrl"),
|
||||
} if user else None,
|
||||
})
|
||||
|
||||
if action == "search":
|
||||
query = str(args.get("query") or "").strip()
|
||||
if not query:
|
||||
return tool_error("query is required for action='search'")
|
||||
count = int(args.get("count", 20))
|
||||
users = client.get_users(query=query, count=count)
|
||||
return tool_result({
|
||||
"success": True,
|
||||
"action": action,
|
||||
"query": query,
|
||||
"count": len(users),
|
||||
"users": [
|
||||
{
|
||||
"id": u.get("_id"),
|
||||
"username": u.get("username"),
|
||||
"name": u.get("name"),
|
||||
"status": u.get("status"),
|
||||
}
|
||||
for u in users
|
||||
],
|
||||
})
|
||||
|
||||
return tool_error(f"Unknown rocketchat_users action: {action}")
|
||||
except Exception as exc:
|
||||
return tool_error(f"rocketchat_users failed: {type(exc).__name__}: {exc}")
|
||||
|
||||
|
||||
def _handle_rocketchat_dm(args: dict, **kw) -> str:
|
||||
action = str(args.get("action") or "").strip().lower()
|
||||
client = _rc_client()
|
||||
if not client:
|
||||
return _rc_error()
|
||||
|
||||
try:
|
||||
if action == "open":
|
||||
username = str(args.get("username") or "").strip()
|
||||
if not username:
|
||||
return tool_error("username is required for action='open'")
|
||||
result = client.create_dm(username)
|
||||
room = result.get("room", {}) if result.get("success") else {}
|
||||
return tool_result({
|
||||
"success": result.get("success", False),
|
||||
"action": action,
|
||||
"room_id": room.get("_id"),
|
||||
"room": _normalize_room(room) if room else None,
|
||||
})
|
||||
|
||||
if action == "send":
|
||||
username = str(args.get("username") or "").strip()
|
||||
user_id = str(args.get("user_id") or "").strip() or None
|
||||
text = str(args.get("text") or "").strip()
|
||||
if not text:
|
||||
return tool_error("text is required for action='send'")
|
||||
# Need a room_id. If user_id or username provided, create/open DM first.
|
||||
room_id = str(args.get("room_id") or "").strip() or None
|
||||
if not room_id:
|
||||
if username:
|
||||
dm_result = client.create_dm(username)
|
||||
if dm_result.get("success"):
|
||||
room_id = dm_result.get("room", {}).get("_id")
|
||||
elif user_id:
|
||||
# Try looking up user info and creating DM by username
|
||||
uinfo = client.get_user_info(user_id=user_id)
|
||||
uname = uinfo.get("user", {}).get("username") if uinfo.get("success") else None
|
||||
if uname:
|
||||
dm_result = client.create_dm(uname)
|
||||
if dm_result.get("success"):
|
||||
room_id = dm_result.get("room", {}).get("_id")
|
||||
if not room_id:
|
||||
return tool_error("Could not resolve room_id for DM. Provide room_id, username, or user_id.")
|
||||
result = client.send_message(room_id, text)
|
||||
return tool_result({"success": result.get("success", False), "action": action, "result": result})
|
||||
|
||||
if action == "list":
|
||||
dms = client.get_dm_rooms()
|
||||
return tool_result({
|
||||
"success": True,
|
||||
"action": action,
|
||||
"count": len(dms),
|
||||
"rooms": [_normalize_room(r) for r in dms],
|
||||
})
|
||||
|
||||
return tool_error(f"Unknown rocketchat_dm action: {action}")
|
||||
except Exception as exc:
|
||||
return tool_error(f"rocketchat_dm failed: {type(exc).__name__}: {exc}")
|
||||
|
||||
|
||||
def _handle_rocketchat_send(args: dict, **kw) -> str:
|
||||
"""Send a message (with optional native Rocket.Chat attachments/buttons)."""
|
||||
client = _rc_client()
|
||||
if not client:
|
||||
return _rc_error()
|
||||
|
||||
room_id = str(args.get("room_id") or "").strip()
|
||||
text = str(args.get("text") or "").strip()
|
||||
if not room_id or not text:
|
||||
return tool_error("room_id and text are required for rocketchat_send")
|
||||
|
||||
# Build attachments if button template requested
|
||||
attachments: Optional[List[dict]] = None
|
||||
template = str(args.get("button_template") or "none").strip().lower()
|
||||
if template and template != "none":
|
||||
# Replicate templates locally to avoid circular import from __init__.py
|
||||
_TMPL_MAP = {
|
||||
"yes_no": {
|
||||
"attachment": {"color": "#1d74f5", "title": "Bitte bestätigen:"},
|
||||
"buttons": [
|
||||
{"text": "✅ Ja", "msg": "ja", "style": "primary"},
|
||||
{"text": "❌ Nein", "msg": "nein", "style": "danger"},
|
||||
],
|
||||
},
|
||||
"confirm_cancel": {
|
||||
"attachment": {"color": "#1d74f5", "title": "Aktion bestätigen:"},
|
||||
"buttons": [
|
||||
{"text": "✅ Bestätigen", "msg": "bestätigen", "style": "primary"},
|
||||
{"text": "🚫 Abbrechen", "msg": "abbrechen", "style": "danger"},
|
||||
],
|
||||
},
|
||||
"ok": {
|
||||
"attachment": {"color": "#1d74f5", "title": "Hinweis:"},
|
||||
"buttons": [
|
||||
{"text": "👍 OK", "msg": "ok", "style": "primary"},
|
||||
],
|
||||
},
|
||||
"multi_choice_3": {
|
||||
"attachment": {"color": "#1d74f5", "title": "Wähle eine Option:"},
|
||||
"buttons": [
|
||||
{"text": "1._Links", "msg": "links", "style": "default"},
|
||||
{"text": "2._Rechts", "msg": "rechts", "style": "default"},
|
||||
{"text": "3._Zwei_Runden", "msg": "zwei_runden", "style": "default"},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
def _build_buttons(labels: list, prefix: str = "") -> list:
|
||||
buttons = []
|
||||
for label in labels:
|
||||
display = str(label).strip()
|
||||
msg_payload = display
|
||||
if prefix:
|
||||
msg_payload = f"{prefix}::{msg_payload}"
|
||||
buttons.append({
|
||||
"type": "button",
|
||||
"text": display,
|
||||
"msg": msg_payload,
|
||||
"msg_in_chat_window": True,
|
||||
"style": "default",
|
||||
})
|
||||
return buttons
|
||||
|
||||
question_id = str(args.get("question_id") or "").strip()
|
||||
if template == "custom" and args.get("custom_buttons"):
|
||||
labels = args["custom_buttons"]
|
||||
if isinstance(labels, str):
|
||||
labels = [l.strip() for l in labels.split(",") if l.strip()]
|
||||
buttons = _build_buttons(labels, prefix=question_id)
|
||||
attachments = [{
|
||||
"color": "#1d74f5",
|
||||
"title": str(args.get("button_title") or "Wähle eine Option:"),
|
||||
"actions": buttons,
|
||||
}]
|
||||
elif template in _TMPL_MAP:
|
||||
tmpl = _TMPL_MAP[template]
|
||||
raw_buttons = tmpl.get("buttons", [])
|
||||
buttons = []
|
||||
for btn in raw_buttons:
|
||||
msg_payload = btn.get("msg", "")
|
||||
if question_id:
|
||||
msg_payload = f"{question_id}::{msg_payload}"
|
||||
buttons.append({
|
||||
"type": "button",
|
||||
"text": btn.get("text", "?"),
|
||||
"msg": msg_payload,
|
||||
"msg_in_chat_window": True,
|
||||
"style": btn.get("style", "default"),
|
||||
})
|
||||
attachment = dict(tmpl.get("attachment", {}))
|
||||
attachment["actions"] = buttons
|
||||
attachments = [attachment]
|
||||
|
||||
try:
|
||||
result = client.send_message(room_id, text, attachments=attachments)
|
||||
return tool_result({"success": result.get("success", False), "result": result})
|
||||
except Exception as exc:
|
||||
return tool_error(f"rocketchat_send failed: {type(exc).__name__}: {exc}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tool schemas (OpenAI function-calling format)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_COMMON_STRING = {"type": "string"}
|
||||
|
||||
ROCKETCHAT_ROOMS_SCHEMA = {
|
||||
"name": "rocketchat_rooms",
|
||||
"description": (
|
||||
"Manage Rocket.Chat rooms (channels, private groups, DMs): list, create, "
|
||||
"archive, delete, inspect room info, fetch history, invite or kick users."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["list", "create", "info", "history", "archive", "delete", "invite", "kick"],
|
||||
"description": "Operation to perform on the room(s)",
|
||||
},
|
||||
"room_type": {
|
||||
"type": "string",
|
||||
"enum": ["channel", "group", "dm", "all"],
|
||||
"description": "For list: filter by room type (default: all)",
|
||||
},
|
||||
"name": {"type": "string", "description": "Room name (required for create)"},
|
||||
"room_id": {"type": "string", "description": "Room ID (required for info, history, archive, delete, invite, kick)"},
|
||||
"members": {"type": "array", "items": _COMMON_STRING, "description": "Usernames to invite during room creation"},
|
||||
"username": {"type": "string", "description": "Username to invite or kick from a room"},
|
||||
"count": {"type": "integer", "description": "Number of history messages to fetch (default: 20)"},
|
||||
},
|
||||
"required": ["action"],
|
||||
},
|
||||
}
|
||||
|
||||
ROCKETCHAT_USERS_SCHEMA = {
|
||||
"name": "rocketchat_users",
|
||||
"description": (
|
||||
"Query Rocket.Chat users: list all, get detailed user info by ID or username, "
|
||||
"or search by name/username."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["list", "info", "search"],
|
||||
"description": "Operation",
|
||||
},
|
||||
"user_id": {"type": "string", "description": "User ID (for info)"},
|
||||
"username": {"type": "string", "description": "Username (for info or as alternative target for dm/open)"},
|
||||
"query": {"type": "string", "description": "Search term (for search/list)"},
|
||||
"count": {"type": "integer", "description": "Maximum results to return (default: 50 for list, 20 for search)"},
|
||||
},
|
||||
"required": ["action"],
|
||||
},
|
||||
}
|
||||
|
||||
ROCKETCHAT_DM_SCHEMA = {
|
||||
"name": "rocketchat_dm",
|
||||
"description": (
|
||||
"Open or send direct messages on Rocket.Chat. Use 'open' to create/lookup a DM room, "
|
||||
"'send' to send text to a DM (by room_id, username, or user_id), 'list' to list DMs."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["open", "send", "list"],
|
||||
"description": "Operation",
|
||||
},
|
||||
"username": {"type": "string", "description": "Username of the DM partner"},
|
||||
"user_id": {"type": "string", "description": "User ID of the DM partner (alternative to username)"},
|
||||
"room_id": {"type": "string", "description": "DM room ID (for send)"},
|
||||
"text": {"type": "string", "description": "Message text (required for send)"},
|
||||
},
|
||||
"required": ["action"],
|
||||
},
|
||||
}
|
||||
|
||||
ROCKETCHAT_SEND_SCHEMA = {
|
||||
"name": "rocketchat_send",
|
||||
"description": (
|
||||
"Send a message to a Rocket.Chat room or DM with optional interactive buttons. "
|
||||
"Use button_template to attach native Rocket.Chat action buttons: 'yes_no', "
|
||||
"'confirm_cancel', 'ok', 'multi_choice_3', or 'custom'. When template='custom', "
|
||||
"provide custom_buttons as an array of short labels (≤10 chars, no spaces — e.g. "
|
||||
"'✅Ja', '❌Nein'). Always provide a unique question_id so the user's click can "
|
||||
"be correlated."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"room_id": {"type": "string", "description": "Target room ID or DM room ID"},
|
||||
"text": {"type": "string", "description": "Message body text"},
|
||||
"button_template": {
|
||||
"type": "string",
|
||||
"enum": ["yes_no", "confirm_cancel", "ok", "multi_choice_3", "custom", "none"],
|
||||
"description": "Built-in button template (or 'none' for plain text)",
|
||||
},
|
||||
"question_id": {"type": "string", "description": "Unique ID for button tracking (e.g. 'freigabe_42')"},
|
||||
"custom_buttons": {
|
||||
"type": "array",
|
||||
"items": _COMMON_STRING,
|
||||
"description": "Custom button labels, max 3-4 items, short (≤10 chars, no spaces)",
|
||||
},
|
||||
"button_title": {"type": "string", "description": "Title above the button group"},
|
||||
},
|
||||
"required": ["room_id", "text"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Registration helpers for the plugin register() function
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_TOOLS = (
|
||||
("rocketchat_rooms", ROCKETCHAT_ROOMS_SCHEMA, _handle_rocketchat_rooms, "🏢"),
|
||||
("rocketchat_users", ROCKETCHAT_USERS_SCHEMA, _handle_rocketchat_users, "👤"),
|
||||
("rocketchat_dm", ROCKETCHAT_DM_SCHEMA, _handle_rocketchat_dm, "💬"),
|
||||
("rocketchat_send", ROCKETCHAT_SEND_SCHEMA, _handle_rocketchat_send, "✉️"),
|
||||
)
|
||||
|
||||
|
||||
def check_rocketchat_tools_available() -> bool:
|
||||
"""Return True if Rocket.Chat credentials are available in the environment."""
|
||||
return bool(
|
||||
os.getenv("ROCKETCHAT_BASE_URL", "").strip()
|
||||
and os.getenv("ROCKETCHAT_USER", "").strip()
|
||||
and os.getenv("ROCKETCHAT_PASSWORD", "").strip()
|
||||
)
|
||||
|
||||
|
||||
def register_tools(ctx) -> None:
|
||||
"""Register all Rocket.Chat tools. Called by the platform plugin register()."""
|
||||
for name, schema, handler, emoji in _TOOLS:
|
||||
ctx.register_tool(
|
||||
name=name,
|
||||
toolset="rocketchat",
|
||||
schema=schema,
|
||||
handler=handler,
|
||||
check_fn=check_rocketchat_tools_available,
|
||||
emoji=emoji,
|
||||
)
|
||||
Reference in New Issue
Block a user