docs/api/Websocket Events

Websocket Events

WebSocket Events & Telemetrie

Neben den klassischen Webhooks für serverseitige Benachrichtigungen bietet KiroCloud native WebSocket-Verbindungen an. Diese sind ideal, um auf einer Website oder in einem Dashboard Live-Updates (wie CPU-Auslastung oder Konsolenausgaben eines Bots) in Echtzeit darzustellen.

Die WebSocket-API ist direkt unter /ws/ verfügbar. Im Gegensatz zur HTTP-API wird zur Authentifizierung der JWT-Token im Query-String ?token=... oder per Cookie übergeben.


1. Dashboard WebSocket (Bot-Telemetrie)

Dieser Endpunkt liefert Live-Daten für einen spezifischen Bot. Das ist nützlich, wenn du ein eigenes Web-Interface für deine Discord Bots bauen möchtest, in dem die User die Live-Konsole ihres Bots sehen können.

Endpunkt:wss://api.kirocloud.de/ws/dashboard?botId=DEINE_BOT_ID&token=DEIN_API_TOKEN

Unterstützte Events

Wenn du dich verbindest, erhältst du sofort ein subscribed Event sowie die Log-Historie (falls vorhanden). Danach pusht der Server bei Änderungen folgende Events:

  • bot:status - Wird gesendet, wenn der Bot online, offline oder abgestürzt ist.
  • bot:log - Jede neue Konsolenausgabe (stdout/stderr) des Bots.
  • bot:stats - Echtzeit CPU- und RAM-Auslastung des Bots (wird i.d.R. im Sekundentakt gepusht).
  • bot:log_history - Ein Array der letzten Log-Einträge, direkt nach der Verbindung gesendet.

Beispiel: Implementierung im Frontend (JavaScript)

<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <title>KiroBot Live Konsole</title>
  <style>
    body { background: #111; color: #0f0; font-family: monospace; padding: 20px; }
    #console { white-space: pre-wrap; }
  </style>
</head>
<body>
  <h2>Live Konsole</h2>
  <div id="console"></div>

  <script>
    const BOT_ID = '1234567890';
    // HINWEIS: Niemals den API-Key dauerhaft im Frontend hardcoden!
    // Nutze Cookies oder einen Backend-Proxy in Produktion.
    const TOKEN = 'DEIN_API_KEY'; 

    const ws = new WebSocket(`wss://api.kirocloud.de/ws/dashboard?botId=${BOT_ID}&token=${TOKEN}`);

    const consoleDiv = document.getElementById('console');

    ws.onmessage = (event) => {
      try {
        const payload = JSON.parse(event.data);
        
        switch (payload.event) {
          case 'subscribed':
            console.log('Erfolgreich mit dem Websocket verbunden!');
            break;

          case 'bot:log_history':
            // Initialer Log-Dump
            payload.data.forEach(logLine => {
              consoleDiv.textContent += logLine + '\n';
            });
            break;

          case 'bot:log':
            // Neue, einzelne Log-Zeile
            consoleDiv.textContent += payload.data + '\n';
            window.scrollTo(0, document.body.scrollHeight);
            break;

          case 'bot:status':
            consoleDiv.textContent += `[SYSTEM] Bot Status geändert zu: ${payload.data.status}\n`;
            break;

          case 'bot:stats':
            // payload.data enthält z.B. { cpu: 2.5, memory: 120 }
            document.title = `RAM: ${payload.data.memory}MB`;
            break;
        }
      } catch (err) {
        // Fallback falls die Daten mal kein JSON sind
        consoleDiv.textContent += event.data + '\n';
      }
    };

    ws.onerror = (error) => {
      console.error('WebSocket Error:', error);
      consoleDiv.textContent += `[WS ERROR] Verbindung fehlgeschlagen.\n`;
    };

    ws.onclose = () => {
      consoleDiv.textContent += `[WS CLOSED] Verbindung getrennt.\n`;
    };
  </script>
</body>
</html>


2. Bot Telemetrie & Performance Stream (Node.js Client)

Für Backend-Dienste, Überwachungstools oder Daemon-Skripte kannst du den WebSocket auch direkt in Node.js konsumieren. Hierfür eignet sich die Standard-Bibliothek ws.

Endpunkt:wss://api.kirocloud.de/ws/dashboard?botId=DEINE_BOT_ID&token=DEIN_API_TOKEN

Implementierung im Backend (Node.js)

// npm install ws
import WebSocket from 'ws';

const BOT_ID = '00000000-0000-0000-0000-000000000000';
const API_TOKEN = 'kiro_sec_DEIN_API_SCHLUESSEL';
const ws = new WebSocket(`wss://api.kirocloud.de/ws/dashboard?botId=${BOT_ID}&token=${API_TOKEN}`);

ws.on('open', () => {
  console.log('Mit KiroCloud Telemetrie-Stream verbunden!');
});

ws.on('message', (data) => {
  const payload = JSON.parse(data.toString());
  
  if (payload.event === 'subscribed') {
    console.log('Abonnement für Bot-Telemetrie aktiv.');
  } else if (payload.event === 'bot:stats') {
    console.log(`[BOT STATS] CPU: ${payload.data.cpu}% | RAM: ${payload.data.memory}MB`);
  } else if (payload.event === 'bot:status') {
    console.log(`[BOT STATUS] Neuer Status: ${payload.data.status}`);
  }
});

ws.on('close', (code, reason) => {
  console.log(`Verbindung geschlossen (${code}):`, reason.toString());
});

ws.on('error', (err) => {
  console.error('WebSocket Fehler:', err.message);
});

3. Fehlerbehebung & Statuscodes

Sollte die WebSocket-Verbindung sofort nach dem Öffnen wieder getrennt werden, liefert der WebSocket Close Code die Ursache:

  • 1008 Policy Violation mit invalid token: Der übergebene API-Schlüssel ist ungültig, abgelaufen oder hat keinen Zugriff auf die angeforderte Bot-Instanz.
  • 1008 Policy Violation mit token+botId required: Der Pflichtparameter botId oder token fehlt in der Verbindungs-URL.
  • 1001 Going Away: Die Bot-Instanz wurde neu gestartet; der Client sollte nach 2 Sekunden eine automatische Wiederverbindung versuchen.
Luca Lichtenwald
Artikel verfasst vonGründer & Lead Cloud Architect

Luca Lichtenwald

Spezialisiert auf hochverfügbare Discord-Bot-Infrastrukturen, V8-Memory-Tuning und kryptografische Zero-Trust-Architekturen.

Cookie-Einstellungen

Wir verwenden Cookies, um deine Erfahrung zu verbessern und unsere Dienste optimal anzubieten. Du kannst deine Einstellungen jederzeit anpassen.

main/11f725c