Setting up the chatbot module
You can set up a chatbot and embed the module onto your website.
Chatbot Core and Shell modes
The IBM RPA chatbot can be embedded onto a webpage in two ways: Core and Shell. The Core method provides HTML and CSS so you can embed the chatbot directly into any section of your webiste. The Shell method contains the chatbot inside of a widget shell, which can be placed in the bottom corner of a website.
Before you begin
You need to download and save the following files:
-
Download both of the following files from the Microsoft Bot Framework Web Chat libraries:
-
Copy, paste, and save one of the following files to set up your chatbot in the Core or Shell approach:
Chatbot Core mode
Click to expand the ChatBotCore.js file.
let botHandle = '<your-bot-handle>';
let apiAddress = '<API-address>';
var script = document.createElement('script');
script.src = '../Content/Scripts/webchat-4.15.1.js';
script.type = 'text/javascript';
document.head.appendChild(script);
var scriptEs5 = document.createElement('script');
scriptEs5.src = '../Content/Scripts/webchat-4.15.1-es5.js';
scriptEs5.type = 'text/javascript';
document.head.appendChild(scriptEs5);
function browserLanguage() {
var nav = window.navigator;
var language = ((nav.language || nav.browserLanguage || nav.systemLanguage || nav.userLanguage) || undefined);
return language;
}
function getQueryString() {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
var urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
return urlParams;
}
function objectAssign(target, source) {
var objs = [target, source],
result = objs.reduce(function (r, o) {
Object.keys(o).forEach(function (k) {
r[k] = o[k];
});
return r;
}, {});
return result;
}
fetch(apiAddress + botHandle, {
method: "POST",
referrerPolicy: 'origin',
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(res => {
var user = res.user;
var locale = res.locale;
var customData = res.customData;
var conversation = res.conversation;
var useEs5 = res.useEs5;
if (useEs5) {
document.head.removeChild(script);
}
else {
document.head.removeChild(scriptEs5);
}
var styleOptions = {};
try {
if (res.StyleOptions) {
var styleOptions = JSON.parse(JSON.stringify(res.styleOptions));
}
}
catch (e) {
//no op
}
var queryString = getQueryString();
var directLine = window.WebChat.createDirectLine({
token: conversation.token,
domain: 'https://directline.botframework.com/v3/directline',
streamUrl: conversation.streamUrl,
conversationId: conversation.id,
webSocket: false
});
if ("locale" in queryString)
locale = queryString.locale;
user = objectAssign(user, queryString);
window.WebChat.renderWebChat(
{
directLine: directLine,
userID: user.id,
username: user.name,
locale: locale || browserLanguage(),
styleOptions: styleOptions
},
document.getElementById('RPAWebChat')
);
directLine.activity$
.filter(function (activity) { return activity.type == 'event' && activity.name == 'redirect' })
.subscribe(function (event) {
if (event.value)
window.location.replace(event.value);
});
//sending event to create a conversation + custom data
var value = {
custom: customData,
debug: res.Debug
};
directLine.postActivity({ type: 'event', name: 'createConversation', value: value, from: user }).subscribe();
// Call the fetchData function to initiate the API call
setInterval(async () => {
let retry = true;
let attempt = 1;
while (retry) {
try {
console.log(`Refreshing conversation token. Attempt: ${attempt}`)
const resp = await fetch('https://directline.botframework.com/v3/directline/tokens/refresh', {
method: 'POST',
headers: {
Authorization: `Bearer ${directLine.token}`
}
})
const content = await resp.json()
directLine.token = content.token
}
catch (err) {
console.error(err)
attempt++;
if (attempt > 3)
retry = false
}
}
}, (conversation.expiresIn - 60) * 1000)
})
.catch(error => {
console.error('Error:', error)
var errorMessageDIV = document.getElementById("errorMessageDIV");
errorMessageDIV.style.display = "block"
});
function toggleChatbot() {
const chatbot = document.querySelector('.chatbot-container');
chatbot.style.display = (chatbot.style.display == 'none') ? 'flex' : 'none'
}
Chatbot Shell mode
Click to expand the ChatBotShell.js file.
let botHandle = '<your-bot-handle>';
let apiAddress = '<API-address>';
const body = document.body;
var script = document.createElement('script');
script.src = '../Content/Scripts/webchat-4.15.1.js';
script.type = 'text/javascript';
document.head.appendChild(script);
var scriptEs5 = document.createElement('script');
scriptEs5.src = '../Content/Scripts/webchat-4.15.1-es5.js';
scriptEs5.type = 'text/javascript';
document.head.appendChild(scriptEs5);
const chatbotContainer = document.createElement('div');
chatbotContainer.className = "chatbot-container";
body.appendChild(chatbotContainer)
const chatbotHeader = document.createElement('div');
chatbotHeader.className = "chatbot-header";
chatbotContainer.appendChild(chatbotHeader);
const spanHeader = document.createElement('span');
chatbotHeader.appendChild(spanHeader);
var spanCloseButton = document.createElement("span");
spanCloseButton.className = "chatbot-close";
spanCloseButton.setAttribute("onclick", "toggleChatbot()");
spanCloseButton.id = "closeBtn";
spanCloseButton.innerHTML = "×";
chatbotHeader.appendChild(spanCloseButton);
var webChatDiv = document.createElement("div");
webChatDiv.id = "RPAWebChat";
var errorMessageDiv = document.createElement("div");
errorMessageDiv.id = "errorMessageDIV";
errorMessageDiv.className = "error-message";
errorMessageDiv.hidden = true;
var exclamationSpan = document.createElement("span");
exclamationSpan.style.color = "red";
exclamationSpan.innerHTML = "!";
var errorTextSpan = document.createElement("span");
errorTextSpan.className = "error-text";
errorTextSpan.textContent = "Unable to connect.";
errorMessageDiv.appendChild(exclamationSpan);
errorMessageDiv.appendChild(errorTextSpan);
chatbotContainer.appendChild(webChatDiv);
chatbotContainer.appendChild(errorMessageDiv);
//carbon chat button
var script = document.createElement("script");
script.type = "module";
script.src = "https://1.www.s81c.com/common/carbon/web-components/version/v2.24.0/chat-button.min.js";
document.head.appendChild(script);
const chatButtonElement = document.createElement('cds-chat-button');
chatButtonElement.setAttribute('id', 'btnchat');
chatButtonElement.setAttribute('class', 'chatbot-open');
chatButtonElement.textContent = 'Chat';
chatButtonElement.addEventListener('click', toggleChatbot);
body.appendChild(chatButtonElement);
// styles
var style = document.createElement("style");
var css = `
#RPAWebChat {
height: 100%;
overflow: hidden;
font-size: 1.25em;
}
body {
font-family: Arial, sans-serif;
height: 100%;
margin: 0;
}
.chatbot-container {
bottom: 75px;
right: 30px;
position: fixed;
width: 500px;
height: 80%;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 10px;
flex-direction: column;
display: flex;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.chatbot-open {
position: fixed;
bottom: 10px;
right: 10px;
}
.chatbot-header {
background-color: black;
color: white;
padding: 5px;
display: flex;
justify-content: space-between;
align-items: center;
font-weight: bold;
}
.chatbot-close {
background: none;
font-size: 40px;
cursor: pointer;
padding-right: 10px;
}
.error-message {
border: 1px solid #fcc2c3;
float: left;
padding: 20px 30px;
bottom: 0;
}
`;
style.innerHTML = css;
document.head.appendChild(style);
function browserLanguage() {
var nav = window.navigator;
var language = ((nav.language || nav.browserLanguage || nav.systemLanguage || nav.userLanguage) || undefined);
return language;
}
function getQueryString() {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
var urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
return urlParams;
}
function objectAssign(target, source) {
var objs = [target, source],
result = objs.reduce(function (r, o) {
Object.keys(o).forEach(function (k) {
r[k] = o[k];
});
return r;
}, {});
return result;
}
fetch(apiAddress + botHandle, {
method: "POST",
referrerPolicy: 'origin',
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(res => {
var user = res.user;
var locale = res.locale;
var customData = res.customData;
var conversation = res.conversation;
var useEs5 = res.useEs5;
if (useEs5) {
document.head.removeChild(script);
}
else {
document.head.removeChild(scriptEs5);
}
var styleOptions = {};
try {
if (res.StyleOptions) {
var styleOptions = JSON.parse(JSON.stringify(res.styleOptions));
}
}
catch (e) {
//no op
}
var queryString = getQueryString();
var directLine = window.WebChat.createDirectLine({
token: conversation.token,
domain: 'https://directline.botframework.com/v3/directline',
streamUrl: conversation.streamUrl,
conversationId: conversation.id,
webSocket: false
});
if ("locale" in queryString)
locale = queryString.locale;
user = objectAssign(user, queryString);
window.WebChat.renderWebChat(
{
directLine: directLine,
userID: user.id,
username: user.name,
locale: locale || browserLanguage(),
styleOptions: styleOptions
},
document.getElementById('RPAWebChat')
);
directLine.activity$
.filter(function (activity) { return activity.type == 'event' && activity.name == 'redirect' })
.subscribe(function (event) {
if (event.value)
window.location.replace(event.value);
});
//sending event to create a conversation + custom data
var value = {
custom: customData,
debug: res.Debug
};
directLine.postActivity({ type: 'event', name: 'createConversation', value: value, from: user }).subscribe();
// Call the fetchData function to initiate the API call
setInterval(async () => {
let retry = true;
let attempt = 1;
while (retry) {
try {
console.log(`Refreshing conversation token. Attempt: ${attempt}`)
const resp = await fetch('https://directline.botframework.com/v3/directline/tokens/refresh', {
method: 'POST',
headers: {
Authorization: `Bearer ${directLine.token}`
}
})
const content = await resp.json()
directLine.token = content.token
}
catch (err) {
console.error(err)
attempt++;
if (attempt > 3)
retry = false
}
}
}, (conversation.expiresIn - 60) * 1000)
})
.catch(error => {
console.error('Error:', error)
var errorMessageDIV = document.getElementById("errorMessageDIV");
errorMessageDIV.style.display = "block"
});
function toggleChatbot() {
const chatbot = document.querySelector('.chatbot-container');
chatbot.style.display = (chatbot.style.display == 'none') ? 'flex' : 'none'
}
- Save your webchat and
ChatBotCore.jsorChatBotShell.jsfiles in the same parent folder for your website. Your webchat files should be saved in../Content/Scriptsas declared in theChatBotCore.jsorChatBotShell.jsfile. See this truncated code sample from theChatBotShell.jsfile:
var script = document.createElement('script');
script.src = '../Content/Scripts/webchat-4.15.1.js';
var scriptEs5 = document.createElement('script');
scriptEs5.src = '../Content/Scripts/webchat-4.15.1-es5.js';
If you change your file path for the webchat files, ensure that you also change the file path values for each webchat file that is declared in the ChatBotCore.js or ChatBotShell.js code.
Create the chabot
The following steps are the same for both Core and Shell mode.
- Log into IBM RPA Control Center.
- In the sidebar menu in the Define section, click on Chatbots.
- On the Chatbots screen, select the Chatbots tab.
- Click the blue Create chatbot button to open the input window.
- In the Create chatbot window, enter a name for your Chatbot handle.
- Enter values for the API key, Password, Secret, and Tenant (optional) for your chatbot.
- Click Save.
- Copy and paste your Chatbot handle and the API endpoint to replace the placeholder values,
'<bot_handle>'and'https://<rpa-api-domain>/api/integration/'in the following section of either theChatBotCore.jsorChatBotShell.jsfile:
let botHandle = '<bot_handle>';
let apiAddress = 'https://<rpa-api-domain>/api/integration/';
- Save and close the
ChatBotCore.jsorChatBotShell.jsfile. - On the Chatbots screen in IBM RPA Control Center, click on the Chat mappings tab.
- Click the blue Create chat mappings button to open the input window.
- Follow the steps for Creating chat mappings.
- In the Allowed Origins step of chat mappings, add the domain and port (if available) for your website. The values entered for Allowed Origins should match the domain where the chatbot will be embedded. If the website doman is not added to the Allowed Origins list, the chatbot will not start.
Embedding the chatbot onto a website
Core mode
To integrate a chatbot to your website by using the Core mode:
- Include the following script tag in your HTML file, preferably within the
<head>tag:
<script async src="~/js/chatbotcore.js"></script>
- Add a
divelement to your HTML file in the section where the chatbot will be embedded on your website. You must give the exact nameRPAWebChatto theidof thisdiv:
<div id="RPAWebChat"></div>
- Save and close the HTML file.
Shell mode
To integrate a chatbot into your website by using the Shell mode:
- Include the following script tag in your HTML file, preferably within the
<head>tag:
<script async src="~/js/chatbotshell.js"></script>
- Save and close the HTML file.