Developers

Hyperchat Adapter

Introduction

The purpose of this document is to explain how to use the HyperChat adapter for the Chatbot SDK and all the configuration options available. It also presents several practical examples.

Internal adapter

This adapter is included in the Chatbot SDK to facilitate the steps to integrate HyperChat and the escalation.

To use an internal adapter, you must set the adapters array like this:

adapters: [
   SDKHCAdapter.build(),
]
Note

The SDK at the beginning of the function name is what forces the SDK to use the internal adapter.

Important

For security reasons, you must integrate the SDK on a site with HTTPS (i.e. with a security certificate). If you try to integrate the SDK on an HTTP site, the adapter will not work properly.

Caution

If you use the internal adapter, you must override every instance of HCAdapter with SDKHCAdapter, not only in the build, but also in the configuration.

If this adapter meets your requirements, you can use it as explained above. If you need to modify its behaviour, see the "Customizing options" section below.

Configuration

Call the configure method with the required parameters to set up the configuration. You can find an explanation for each parameter in the "Configuration parameters" section below:

SDKHCAdapter.configure({
    apiKey: '<chat_api_key>',  // former "appId"
    region: '<chat_app_region>',
    room: function () {
        return '<roomId>';
    },
});
Caution

The chat API key (apiKey) is not the same as your Inbenta app API key (inbentaKey). To find your chat API key, open your Messenger instance and go to Messenger > Settings > Chat.

Notes

The appId parameter is DEPRECATED in favor of apiKey, for consistency with Inbenta terminology. If you use appId, Inbenta recommends that you update your configuration.

You must build the adapter in the adapters array inside the Chatbot SDK configuration:

var authorization = {
    domainKey:"<your_domain_key>",
    inbentaKey:"<your_API_key>",
};
InbentaChatbotSDK.buildWithDomainCredentials(authorization, {
    "adapters": [
        SDKHCAdapter.build(),
    ],
});

Configuration parameters

  • apiKey (string) : The key of the HyperChat API (former "appId"). This defines the instance in which the chat opens.
  • region (string) : The geographical region where the HyperChat app "lives". Valid values are: "eu" for Europe and "us" for the United States.
  • room (function) : The room where the chat opens. This is mapped directly to a queue ID in the Messenger App.
  • surveyTimeout (number) : Number of milliseconds between the user successfully answers a survey and the chat closing the window and session. It is optional.

Example
To get the room from a query parameter where the current URL is www.currentweb.com?room=1, configure it like this:

room: function () {
    var queueID = SDKHCAdapter.helpers.getQueryParameterValue('room');
        return queueID;
}
  • importBotHistory (Boolean) [optional] : Whether to import the chatbot previous conversation transcript to the chat or not. Defaults to false.
  • setCookieOnDomain (Boolean) [optional] : Useful for multi-subdomain integrations. It defines whether HyperChat works in all the site (true) or just in the current subdomain (false). Defaults to false.
  • setCookieSameSite (enum("None", "Strict", "Lax")) [optional] : Defines the SameSite cookie attribute. This setting allows to you to declare if Hyperchat cookie should be restricted to a first-party or same-site context. By default, no value is set.
  • source (function) [optional]: The source ID for the chat (used to load FAQs for the agents, for example). Defaults to 3 (which in all instances corresponds to source Chat).
  • lang (function) [optional]: Language code (in ISO 639-1 format) for the current chat. This is used when the engine checks if there are agents available for this language to assign the chat to one of them. Defaults to no language restriction. Note: this parameter is mandatory if the instance has languages.

Example
To get the user's configured browser language, configure it like this:

lang: function () {
    return SDKHCAdapter.helpers.getUserBrowserLanguage();
}
  • fileUploadsActive (Boolean) [optional] : Defines if the user can see the file selector. If they can, they can send attachments. (Default value: false)
  • extraInfo (function) [optional] : Extra information about the user context (or anything that might be useful for the agents to check). This is set as a chat user's "metadata". This information appears in the collapsible panel next to the chat window in the Messenger App. (Default value: empty object)

Example
To capture the current URL (page from which the user opens the chat) and the text in an HTML element by its ID:

extraInfo: function () {
    return {
        url: SDKHCAdapter.helpers.getCurrentUrl(),
        property: SDKHCAdapter.helpers.getHTMLTagValueById('propertyId')
    }
}
  • port (Number) [optional] : The service port to connect. Defaults to 8000. Possible ports are 8000 and 443.
  • surveys (object) [optional] : Id of the Inbenta survey or url for an external survey.

Example
To use an Inbenta survey with id 2:

surveys: { 
     id: 2 
}

Example
To use an external survey URL:

surveys: { 
      url: 'https://www.external-url.com/aSurvey'
}
  • transcript (object) [optional]: Configuration on downloading the chat conversation to PDF.

Example
To show the download button:

transcript: { 
     download: true
}

transcript.template (String) : Contains an alternative to the default template. The string must be an HTML fulfilling the Vue Template Syntax. The following properties are available:

Example
Default template:

<div class="inbenta-bot__pdf" style="padding: 20px">
    <h1 class="inbenta-bot__pdf__title" style="font-family: Arial; font-size: 16px; color: #3d3f43; margin-bottom: 15px">{{ticketId}}</h1>
    <div class="inbenta-bot__pdf__body" v-for="entry in history" v-if="['messages:new', 'chats:join', 'chats:close', 'chats:create', 'chats:leave'].indexOf(entry.event) > -1">
        <div class="body__start-chat" style="padding: 10px; color: #3d3f43; font-size: 13px; font-family: Arial; font-style: italic; background-color: #EFF1F4; text-align: center; margin: 25px 0 15px; border-radius: 5px;" v-if="entry.event==='chats:create'">
            {{ $t('chatStarted', { date: $d(new Date(entry.created*1000), 'long') }) }}
        </div>
        <div class="body__messages" v-else style="padding: 14px 0; border-bottom: 1px solid #EFF1F4">
            <!-- show time -->
            <div class="body__messages__date" style="color: #8C8D8F; font-size: 12px; font-family: Arial; padding-bottom: 3px;">{{ $d(new Date(entry.created*1000), 'short') }}</div>
            <!-- messages:new case -->
            <div class="body__messages__message" v-if="entry.event === 'messages:new'">
                <div class="message__label" style="font-family: Arial; font-size: 12px; color: #3d3f43; font-weight: bold; padding-bottom: 3px;">{{entry.data.sender.nickname || entry.data.sender.name}}:</div>
                <div class="message__text" style="font-family: Arial; font-size: 14px; color: #3d3f43;" v-html="entry.data.message.message"></div>
            </div>
            <div class="body__messages__message body__messages__message--system" v-else-if="entry.event ==='chats:join'">
                <i style="font-family: Arial; font-size: 13px; color: #8C8D8F;">{{ $t('chatJoin', { name: entry.data.user.nickname || entry.data.user.name }) }}</i>
            </div>
            <div class="body__messages__message body__messages__message--system" v-else-if="entry.event ==='chats:leave'">
                <i style="font-family: Arial; font-size: 13px; color: #8C8D8F;">{{ $t('chatLeave', { name: entry.data.user.nickname || entry.data.user.name }) }}</i>
            </div>
            <div class="body__messages__message body__messages__message--system" v-else-if="entry.event ==='chats:close'">
                <i style="font-family: Arial; font-size: 13px; color: #8C8D8F;">{{ $t('chatClosed') }}</i>
            </div>
        </div>
    </div>
</div>

The template style can be customized by previously loading CSS styles into the page where the chat is taking place.

  • transcript.methods (object): It contains functions that will be available in the custom template.

  • transcript.labels (object): An object in the vue-i18n format for template labels in different languages.

  • transcript.dateTimeFormats (object): An object in the vue-i18n DateTime localization format for date and time formats in different languages.

Example
Using all the possible properties:

transcript: {
    download: true,
    template: 'HTML',
    methods: {
        usefulFunction: () => {
            return 0;
        },
    },
    labels: {
        'en': {
            chatStarted: 'Chat started on {date}',
            chatJoin: '*** {name} joined the chat ***',
            chatLeave: '*** {name} left the chat ***',
            chatClosed: '*** Chat has been closed ***',
            customText: 'text' // also allows all the custom labels you might put in your customized template
        },
    },
    dateTimeFormats: {
        'en': {
            short: {
                hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
            },
            long: {
                year: 'numeric', month: 'short', day: 'numeric',
                hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
            }
        },
    }
}
  • queue (object) [optional] : To toggle Queue mode, define the priority and queue position message update mode.
Important

This configuration is only available from the Chatbot SDK version `1.25.0` onwards.

From version 1.25.0 until 1.34.0 (both inclusive), you have to have both the configuration in your HyperChat instance and this one active for the queue mode to work.

From version 1.34.1 onwards, the "active" configuration in the adapter is not needed anymore. If the configuration in your HyperChat instance is active, the queue mode will be active, which makes it easier to set up.

For more information, see here.

  • singleQueuePositionMessage is available from version 1.38.0
  • showEstimatedWaitingTime and shortWaitMessageCutoffTime are available from version 1.39.0

Example

queue: { 
    active: true, // (DEPRECATED AS OF v1.30.0 - DO NOT USE if you use v1.30.0 or older) Whether to set the queue mode active or not
    priority: function () { // Optional function to set the priority of the chat. Priority sets the "preference" of a user to be attended. Being 1 the highest priority. (i. e. a chat is created with priority 2, and later another with priority 1. Both are waiting. When a free slot is available, the chat with priority 1 will be released from the queue before the one with priority 2, even though it was created later).
        return 1;
    },
    singleQueuePositionMessage: true, // (default: true) If true, every time the queue position is updated, the message is updated. The queue position message will be appended as a new message if this parameter is set to false
    showEstimatedWaitingTime: true, // (default: false) If true, it displays users the estimated waiting time until they are attended by an agent. Check the "labels" section to know which labels are available for messages customization
    shortWaitMessageCutoffTime: 60, // (default: 60 seconds) Time from which "you'll be attended shortly" or the exact time will be shown
}
  • keepConversationAfterSurvey (Boolean) [optional] : Avoid closing the chat window and restoring the chat session keeping the conversation once survey is submitted. Defaults to true.
  • userMessageNotifications (object) [optional] : Play a sound when the end-user (web user) has not the browser tab focused and receives a message. The "source" property should be a valid URL where the sound file is stored. This setting is available from version 1.60.0.

Example

userMessageNotifications: { 
    active: true,
    source: 'https://freesound.org/data/previews/171/171671_2437358-lq.mp3', 
}
  • notificationMessages (object) [optional] : Configures client-side browser notifications that inform the user about new messages received from chat agents.

Example

notificationMessages: {
   configured: true,
   titleMessage: 'title text',
   bodyMessage: 'body text',
   icon: 'https://www.inbenta.pro/backstage/images/notification-chat-big.png',
}
  • notificationMessages.configured (boolean) : To define whether or not notifications should be sent to the user.

  • notificationMessages.titleMessage (string) [optional] : To define the title of the notification.

  • notificationMessages.bodyMessage (string) [optional] : To define the message body of the notification.

  • notificationMessages.bodyMessage (string) [optional] : To add an icon to the notification.

  • continueInQueueRequest (object) [optional] : Request the user to confirm whether they want to keep waiting for a chat agent or leave the queue. If the user remains inactive, this is considered a confirmation to leave the queue. The message can only be shown in browsers that support these notifications and if the user allows notifications on the webpage where the SDK is integrated.

Example

continueInQueueRequest: {
   requestIntervalTime: 3,
   timeToAnswerRequest: 10,
}
  • continueInQueueRequest.requestIntervalTime (number) : The waiting time in minutes after which the confirmation request should be sent to users in the queue or sent again to users that have previously confirmed that they want to keep waiting.
  • continueInQueueRequest.timeToAnswerRequest (number) : The time in seconds that the user has to answer the confirmation request before they are considered inactive and the chat closes automatically.
  • adviceConnectionStatus (boolean) [optional] : Shows connection status updates to users when they lose the connection to the HyperChat or when the connection is restored.
  • messageCharacterLimit (number) [optional] : This parameter contains the maximum number of characters that can be sent by a user in a single message in a HyperChat conversation. This limit does not apply to chatbot queries, but by default it has the same value as the limit defined for chatbot conversations.

Event subscription

The HyperChat adapter triggers events when certain actions happen in a chat. The events are the following:

  • chat:created: Triggered when the chat is created.

    { chat }
  • chat:closed: Triggered when the chat is closed.

    { chatId, 
      userId,
      reason // Optional String with the reason for closing the chat if it was not closed manually by a user. It can be "inactivity" if the chat was closed due to no activity in the chat, "forever:alone" if there were no agents to attend the chat, or "allAgentsDisconnected" if the chat was waiting in a queue and all the agents online in this queue then disconnected.
    }
  • user:joined: Triggered when a user joins the chat.

    {
      chat, // Object with chat properties
      mode, // String 'watch' or empty otherwise
      sender, // String with the sender id
      transfer, // Boolean stating whether the join is from a transfer or not
      user // Object with the user properties
    }
  • user:left: Triggered when a user leaves the chat.

    { chatId, userId }
  • ticket:created Triggered when a chat is converted to ticket.

    {
      ticketId, // String with the ticket id in the form PROJECT-ID
      rawTicketId, // String with the ticket id in the form ID
      chat: {
        attended // Boolean stating if the chat was attended
      },
    }
  • forever:alone: Triggered when there aren't any agents available for a chat.

    { chatId }
  • expiry:alert: Triggered when the chat is about to expire due to inactivity. Whether to activate or not this feature and the time left for the event to trigger can be configured in CM > Settings > Chat.

    { chatId,
      timeLeft // Time left in seconds before the chat closes
    }
  • hyperChatAdapterError: Triggered when an error happens in the Adapter. The error is captured and this event triggered, but the execution is not stopped.

    [
      errorObject, // object
      extraInfo // string. More information about the error
    ]
  • hyperChatAdapterInfo: Triggered when an event happens in the Adapter. It returns the event name and the data provided by each event.

    { 
      eventName, // string 
      data // object 
    }
    • agentsOnline: Triggered once agents online status is checked by the SDK.
    { 
      eventName: 'agentsOnline',
      data: {
        agentsOnline // boolean
      }
    }

It is easy to subscribe to these events. Here is an example:

// Function called when chatbot script is loaded
function buildUI () {
    // ...
    // SDKHCAdapter.configure and SDKHCAdapter.build
    // ...
    SDKHCAdapter.events.on('chat:created', (data) => {
        console.log('created', data);
    })
    SDKHCAdapter.events.on('chat:closed', (data) => {
        console.log('closed', data);
    })
    SDKHCAdapter.events.on('user:joined', (data) => {
        console.log('joined', data);
    })
    SDKHCAdapter.events.on('user:left', (data) => {
        console.log('left', data);
    })
    SDKHCAdapter.events.on('ticket:created', (data) => {
        console.log('ticket', data);
    })
    SDKHCAdapter.events.on('hyperChatAdapterError', (err, info) => {
        console.error(error, info);
    })
    SDKHCAdapter.events.on('hyperChatAdapterInfo', (info) => {
        console.error(info);
    })

}

Event subscription objects

  • chat
    { 
    id, // String
    room // String
    creator // String with the creator user id
    source // Integer
    lang // String with the ISO 639-1 Code
    closed, // falsy value or a Unix timestamp of when the chat was closed
    users, // Array with users in the chat
    lastActivity, // Unix timestamp
    inQueue: Boolean
    }
  • user
    { 
    id, // String
    name, // String
    nickname, // String
    providerId, // usually the instance user id
    gender // "N/A", "male" or "female"
    }

Helper functions

  • setRoomFunction: Sets the function that determines the room where the chat will be created. Can be called anytime, for example just before the chat escalation.
SDKHCAdapter.setRoomFunction(function () {
    return 1; // Chat will be created in room 1
});
  • resetAdapter: Clears all data stored by the adapter and leaves it ready to open a new chat from scratch.
    SDKHCAdapter.resetAdapter();

Labels

The HyperChat adapter uses labels defined in the chatbot sdk. These labels can be replaced and customized just like the other chatbot sdk labels:

label text description variables
chat-ticket {ticketId} Showed when the ticket ID is received after the chat is closed ticketId: The ticket identifier.
queue-estimation-first There is 1 person ahead of you. Shown when the user is the first in the queue. It might be somewhat confusing but, if you are the first in the queue, it means that there is someone being attended by the agent before you. Therefore, you have 1 person in front of you. When this person has finished, then it's your turn and the label "waiting for an agent" (or "agent joined" in case of forced invitations) will be displayed. queuePosition: The number of people in front of the user in the queue.
queue-estimation There are {queuePosition} people ahead of you. Shown when there is more than one person in front of the user in the queue. queuePosition: The number of people in front of the user in the queue.
queue-estimation-first-short-wait There is 1 person ahead of you.
You will be attended shortly.
Shown when there is 1 person in front of the user in the queue and the wait time is lower than the "shortWaitMessageCutoffTime". -
queue-estimation-short-wait There are {queuePosition} people ahead of you.
You will be attended shortly.
Shown when there is more than one person in front of the user in the queue and the wait time is lower than the "shortWaitMessageCutoffTime". queuePosition: The number of people in front of the user in the queue.
queue-estimation-first-wait-time There is 1 person ahead of you.
Estimated waiting time: {minutes} minutes
Shown when there is 1 person in front of the user in the queue and the wait time has to be shown. minutes: The estimated wait time in minutes
queue-estimation-wait-time There are {queuePosition} people ahead of you.
Estimated waiting time: {minutes} minutes
Shown when there is more than one person in front of the user in the queue and the wait time has to be shown. queuePosition: The number of people in front of the user in the queue, minutes: The estimated wait time in minutes

Customizing options

This internal adapter works for the majority of cases and can be configured to perform more advanced operations. However, if you need to change its default logic for a truly custom solution, you can override this internal adapter with your own implementation.

To help you in this, the source code is available on GitHub at https://github.com/inbenta-products/hyperchat-bot-adapter. Feel free to take this code and modify it according to your specific needs.

Important

Inbenta does not provide any support for this code. It was open-sourced as an example.