captivate-chat-api v1.1.12
captivate-chat-api
WebSocket-based chat API for real-time conversations with support for bot and human agents.
Installation
Install the package using npm:
npm install captivate-chat-api
Usage
Basic Setup
Import and initialize the API client:
import { CaptivateChatAPI } from 'captivate-chat-api';
const api = new CaptivateChatAPI('YOUR_API_KEY');
// Connect to the WebSocket server
await api.connect();
Create a Conversation
Create a new conversation with the following options:
Basic setup with just a user ID:
const conversation = await api.createConversation('user123');
Include user information and custom data:
const conversation = await api.createConversation( 'user123', { name: 'John Doe', email: 'john@example.com' }, { customField: 'value' }, 'user-first' // Start the conversation with user-first or bot-first mode );
Send and Receive Messages
Send a message to the conversation:
await conversation.sendMessage('Hello!'); await conversation.sendMessage({type:'files',files:[{filename:'test.pdf'}]});
Listen for responses:
conversation.onMessage((message, type) => { console.log(`${type}: ${message}`); });
Handle Events
Use event listeners to handle various updates, errors, or custom actions:
Error handling:
conversation.onError((error) => { console.error('Error:', error); });
Updates on conversation status:
conversation.onConversationUpdate((update) => { console.log('Conversation Update:', update); });
Handling custom actions:
conversation.onActionReceived((actions) => { console.log(`Actions:`, actions); });
Get Conversation History
Retrieve the transcript of a conversation:
const transcript = await conversation.getTranscript();
console.log('Transcript:', transcript);
Delete Conversation
Delete the current conversation
const transcript = await conversation.delete();
console.log('Deleted conversation');
Retrieve User Conversations
Fetch a list of conversations associated with a specific user ID:
const conversations = await api.getUserConversations('user123');
console.log('User Conversations:', conversations);
/*
Returns Conversation Object
*/
Delete User Conversations
Delete list of conversations associated with a specific user ID:
const conversations = await api.deleteUserConversations('user123');
console.log('Conversations Deleted successfully');
/*
Throws error if failed
*/
Example: Full Workflow
Here’s a complete example of how to use the API:
import { CaptivateChatAPI } from 'captivate-chat-api';
(async () => {
try {
const api = new CaptivateChatAPI('YOUR_API_KEY', 'prod');
// Connect to the API
await api.connect();
console.log('Connected to CaptivateChat API');
// Create a conversation
const conversation = await api.createConversation(
'user123',
{
name: 'John Doe',
email: 'john@example.com',
},
{ role: 'admin' },
'bot-first'
);
console.log('Conversation started:', conversation);
// Listen for messages
conversation.onMessage((message, type) => {
console.log(`Received (${type}): ${message}`);
});
// Send a message
await conversation.sendMessage('Hello! How can I assist you today?');
// Handle conversation updates
conversation.onConversationUpdate((update) => {
console.log('Conversation Update:', update);
});
// Fetch the transcript
const transcript = await conversation.getTranscript();
console.log('Transcript:', transcript);
// Delete the conversation
await conversation.delete();
console.log('Conversation deleted successfully.');
} catch (error) {
console.error('Error:', error);
}
})();
Development Mode
Switch to development mode for testing:
const api = new CaptivateChatAPI('YOUR_API_KEY', 'dev');
Environment Support
The API supports the following environments:
- Browser
- Node.js
- React Native
API Reference
CaptivateChatAPI
Methods
constructor(apiKey: string, mode: 'prod' | 'dev' = 'prod')
Initializes the API with the given API key and mode.connect(): Promise<void>
Connects to the WebSocket server.createConversation(userId: string, userBasicInfo?: object, userData?: object, autoConversationStart?: 'bot-first' | 'user-first'): Promise<Conversation>
Creates a new conversation.getConversation(conversationId: string): Conversation
Retrieves an existing conversation by its ID.getUserConversations(userId: string): Promise<Conversation>
Fetches a list of conversations associated with the given user ID. Returns Conversation ObjectdeleteUserConversations(userId: string): Promise<void>
Deletes all conversations associated with the given user ID
Conversation
Methods
sendMessage(content: string): Promise<void>
Sends a message to the conversation.sendMessage(content: object): Promise<void>
Can also send custom payload instead of default stringsetMetadata(metadata: object): Promise<void>
Updates metadata for the conversation.getMetadata(): Promise<object>
Returns the metadata for that current conversation sessionsendAction(actionId: string, data?: object): Promise<void>
Sends a custom action to the conversation.getTranscript(): Promise<object[]>
Retrieves the conversation transcript.delete(): Promise<void>
Deletes the current conversation
Events
onMessage(callback: (message: string, type: string) => void): void
Listens for new messages.onError(callback: (error: any) => void): void
Listens for errors.onConversationUpdate(callback: (update: any) => void): void
Listens for updates to the conversation.onActionReceived(callback: (actions:[Action]) => void): void
Handles custom actions received during the conversation.
Interfaces
interface Action {
id: string;
data: any;
}