OVERVIEW
Virtual Assistants
Kore.ai Platform
Key Concepts
Natural Language Processing (NLP)
Accessing Platform
VIRTUAL ASSISTANTS
Virtual Assistant Builder
Virtual Assistant Types
Getting Started
Create a Simple Bot
SKILLS
Storyboard
Dialog Tasks
Introduction
Dialog Builder (New)
Dialog Builder (Legacy)
User Intent Node
Dialog Node
Entity Node
Supported Entity Types
Composite Entities
Supported Colors
Supported Company Names
Form Node
Logic Node
Message Nodes
Confirmation Nodes
Bot Action Node
Service Node
Custom Authentication
2-way SSL for Service nodes
Script Node
Agent Transfer Node
WebHook Node
Grouping Nodes
Connections & Transitions
Manage Dialogs
User Prompts
Knowledge Graph
Terminology
Building
Generation
Importing and Exporting
Analysis
Knowledge Extraction
Train
Build
Alert Tasks
Introduction
Ignore Words and Field Memory
How to Schedule a Smart Alert
Small Talk
Digital Views
Introduction
How to Configure Digital Views
Digital Forms
Overview
How to Configure Digital Forms
NATURAL LANGUAGE
Overview
Machine Learning
Introduction
Model Validation
Fundamental Meaning
Introduction
NLP Guidelines
Knowledge Graph
Traits
Introduction
How to Use Traits
Ranking and Resolver
Advanced NLP Configurations
INTELLIGENCE
Overview
Context Management
Overview
Session and Context Variables
Context Object
How to Manage Context Switching
Manage Interruptions
Dialog Management
Sub Intents & Follow-up Intents
Amend Entity
Multi-Intent Detection
Sentiment Management
Tone Analysis
Sentiment Management
Event Based Bot Actions
Default Conversations
Default Standard Responses
TEST & DEBUG
Talk to Bot
Utterance Testing
Batch Testing
Record Conversations
Conversation Testing
CHANNELS
PUBLISH
ANALYZE
Overview
Dashboard
Custom Dashboard
Overview
How to Create Custom Dashboard
Conversation Flows
NLP Metrics
ADVANCED TOPICS
Universal Bots
Overview
Defining
Creating
Training
Customizing
Enabling Languages
Store
Smart Bots
Defining
koreUtil Libraries
SETTINGS
Authorization
Language Management
PII Settings
Variables
Functions
IVR Integration
General Settings
Management
Import & Export
Delete
Bot Versioning
Collaborative Development
Plan Management
API GUIDE
API Overview
API List
API Collection
SDKs
SDK Overview
SDK Security
SDK App Registration
Web SDK Tutorial
Message Formatting and Templates
Mobile SDK Push Notification
Widget SDK Tutorial
Widget SDK – Message Formatting and Templates
Web Socket Connect & RTM
Using the BotKit SDK
Installing
Configuring
Events
Functions
BotKit SDK Tutorial – Agent Transfer
BotKit SDK Tutorial – Flight Search Sample Bot
Using an External NLP Engine
ADMINISTRATION
HOW TOs
Create a Simple Bot
Create a Banking Bot
Transfer Funds Task
Update Balance Task
Context Switching
Using Traits
Schedule a Smart Alert
Configure UI Forms
Add Form Data into Data Tables
Configuring Digital Views
Add Data to Data Tables
Update Data in Data Tables
Custom Dashboard
Custom Tags to filter Bot Metrics
Patterns for Intents & Entities
Build Knowledge Graph
Global Variables
Content Variables
Using Bot Functions
Configure Agent Transfer
RELEASE NOTES

BotKit SDK のイベント

Kore.ai BotKit SDK を使用して、ボット プラットフォームでイベントをキャプチャして処理することで、ユーザーのボット体験について管理性を向上させ、カスタマイズすることができます。BotKit SDK では、以下のイベントがサポートされています:

onMessage

このイベントは、以下の 2 つのコンポーネントで構成されています:

  • onUserMessage: このイベントは、ユーザーが ボットにメッセージを送信し、チャネル アダプタがそれを受信したときにトリガーされます。ユーザー メッセージはこのイベントにラップされ、SDK に送信されます。
  • onBotMessage: このイベントは、メッセージをユーザーに送信する必要がある場合にトリガーされます。これらのメッセージは、 context オブジェクトとともに SDK に送信されます。

onUserMessage

構文:

on_user_message : function(requestId, data, callback)

パラメータ:

  • requestId ー 各メッセージ イベントに固有の ID。
  • payload ー 以下に示すような、JSON のレスポンス ペイロードです:
    { "message":"message sent by bot to the user", "taskId":"Dialog task Id", "nodeId":"current node id in the dialog flow", "channel":"channel name", "context":"context object" }
  • callback ー イベント完了時に呼び出される関数で、更新されたメッセージとコンテキストを ボット プラットフォームに送信します。

サンプル: 以下の onUserMessage イベントのコード サンプルでは、ユーザー メッセージはライブ エージェントへの転送が評価されて転送され、そうでなければメッセージは BotKit SDK に渡されて処理されます。

/* * OnUserMessage event handler */ function onUserMessage(requestId, payload, callback){ debug("user message", payload); var visitorId = _.get(payload, 'channel.from'); visitorId = payload.context.session.UserContext._id; var entry = _map[visitorId]; if (payload.message === "clearagent") // disconnect from LiveChat on user utterance { sdk.clearAgentSession(payload); } if(entry){//check for live agent //route to live agent var formdata = {}; formdata.secured_session_id = entry.secured_session_id; formdata.licence_id = config.liveagentlicense; formdata.message = payload.message; return api.sendMsg(visitorId, formdata) .catch(function(e){ console.error(e); delete userDataMap[visitorId]; delete _map[visitorId]; return sdk.sendBotMessage(payload, callback); }); } else { return sdk.sendBotMessage(payload, callback); } }

onBotMessage

構文:

 on_bot_message : function(requestId, data, callback)

パラメータ:

  • requestId ー 各メッセージイベントに固有の ID。
  • payload — 以下に示すような、JSON のレスポンス ペイロードです:
    { "message":"message sent to the user", "channel":"channel name", "context":"context object" }
  • callback ー イベント完了時に呼び出される関数で、更新されたメッセージとコンテキストをユーザーに送り返します。

サンプル: 以下のコードスニペット onBotMessage イベントは、ユーザー メッセージの内容を評価し、次にメッセージ トーンを評価します。メッセージ トーンが怒りのトーンの 2 以上の場合、ユーザーとボットの間のボット通信はライブ エージェントに切り替わります。

/* * onBotMessage event handler */ function onBotMessage(requestId, payload, callback){ debug("Bot Message Data",payload); console.log("in bot message"); var visitorId = _.get(paylod, 'channel.from'); var entry = _map[visitorId]; if(data.message.length === 0 || payload.message === '') { return; } var message_tone = _.get(payload, 'context.message_tone');console.log("message tone -----",message_tone); if(message_tone && message_tone.length> 0){ var angry = _.filter(message_tone, {tone_name: 'angry'}); if(angry.length){ angry = angry[0]; if(angry.level >=2){ return connectToAgent(requestId, data); } } } if(!entry) { sdk.sendUserMessage(payload, callback); } }

onWebHook

このイベントは、Kore NL Engine がダイアログ フローで Webhook ノードを処理するときにトリガーされます。このイベントは、 componentId およびコンテキストとともに SDK に送信されます。SDK はビジネス ロジックを実行し、更新されたコンテキストをプラットフォームに送り返すことができます。構文:

on_webhook = function(requestId, componentId, payload, callback)

パラメータ:

  • requestId ー 各 Webhook イベントに固有の ID です。
  • componentId ー SDKWebhook ノードに固有の ID です。
  • payload — 以下に示すような、JSON のレスポンス ペイロードです:
    { "message":"message sent by bot to the Bots platform", "taskId":"Dialog task Id", "nodeId":"current node id in the dialog flow", "channel":"channel name", "context":"context object" }
  • callback ー イベント完了時に呼び出される関数で、更新されたメッセージとコンテキストを ボット プラットフォームに送信します。

サンプル 次の on_webhook イベントのサンプルでは、ユーザー入力に対するレスポンスとして 2 つのホテル名が結果として返されます。

//on_webhook handler on_webhook : function(requestId, payload, componentId, callback) { if (componentId === 'sendResponse') { var hotels = { "hotels":[ "Taj Banjara", "Novotel" ] }; payload.context.hotelResults = hotels; callback(null,data); } }

この on_webhook イベントのサンプルでは、ダイアログ タスクの フライト情報ノードで、要求された日付に基づく出発空港または目的地空港のリストが、ダイアログのフローに基づいて、エンド ユーザーに表示される結果のリストとして返されます。

on_webhook : function(requestId, payload, componentId, callback) { var context = payload.context; if (componentName === 'FlightsInfo') { var origin = context.entities.Source; var destination = context.entities.Dest; var departureDate = context.entities.Date; findFlights(origin,destination,departureDate) .then(function(flightResults) { payload.context.flightResults = flightResults; callback(null, data); }); } else if(componentId === 'GetSourceAirports'){ var searchTerm = context.entities.SourceName; findAirports(searchTerm) .then(function(airportResults) { payload.context.sourceAirports = airportResults; callback(null, data); }); } else if(componentId === 'GetDestAirports'){ var searchTerm = context.entities.DestName; findAirports(searchTerm) .then(function(airportResults) { payload.context.destAirports = airportResults; callback(null, data); }); }

onAgentTransfer

このイベントは、Kore NL エンジンがダイアログ フローでエージェント転送ノードを処理したときにトリガーされます。このイベントは、 requestId およびコンテキストとともに SDK に送信されます。SDK はビジネス ロジックを実行して、ユーザーをシームレスにライブ エージェントに切り替えることができます。構文:

function onAgentTransfer(requestId, data, callback){ connectToAgent(requestId, data, callback); }

パラメータ:

  • requestId ー 各メッセージ イベントに固有の ID。
  • payload — 以下に示すような、JSON のレスポンス ペイロードです:
    { OnAgentTransferPayload "," requestId ":1501244156289," botId ":"st - b4a22e86 - e95b - 575 c - b888 - e106d083a251 "," callbackUrl ":"https: //bots.kore.ai/api/botsdk/stream/st-b4a22e86-e95b-575c-b888-e106d083a251/serviceCallback/1501244156289","context": ...}
  • callback ー イベント完了時に呼び出される関数で、更新されたメッセージとコンテキストを ボット プラットフォームに送信します。

サンプル: 以下のコードスニペット onAgentTransfer イベントは、ユーザーをライブ エージェントに接続し、ユーザー メッセージ、ボット メッセージ、セッションの履歴チャットメッセージを渡します。

function connectToAgent(requestId, data, cb){ var formdata = {}; console.log("userlog",JSON.stringify(data.context.session.UserContext._id)); formdata.licence_id = config.liveagentlicense; formdata.welcome_message = ""; var visitorId = _.get(data, 'channel.channelInfos.from'); if(!visitorId){ visitorId = _.get(data, 'channel.from'); } visitorId = data.context.session.UserContext._id; userDataMap[visitorId] = data; data.message="An Agent will be assigned to you shortly!!!"; var d = new Date(); data.context.session.BotUserSession.startTime = new Date().toLocaleString(); console.log("userlog",JSON.stringify(data.context.session)); sdk.sendUserMessage(data, cb); formdata.welcome_message = "Link for user Chat history with bot: "+ config.app.url +"/history/index.html?visitorId=" + visitorId; return api.initChat(visitorId, formdata) .then(function(res){ _map[visitorId] = { secured_session_id: res.secured_session_id, visitorId: visitorId, last_message_id: 0 }; }); }

OnEvent

このイベントは、ダイアログ タスクまたは FAQ がボット内で終了し、リクエスト ID とコンテキストを SDK に送信したときにトリガーされます。構文:on_event : 関数 (requestId, data, callback) パラメータ:

  • requestId ー 各メッセージ イベントに固有の ID です。
  • data ー 以下のサンプルに示すような、JSON のレスポンス ペイロードです。
  • callback ー イベントが完了した後に呼び出される関数で、更新されたメッセージとコンテキストを ボット プラットフォーム に送り返すために使用されます。

サンプル:

on_event : function (requestId, data, callback) { return sdk.sendAlertMessage(data, callback); }

このイベントでは、キットに送られた データ オブジェクトに以下のコードが追加されます:

"event": { "event Type": "endDialog"/ “endFAQ” }

OnAlert

このイベントは、ボット ユーザーがアラートを受信したときにトリガーされます。構文: on_alert : 関数 (requestId, data, callback) パラメータ:

  • requestId ー 各メッセージ イベントに固有の ID。
  • data— JSON のレスポンス ペイロードです。
  • callback ー イベント完了時に呼び出される関数で、更新されたメッセージとコンテキストを ボット プラットフォーム に送り返します。

サンプル:

on_alert: function(requestId, data, callback) { return sdk.sendAlertMessage(data, callback); }

アラート レスポンス データは、キットに送られたデータ オブジェクトの中にあります。

OnVariableUpdate

このイベントは、ボットが公開された際に variable_update でトリガーされます。構文: variable_update : 関数 (requestId, data, callback) パラメータ:

  • requestId ー 各メッセージ イベントに固有の ID。
  • data— JSON のレスポンス ペイロードです
  • callback ー イベント完了時に呼び出される関数で、更新されたメッセージとコンテキストを ボット プラットフォーム に送り返します。
var event = data.eventType; console.log("event----------->", event); if (first || event == "variable_update") { // fetch BotVariables List for published Bots sdk.fetchBotVariable(data, langArr, function(err, response) { dataStore.saveAllVariables(response, langArr); first = false; }); } else { var lang = data.language; //update Existing BotVariables in Storage updateBotVariableInDataStore(botVariables, data, event, lang); } console.log(dataStore);

OnClientEvent

このイベントは、ボットがサード パーティ アプリケーションから送信されたクライアント イベントを受信すると、client_event でトリガーされます。構文: on_client_event : 関数 (requestId, data, callback) パラメータ:

  • requestId ー 各メッセージ イベントに固有の ID。
  • data— JSON のレスポンス ペイロードです
  • callback ー イベント完了時に呼び出される関数で、更新されたメッセージとコンテキストを ボット プラットフォームに送り返します。
on_client_event : function (requestId, data, callback) { console.log("on_client_event --> : ", data.preDefinedEvent, data.customEvent); return sdk.sendBotEvent(data, callback); }

これらのイベントは、BotKit のイベント タイプである onMessage および onagenttransfer をサブスクライブするアプリケーションに関連付けられています。これらのイベントは、ユーザーが入力している、ユーザーが入力を止めた、ユーザーがメッセージを読んだ、などのイベントを追跡するために使用できます。サンプル:

  • ユーザーが入力を開始したとき: リクエスト: { "resourceid": "/bot.clientEvent", "preDefinedEvent" : { "type": "TYPING_STARTED" }, "customEvent": {"test":"test"}, "botInfo": {"chatBot":"<bot-name>", "taskBotId":"<bot-id>"} } Response1: {"ok":true,"type":"ack"} Response2: {"type":"events", "from":"bot", "botInfo": {"chatBot":"<bot-name>", "taskBotId":"<bot-id>"} }, "preDefinedEvent":{"type":"TYPING_STARTED"}, "customEvent":{"test":"test"},"traceId":"6b12f4cc73c806dd"}
  • ユーザーが入力を停止したとき: リクエスト: { "resourceid": "/bot.clientEvent", "preDefinedEvent" : { "type": "TYPING_STOPPED" }, "customEvent": {"test":"test"}, "botInfo": {"chatBot":"<bot-name>", "taskBotId":"<bot-id>"} } Response1: {"ok":true,"type":"ack"} Response2: {"type":"events", "from":"bot", "botInfo": {"chatBot":"<bot-name>", "taskBotId":"<bot-id>"} }, "preDefinedEvent":{"type":"TYPING_STOPPED"}, "customEvent":{"test":"test"},"traceId":"6b12f4cc73c806dd"}
  • ユーザーがメッセージを既読にしたとき: リクエスト: { "resourceid": "/bot.clientEvent", "preDefinedEvent" : { "type": "MESSAGE_READ", "id": "<msg-id>" }, "customEvent": {"string"}, "botInfo": {"chatBot":"<bot-name>", "taskBotId":"<bot-id>"} } Response1: {"ok":true,"type":"ack"} Response2: {"type":"events", "from":"bot", "botInfo": {"chatBot":"<bot-name>", "taskBotId":"<bot-id>"} }, "preDefinedEvent":{"type":"MESSAGE_READ", "id":"<msg-id>"}, "customEvent":{"string"},"traceId":"6b12f4cc73c806dd"}
OVERVIEW
Virtual Assistants
Kore.ai Platform
Key Concepts
Natural Language Processing (NLP)
Accessing Platform
VIRTUAL ASSISTANTS
Virtual Assistant Builder
Virtual Assistant Types
Getting Started
Create a Simple Bot
SKILLS
Storyboard
Dialog Tasks
Introduction
Dialog Builder (New)
Dialog Builder (Legacy)
User Intent Node
Dialog Node
Entity Node
Supported Entity Types
Composite Entities
Supported Colors
Supported Company Names
Form Node
Logic Node
Message Nodes
Confirmation Nodes
Bot Action Node
Service Node
Custom Authentication
2-way SSL for Service nodes
Script Node
Agent Transfer Node
WebHook Node
Grouping Nodes
Connections & Transitions
Manage Dialogs
User Prompts
Knowledge Graph
Terminology
Building
Generation
Importing and Exporting
Analysis
Knowledge Extraction
Train
Build
Alert Tasks
Introduction
Ignore Words and Field Memory
How to Schedule a Smart Alert
Small Talk
Digital Views
Introduction
How to Configure Digital Views
Digital Forms
Overview
How to Configure Digital Forms
NATURAL LANGUAGE
Overview
Machine Learning
Introduction
Model Validation
Fundamental Meaning
Introduction
NLP Guidelines
Knowledge Graph
Traits
Introduction
How to Use Traits
Ranking and Resolver
Advanced NLP Configurations
INTELLIGENCE
Overview
Context Management
Overview
Session and Context Variables
Context Object
How to Manage Context Switching
Manage Interruptions
Dialog Management
Sub Intents & Follow-up Intents
Amend Entity
Multi-Intent Detection
Sentiment Management
Tone Analysis
Sentiment Management
Event Based Bot Actions
Default Conversations
Default Standard Responses
TEST & DEBUG
Talk to Bot
Utterance Testing
Batch Testing
Record Conversations
Conversation Testing
CHANNELS
PUBLISH
ANALYZE
Overview
Dashboard
Custom Dashboard
Overview
How to Create Custom Dashboard
Conversation Flows
NLP Metrics
ADVANCED TOPICS
Universal Bots
Overview
Defining
Creating
Training
Customizing
Enabling Languages
Store
Smart Bots
Defining
koreUtil Libraries
SETTINGS
Authorization
Language Management
PII Settings
Variables
Functions
IVR Integration
General Settings
Management
Import & Export
Delete
Bot Versioning
Collaborative Development
Plan Management
API GUIDE
API Overview
API List
API Collection
SDKs
SDK Overview
SDK Security
SDK App Registration
Web SDK Tutorial
Message Formatting and Templates
Mobile SDK Push Notification
Widget SDK Tutorial
Widget SDK – Message Formatting and Templates
Web Socket Connect & RTM
Using the BotKit SDK
Installing
Configuring
Events
Functions
BotKit SDK Tutorial – Agent Transfer
BotKit SDK Tutorial – Flight Search Sample Bot
Using an External NLP Engine
ADMINISTRATION
HOW TOs
Create a Simple Bot
Create a Banking Bot
Transfer Funds Task
Update Balance Task
Context Switching
Using Traits
Schedule a Smart Alert
Configure UI Forms
Add Form Data into Data Tables
Configuring Digital Views
Add Data to Data Tables
Update Data in Data Tables
Custom Dashboard
Custom Tags to filter Bot Metrics
Patterns for Intents & Entities
Build Knowledge Graph
Global Variables
Content Variables
Using Bot Functions
Configure Agent Transfer
RELEASE NOTES

Events for the BotKit SDK

You can use the Kore.ai BotKit SDK to capture and handle events in the Bots Platform for better control and customization of the bot experience for users. The following events are supported by the BotKit SDK:

onMessage

This event consists of the following two components:

  • onUserMessage: This event is triggered when a user sends a message to Bot and it is received by the channel adapter. The user message is wrapped in this event and sent to the SDK.
  • onBotMessage: This event is triggered when any messages need to be sent to the user. These messages are sent to the SDK along with context object.

onUserMessage

Syntax:

on_user_message : function(requestId, data, callback)

Parameters:

  • requestId – A unique ID for each message event.
  • payload – A JSON response payload as follows:
    {
       "message":"message sent by bot to the user",
       "taskId":"Dialog task Id",
       "nodeId":"current node id in the dialog flow",
       "channel":"channel name",
       "context":"context object"
    }
  • callback – The function to call at event completion used to send the updated message and context back to the Bots Platform.

Example:
In the following code example for the onUserMessage event, the user message is evaluated for transfer to a live agent and transferred, otherwise, the message is passed on to the BotKit SDK for processing.

/*
 * OnUserMessage event handler
 */
function onUserMessage(requestId, payload, callback){
    debug("user message", payload);
    var visitorId = _.get(payload, 'channel.from');
	visitorId = payload.context.session.UserContext._id;
	var entry = _map[visitorId];
	if (payload.message === "clearagent") // disconnect from LiveChat on user utterance
	{
		sdk.clearAgentSession(payload);
	}
    if(entry){//check for live agent
        //route to live agent
        var formdata = {};
        formdata.secured_session_id = entry.secured_session_id;
        formdata.licence_id = config.liveagentlicense;
        formdata.message = payload.message;
        return api.sendMsg(visitorId, formdata)
            .catch(function(e){
                console.error(e);
                delete userDataMap[visitorId];
                delete _map[visitorId];
                return sdk.sendBotMessage(payload, callback);
            });
    }
    else {
        return sdk.sendBotMessage(payload, callback);
    }
}

onBotMessage

Syntax:

 on_bot_message : function(requestId, data, callback)

Parameters:

  • requestId – A unique ID for each message event.
  • payload – A JSON response payload as follows:
    {
       "message":"message sent to the user",
       "channel":"channel name",
       "context":"context object"
    }
  • callback – The function to call at event completion used to send the updated message and context back to the user.

Example:
The following code snippet onBotMessage event evaluates the user message for content and then for message tone. If the message tone is greater than or equal to 2 for the angry tone, then the bot communication between the user and the bot is switched to a live agent.

/*
 * onBotMessage event handler
 */
function onBotMessage(requestId, payload, callback){
    debug("Bot Message Data",payload);
	console.log("in bot message");
    var visitorId = _.get(paylod, 'channel.from');
    var entry = _map[visitorId];
    if(data.message.length === 0 || payload.message === '') {
        return;
    }
    var message_tone = _.get(payload, 'context.message_tone');console.log("message tone -----",message_tone);
    if(message_tone && message_tone.length> 0){
        var angry = _.filter(message_tone, {tone_name: 'angry'});
        if(angry.length){
            angry = angry[0];
            if(angry.level >=2){
              return  connectToAgent(requestId, data);
            }
        }
    }
    if(!entry)
    {
        sdk.sendUserMessage(payload, callback);
    }
}

onWebHook

This event is triggered when the Kore NL Engine processes the Webhook node in the dialog flow. This event is sent to the SDK with componentId and context. The SDK can execute business logic and send the updated context back to the platform.
Syntax:

on_webhook = function(requestId, componentId, payload, callback)

Parameters:

  • requestId – A unique ID for each webhook event.
  • componentId – The unique ID for the SDKWebhook node.
  • payload – A JSON response payload as follows:
    {
       "message":"message sent by bot to the Bots platform",
       "taskId":"Dialog task Id",
       "nodeId":"current node id in the dialog flow",
       "channel":"channel name",
       "context":"context object"
    }
  • callback – The function to call at event completion used to send the updated message and context back to the Bots Platform.

Examples
In the following example for the on_webhook event, two hotel names are returned as results as a response to user input.

    //on_webhook handler
    on_webhook  : function(requestId, payload, componentId, callback) {
        if (componentId === 'sendResponse') {
          var hotels = {
            "hotels":[
                  "Taj Banjara",
                  "Novotel"
            ]
          };
          payload.context.hotelResults = hotels;
          callback(null,data);
        }
    }

In this example for the on_webhook event, for the Flights Info node in a dialog task, either a list of departure or destination airports based on the requested date is returned based on the flow of the dialog, as a list of results displayed to the end user.

    on_webhook : function(requestId, payload, componentId, callback) {
        var context = payload.context;
	    if (componentName === 'FlightsInfo') {
		  var origin = context.entities.Source;
          var destination = context.entities.Dest;
          var departureDate = context.entities.Date;
          findFlights(origin,destination,departureDate)
			.then(function(flightResults) {
                payload.context.flightResults = flightResults;
				callback(null, data);
			});
	    } else if(componentId === 'GetSourceAirports'){
             var searchTerm = context.entities.SourceName;
             findAirports(searchTerm)
            .then(function(airportResults) {
                payload.context.sourceAirports = airportResults;
                callback(null, data);
            });
        } else if(componentId === 'GetDestAirports'){
           var searchTerm = context.entities.DestName;
             findAirports(searchTerm)
            .then(function(airportResults) {
                payload.context.destAirports = airportResults;
                callback(null, data);
            });
        }

onAgentTransfer

This event is triggered when the Kore NL Engine processes an Agent Transfer node in the dialog flow. This event is sent to the SDK with requestId and context. The SDK can execute a business logic to switch the user seamlessly to a Live Agent.
Syntax:

function onAgentTransfer(requestId, data, callback){
connectToAgent(requestId, data, callback);
}

Parameters:

  • requestId – A unique ID for each message event.
  • payload – A JSON response payload as follows:
    {
       OnAgentTransferPayload ","
          requestId ":1501244156289,"
          botId ":"st - b4a22e86 - e95b - 575 c - b888 - e106d083a251 ","
          callbackUrl ":"https: //bots.kore.ai/api/botsdk/stream/st-b4a22e86-e95b-575c-b888-e106d083a251/serviceCallback/1501244156289","context": ...
    }
  • callback – The function to call at event completion used to send the updated message and context back to the Bots Platform.

Example:
The following code snippet onAgentTransfer event connects the user to a Live Agent and passing the user message, bot message, and historical chat messages of the session.

function connectToAgent(requestId, data, cb){
var formdata = {}; console.log("userlog",JSON.stringify(data.context.session.UserContext._id));
formdata.licence_id = config.liveagentlicense;
formdata.welcome_message = "";
var visitorId = _.get(data, 'channel.channelInfos.from');
if(!visitorId){
visitorId = _.get(data, 'channel.from');
}
visitorId = data.context.session.UserContext._id;
userDataMap[visitorId] = data;
data.message="An Agent will be assigned to you shortly!!!";
var d = new Date();
data.context.session.BotUserSession.startTime = new Date().toLocaleString();
console.log("userlog",JSON.stringify(data.context.session));
sdk.sendUserMessage(data, cb);
formdata.welcome_message = "Link for user Chat history with bot: "+ config.app.url +"/history/index.html?visitorId=" + visitorId;
return api.initChat(visitorId, formdata)
.then(function(res){
_map[visitorId] = {
secured_session_id: res.secured_session_id,
visitorId: visitorId,
last_message_id: 0
};
});
}

OnEvent

This event is triggered when Dialog Task or FAQ ends in the bot and sends request ID and context to the SDK.
Syntax:
on_event : function (requestId, data, callback)
Parameters:

  • requestId – A unique ID for each message event.
  • data– A JSON response payload as shown in the example below:
  • callback – The function to call after event completion; it is used to send the updated message and context back to the Bots Platform.

Example:

on_event : function (requestId, data, callback)
{
return sdk.sendAlertMessage(data, callback);
}

The event adds the following code in the Data object sent to kit:

"event":
{
"event Type": "endDialog"/ “endFAQ”
}

OnAlert

This event is triggered when a bot user receives an alert.
Syntax:
on_alert : function (requestId, data, callback)
Parameters:

  • requestId – A unique ID for each message event.
  • data– A JSON response payload.
  • callback – The function to call at event completion; it is used to send the updated message and context back to the Bots Platform.

Example:

on_alert: function(requestId, data, callback)
{
 return sdk.sendAlertMessage(data, callback);
}

The alert response data is found in the data object sent to the kit.

OnVariableUpdate

This event is triggered on variable_update when Bot is published.

Syntax:
variable_update : function (requestId, data, callback)
Parameters:

  • requestId – A unique ID for each message event.
  • data– A JSON response payload
  • callback – The function to call after event completion; it is used to send the updated message and context back to the Bots Platform.
var event = data.eventType;
console.log("event----------->", event);
if (first || event == "variable_update") {
// fetch BotVariables List for published Bots
sdk.fetchBotVariable(data, langArr, function(err, response) {
dataStore.saveAllVariables(response, langArr);
first = false;
});
} else {
var lang = data.language;
//update Existing BotVariables in Storage
updateBotVariableInDataStore(botVariables, data, event, lang);
}
console.log(dataStore);

OnClientEvent

This event is triggered on client_event when Bot receives client events sent by the third party application.

Syntax:
on_client_event : function (requestId, data, callback)
Parameters:

  • requestId – A unique ID for each message event.
  • data– A JSON response payload
  • callback – The function to call after event completion; it is used to send the updated message and context back to the Bots Platform.
on_client_event : function (requestId, data, callback) {
    console.log("on_client_event -->  : ", data.preDefinedEvent, data.customEvent);
    return sdk.sendBotEvent(data, callback);
    }

These events are associated with the application subscribing to botkit event type – onMessage and onagenttransfer. These event can be used to track the events like user is typing, user has stopped typing or user has read the message.

Examples:

  • User started typing:
    Request:
    { “resourceid”: “/bot.clientEvent”,
    “preDefinedEvent” : { “type”: “TYPING_STARTED” },
    “customEvent”: {“test”:”test”},
    “botInfo”: {“chatBot”:”<bot-name>”,
    “taskBotId”:”<bot-id>”} }
    Response1:
    {“ok”:true,”type”:”ack”}
    Response2:
    {“type”:”events”,
    “from”:”bot”,
    “botInfo”: {“chatBot”:”<bot-name>”, “taskBotId”:”<bot-id>”} },
    “preDefinedEvent”:{“type”:”TYPING_STARTED”},
    “customEvent”:{“test”:”test”},”traceId”:”6b12f4cc73c806dd”}
  • User stopped typing:
    Request:
    { “resourceid”: “/bot.clientEvent”,
    “preDefinedEvent” : { “type”: “TYPING_STOPPED” },
    “customEvent”: {“test”:”test”},
    “botInfo”: {“chatBot”:”<bot-name>”,
    “taskBotId”:”<bot-id>”} }
    Response1:
    {“ok”:true,”type”:”ack”}
    Response2:
    {“type”:”events”,
    “from”:”bot”,
    “botInfo”: {“chatBot”:”<bot-name>”, “taskBotId”:”<bot-id>”} },
    “preDefinedEvent”:{“type”:”TYPING_STOPPED”},
    “customEvent”:{“test”:”test”},”traceId”:”6b12f4cc73c806dd”}
  • User read the message:
    Request:
    { “resourceid”: “/bot.clientEvent”,
    “preDefinedEvent” : { “type”: “MESSAGE_READ”, “id”: “<msg-id>” },
    “customEvent”: {“string”},
    “botInfo”: {“chatBot”:”<bot-name>”,
    “taskBotId”:”<bot-id>”} }
    Response1:
    {“ok”:true,”type”:”ack”}
    Response2:
    {“type”:”events”,
    “from”:”bot”,
    “botInfo”: {“chatBot”:”<bot-name>”, “taskBotId”:”<bot-id>”} },
    “preDefinedEvent”:{“type”:”MESSAGE_READ”, “id”:”<msg-id>”},
    “customEvent”:{“string”},”traceId”:”6b12f4cc73c806dd”}