UNPKG

@robylon/web-react-sdk

Version:
600 lines (475 loc) 22.7 kB
# Robylon SDK The Robylon SDK provides an easy way to integrate a customizable chatbot into your application. This SDK supports both React applications and plain JavaScript/no-code websites. ## Table of Contents - [Installation](#installation) - [React SDK Usage](#react-sdk-usage) - [Basic Implementation](#react-basic-implementation) - [External Triggers](#react-external-triggers) - [Event Handling](#react-event-handling) - [Plain JavaScript & No-Code Integration](#plain-javascript--no-code-integration) - [Quick Embed (Easiest Method)](#quick-embed-easiest-method) - [ES5/Google Tag Manager](#es5google-tag-manager) - [Option 1: Quick Setup - Load with Page](#option-1-quick-setup---load-with-page) - [Option 2: Reliable Loading - After DOM is Ready](#option-2-reliable-loading---after-dom-is-ready) - [Option 3: User Context - Initialize After User Data](#option-3-user-context---initialize-after-user-data) - [Configuration Options](#configuration-options) - [Event Handling](#event-handling) ## Installation ### For React applications: ```bash npm install @robylon/web-react-sdk # or yarn add @robylon/web-react-sdk ``` ### For plain JavaScript and no-code websites: Add this script to your website by copying and pasting the following code into the `<head>` section of your HTML: ```html <script src="https://cdn.robylon.ai/sdk/latest/chatbot.js"></script> ``` #### Where to place the script: 1. **For website builders (Wix, Squarespace, etc.):** - Find your site editor or dashboard - Look for "Custom Code", "Header Code", or "Site Settings" options - Paste the script there, usually in a section labeled "Header" or "Head" 2. **For custom HTML sites:** - Open your website's HTML file in your editor - Find the `<head>` section (it's near the top, between `<html>` and `<body>` tags) - Paste the script tag just before the closing `</head>` tag 3. **For WordPress:** - Go to your WordPress dashboard - Navigate to Appearance → Theme Editor or use a header/footer plugin - Add the script to the header.php file before the closing `</head>` tag > **Note:** Some of the integration options later in this guide will show different placements of this script - follow the specific example that best matches your needs. ## React SDK Usage ### React: Basic Implementation To use the Robylon SDK in a React application: ```jsx import { Chatbot } from "@robylon/web-react-sdk"; function App() { const handleChatbotEvent = (event) => { console.log("Chatbot event:", event.type, event.data); }; return ( <div className="App"> <h1>My Website</h1> <Chatbot api_key="YOUR_API_KEY" user_id="optional-user-id" user_token="optional-auth-token" user_profile={{ name: "Optional User Name", email: "optional.email@example.com", }} onEvent={handleChatbotEvent} /> </div> ); } export default App; ``` ### React: Event Handling The React component accepts an `onEvent` prop for handling chatbot events: ```jsx <Chatbot api_key="YOUR_API_KEY" onEvent={(event) => { switch (event.type) { case "CHATBOT_LOADED": console.log("Chatbot loaded"); break; case "CHATBOT_OPENED": console.log("Chatbot opened"); break; case "CHATBOT_CLOSED": console.log("Chatbot closed"); break; // See the Supported Events section for all available events } }} /> ``` The `Chatbot` component renders a floating button that opens a chat interface when clicked. It handles all the communication with the Robylon backend services. ### React: External Triggers You can control the chatbot iframe from outside the component using a ref. This allows you to trigger open, close, or toggle actions from anywhere in your application: ```jsx import React, { useRef, useState, useEffect } from "react"; import { Chatbot, ChatbotRef } from "@robylon/web-react-sdk"; function App() { const chatbotRef = useRef < ChatbotRef > null; const [isChatbotReady, setIsChatbotReady] = useState(false); // Method 1: Check readiness state before calling methods const showChatbot = () => { if (chatbotRef.current?.isReady) { chatbotRef.current.show(); } else { console.log("Chatbot not ready yet"); } }; const hideChatbot = () => { chatbotRef.current?.hide(); }; const toggleChatbot = () => { chatbotRef.current?.toggle(); }; // Method 2: Listen for ready event const handleChatbotEvent = (event) => { if (event.type === "CHATBOT_READY") { setIsChatbotReady(true); } }; return ( <div className="App"> <h1>My Website</h1> {/* External control buttons with readiness state */} <button onClick={showChatbot} disabled={!isChatbotReady}> Show Chatbot </button> <button onClick={hideChatbot}>Hide Chatbot</button> <button onClick={toggleChatbot}>Toggle Chatbot</button> <Chatbot ref={chatbotRef} api_key="YOUR_API_KEY" user_id="optional-user-id" onEvent={handleChatbotEvent} /> </div> ); } ``` #### Available External Methods & Properties | Method/Property | Type | Description | | --------------- | -------- | ------------------------------------------------------ | | `show()` | function | Opens the chatbot iframe if it's currently closed | | `hide()` | function | Closes the chatbot iframe if it's currently open | | `toggle()` | function | Toggles the chatbot iframe visibility | | `isReady` | boolean | Indicates if the chatbot is ready for external control | #### Event Handling with External Triggers External trigger methods emit the same events as internal triggers: - `CHATBOT_BUTTON_CLICKED` - When `show()` or `toggle()` opens the chatbot - `CHATBOT_CLOSED` - When `hide()` or `toggle()` closes the chatbot - `CHATBOT_READY` - When the chatbot is ready for external control (emitted once after initialization) This ensures consistent event handling regardless of how the chatbot is triggered. #### Readiness Handling The SDK provides multiple ways to handle chatbot readiness: 1. **Check `isReady` property** - Synchronous check before calling methods 2. **Listen for `CHATBOT_READY` event** - Event-based notification when ready 3. **Guard clauses** - Methods safely handle early calls with console warnings This prevents race conditions and provides a smooth user experience. ## Plain JavaScript & No-Code Integration > **IMPORTANT:** You will need an API key from Robylon for any integration to work. ### Quick Embed (Easiest Method) This is the simplest way to add the Robylon chatbot to any website with a single line of code. Just copy and paste this script tag into your HTML: ``` <script>(function(k){window.R=window.R||function(){(window.R.q=window.R.q||[]).push(arguments)};window.R=new Proxy(window.R,{get:(t,p)=>p==="q"?t.q:(...a)=>t(p,...a)});function l(){var s=document.createElement("script");s.src="https://cdn.robylon.ai/sdk/latest/chatbot.js";s.onload=()=>k&&window.RobylonChatbot.create({api_key:k});document.body.appendChild(s)}document.readyState==="complete"?l():window.addEventListener("load",l)})("YOUR_API_KEY_HERE");</script> ``` Just replace `YOUR_API_KEY_HERE` with your actual Robylon API key, and you're done! No additional code is needed. ### ES5/Google Tag Manager #### ES5 Compatible Version For older browsers that don't support ES6 features, use this ES5 compatible version: ``` <script>(function(a){window.R=window.R||function(){(window.R.q=window.R.q||[]).push(Array.prototype.slice.call(arguments))};window.R.show=function(){window.R('show')};window.R.hide=function(){window.R('hide')};window.R.toggle=function(){window.R('toggle')};window.R.track=function(){window.R('track',Array.prototype.slice.call(arguments))};var o=function(){var s=document.createElement("script");s.src="https://cdn.robylon.ai/sdk/latest/chatbot.js";s.id="robylon-chatbot-sdk";s.onload=function(){if(a){window.RobylonChatbot.create({api_key:a})}};document.body.appendChild(s)};if(document.readyState==="complete"){o()}else{window.addEventListener("load",o)}})("YOUR_API_KEY_HERE");</script> ``` This version is compatible with Internet Explorer 11 and other older browsers that don't support ES6 features like arrow functions, `const`/`let`, and Proxy objects. #### Quick Embed with Custom Position and Spacing If you want to customize the position and spacing of the chatbot button, you can use this alternative version: ``` <script>(function(k,p,side,bottom){window.R=window.R||function(){(window.R.q=window.R.q||[]).push(arguments)};window.R=new Proxy(window.R,{get:(t,p)=>p==="q"?t.q:(...a)=>t(p,...a)});function l(){var s=document.createElement("script");s.src="https://cdn.robylon.ai/sdk/latest/chatbot.js";s.onload=()=>k&&window.RobylonChatbot.create({api_key:k,position:p,sideSpacing:side,bottomSpacing:bottom});document.body.appendChild(s)}document.readyState==="complete"?l():window.addEventListener("load",l)})("YOUR_API_KEY_HERE","Left",30,25);</script> ``` Just replace: - `YOUR_API_KEY_HERE` with your actual API key - `"Left"` with `"Left"` or `"Right"` for button position - `30` with your desired side spacing in pixels - `25` with your desired bottom spacing in pixels ##### ES5 Compatible Version with Custom Position and Spacing For older browsers, use this ES5 compatible version with custom positioning: ``` <script>(function(a,p,s,b){window.R=window.R||function(){(window.R.q=window.R.q||[]).push(Array.prototype.slice.call(arguments))};window.R.show=function(){window.R('show')};window.R.hide=function(){window.R('hide')};window.R.toggle=function(){window.R('toggle')};window.R.track=function(){window.R('track',Array.prototype.slice.call(arguments))};var o=function(){var s=document.createElement("script");s.src="https://cdn.robylon.ai/sdk/latest/chatbot.js";s.id="robylon-chatbot-sdk";s.onload=function(){if(a){window.RobylonChatbot.create({api_key:a,position:p,sideSpacing:s,bottomSpacing:b})}};document.body.appendChild(s)};if(document.readyState==="complete"){o()}else{window.addEventListener("load",o)}})("YOUR_API_KEY_HERE","Left",30,25);</script> ``` Replace the same parameters as above for the ES5 compatible version. #### Where to place the script: - At the end of your HTML `<body>` section for best performance - Or anywhere in your HTML code if you're using a website builder There are several other ways to add the Robylon chatbot to your website or no-code platform, depending on your needs: ### Option 1: Quick Setup - Load with Page This is the simplest approach for any website. The chatbot loads while the page is loading but doesn't block the page from appearing. #### What to copy: 1️⃣ **Add this to your HTML `<head>` section:** ```html <script src="https://cdn.robylon.ai/sdk/latest/robylon-chatbot.js" defer ></script> <script> // Initialize when page is ready document.addEventListener("DOMContentLoaded", () => { RobylonChatbot.create({ api_key: "YOUR_API_KEY", // Replace with your actual API key user_id: "optional-user-id", // Optional: remove if not needed user_profile: { name: "Optional User Name", // Optional: remove if not needed email: "optional.email@example.com", // Optional: remove if not needed }, }); }); </script> ``` #### Complete example: ```html <!DOCTYPE html> <html> <head> <title>Robylon SDK - Quick Setup</title> <!-- COPY FROM HERE --> <script src="https://cdn.robylon.ai/sdk/latest/robylon-chatbot.js" defer ></script> <script> // Initialize when page is ready document.addEventListener("DOMContentLoaded", () => { RobylonChatbot.create({ api_key: "YOUR_API_KEY", // Replace with your actual API key user_id: "optional-user-id", // Optional: remove if not needed user_profile: { name: "Optional User Name", // Optional: remove if not needed email: "optional.email@example.com", // Optional: remove if not needed }, }); }); </script> <!-- COPY UNTIL HERE --> </head> <body> <h1>Your Website Content</h1> <!-- Your website content here --> </body> </html> ``` ### Option 2: Reliable Loading - After DOM is Ready This approach ensures the chatbot only initializes after your page is fully loaded, making it more reliable for websites with complex layouts. #### What to copy: 1️⃣ **Add this to your HTML `<head>` section:** ```html <script src="https://cdn.robylon.ai/sdk/latest/robylon-chatbot.js"></script> ``` 2️⃣ **Add this at the end of your HTML `<body>` section:** ```html <script> // Wait for page to be fully loaded before showing chatbot document.addEventListener("DOMContentLoaded", () => { RobylonChatbot.create({ api_key: "YOUR_API_KEY", // Replace with your actual API key user_id: "optional-user-id", // Optional: remove if not needed user_profile: { name: "Optional User Name", // Optional: remove if not needed email: "optional.email@example.com", // Optional: remove if not needed }, }); }); </script> ``` #### Complete example: ```html <!DOCTYPE html> <html> <head> <title>Robylon SDK - Reliable Loading</title> <!-- COPY FROM HERE --> <script src="https://cdn.robylon.ai/sdk/latest/robylon-chatbot.js"></script> <!-- COPY UNTIL HERE --> </head> <body> <h1>Your Website Content</h1> <!-- Your website content here --> <script> // Wait for page to be fully loaded before showing chatbot document.addEventListener("DOMContentLoaded", () => { RobylonChatbot.create({ api_key: "YOUR_API_KEY", // Replace with your actual API key user_id: "optional-user-id", // Optional: remove if not needed user_profile: { name: "Optional User Name", // Optional: remove if not needed email: "optional.email@example.com", // Optional: remove if not needed }, }); }); </script> </body> </html> ``` ### Option 3: User Context - Initialize After User Data This approach loads the chatbot after user data is available. Great for websites where you want to personalize the chat experience. #### What to copy: 1️⃣ **Add this to your HTML `<head>` section:** ```html <script src="https://cdn.robylon.ai/sdk/latest/robylon-chatbot.js" defer ></script> ``` 2️⃣ **Add this script at the end of your HTML `<body>` section:** ```html <script> // Wait for page to be ready document.addEventListener("DOMContentLoaded", () => { // Get your user data (replace this with your own method) getUserData().then((user) => { // Initialize chatbot with user info RobylonChatbot.create({ api_key: "YOUR_API_KEY", // Replace with your actual API key user_id: user.id, user_profile: { name: user.name, email: user.email, }, }); }); }); // Example function to get user data - replace with your own function getUserData() { // This is just a placeholder - replace with your actual code return Promise.resolve({ id: "user123", name: "Jane Smith", email: "jane@example.com", }); } </script> ``` #### Complete example: ```html <!DOCTYPE html> <html> <head> <title>My Website</title> <!-- COPY FROM HERE --> <script src="https://cdn.robylon.ai/sdk/latest/robylon-chatbot.js" defer ></script> <!-- COPY UNTIL HERE --> </head> <body> <h1>Your Website Content</h1> <!-- Your website content here --> <!-- COPY FROM HERE --> <script> // Wait for page to be ready document.addEventListener("DOMContentLoaded", () => { // Get your user data (replace this with your own method) getUserData().then((user) => { // Initialize chatbot with user info RobylonChatbot.create({ api_key: "YOUR_API_KEY", // Replace with your actual API key user_id: user.id, user_profile: { name: user.name, email: user.email, }, }); }); }); // Example function to get user data - replace with your own function getUserData() { // This is just a placeholder - replace with your actual code return Promise.resolve({ id: "user123", name: "Jane Smith", email: "jane@example.com", }); } </script> <!-- COPY UNTIL HERE --> </body> </html> ``` ### Plain JS & No-Code: Event Handling You can handle chatbot events in plain JavaScript using the `onEvent` callback: #### What to copy: ```javascript const chatbot = RobylonChatbot.create({ api_key: "YOUR_API_KEY", // Replace with your actual API key onEvent: function (event) { switch (event.type) { case "CHATBOT_LOADED": console.log("Chatbot loaded"); break; case "CHATBOT_OPENED": console.log("Chatbot opened"); break; case "CHATBOT_CLOSED": console.log("Chatbot closed"); break; // See the Supported Events section for all available events } }, }); // The chatbot instance provides methods to control the chatbot // chatbot.show(); // Show the chatbot // chatbot.hide(); // Hide the chatbot // chatbot.toggle(); // Toggle visibility // chatbot.destroy(); // Remove the chatbot from the page > **Note:** The plain JavaScript SDK provides direct instance methods for external control. The React SDK provides similar functionality through refs (see [React External Triggers](#react-external-triggers) section above). ``` ## Configuration Options The SDK supports the following configuration options for both React and plain JavaScript implementations. **Note:** The React SDK also supports external triggers via refs for programmatic control of the chatbot iframe. | Option | Type | Description | Required/Optional | | ------------- | -------- | ------------------------------------------------- | ----------------- | | api_key | string | Your Robylon API key | Required | | user_id | string | User identifier for conversation tracking | Optional | | user_token | string | Authentication token | Optional | | user_profile | object | Additional user information | Optional | | onEvent | function | Event handler for chatbot interactions | Optional | | position | string | Position of the chatbot button ("Left"/"Right") | Optional | | sideSpacing | number | Distance from the side of the screen (in px) | Optional | | bottomSpacing | number | Distance from the bottom of the screen (in px) | Optional | | show_launcher | boolean | Show the floating launcher button (default: true) | Optional | ### Position and Spacing Configuration You can control the position and spacing of the chatbot button either through the API configuration or directly in the SDK. If both are provided, the SDK configuration takes precedence. #### React Example: ```jsx <Chatbot api_key="YOUR_API_KEY" position="Left" sideSpacing={30} bottomSpacing={25} /> ``` #### React: Hide Floating Launcher Button To hide the floating launcher and manage visibility via external triggers or custom UI, set `show_launcher` to `false` (defaults to `true`): ```jsx <Chatbot api_key="YOUR_API_KEY" show_launcher={false} /> ``` #### Plain JavaScript Example: ```javascript RobylonChatbot.create({ api_key: "YOUR_API_KEY", position: "Left", sideSpacing: 30, bottomSpacing: 25, }); ``` ## Event Handling ### Supported Events The SDK emits the following events that you can listen for in both React and plain JavaScript implementations: | Event Type | Description | Data | | ---------------------------- | ----------------------------------------------- | ---------------------------------------- | | `CHATBOT_BUTTON_LOADED` | The chatbot button has been loaded and rendered | - | | `CHATBOT_LOADED` | The chatbot iframe has been loaded | - | | `CHATBOT_OPENED` | The chatbot has been opened | - | | `CHATBOT_CLOSED` | The chatbot has been closed | - | | `CHATBOT_READY` | The chatbot is ready for external control | - | | `CHAT_INITIALIZED` | The chat session has been initialized | - | | `CHAT_INITIALIZATION_FAILED` | The chat session failed to initialize | `{ error: string }` | | `SESSION_REFRESHED` | The chat session has been refreshed | - | | `MESSAGE_SENT` | User has sent a message | `{ message: string }` | | `MESSAGE_RECEIVED` | A message was received from the chatbot | `{ message: string }` | | `CONVERSATION_STARTED` | A new conversation has started | `{ conversationId: string }` | | `CONVERSATION_ENDED` | The current conversation has ended | `{ conversationId: string }` | | `USER_AUTHENTICATED` | The user has been authenticated | `{ userId: string }` | | `USER_PROFILE_UPDATED` | The user profile has been updated | `{ profile: object }` | | `USER_FEEDBACK_SUBMITTED` | The user has submitted feedback | `{ rating: number, comment: string }` | | `FILE_UPLOAD_STARTED` | A file upload has started | `{ fileName: string, fileSize: number }` | | `FILE_UPLOAD_COMPLETED` | A file upload has completed | `{ fileName: string, fileUrl: string }` | | `FILE_UPLOAD_FAILED` | A file upload has failed | `{ fileName: string, error: string }` | | `CHATBOT_ERROR`