1. Home
  2. Kore.ai Conversational Platform
  3. SDKs & APIs
  4. Using the BotKit SDK
  5. Functions for the BotKit SDK

Functions for the BotKit SDK

The Kore.ai BotKit SDK provides functions that you can use for greater control of your bot and provide a better user experience.

The following functions are supported by the BotKit SDK.

  • sdk.sendUserMessage
  • sdk.sendBotMessage
  • sdk.AsyncResponse
  • sdk.respondToHook
  • sdk.saveData
  • sdk.registerBot
  • sdk.getSavedData
  • sdk.getMessages
  • sdk.clearAgentSession
  • sdk.Promise
  • sdk.resetBot
  • sdk.startAgentSession
  • sdk.closeAgentSession
  • sdk.getChatSession

sdk.sendUserMessage

This function sends the message to the bot user.

Usage

Used inside the on_bot_message event callback. An on_bot_message event is called when the bot sends the reply to the user. In the SDK, payload data such as message can be modified and sent to the Bots Platform.

Syntax:

sdk.sendUserMessage(payload, callback)

Parameters:

  • 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.

Examples

The following code snippet show an example of the sdk.sendUserMessage function returning an error to the user.

return sdk.sendUserMessage(payload, function(err){
    if(err)
       console.log("err", err);

In the following code example, the initial message to a user is displayed when a user switches to a Live Agent.

    formdata.welcome_message = "";
    var visitorId = _.get(payload, 'channel.channelInfos.from');
    if (!visitorId) {
        visitorId = _.get(payload, 'channel.from');
    }
    visitorId = payload.context.session.UserContext._id;
    userDataMap[visitorId] = payload;
    data.message = "An Agent will be assigned to you shortly!!!";
    sdk.sendUserMessage(payload, callback);

In the next code example, the message sent to the user with the sdk.sendUserMessage function is based on user selection for converting currency. The isTemplate parameter determines if custom or default message formatting should be used.

    on_user_message : function(requestId, payload, callback) {
		message = payload.message.toLowerCase();console.log("MESSAGE",payload.message);
		//payload .context.session.BotContext.currency = "koko";
		if ( message == "Yes" || message == "yes")
		{ 
			var overrideMessagePayload = {
				body : " Enter the currency code for which the amount will be converted",
				isTemplate :false
			};
			data.overrideMessagePayload = overrideMessagePayload;
			currCode = true;
			return sdk.sendUserMessage(payload);
		}
		else if ( message == "No" || message == "no" )
		{
			 var overrideMessagePayload = {
				body : "Ok, Enter the country name so that I can fetch it on your behalf",
				isTemplate :false
			};
			payload.overrideMessagePayload = overrideMessagePayload;
			countryname = true;
			return sdk.sendUserMessage(payload);

sdk.sendBotMessage

This function sends the message to the bot.

Usage

Used inside the on_user_message event callback. An on_user_message event is called when the user sends a message to the bot. In the SDK, payload data such as message can be modified and sent to the Bots Platform.

Syntax:

sdk.sendBotMessage(payload, callback)

Parameters:

  • payload – A JSON response payload as follows:
     {  
       "message":"Message sent by 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 Bots Platform.

Examples

The following code snippet send the user response to the bot.

    on_user_message: function(requestId, payload, callback) {
        sdk.sendBotMessage(payload, callback);
    },

In this on_user_message function, the message is returned directly to the user, and if not a transfer to a Live Agent, then is sent to the bot.

    on_user_message: function(requestId, payload, callback) {
        if (payload.message === "Hi") {
            payload.message = "Hello";
            //Sends back 'Hello' to user.
            return sdk.sendUserMessage(payload, callback);
        } else if (!payload.agent_transfer) {
            //Forward the message to bot
            return sdk.sendBotMessage(payload, callback);
        } else {
            payload.message = "Agent Message";
            return sdk.sendUserMessage(payload, callback);
        }
    },

sdk.AsyncResponse

This function prepares the asynchronous response to send to the Bots Platform.

Usage

If the dialog task execution flow reaches a webhook node, the Bots Platform makes an on_webhook event call to the SDK. The on_webhook event call supports two type of responses:

  • Synchronous response – If the business logic execution can be completed within an acceptable time, the SDK can respond synchronously using the callback(null, payload) function.
  • Asynchronous response – If the business logic execution needs more time, the SDK can send the asynchronous response to the Bots Platform by calling the callback(null, new sdk.AsyncResponse()) function to send an HTTP code 202 to the Bots Platform. When the response is ready, the SDK can call the sdk.respondToHook(payload) function.

Syntax:

sdk.AsyncResponse()
callback(null, new sdk.AsyncResponse())

Parameters:

None.

Examples

This example of an on_webhook function, the Bot waits asynchronously for the booking of the cab selected by the user.

on_webhook : function(requestId, payload, componentName, callback) {
        var context = payload.context;

        if (componentName === 'FindNearbyCabs') {
            findCabs()
                .then(function(cabList) {
                    context.cabList = cabList;
                    callback(null, data);
                });
        } else if (componentName === 'BookTheCab') {
            sdk.saveData(requestId, payload)
                .then(function() {
                    bookTheCab(requestId, context.entities.selectedCab.id, context.session.UserSession.location, context.entities.whereTo);
                    callback(null, new sdk.AsyncResponse());
                });
        }
    }

sdk.respondToHook

This function sends the webhook response to the Bots Platform.

Usage

If the dialog task execution flow reaches a webhook node, the Bots Platform makes an on_webhook event call to the SDK. The on_webhook event call supports two type of responses:

  • Synchronous response – If the business logic execution can be completed within an acceptable time, the SDK can respond synchronously using the callback(null, payload) function.
  • Asynchronous response – If the business logic execution needs more time, the SDK can send the asynchronous response to the Bots Platform by calling the callback(null, new sdk.AsyncResponse()) function to send an HTTP code 202 to the Bots Platform. When the response is ready, the SDK can call the sdk.respondToHook(payload) function.

Syntax:

sdk.respondToHook(payload)

Parameters:

  • payload – A JSON response payload as follows:
     {  
       "taskId":"Dialog task ID",
       "nodeId":"Current node ID in the dialog flow",
       "channel":"Channel name",
       "context": <context object>
    }

Examples

In the following code snippet, if the booking of the cab fails, the event is handled synchronously. Conversely, the booking of the cab is handled asynchronously via a webhook.

function onBookingFailure(requestId) {
    sdk.getSavedData(requestId)
        .then(function(payload) {
            payload.context.successful = false;

            sdk.respondToHook(payload);
        });
}

//call cabBookingService with the requestId. This service is expected to respond asynchronously.
//'requestId' must be passed along all asynchronous flows, to allow the BotKit to respond
// back to the hook once the async process is completed.
function bookTheCab(requestId, cabId, userLoc, destination) {
    cabBookingService(requestId, cabId, userLoc, destination, {
        on_success: onBookingSuccess,
        on_failure: onBookingFailure
    });
}

sdk.registerBot

This function registers the bot and makes callback events available at runtime.

Usage

The BotKit SDK is designed to require you to create one Node.js file for each bot. All callbacks for that bot are maintained in the Node.js file. To register a bot, you must export the following variables and functions as:

module.exports = {

      botId : “xxxxx”,

      botName : ““xxxxx”,

      on_user_message : function(requestId, data, callback) {

           //code goes here

      },

      on_bot_message : function(requestId, data, componentName, callback) {

           //code goes here

      },

     on_webhook : function(requestId, data, componentName, callback) {

           //code goes here

      },

}

Syntax:

To register the bot, call

sdk.registerBot(require('./<Bot Name>.js'));

Parameters:

  • Node.js file for the bot to register

Examples

The following code example shows registration of the bot by botId and botName.

module.exports = {
    botId : botId,
    botName : botName,
    on_user_message : function(requestId, payload, callback) {
        debug('on_user_message');
        onUserMessage(requestId, payload, callback);
    },
    on_bot_message : function(requestId, payload, callback) {
        debug('on_bot_message');
        onBotMessage(requestId, payload, callback);
    },
    on_agent_transfer : function(requestId, payload, callback) { console.log("on agent transfer event");
        debug('on_webhook');
        onAgentTransfer(requestId, payload, callback);
    },
    gethistory: gethistory
};

sdk.saveData

This function saves the data in the Redis in-memory data structure store.

Usage

When you respond to an on_webhook event call asynchronously, you can store the payload in the Redis store by requestId. After completion of your business logic execution, you can read the data using the sdk.getSavedData(requestId)function while preparing the webhook response.

Syntax:

sdk.saveData(requestId, payload)

Parameters:

  • requestId – The requestId from the asynchronous on_webhook event call.
  • payload – A JSON response payload as follows:
     {  
       "taskId":"Dialog task ID",
       "nodeId":"Current node ID in the dialog flow",
       "channel":"Channel name",
       "context": <context object>
    }

Examples

In this on_webhook event, the user request to book a cab is saved in the Redis store and the asynchronous processing of the booking begins.

on_webhook : function(requestId, payload, componentId, callback) {
        var context = data.context;

        if (componentId === 'FindNearbyCabs') {
            findCabs()
                .then(function(cabList) {
                    context.cabList = cabList;
                    callback(null, payload);
                });
        } else if (componentName === 'BookTheCab') {
            sdk.saveData(requestId, payload)
                .then(function() {
                    //Assuming the cab booking was successful. A mock service to book the cab can be called here.
                    payload.successful = 'true';
                    payload.bookedCab = context.entities.selectedCab || {};
                    callback(null, payload);
                });
        }
    }

sdk.getSavedData

This function reads the data in the Redis in-memory data structure store.

Usage

When you respond to an on_webhook event call asynchronously, you can store the payload in the Redis store by requestId. After completion of your business logic execution, you can read the data using the sdk.getSavedData(requestId)function while preparing the webhook response.

Syntax:

sdk.getSavedData(requestId, payload)

Parameters:

  • requestId – The requestId from the asynchronous on_webhook event call.
  • payload – A JSON response payload as follows:
     {  
       "taskId":"Dialog task ID",
       "nodeId":"Current node ID in the dialog flow",
       "channel":"Channel name",
       "context": <context object>
    }

Examples

In this code example, the sdk.getSavedData function is used to return the selected cab and booking information, or if the asynchronous booking webhook event fails, sends the failure message for the selected booking to the user.

/*/
 * Responds to the webhook asynchronously with the success flag.
 */
function onBookingSuccess(requestId) {
    sdk.getSavedData(requestId)
        .then(function(payload) {
            payload.context.bookedCab = payload.entities.selectedCab;
            payload.context.successful = true;

            sdk.respondToHook(payload);
        });
}

function onBookingFailure(requestId) {
    sdk.getSavedData(requestId)
        .then(function(payload) {
            payload.context.successful = false;

            sdk.respondToHook(payload);
        });
}

sdk.registerBot

This function is used to…

Usage

Coming soon.

Syntax:

sdk.registerBot()

Parameters:

  • coming soon – The .
  • coming soon – The .

Examples

sdk.registerBot(require('./FindAFlight.js'));
sdk.registerBot(require('./SimpleConversationalBot.js'));
sdk.registerBot(require('./GuessTheNumber.js'));
sdk.registerBot(require('./BookACab.js'));
sdk.registerBot(require('./OrderAPizza.js'));
Was this article helpful to you? Yes No