Skip to main content

JavaScript (Browser)

class CoreTrackerWebSocket {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.ws = null;
    this.subscriptions = new Map();
    this.reconnectAttempts = 0;
  }

  connect() {
    const url = `wss://api.corebot.app/ws/v1/stream?apiKey=${this.apiKey}`;
    this.ws = new WebSocket(url);

    this.ws.onopen = () => {
      console.log('Connected to CoreTracker WebSocket');
      this.reconnectAttempts = 0;
    };

    this.ws.onmessage = (event) => {
      const message = JSON.parse(event.data);
      this.handleMessage(message);
    };

    this.ws.onerror = (error) => {
      console.error('WebSocket error:', error);
    };

    this.ws.onclose = (event) => {
      console.log('Connection closed:', event.code, event.reason);
      this.handleReconnect();
    };
  }

  handleMessage(message) {
    switch(message.type) {
      case 'connected':
        console.log('Connection ID:', message.connection_id);
        this.resubscribe();
        break;
      case 'subscription_confirmed':
        console.log('Subscription confirmed:', message.subscription_id);
        break;
      case 'data':
        const handler = this.subscriptions.get(message.subscription_id);
        if (handler) handler(message.data);
        break;
      case 'error':
        console.error('Error:', message.error_code, message.message);
        break;
    }
  }

  subscribe(type, params, handler) {
    const subscriptionId = `sub_${Date.now()}`;
    this.subscriptions.set(subscriptionId, handler);
    
    this.ws.send(JSON.stringify({
      type: 'subscribe',
      subscription_type: type,
      subscription_id: subscriptionId,
      params: params
    }));
    
    return subscriptionId;
  }

  unsubscribe(subscriptionId) {
    this.subscriptions.delete(subscriptionId);
    this.ws.send(JSON.stringify({
      type: 'unsubscribe',
      subscription_id: subscriptionId
    }));
  }

  handleReconnect() {
    if (this.reconnectAttempts < 5) {
      this.reconnectAttempts++;
      const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
      console.log(`Reconnecting in ${delay}ms...`);
      setTimeout(() => this.connect(), delay);
    }
  }

  resubscribe() {
    // Resubscribe after reconnection
    for (const [id, handler] of this.subscriptions) {
      // Re-subscribe logic here
    }
  }
}

// Usage
const tracker = new CoreTrackerWebSocket('ct_live_xxxxx');
tracker.connect();

// Subscribe to user timeline
tracker.subscribe('user_timeline', 
  { username: 'elonmusk' },
  (data) => {
    console.log('New tweet:', data.text);
  }
);

Node.js

const WebSocket = require('ws');

class CoreTrackerClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.ws = null;
    this.pingInterval = null;
  }

  connect() {
    return new Promise((resolve, reject) => {
      this.ws = new WebSocket(`wss://api.corebot.app/ws/v1/stream?apiKey=${this.apiKey}`);

      this.ws.on('open', () => {
        console.log('Connected');
        this.setupPing();
        resolve();
      });

      this.ws.on('message', (data) => {
        const message = JSON.parse(data);
        this.handleMessage(message);
      });

      this.ws.on('error', reject);

      this.ws.on('close', () => {
        clearInterval(this.pingInterval);
        setTimeout(() => this.connect(), 5000);
      });
    });
  }

  setupPing() {
    this.pingInterval = setInterval(() => {
      if (this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify({ type: 'ping' }));
      }
    }, 30000);
  }

  handleMessage(message) {
    if (message.type === 'data') {
      console.log('Tweet:', message.data.text);
    }
  }

  subscribeToUser(username) {
    this.ws.send(JSON.stringify({
      type: 'subscribe',
      subscription_type: 'user_timeline',
      params: { username }
    }));
  }
}

// Usage
async function main() {
  const client = new CoreTrackerClient('ct_live_xxxxx');
  await client.connect();
  client.subscribeToUser('elonmusk');
}

main().catch(console.error);

Python

import json
import time
import websocket
from threading import Thread

class CoreTrackerWebSocket:
    def __init__(self, api_key):
        self.api_key = api_key
        self.ws = None
        self.running = True
        
    def on_message(self, ws, message):
        data = json.loads(message)
        
        if data['type'] == 'connected':
            print(f"Connected: {data['connection_id']}")
            self.subscribe_to_timeline('elonmusk')
            
        elif data['type'] == 'data':
            tweet = data['data']
            print(f"New tweet: {tweet.get('text', '')[:100]}...")
            
        elif data['type'] == 'error':
            print(f"Error: {data['message']}")
    
    def on_error(self, ws, error):
        print(f"WebSocket error: {error}")
    
    def on_close(self, ws, close_status_code, close_msg):
        print(f"Connection closed: {close_msg}")
        if self.running:
            time.sleep(5)
            self.connect()
    
    def on_open(self, ws):
        print("WebSocket connected")
        
        # Start ping thread
        def ping():
            while self.running:
                time.sleep(30)
                if ws.sock and ws.sock.connected:
                    ws.send(json.dumps({'type': 'ping'}))
        
        Thread(target=ping, daemon=True).start()
    
    def subscribe_to_timeline(self, username):
        subscription = {
            'type': 'subscribe',
            'subscription_type': 'user_timeline',
            'params': {'username': username}
        }
        self.ws.send(json.dumps(subscription))
    
    def connect(self):
        url = f"wss://api.corebot.app/ws/v1/stream?apiKey={self.api_key}"
        self.ws = websocket.WebSocketApp(
            url,
            on_open=self.on_open,
            on_message=self.on_message,
            on_error=self.on_error,
            on_close=self.on_close
        )
        
        self.ws.run_forever()
    
    def disconnect(self):
        self.running = False
        if self.ws:
            self.ws.close()

# Usage
if __name__ == "__main__":
    client = CoreTrackerWebSocket('ct_live_xxxxx')
    
    try:
        client.connect()
    except KeyboardInterrupt:
        print("Shutting down...")
        client.disconnect()

Go

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "time"
    "github.com/gorilla/websocket"
)

type Message struct {
    Type           string         `json:"type"`
    SubscriptionID string         `json:"subscription_id,omitempty"`
    Data          interface{}    `json:"data,omitempty"`
    ErrorCode     string         `json:"error_code,omitempty"`
    Message       string         `json:"message,omitempty"`
}

type Subscription struct {
    Type           string         `json:"type"`
    SubscriptionType string       `json:"subscription_type"`
    Params        map[string]interface{} `json:"params"`
}

type CoreTrackerClient struct {
    apiKey string
    conn   *websocket.Conn
}

func NewCoreTrackerClient(apiKey string) *CoreTrackerClient {
    return &CoreTrackerClient{apiKey: apiKey}
}

func (c *CoreTrackerClient) Connect() error {
    url := fmt.Sprintf("wss://api.corebot.app/ws/v1/stream?apiKey=%s", c.apiKey)
    
    conn, _, err := websocket.DefaultDialer.Dial(url, nil)
    if err != nil {
        return err
    }
    
    c.conn = conn
    log.Println("Connected to CoreTracker WebSocket")
    
    // Start ping routine
    go c.pingRoutine()
    
    return nil
}

func (c *CoreTrackerClient) pingRoutine() {
    ticker := time.NewTicker(30 * time.Second)
    defer ticker.Stop()
    
    for range ticker.C {
        if err := c.conn.WriteJSON(map[string]string{"type": "ping"}); err != nil {
            log.Printf("Ping error: %v", err)
            return
        }
    }
}

func (c *CoreTrackerClient) Subscribe(username string) error {
    sub := Subscription{
        Type:             "subscribe",
        SubscriptionType: "user_timeline",
        Params: map[string]interface{}{
            "username": username,
        },
    }
    
    return c.conn.WriteJSON(sub)
}

func (c *CoreTrackerClient) Listen() {
    for {
        var msg Message
        err := c.conn.ReadJSON(&msg)
        if err != nil {
            log.Printf("Read error: %v", err)
            c.reconnect()
            continue
        }
        
        switch msg.Type {
        case "connected":
            log.Println("Received connection confirmation")
        case "data":
            log.Printf("New data: %v", msg.Data)
        case "error":
            log.Printf("Error: %s - %s", msg.ErrorCode, msg.Message)
        }
    }
}

func (c *CoreTrackerClient) reconnect() {
    time.Sleep(5 * time.Second)
    if err := c.Connect(); err != nil {
        log.Printf("Reconnection failed: %v", err)
        c.reconnect()
    }
}

func main() {
    client := NewCoreTrackerClient("ct_live_xxxxx")
    
    if err := client.Connect(); err != nil {
        log.Fatal(err)
    }
    
    if err := client.Subscribe("elonmusk"); err != nil {
        log.Fatal(err)
    }
    
    client.Listen()
}

Quick Tips

Always implement reconnection logic with exponential backoff to handle network issues gracefully.
Send a ping message every 30 seconds to keep the connection alive during quiet periods.
Store subscription IDs to resubscribe automatically after reconnection.