Advanced Features

Chat Data SDK

The Chat Data SDK enables seamless real-time communication between your website and the chatbot, enhancing the user experience. This guide will cover bidirectional information flow: sending user data from your website to the chatbot and receiving user actions from the chatbot. To help you get started, we'll provide a live demo website and a GitHub repository containing an example implementation.


Chat Data SDK

The Chat Data SDK provides a simple and standardized way to communicate with your embedded chatbot. While both webhooks and the SDK can handle events in real-time, the SDK offers advantages like direct communication between your website and the chatbot, eliminating network request delays and allowing immediate responses to user activities. For example, you can display a customer's name on your website right after they enter it in the chatbot widget - something not possible with webhooks.

Video Demo

Watch our video tutorial that demonstrates how to implement and use the Chat Data SDK:

Installation and Initialization

There are two ways to initialize the Chat Data SDK:

Method 1: Auto-initialization with data attribute

<script src="https://www.chat-data.com/static/chatbotsdk.min.js" data-chatbot-id="YOUR_CHATBOT_ID"></script>

Method 2: Manual initialization

<script src="https://www.chat-data.com/static/chatbotsdk.min.js"></script>
<script>
  window.chatbot.initialize({
    chatbot_id: "YOUR_CHATBOT_ID"
  });
</script>

If you're using a custom domain, replace the URL accordingly:

<script src="https://your-domain.com/static/chatbotsdk.min.js" data-chatbot-id="YOUR_CHATBOT_ID"></script>

Send User Information From Website to Chatbot

Consider a scenario where your website implements user authentication. Upon successful login, you can leverage the SDK to transmit user information to the chatbot, eliminating the need for redundant data collection. Furthermore, if your website offers diagnostic tools that generate user-specific metrics, you may want the chatbot to address follow-up inquiries about these metrics.

The SDK makes this easy with the sendUserInfo method:

window.chatbot.sendUserInfo({
       name: "Customer",
        email: "[email protected]",
        phone: "1234567890",
  info: "The user's lucky number is 654321"  // Any additional information as text
}).then(response => {
  console.log("User info sent successfully:", response);
}).catch(error => {
  console.error("Error sending user info:", error);
});

If you want to remove the user's information from the chatbot, you can use the clearUserInfo method:

window.chatbot.clearUserInfo()
  .then(response => {
    console.log("User info cleared successfully:", response);
  })
  .catch(error => {
    console.error("Error clearing user info:", error);
  });

Website Demo

To experience this functionality, visit our Demo Website and input user information as shown below: User Information

In this demonstration, the website communicates to the chatbot that the user's lucky number is 934383 - a randomly chosen number. Subsequently, users can pose questions like What is my name and double of my lucky number?. This query necessitates the chatbot to access the user's information for an accurate response. As evidenced by the screenshot below, the chatbot successfully recognizes the user's lucky number and performs the calculation correctly.

User Information Testing

This example demonstrates that you can sync the user's information from your website to the chatbot to create a personalized experience.

Receiving Events From Chatbot to Website

When embedding our chatbot as a widget bubble or an iframe on your website, you can receive four types of events through the SDK: chat, lead-submission, live-chat-escalation, and minimize-widget. These events allow for seamless communication between the chatbot and your website.

Event Types and Payloads

Chat

All chat conducted in the chatbot will trigger a chat event. Here is an example of the event's data payload:

{
    "chatbot_id": "654aee418bc9a33b0e50d0ad",
    "chatbot_name": "Chat Data AI assistant",
    "chatbot_display_name": "Chat Data",
    "conversation_id": "5d4e7c46-4c54-4bb2-9bc8-170a3fc647e2",
    "message": "How to resell the chatbot with my own domain?",
    "source": "widget",
    "lead": {
        "uuid": "90e8c9cc-017e-4876-882d-19efd88b10ba",
        "name": "Customer",
        "email": "[email protected]",
        "source": "widget"
    }
}

Live Chat Escalation

When the user clicks the live chat escalation button, a live-chat-escalation event will be triggered.

{
    "chatbot_id": "654aee418bc9a33b0e50d0ad",
    "chatbot_name": "Chat Data AI assistant",
    "chatbot_display_name": "Chat Data",
    "conversation_id": "5d4e7c46-4c54-4bb2-9bc8-170a3fc647e2",
    "messages": [
        {
            "role": "assistant",
            "content": "👋 Hello there! I'm Chat Data AI, your go-to source about Chat Data!",
            "timestamp": "2024-08-24T06:10:29.077Z",
            "_id": "66c97975a5f5d4ceebebb86e"
        },
        ...
    ],
    "source": "widget",
    "lead": {
        "uuid": "90e8c9cc-017e-4876-882d-19efd88b10ba"
    }
}

Lead Submission

The lead form submission will trigger a lead-submission event.

{
    "uuid": "90e8c9cc-017e-4876-882d-19efd88b10ba",
    "name": "Customer",
    "email": "[email protected]",
    "source": "widget"
}

Minimize Widget

A click on the close icon on the chatbot will trigger a minimize-widget event. The minimize-widget event doesn't have any specific payload.

How to handle Events with the SDK

The Chat Data SDK events are available in the Standard plan or above. Here's how to implement event listeners:

Event Listener Implementation

// 1. Chat messages
const chatHandler = function(data) {
  console.log("Chat event received:", data);
  // Handle new chat messages from the chatbot
};
window.chatbot.addEventListener("chat", chatHandler);

// 2. Lead submissions
const leadSubmissionHandler = function(data) {
  console.log("Lead submission received:", data);
  // Handle when a user submits a lead form in the chatbot
};
window.chatbot.addEventListener("lead-submission", leadSubmissionHandler);

// 3. Live chat escalation 
const liveChatEscalationHandler = function(data) {
  console.log("Live chat escalation requested:", data);
  // Handle when user requests to speak with a human agent
};
window.chatbot.addEventListener("live-chat-escalation", liveChatEscalationHandler);

// 4. Widget minimization
const minimizeWidgetHandler = function(data) {
  console.log("Widget minimized:", data);
  // Handle when user minimizes the chat widget
};
window.chatbot.addEventListener("minimize-widget", minimizeWidgetHandler);

Removing Event Listeners

To remove event listeners when they're no longer needed:

// Remove a specific event listener
window.chatbot.removeEventListener("chat", chatHandler);

// You should remove event listeners when components unmount (React example)
useEffect(() => {
  window.chatbot.addEventListener("chat", chatHandler);
  
  return () => {
    window.chatbot.removeEventListener("chat", chatHandler);
  };
}, []);

Website Demo

To experience the SDK events in action, visit our Demo Website. If you've previously entered your information, start by clicking the Clear User Info button to reset. Then, initiate a conversation with the chatbot by sending a query. After responding to your initial question, the chatbot will prompt you to provide your contact information.

User Information Input

Upon submitting the lead form, you'll see the provided information displayed on the website, as shown in the screenshot below:

Displayed User Information

This demonstration illustrates how listening to events enables real-time responses to user actions on your website. For instance, you could create personalized pop-ups featuring the user's name, email, and conversation history. Such implementations can significantly enhance user experience and engagement on your platform.

Full Implementation Example

Below is a comprehensive example showing how to implement the Chat Data SDK in a typical application:

// Initialize the SDK (if not using auto-initialization)
if (window.chatbot) {
  // SDK is already loaded
  console.log("SDK initialized with config:", window.chatbot.getConfig());
} else {
  console.error("SDK failed to load");
}

// Setup event listeners
function setupEventListeners() {
  // Chat events
  window.chatbot.addEventListener("chat", function(data) {
    console.log("Chat message:", data);
    document.getElementById("lastMessage").textContent = data.message;
  });
  
  // Lead submission
  window.chatbot.addEventListener("lead-submission", function(data) {
    console.log("Lead submitted:", data);
    // Update UI with lead info
    document.getElementById("leadName").textContent = data.name || "Unknown";
    document.getElementById("leadEmail").textContent = data.email || "Unknown";
  });
  
  // Live chat escalation
  window.chatbot.addEventListener("live-chat-escalation", function(data) {
    console.log("Live chat requested:", data);
    // Maybe show a notification or alert customer service
    alert("Customer has requested live chat assistance!");
  });
  
  // Minimize widget
  window.chatbot.addEventListener("minimize-widget", function() {
    console.log("Widget minimized");
    // Maybe update UI state
    document.getElementById("chatStatus").textContent = "Chat minimized";
  });
}

// Send user info after login
function onUserLogin(userData) {
  window.chatbot.sendUserInfo({
    userId: userData.id,
    email: userData.email,
    name: userData.displayName,
    info: userData.accountType || "Standard user"
  }).then(() => {
    console.log("User info sent to chatbot after login");
  }).catch(error => {
    console.error("Failed to send user info:", error);
  });
}

// Example usage when page loads
document.addEventListener("DOMContentLoaded", function() {
  setupEventListeners();
  
  // Example: Send sample user data
  document.getElementById("loginButton").addEventListener("click", function() {
    const sampleUser = {
      id: "user123",
      email: "[email protected]",
      displayName: "John Doe",
      accountType: "Premium member since 2023"
    };
    onUserLogin(sampleUser);
  });
  
  // Example: Clear user data
  document.getElementById("logoutButton").addEventListener("click", function() {
    window.chatbot.clearUserInfo()
      .then(() => {
        console.log("User info cleared");
      })
      .catch(error => {
        console.error("Failed to clear user info:", error);
      });
  });
});

For more detailed implementation examples and to interact with a live demo, visit our SDK Demo Page.

Previous
Webhooks Setup