Oracle Mobile Cloud, Enterpise Bots Client SDK for JavaScript
Release 18.2.3
E91737-03
Use the OMCe Bots Client SDK for JavaScript to add live messaging to your web site or web app.
Configuration
To improve performance, the Bots library, which is composed of multiple resources, is fetched at runtime. For that reason, the URL where the library's static files are hosted (that is, the public path), is hard coded in many places.
To configure the library for your environment, run:
./configure <public-path>
The script will generate a folder with the configured project in it.
Examples
Local Testing Setup
- The static files are hosted at
http://localhost:8000/static/
. - The script is run in the
/home/your-name/
folder. For example:./configure http://localhost:8000/static/
The files will be available at /home/your-name/http:__localhost:8000_static_/
.
Production Setup
- The static files are hosted at
https://cdn.acme.org/
- The script is run in the /home/your-name/ folder. For example:
/configure https://cdn.acme.org/
The Files will be available at /home/your-name/https:__cdn.acme.org_/
.
Deployment
- Put all of the files from the generated folder at the root of the storage after
https://placeholder.public.path/
.
For example, if your files are hosted athttp://localhost:8000/static/
, copy all the files to thestatic
folder on your local server. - If your storage is behind a CDN, make sure to issue a cache invalidation for
https://placeholder.public.path/loader.json
. - Make sure your server allows CORS requests.
- Test your deployment by initializing the SDK.
Usage
Script Tag
Add the following code towards the end of the head
section on your page and replace <sdk-folder-url>
with the URL where the SDK is hosted.
function s() {
try {
var e;
if ((e = "string" == typeof this.response ? JSON.parse(this.response) : this.response).url) {
var n = t.getElementsByTagName("script")[0]
, r = t.createElement("script");
r.async = !0, r.src = e.url, n.parentNode.insertBefore(r, n)
}
} catch (e) {}
}
var o, p, a, i = []
, c = [];
e[n] = {
init: function () {
o = arguments;
var e = {
then: function (t) {
return c.push({
type: "t"
, next: t
}), e
}
, catch: function (t) {
return c.push({
type: "c"
, next: t
}), e
}
};
return e
}
, on: function () {
i.push(arguments)
}
, render: function () {
p = arguments
}
, destroy: function () {
a = arguments
}
}, e.__onWebMessengerHostReady__ = function (t) {
if (delete e.__onWebMessengerHostReady__, e[n] = t, o)
for (var r = t.init.apply(t, o), s = 0; s < c.length; s++) {
var u = c[s];
r = "t" === u.type ? r.then(u.next) : r.catch(u.next)
}
p && t.render.apply(t, p), a && t.destroy.apply(t, a);
for (s = 0; s < i.length; s++) t.on.apply(t, i[s])
};
var u = new XMLHttpRequest;
u.addEventListener("load", s), u.open("GET", r + "/loader.json", !0), u.responseType = "json", u.send()
}
(window, document, "Bots", "<SDK_FOLDER_URL>");
Then initialize the SDK by placing this snippet towards the end of the body
section of your page.
<script>
Bots.init({appId: '<app-id>'});
</script>
Browser support
The Bots Client JavaScript SDK supports all popular browsers.
Desktop Versions
- Chrome: The latest version along with the previous major version.
- Edge: The latest version along with the previous major version.
- Firefox: The latest version along with the previous major version.
- Internet Explorer: Version 11 and higher.
- Safari: The latest version along with the previous major version.
Mobile Versions
- Stock browser on Android 4.1 and higher.
- Safari on iOS 8 and higher.
Other Browsers
Although we only tested the SDK against these versions, it may be compatible with older browsers as well.
API
Individual functions
init(options)
Initializes the Bots widget (the Web Messenger) in the web page using the specified options. It returns a promise that will resolve when the SDK is ready.
Note: Except for on
and off
, all methods must be called after a successful init
. For more about Bots.on
and Bots.off
, see Events.
Options
Option | Optional? | Default value | Description |
---|---|---|---|
appId |
No | The App ID generated by Intelligent Bots when you create a channel. | |
locale |
Yes | en-US |
The locale that formats date using the |
soundNotificationEnabled |
Yes | true |
Enables the sound notification for new messages. |
imageUploadEnabled |
Yes | true |
Enables the image upload feature. |
embedded |
Yes | false |
Tells the widget that it will be embedded. See Embedded Mode. |
customText |
Yes | See the following example. | The strings used in the widget UI. You can use these to either customize the text or translate it. Anything enclosed in curly braces ( |
displayStyle |
Yes | How the messenger widget appears on your web site. This is defined as either a button or tab. You can style the button’s size and icon | |
buttonIconUrl |
Yes | The URL that points to the button icon. The icon image must be:
|
|
buttonWidth |
Yes | 8px |
The button width, in pixels. |
buttonHeight |
Yes | 58px |
The button height, in pixels. |
businessName |
Yes | The business name. For example: businessName: “Oracle” |
|
businessIconUrl |
Yes | The URL that points to the business’ icon image. This image must be:
|
|
backgroundImageUrl |
Yes | The URL that points to the image that appears in the background of the conversation. This image is tiled to fit the chat window. | |
integrationOrder |
An array of integration IDs. When set, only integrations from this list will be displayed. If the array is empty, then no integrations will be displayed. Note: Listing an integration in the array doesn't guarantee that it will be displayed in the widget. |
||
customColors |
Yes | The colors used in the UI. | |
brandColor |
Yes | 65758e |
The color used in the messenger header and for the button or tab in idle state. |
conversationColor |
Yes | 0099ff |
This color used for customer messages, quick replies and actions in the footer. |
actionColor |
Yes | 0099ff |
The color used to change the appearance of selected actions inside your messages, like tapped buttons or links. This color is also used for the Send button when it is in active state. |
var initPromise = Bots.init({
appId: '<app-id>',
locale: 'en-US',
customText: {
actionPostbackError: 'An error occurred while processing your action. Please try again.',
clickToRetry: 'Message not delivered. Click to retry.',
conversationTimestampHeaderFormat: 'MMMM D YYYY, h:mm A',
fetchHistory: 'Load more',
fetchingHistory: 'Retrieving history...',
headerText: 'How can we help?',
inputPlaceholder: 'Type a message...',
invalidFileError: 'Only images are supported. Choose a file with a supported extension (jpg, jpeg, png, gif, or bmp).',
locationNotSupported: 'Your browser does not support location services or it’s been disabled. Please type your location instead.',
locationSecurityRestriction: 'This website cannot access your location. Please type your location instead.',
locationSendingFailed: 'Could not send location',
locationServicesDenied: 'This website cannot access your location. Allow access in your settings or type your location instead.',
messageError: 'An error occurred while sending your message. Please try again.',
messageIndicatorTitlePlural: '({count}) New messages',
messageIndicatorTitleSingular: '({count}) New message',
messageRelativeTimeDay: '{value}d ago',
messageRelativeTimeHour: '{value}h ago',
messageRelativeTimeJustNow: 'just now',
messageRelativeTimeMinute: '{value}m ago',
messageTimestampFormat: 'hh:mm A',
sendButtonText: 'Send',
settingsHeaderText: 'Settings',
tapToRetry: 'Message not delivered. Tap to retry.'
}
});
open()
Opens the conversation widget (no-op when embedded).
Bots.open();
close()
Closes the conversation widget (no-op when embedded).
Bots.close();
isOpened()
Tells if the widget is currently opened or closed.
Bots.isOpened();
destroy()
Destroys the widget, making it disappear. To get it back, reinitialize the widget with init
. This also clears the App ID from the widget and unbinds all of the listeners you might have bound to it using Bots.on
. See Events.
Bots.destroy();
sendMessage(message)
Sends a message on the user’s behalf.
Bots.sendMessage({
type: 'text',
text: 'hello'
});
// OR
Bots.sendMessage('hello');
getConversation()
Returns the conversation (if it exists).
var conversation = Bots.getConversation();
startConversation()
Creates a user and a conversation on the server, allowing the business to reach out proactively to the user through the public API.
Important: Only call this method when a message is likely to be sent.
This method is called automatically when starting a conversation with the sendMessage
method, or when a user sends a message through the conversation view.
If a conversation already exists for the current user, this call is a no-op.
Bots.startConversation();
triggerPostback
Triggers a postback action on the user's behalf.
const actionId = '5a747faa065bbe4e7804f2a4';
Bots.triggerPostback(actionId);
updateUser
Updates user information.
Bots.updateUser({
givenName: 'Updated',
surname: 'Name',
email: 'updated@email.com',
properties: {
'justGotUpdated': true
}
});
Events
If you want to make sure your events are triggered, bind them before calling Bots.init
.
To bind an event, use Bots.on(<event name>, <handler>);
. To unbind events, you can either:
- Call
Bots.off(<event name>, handler)
to remove one specific handler. - Call
Bots.off(<event name>)
to remove all handlers for an event. - Call
Bots.off()
to unbind all handlers.
ready
This event triggers when init completes successfully. Be sure to bind before calling init
.
Bots.on('ready', function(){
console.log('the init has completed!');
});
Bots.init(...);
destroy
This event triggers when the widget is destroyed.
Bots.on('destroy', function(){
console.log('the widget is destroyed!');
});
Bots.destroy();
message:received
This event triggers when the user receives a message.
Bots.on('message:received', function(message) {
console.log('the user received a message', message);
});
message:sent
This event triggers when the user sends a message.
Bots.on('message:sent', function(message) {
console.log('the user sent a message', message);
});
message
This event triggers when a message was added to the conversation.
Bots.on('message', function(message) {
console.log('a message was added to the conversation', message);
});
unreadCount
This event triggers when the number of unread messages changes.
Bots.on('unreadCount', function(unreadCount) {
console.log('the number of unread messages was updated', unreadCount);
});
widget:opened
This event triggers when the widget is opened.
Bots.on('widget:opened', function() {
console.log('Widget is opened!');
});
widget:closed
This event triggers when the widget is closed.
Bots.on('widget:closed', function() {
console.log('Widget is closed!');
});
Embedded mode
As described above, to activate the embedded mode, you need to pass embedded: true
when calling Bots.init
. This disables the auto-rendering mechanism, so you will need to call Bots.render
manually. This method accepts a DOM element which will be used as the container where the widget will be rendered.
The embedded widget will occupy the full width and height of the container. You must specify a height or else the widget will collapse.
Message Types
Text Message
A text type message is a message that is sent with text and/or actions.
{
/**
* The text content of the message. Optional only if actions are provided.
*/
text?: string,
/**
* Message type
*/
type: 'text',
/**
* Message role can be 'appUser' or 'appMaker'
* Added by SDK when send through the sendMessage method
*/
role?: 'appMaker',
/**
* Array of action buttons.
*/
actions?: MessageAction[],
/**
* Url to the avatar for this message sender
*/
avatarUrl?: string
}
Carousel Message
Carousel messages are a horizontally scrollable set of items that may each contain text, an image, and action buttons.
{
/**
* Message type
*/
type: 'carousel',
/**
* Message role can be 'appUser' or 'appMaker'
* Added by SDK when send through the sendMessage method
*/
role?: 'appMaker',
/**
* Url to the avatar for this message sender
*/
avatarUrl?: string,
/**
* Array of message items. The array is limited to 10 items.
*/
items: Item[],
/**
* Settings to adjust the carousel layout.
*/
displaySettings?: {
imageAspectRatio: 'horizontal' | 'square'
}
}
Image Message
An image type message is a message that is sent with an image, and, optionally, text and/or actions.
{
/**
* Message type
*/
type: 'image',
/**
* Message role can be 'appUser' or 'appMaker'
* Added by SDK when send through the sendMessage method
*/
role?: 'appMaker',
/**
* Url to the avatar for this message sender
*/
avatarUrl?: string,
/**
* The text content of the message. Optional only if actions are provided.
*/
text?: string,
/**
* The media type is defined here, for example image/jpeg. If mediaType is not specified, the media type will be resolved with the mediaUrl.
*/
mediaType?: string;
/**
* The image URL used for the image message.
*/
mediaUrl: string;
/**
* Array of action buttons.
*/
actions?: MessageAction[]
}
File Message
{
/**
* Message type
*/
type: 'file',
/**
* Message role can be 'appUser' or 'appMaker'
* Added by SDK when send through the sendMessage method
*/
role?: 'appMaker',
/**
* Url to the avatar for this message sender
*/
avatarUrl?: string,
/**
* The text content of the message. Optional only if actions are provided.
*/
text?: string,
/**
* The media type is defined here, for example application/pdf. If mediaType is not specified, the media type will be resolved with the mediaUrl.
*/
mediaType?: string;
/**
* The URL of the file attachment.
*/
mediaUrl: string;
}
Location Message
A location type message includes the coordinates (latitude and longitude) of a location. Typically, this type of message is sent in response to a location request.
{
/**
* Message type
*/
type: 'location',
/**
* Message role can be 'appUser' or 'appMaker'
* Added by SDK when send through the sendMessage method
*/
role?: 'appMaker',
/**
* Url to the avatar for this message sender
*/
avatarUrl?: string,
/**
* The coordinates of the location.
*/
coordinates?: {
/**
* A floating point value representing the latitude of the location
*/
lat: number,
/**
* A floating point value representing the longitude of the location
*/
long: number
}
}
Message Actions
Postback Action
A postback
action posts the action payload to the server when tapped.
{
_id: string,
/**
* The button text.
*/
text: string,
/**
* Type of the action
*/
type: 'postback',
/**
* Value indicating whether the action is the default action for a message item.
*/
default: boolean,
/**
* Flat object containing any custom properties associated with the action.
*/
metadata?: any,
/**
* A string payload to help you identify the action context. You can also use metadata for more complex needs.
*/
payload: string
}
Link Action
A link
action opens the specified URI when tapped.
{
/**
* The button text.
*/
text: string,
/**
* Type of the action
*/
type: 'link',
/**
* Value indicating whether the action is the default action for a message item.
*/
default: boolean,
/**
* Flat object containing any custom properties associated with the action.
*/
metadata?: any,
/**
* The action URI. This is the link that will be used in the clients when clicking the button.
*/
uri: string
/**
* Extra options to pass directly to the channel API.
*/
extraChannelOptions?: any
}
Location Request Action
A locationRequest
action prompts a user to share his location.
{
/**
* The button text.
*/
text: string,
/**
* Type of the action
*/
type: 'locationRequest',
/**
* Value indicating whether the action is the default action for a message item.
*/
default: boolean,
/**
* Flat object containing any custom properties associated with the action.
*/
metadata?: any,
}
Reply Action
A reply
action echoes the user’s choice as a message.
Tip: You can
optionally specify an iconUrl
which will render as an icon for each option.
{
/**
* The button text.
*/
text: string,
/**
* Type of the action
*/
type: 'reply',
/**
* Value indicating whether the action is the default action for a message item.
*/
default: boolean,
/**
* Flat object containing any custom properties associated with the action.
*/
metadata?: any,
/**
* A string payload to help you identify the action context. Used when posting the reply. You can also use metadata for more complex needs.
*/
payload: string,
/**
* An icon to render next to the reply option
*/
iconUrl?: string
}
Webview Action
When a webview action is clicked or tapped, the provided URI will be loaded in a webview.
{
/**
* The button text.
*/
text: string,
/**
* Type of the action
*/
type: 'webview',
/**
* Value indicating whether the action is the default action for a message item.
*/
default: boolean,
/**
* Flat object containing any custom properties associated with the action.
*/
metadata?: any,
/**
* The webview URI. This is the URI that will open in the webview when clicking the button.
*/
uri: string,
/**
* The webview fallback URI. This is the link that will be opened when not support webviews.
*/
fallback: string,
/**
* Controls the webview height.
*/
size?: 'compact' | 'tall' | 'full',
/**
* Extra options to pass directly to the channel API.
*/
extraChannelOptions?: any
}
Share Action
The share button.
{
/**
* The button text.
*/
text: string,
/**
* Type of the action
*/
type: 'share',
/**
* Value indicating whether the action is the default action for a message item.
*/
default: boolean,
/**
* Flat object containing any custom properties associated with the action.
*/
metadata?: any
}
Message Item
{
/**
* The image URL to be shown in the carousel/list item.
*/
mediaUrl?: string,
/**
* The text description, or subtitle.
*/
description?: string,
/**
* The title of the carousel item.
*/
title: string,
/**
* If a mediaUrl was specified, the media type is defined here, for example image/jpeg. If mediaType is not specified, the media type will be resolved with the mediaUrl.
*/
mediaType: string,
/**
* Array of action buttons. At least 1 is required, a maximum of 3 are allowed. link and postback and share actions are supported.
*/
actions: IBotsSDKMessageAction[],
/**
* The size of the image to be shown in the carousel/list item
*/
size: 'compact' | 'large'
}