Websocket API
Moveo's websocket API enables real-time communication between your application and Moveo's services. This is the same websocket API that the Moveo Web Client
uses internally. You can use this API to build your own custom integration.With this API you can:
- Create and manage conversation sessions
- Send and receive messages in real-time
- Handle session lifecycle events
- Implement custom message handling logic
Socket.IO protocol
We use the Socket.IO protocol v4 to establish websocket communication between the client, and our channels service.
To initiate a websocket connection, send a GET
request to:
wss://channels-ws.moveo.ai/v1/web/{INTEGRATION-ID}/ws
Replace {INTEGRATION-ID}
with the ID of the Web
integration in Moveo.
Example complete URL:
wss://channels-ws.moveo.ai/v1/web/1d093558-bac1-4954-acdd-c8d8dc05fa30/ws/
Required headers
To upgrade the connection, include the following headers:
- Connection:
upgrade
- Upgrade:
websocket
Connection upgrade response
Upon successful upgrade, the server responds with an open
packet:
0{"sid":SESSION-ID,"upgrades":["websocket"],"pingInterval":10000,"pingTimeout":5000}
Heartbeat
The server will send a ping packet (2
) every pingInterval
milliseconds and expects a pong response before pingTimeout
.
Message structure
After connection upgrade, the server only responds to packets prefixed with 4
, indicating a message packet type.
The second character of the packet defines the message type:
0
: Connect message (server responds with40{"sid":"SESSION-ID"}
)1
: Disconnect message2
: Event message (see supported events below)
Event messages must be an array of exactly two elements:
- The
event type
(string), e.g.,message:send
- The
event payload
(object), e.g.:
{
"input": {
"text": "defaultstartmessage"
},
"session_id": "5ebeb74f-b3af-4ec0-960f-cd13ad7154d0",
"channel": "web",
"timestamp": 1737028058711
}
Complete example of a message
42["message:send",{"input":{"text":"defaultstartmessage"},"session_id":"5ebeb74f-b3af-4ec0-960f-cd13ad7154d0","channel":"web","timestamp":1737028058711}]
Depending on the event type, the server may respond after processing.
Code Example
This is a comprehensive Node.js example using the socket.io-client
library. The example demonstrates:
- Connection establishment with proper error handling
- Session creation and management
- Message sending and receiving
- Error handling and reconnection logic
- Rate limit handling
- Logging and monitoring
import { io } from "socket.io-client";
// Configuration
const INTEGRATION_ID = "c3725769-d21e-4391-9f15-63f47eefe211"; // replace with your real one
const URL = `wss://channels-ws.moveo.ai/`;
const MAX_RECONNECT_ATTEMPTS = 5;
const RECONNECT_DELAY = 1000; // 1 second
const RATE_LIMIT_RETRY_DELAY = 60000; // 1 minute
// Connection options
const socketOptions = {
path: `/v1/web/${INTEGRATION_ID}/ws`,
transports: ["websocket"],
autoConnect: true,
upgrade: false,
extraHeaders: {
Connection: "upgrade",
Upgrade: "websocket",
},
// Reconnection settings
reconnection: true,
reconnectionAttempts: MAX_RECONNECT_ATTEMPTS,
reconnectionDelay: RECONNECT_DELAY,
reconnectionDelayMax: 5000,
};
// Initialize socket connection
const socket = io(URL, socketOptions);
// Connection event handlers
socket.on("connect", () => {
console.log("✅ Connected", socket.id);
// Create a new session
const sessionCreatePayload = {
context: {
user: {
// Add any user-specific context here
email: "user123@example.com",
name: "John Doe",
},
},
timestamp: Date.now(),
is_test: true, // Set to false in production
};
socket.emit("session:create", sessionCreatePayload);
});
// Session management
socket.on("session:created", (data) => {
console.log("🆕 Session created:", data);
// Store session ID for future messages
const sessionId = data.session_id;
// Send initial message
const eventPayload = {
input: {
text: "defaultstartmessage",
},
session_id: sessionId,
channel: "web",
timestamp: Date.now(),
};
socket.emit("message:send", eventPayload);
});
// Message handling
socket.on("message:receive", (data) => {
console.log("📥 Message received:", data);
});
// Error handling
socket.on("connect_error", (err) => {
console.error("❌ Connection error:", err);
// Handle specific error types
if (err.message.includes("rate_limit")) {
console.log("Rate limit exceeded, retrying in 1 minute...");
setTimeout(() => {
socket.connect();
}, RATE_LIMIT_RETRY_DELAY);
}
});
socket.on("disconnect", (reason) => {
console.log("🔌 Disconnected:", reason);
// Handle specific disconnect reasons
if (reason === "io server disconnect") {
// Server initiated disconnect, try to reconnect
socket.connect();
}
});
// Handle rate limit errors
socket.on("error", (error) => {
if (error.type === "rate_limit") {
console.log("Rate limit exceeded:", error.message);
// Implement your rate limit handling logic here
}
});
// Cleanup on process exit
process.on("SIGINT", () => {
console.log("Closing connection...");
socket.close();
process.exit();
});
Rate Limits and Error Handling
Rate Limits
- Maximum concurrent connections per integration: 1000
- Maximum messages per second: 100
- Maximum reconnection attempts: 5
- Rate limit window: 60 seconds
When rate limits are exceeded, the server will respond with a 429 Too Many Requests
status code and the following error message:
{
"error": "rate_limit_exceeded",
"message": "Too many requests",
"retry_after": 60
}
Error Codes
Code | Description | Action |
---|---|---|
400 | Bad Request | Check request format and parameters |
401 | Unauthorized | Verify integration ID |
403 | Forbidden | Check permissions |
429 | Too Many Requests | Implement backoff strategy |
500 | Internal Server Error | Retry with exponential backoff |
Error Handling Best Practices
- Implement exponential backoff for retries
- Log errors with appropriate context
- Monitor error rates and patterns
- Set up alerts for critical errors
- Implement circuit breakers for persistent failures
Troubleshooting
Common issues and their solutions:
-
Connection Failures:
- Verify the integration ID is correct
- Check network connectivity
- Ensure proper headers are set
- Verify SSL/TLS configuration
-
Message Delivery Issues:
- Check message format and structure
- Verify session ID is valid
- Ensure proper event type is used
-
Performance Issues:
- Monitor connection health
- Implement reconnection logic
- Handle backpressure appropriately
Rate Limits and Best Practices
-
Connection Management:
- Implement exponential backoff for reconnection attempts
- Monitor connection health
- Handle disconnections gracefully
-
Message Handling:
- Process messages in order
- Implement message queuing if needed
- Handle message acknowledgments
-
Resource Management:
- Close connections when not needed
- Monitor memory usage
- Implement proper cleanup procedures