### Install and Run Simple Agent Example (Bash) Source: https://github.com/livechat/chat-sdk/blob/master/README.md Commands to set up and run the 'Simple Agent' example application. This involves installing Node.js dependencies and starting the application server. Ensure you have cloned the Chat SDK repository and configured environment variables. ```bash npm install npm start ``` -------------------------------- ### Install and Initialize LiveChat Chat SDK Source: https://context7.com/livechat/chat-sdk/llms.txt Installs the Chat SDK using npm and initializes it with authentication credentials. Supports both OAuth and Personal Access Tokens. Includes optional configuration for debugging, region, and API version. ```javascript // Installation // npm i @livechat/chat-sdk import ChatSDK from '@livechat/chat-sdk'; // Initialize SDK with optional configuration const chatSDK = new ChatSDK({ debug: true, // Enable debug logging region: 'america', // or 'europe' apiVersion: 'v3.4' // Specify API version }); // Initialize connection with access token (OAuth) chatSDK.init({ access_token: 'dal:test_-hKFLDSALKFJLKADJFLKADLKAJFLK' }); // OR initialize with Personal Access Token const encodedToken = btoa('account_id:personal_access_token'); chatSDK.init({ personal_access_token: encodedToken }); // Listen for ready event chatSDK.on('ready', () => { console.log('Agent successfully logged in and ready to use SDK'); }); // Error handling during connection chatSDK.on('connect', () => { console.log('WebSocket connected'); }); ``` -------------------------------- ### Install LiveChat Chat SDK via NPM Source: https://github.com/livechat/chat-sdk/blob/master/README.md The command required to download and install the @livechat/chat-sdk package into your JavaScript project dependencies. ```bash npm i @livechat/chat-sdk ``` -------------------------------- ### Create Custom Method with methodFactory (JavaScript) Source: https://github.com/livechat/chat-sdk/blob/master/README.md Demonstrates creating a custom SDK method to interact with the RTM API. It uses `methodFactory` with a specified action and payload. The example retrieves chat details, requiring only `chat_id`, but also supporting optional parameters. It includes basic .then and .catch for handling the asynchronous response. ```javascript const getChat = (chat_id) => ChatSDK.methodFactory({ action: "get_chat", payload: { chat_id } }); getChat("PJ0MRSHTDG") .then(data => { // get a chat details with the latest thread (if exists) }) .catch(error => { // catch an error }) ``` -------------------------------- ### GET getAgentDetails Source: https://context7.com/livechat/chat-sdk/llms.txt Retrieves the profile information and current status of the currently authenticated agent. ```APIDOC ## GET getAgentDetails ### Description Fetches profile data for the agent currently authenticated within the SDK session. ### Method GET ### Response #### Success Response (200) - **id** (string) - Agent unique ID - **name** (string) - Full name of the agent - **email** (string) - Agent email address - **role** (string) - Permissions role (e.g., administrator) - **avatar** (string) - URL to the agent's avatar image - **routing_status** (string) - Current chat routing status #### Response Example { "id": "agent-id-123", "name": "John Doe", "email": "john.doe@company.com", "role": "administrator", "avatar": "https://cdn.livechat.com/avatars/abc123.jpg", "routing_status": "accepting_chats" } ``` -------------------------------- ### Get Agent Details with LiveChat Chat SDK Source: https://context7.com/livechat/chat-sdk/llms.txt Retrieves information about the currently authenticated agent using the Chat SDK. Fetches agent's ID, name, email, role, avatar, and routing status. Includes error handling for cases where the agent is not logged in. ```javascript chatSDK.getAgentDetails() .then(agentData => { console.log('Agent ID:', agentData.id); console.log('Agent Name:', agentData.name); console.log('Agent Email:', agentData.email); console.log('Agent Role:', agentData.role); console.log('Avatar URL:', agentData.avatar); // Example output structure: // { // id: 'agent-id-123', // name: 'John Doe', // email: 'john.doe@company.com', // role: 'administrator', // avatar: 'https://cdn.livechat.com/avatars/abc123.jpg', // routing_status: 'accepting_chats' // } }) .catch(error => { console.error('Error fetching agent details:', error); // Error: 'ChatSDK.getAgentDetails: Agent is not logged in yet' }); // Wait for ready event before calling chatSDK.once('ready', async () => { const agent = await chatSDK.getAgentDetails(); console.log(`Logged in as ${agent.name}`); }); ``` -------------------------------- ### Create Custom API Methods with Method Factory Source: https://context7.com/livechat/chat-sdk/llms.txt Define custom methods for LiveChat Agent Chat API RTM actions. This allows for streamlined interaction with the API by abstracting common actions like getting chat details, listing chats, and updating agent status. Requires the chatSDK instance. ```javascript // Create a custom method to get chat details const getChat = (chat_id, thread_id = null) => chatSDK.methodFactory({ action: 'get_chat', payload: { chat_id, ...(thread_id && { thread_id }) } }); // Use the custom method getChat('PJ0MRSHTDG') .then(data => { console.log('Chat details:', data); console.log('Chat users:', data.users); console.log('Last thread:', data.thread); // Access complete chat object with threads, properties, etc. }) .catch(error => { console.error('Error:', error); }); // Create method to list chats const listChats = (filters = {}) chatSDK.methodFactory({ action: 'list_chats', payload: { sort_order: 'desc', limit: 25, ...filters } }); // Get active chats listChats({ filters: { include_active: true } }) .then(data => { console.log('Active chats:', data.chats); data.chats.forEach(chat => { console.log(`Chat ${chat.id}: ${chat.users.length} participants`); }); }) .catch(error => { console.error('Error listing chats:', error); }); // Create method to update agent status const setRoutingStatus = (status, agent_id = 'my') => chatSDK.methodFactory({ action: 'set_routing_status', payload: { agent_id, status // 'accepting_chats', 'not_accepting_chats', 'offline' } }); // Update status await setRoutingStatus('accepting_chats'); console.log('Agent is now accepting chats'); ``` -------------------------------- ### Manage SDK Lifecycle and Reconnection Source: https://context7.com/livechat/chat-sdk/llms.txt Demonstrates how to initialize the SDK, handle component unmounting via the destroy method, and implement custom reconnection logic with exponential backoff. ```javascript const chatSDK = new ChatSDK({ debug: false }); chatSDK.init({ access_token: 'dal:test_token_here' }); function cleanup() { chatSDK.destroy(); } // React implementation useEffect(() => { const sdk = new ChatSDK({ debug: true }); sdk.init({ access_token: '...' }); return () => sdk.destroy(); }, []); // Reconnection strategy chatSDK.on('disconnect', () => { if (reconnectAttempts < MAX_RECONNECT) { setTimeout(() => chatSDK.init({ access_token: token }), 2000 * reconnectAttempts); } }); ``` -------------------------------- ### Authenticate and Initialize Connection Source: https://github.com/livechat/chat-sdk/blob/master/README.md Establishes a WebSocket connection and authenticates the agent using either a standard access token or a base64-encoded personal access token. ```javascript chatSDK.init({ access_token: access_token // OR personal_access_token: personal_access_token }) ``` -------------------------------- ### Initialize LiveChat Chat SDK Source: https://github.com/livechat/chat-sdk/blob/master/README.md Instantiates the ChatSDK class with configuration options. The debug parameter can be enabled to log message exchanges to the console. ```javascript const chatSDK = new ChatSDK({ debug: true }) ``` -------------------------------- ### Build Advanced Agent Chat Application Source: https://context7.com/livechat/chat-sdk/llms.txt Provides a robust class-based implementation for managing multiple chat sessions, listening for events, sending messages, and performing administrative actions like chat transfers and status updates. ```javascript class LiveChatAgent { constructor(accessToken) { this.sdk = new ChatSDK({ debug: true }); this.activeChats = new Map(); } async initialize() { return new Promise((resolve) => { this.sdk.init({ access_token: this.accessToken }); this.sdk.once('ready', resolve); }); } setupEventHandlers() { this.sdk.on('incoming_chat', (data) => { const chat = data.payload.chat; this.activeChats.set(chat.id, chat); }); } async sendMessage(chatId, text) { return await this.sdk.sendMessage(chatId, text); } destroy() { this.sdk.destroy(); } } ``` -------------------------------- ### Retrieve Agent Details Source: https://github.com/livechat/chat-sdk/blob/master/README.md Fetches profile and status information for the currently authenticated agent. Returns a promise that resolves with the agent data object. ```javascript chatSDK.getAgentDetails() .then(agentData => { // access to the agentData object }) .catch(error => { // catch an error object }) ``` -------------------------------- ### Subscribe to Events with on (JavaScript) Source: https://github.com/livechat/chat-sdk/blob/master/README.md This method subscribes to specified events emitted by the Chat SDK. A callback function is executed whenever the event occurs, receiving the event data. This is useful for real-time updates and reactions to SDK status changes like login. ```javascript chatSDK.on("event_name", (data) => { console.log(data) }) ``` -------------------------------- ### Subscribe to Real-time Push Events with Event Listeners Source: https://context7.com/livechat/chat-sdk/llms.txt Listen for real-time push notifications from the LiveChat API. This allows your application to react to events such as incoming chats, new messages, and chat deactivations. You can register listeners for specific events, trigger actions only once, or remove listeners when no longer needed. Requires the chatSDK instance. ```javascript // Listen for incoming chat events chatSDK.on('incoming_chat', (data) => { console.log('New chat incoming:', data.payload.chat); const chat = data.payload.chat; console.log(`Chat ID: ${chat.id}`); console.log(`Requester: ${chat.users[0].name}`); }); // Listen for new events (messages) chatSDK.on('incoming_event', (data) => { const event = data.payload.event; console.log('New event:', event); if (event.type === 'message') { console.log(`Message from ${event.author_id}: ${event.text}`); } }); // Listen for chat deactivated chatSDK.on('chat_deactivated', (data) => { console.log('Chat closed:', data.payload.chat_id); console.log('Thread ID:', data.payload.thread_id); }); // One-time event listener chatSDK.once('incoming_chat', (data) => { console.log('First chat received:', data.payload.chat); // This listener will be automatically removed after first trigger }); // Remove specific event listener const messageHandler = (data) => { console.log('Event received:', data); }; chatSDK.on('incoming_event', messageHandler); // Later, remove the listener chatSDK.off('incoming_event', messageHandler); // Complete example: Auto-respond to new chats chatSDK.on('ready', () => { console.log('SDK ready, listening for chats...'); chatSDK.on('incoming_chat', async (data) => { const chatId = data.payload.chat.id; const userName = data.payload.chat.users[0].name; try { await chatSDK.sendMessage( chatId, `Hello ${userName}! An agent will be with you shortly.` ); console.log('Auto-response sent'); } catch (error) { console.error('Failed to send auto-response:', error); } }); }); ``` -------------------------------- ### Subscribe Once to Events with once (JavaScript) Source: https://github.com/livechat/chat-sdk/blob/master/README.md The `once` method subscribes to an event but automatically unsubscribes after the callback function has been executed for the first time. This is useful for one-off actions that should only occur immediately upon an event. ```javascript chatSDK.once("event_name", (data) => { console.log(data) }) ``` -------------------------------- ### Destroy SDK Instance Source: https://github.com/livechat/chat-sdk/blob/master/README.md Clears all internal resources, removes registered event listeners, and terminates the active WebSocket network connection. ```javascript chatSDK.destroy() ``` -------------------------------- ### Send Messages with LiveChat Chat SDK Source: https://context7.com/livechat/chat-sdk/llms.txt Sends plain text messages to chat conversations using the Chat SDK. Supports sending messages to all participants or specifically to agents. Includes error handling for missing parameters and API issues. ```javascript const chatId = 'PJ0MRSHTDG'; const message = 'Hello! How can I help you today?'; // Send message to all participants (default) chatSDK.sendMessage(chatId, message) .then(event => { console.log('Message sent successfully:', event.event_id); // Output: { event_id: 'K600PKZON8' } }) .catch(error => { console.error('Failed to send message:', error); // Handles errors like missing chat_id or API unavailable }); // Send message only to agents chatSDK.sendMessage(chatId, 'Internal note for agents', 'agents') .then(event => { console.log('Agent-only message sent:', event.event_id); }) .catch(error => { console.error('Error:', error); }); // Example with error handling for missing parameters try { await chatSDK.sendMessage(null, 'Test'); // Will throw error } catch (error) { console.error(error.message); // Output: 'ChatSDK.sendMessage: Missing chat_id param' } ``` -------------------------------- ### POST sendMessage Source: https://context7.com/livechat/chat-sdk/llms.txt Sends a plain text message to a specific chat conversation. Supports sending messages to all participants or restricted visibility to agents only. ```APIDOC ## POST sendMessage ### Description Sends a plain text message to a specific chat session. ### Method POST ### Parameters #### Path Parameters - **chatId** (string) - Required - The unique identifier of the chat conversation. #### Request Body - **message** (string) - Required - The text content to send. - **recipient_type** (string) - Optional - Specify 'agents' to send internal notes visible only to agents. ### Request Example { "chatId": "PJ0MRSHTDG", "message": "Hello! How can I help you today?" } ### Response #### Success Response (200) - **event_id** (string) - Unique identifier for the sent message event. #### Response Example { "event_id": "K600PKZON8" } ``` -------------------------------- ### Unsubscribe from Events with off (JavaScript) Source: https://github.com/livechat/chat-sdk/blob/master/README.md The `off` method is used to unsubscribe from previously subscribed events. This prevents the callback function from being executed when the specified event is emitted. It requires the event name and optionally the callback function to remove. ```javascript chatSDK.off("event_name", (data) => { console.log(data) }) ``` -------------------------------- ### Send Plain Text Message Source: https://github.com/livechat/chat-sdk/blob/master/README.md Sends a text message to a specific chat identified by its ID. Returns a promise that resolves with the unique event_id of the sent message. ```javascript const chatId = 'PJ0MRSHTDG' const message = 'Hello world' chatSDK.sendMessage(chatId, message) .then(event => { // get event_id or handle a success scenario }) .catch(error => { // catch an error object }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.