1.1.12 • Published 3 months ago

captivate-chat-api v1.1.12

Weekly downloads
-
License
MIT
Repository
github
Last release
3 months ago

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:

  1. Basic setup with just a user ID:

    const conversation = await api.createConversation('user123');
  2. 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

  1. Send a message to the conversation:

    await conversation.sendMessage('Hello!');
    await conversation.sendMessage({type:'files',files:[{filename:'test.pdf'}]});
  2. Listen for responses:

    conversation.onMessage((message, type) => {
      console.log(`${type}: ${message}`);
    });

Handle Events

Use event listeners to handle various updates, errors, or custom actions:

  1. Error handling:

    conversation.onError((error) => {
      console.error('Error:', error);
    });
  2. Updates on conversation status:

    conversation.onConversationUpdate((update) => {
      console.log('Conversation Update:', update);
    });
  3. 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 Object

  • deleteUserConversations(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 string

  • setMetadata(metadata: object): Promise<void>
    Updates metadata for the conversation.

  • getMetadata(): Promise<object>
    Returns the metadata for that current conversation session

  • sendAction(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;
}
1.1.12

3 months ago

1.1.9

4 months ago

1.1.8

4 months ago

1.1.11

4 months ago

1.1.10

4 months ago

1.1.7

5 months ago

1.1.6

5 months ago

1.1.1

5 months ago

1.1.5

5 months ago

1.1.4

5 months ago

1.1.3

5 months ago

1.1.2

5 months ago

1.1.0

5 months ago

1.0.4

6 months ago

1.0.3

6 months ago

1.0.2

6 months ago

1.0.0

6 months ago