{"id":17999,"date":"2017-08-08T17:23:12","date_gmt":"2017-08-08T17:23:12","guid":{"rendered":"http:\/\/developer.kore.ai\/developer-2\/?post_type=docs&#038;p=11758"},"modified":"2021-03-26T06:05:06","modified_gmt":"2021-03-26T06:05:06","slug":"functions-for-the-botkit-sdk","status":"publish","type":"post","link":"https:\/\/developer.kore.ai\/v7-0\/docs\/bots\/sdks\/functions-for-the-botkit-sdk\/","title":{"rendered":"Functions for the BotKit SDK"},"content":{"rendered":"<section class=\"l-section wpb_row height_auto\"><div class=\"l-section-h i-cf\"><div class=\"g-cols vc_row type_default valign_top\"><div class=\"vc_col-sm-12 wpb_column vc_column_container\"><div class=\"vc_column-inner\"><div class=\"wpb_wrapper\">\r\n\t<div class=\"wpb_text_column \">\r\n\t\t<div class=\"wpb_wrapper\">\r\n\t\t\t<p>The Kore.ai BotKit SDK provides functions that you can use for greater control of your bot and provide a better user experience.<br \/>\nThe following functions are supported by the BotKit SDK.<\/p>\n<ul>\n<li><a href=\"#sdk-sendusermessage\">sdk.sendUserMessage<\/a><\/li>\n<li><a href=\"#sdk-sendbotmessage\">sdk.sendBotMessage<\/a><\/li>\n<li><a href=\"#sdk-asyncresponse\">sdk.AsyncResponse<\/a><\/li>\n<li><a href=\"#sdk-respondtohook\">sdk.respondToHook<\/a><\/li>\n<li><a href=\"#sdk-savedata\">sdk.saveData<\/a><\/li>\n<li><a href=\"#sdk-registerbot\">sdk.registerBot<\/a><\/li>\n<li><a href=\"#sdk-getsaveddata\">sdk.getSavedData<\/a><\/li>\n<li><a href=\"#sdk-getmessages\">sdk.getMessages<\/a><\/li>\n<li><a href=\"#sdk-resetbot\">sdk.resetBot<\/a><\/li>\n<li><a href=\"#sdk-startagentsession\">sdk.startAgentSession<\/a><\/li>\n<li><a href=\"#sdk-clearagentsession\">sdk.clearAgentSession<\/a><\/li>\n<li><a href=\"#sdk-extendRequestId\">sdk.extendRequestId<\/a><\/li>\n<\/ul>\n<h2 id=\"sdk-sendusermessage\"><span class=\"ez-toc-section\" id=\"sdksendUserMessage\"><em>sdk.sendUserMessage<\/em><\/span><\/h2>\n<p>This\u00a0function sends the message to the bot user.<br \/>\n<strong>Usage<\/strong><br \/>\nUsed inside the <code>on_bot_message<\/code> event callback. An <code>on_bot_message<\/code> event is\u00a0called when the bot sends the reply to the user. In the SDK, payload data such as <code>message<\/code> can be modified and sent to the Bots Platform.<br \/>\n<strong>Syntax<\/strong><\/p>\n<pre class=\"lang:default decode:true\">sdk.sendUserMessage(payload, callback)<\/pre>\n<p><strong>&gt;Parameters:<\/strong><\/p>\n<ul>\n<li><code>payload<\/code> &#8211; A JSON response payload as follows:\n<pre class=\"lang:default decode:true\"> {\r\n   \"message\":\"Message sent by bot to the user\",\r\n   \"taskId\":\"Dialog task ID\",\r\n   \"nodeId\":\"Current node ID in the dialog flow\",\r\n   \"channel\":\"Channel name\",\r\n   \"context\": &lt;context object&gt;\r\n}\r\n<\/pre>\n<\/li>\n<li><code>callback<\/code> &#8211; The function to call at event completion used to send the updated message and context back to the Bots Platform.<\/li>\n<\/ul>\n<p><strong>Examples<\/strong><br \/>\nThe following code snippet shows an example of the <code>sdk.sendUserMessage<\/code> function returning an error to the user.<\/p>\n<pre class=\"lang:default decode:true\">return sdk.sendUserMessage(payload, function(err){\r\n    if(err)\r\n       console.log(\"err\", err);<\/pre>\n<p>In the following code example, the initial message to a user is displayed when a user switches to a Live Agent.<\/p>\n<pre class=\"lang:default decode:true\">    formdata.welcome_message = \"\";\r\n    var visitorId = _.get(payload, 'channel.channelInfos.from');\r\n    if (!visitorId) {\r\n        visitorId = _.get(payload, 'channel.from');\r\n    }\r\n    visitorId = payload.context.session.UserContext._id;\r\n    userDataMap[visitorId] = payload;\r\n    data.message = \"An Agent will be assigned to you shortly!!!\";\r\n    sdk.sendUserMessage(payload, callback);<\/pre>\n<p>In the next code example, the message sent to the user with the <code>sdk.sendUserMessage<\/code> function is based on user selection for converting currency. The <code>isTemplate<\/code> parameter determines if custom or default message formatting should be used.<\/p>\n<pre class=\"lang:default decode:true\">    on_user_message : function(requestId, payload, callback) {\r\n\t\tmessage = payload.message.toLowerCase();console.log(\"MESSAGE\",payload.message);\r\n\t\t\/\/payload .context.session.BotContext.currency = \"koko\";\r\n\t\tif ( message == \"Yes\" || message == \"yes\")\r\n\t\t{\r\n\t\t\tvar overrideMessagePayload = {\r\n\t\t\t\tbody : \" Enter the currency code for which the amount will be converted\",\r\n\t\t\t\tisTemplate :false\r\n\t\t\t};\r\n\t\t\tdata.overrideMessagePayload = overrideMessagePayload;\r\n\t\t\tcurrCode = true;\r\n\t\t\treturn sdk.sendUserMessage(payload);\r\n\t\t}\r\n\t\telse if ( message == \"No\" || message == \"no\" )\r\n\t\t{\r\n\t\t\t var overrideMessagePayload = {\r\n\t\t\t\tbody : \"Ok, Enter the country name so that I can fetch it on your behalf\",\r\n\t\t\t\tisTemplate :false\r\n\t\t\t};\r\n\t\t\tpayload.overrideMessagePayload = overrideMessagePayload;\r\n\t\t\tcountryname = true;\r\n\t\t\treturn sdk.sendUserMessage(payload);<\/pre>\n<h2 id=\"sdk-sendbotmessage\"><span class=\"ez-toc-section\" id=\"sdksendBotMessage\"><em>sdk.sendBotMessage<\/em><\/span><\/h2>\n<p><span style=\"font-weight: 400\">This\u00a0function sends the message to the bot.<\/span><br \/>\n<strong>Usage<\/strong><br \/>\nUsed inside the <code>on_user_message<\/code> event callback. An <code>on_user_message<\/code> event is\u00a0called when the user\u00a0sends a message to the bot. In the SDK, payload data such as <code>message<\/code> can be modified and sent to the Bots Platform.<br \/>\n<strong>Syntax:<\/strong><\/p>\n<pre class=\"lang:default decode:true\">sdk.sendBotMessage(payload, callback)<\/pre>\n<p><strong>Parameters:<\/strong><\/p>\n<ul>\n<li><code>payload<\/code> &#8211; A JSON response payload as follows:\n<pre class=\"lang:default decode:true\"> {\r\n   \"message\":\"Message sent by the user\",\r\n   \"channel\":\"Channel name\",\r\n   \"context\": &lt;context object&gt;\r\n}\r\n<\/pre>\n<\/li>\n<li><code>callback<\/code> &#8211; The function to call at event completion used to send the updated message and context back to the Bots Platform.<\/li>\n<\/ul>\n<p><strong>Examples<\/strong><br \/>\nThe following code snippet send the user response to the bot.<\/p>\n<pre class=\"lang:default decode:true\">    on_user_message: function(requestId, payload, callback) {\r\n        sdk.sendBotMessage(payload, callback);\r\n    },<\/pre>\n<p>In this <code>on_user_message<\/code> function, the message is returned directly to the user, and if not a transfer to a Live Agent, then is sent to the bot.<\/p>\n<pre class=\"lang:default decode:true\">    on_user_message: function(requestId, payload, callback) {\r\n        if (payload.message === \"Hi\") {\r\n            payload.message = \"Hello\";\r\n            \/\/Sends back 'Hello' to user.\r\n            return sdk.sendUserMessage(payload, callback);\r\n        } else if (!payload.agent_transfer) {\r\n            \/\/Forward the message to bot\r\n            return sdk.sendBotMessage(payload, callback);\r\n        } else {\r\n            payload.message = \"Agent Message\";\r\n            return sdk.sendUserMessage(payload, callback);\r\n        }\r\n    },<\/pre>\n<h2 id=\"sdk-asyncresponse\"><span class=\"ez-toc-section\" id=\"sdkAsyncResponse\"><em>sdk.AsyncResponse<\/em><\/span><\/h2>\n<p><span style=\"font-weight: 400\">This\u00a0function\u00a0prepares the asynchronous response to send\u00a0to the Bots Platform. <\/span><br \/>\n<strong>Usage<\/strong><br \/>\nIf the dialog task execution flow reaches a webhook node, the Bots Platform makes an <code>on_webhook<\/code> event call to the SDK. The <code>on_webhook<\/code> event call supports two types of responses:<\/p>\n<ul>\n<li><strong>Synchronous response<\/strong> &#8211; If the business logic execution can be completed within an acceptable time, the SDK can respond synchronously using the <code>callback(null, payload)<\/code> function.<\/li>\n<li><strong>Asynchronous response<\/strong> &#8211; If the business logic execution needs more time, the SDK can send the asynchronous response to the Bots Platform by calling the <code>callback(null, new sdk.AsyncResponse())<\/code> function\u00a0to send an HTTP code 202 to the Bots Platform.\u00a0When the response is ready, the SDK can call the <code>sdk.respondToHook(payload)<\/code> function.<\/li>\n<\/ul>\n<p><strong>Syntax:<\/strong><\/p>\n<pre class=\"lang:default decode:true \">sdk.AsyncResponse()\r\ncallback(null, new sdk.AsyncResponse())<\/pre>\n<p><strong>Parameters:<\/strong><br \/>\nNone.<br \/>\n<strong>Examples<\/strong><br \/>\nThis example of an <code>on_webhook<\/code> function, the Bot waits asynchronously for the booking of the cab selected by the user.<\/p>\n<pre class=\"lang:default decode:true\">on_webhook : function(requestId, payload, componentName, callback) {\r\n        var context = payload.context;\r\n        if (componentName === 'FindNearbyCabs') {\r\n            findCabs()\r\n                .then(function(cabList) {\r\n                    context.cabList = cabList;\r\n                    callback(null, data);\r\n                });\r\n        } else if (componentName === 'BookTheCab') {\r\n            sdk.saveData(requestId, payload)\r\n                .then(function() {\r\n                    bookTheCab(requestId, context.entities.selectedCab.id, context.session.UserSession.location, context.entities.whereTo);\r\n                    callback(null, new sdk.AsyncResponse());\r\n                });\r\n        }\r\n    }<\/pre>\n<h2 id=\"sdk-respondtohook\"><span class=\"ez-toc-section\" id=\"sdkrespondToHook\"><em>sdk.respondToHook<\/em><\/span><\/h2>\n<p><span style=\"font-weight: 400\">This\u00a0function sends the webhook response\u00a0to the Bots Platform.<\/span><br \/>\n<strong>Usage<\/strong><br \/>\nIf the dialog task execution flow reaches a webhook node, the Bots Platform makes an <code>on_webhook<\/code> event call to the SDK. The <code>on_webhook<\/code> event call supports two types of responses:<\/p>\n<ul>\n<li><strong>Synchronous response<\/strong> &#8211; If the business logic execution can be completed within an acceptable time, the SDK can respond synchronously using the <code>callback(null, payload)<\/code> function.<\/li>\n<li><strong>Asynchronous response<\/strong> &#8211; If the business logic execution needs more time, the SDK can send the asynchronous response to the Bots Platform by calling the <code>callback(null, new sdk.AsyncResponse())<\/code> function\u00a0to send an HTTP code 202 to the Bots Platform.\u00a0When the response is ready, the SDK can call the <code>sdk.respondToHook(payload)<\/code> function.<\/li>\n<\/ul>\n<p><strong>Syntax:<\/strong><\/p>\n<pre class=\"lang:default decode:true\">sdk.respondToHook(payload)<\/pre>\n<p><strong>Parameters:<\/strong><\/p>\n<ul>\n<li><code>payload<\/code> &#8211; A JSON response payload as follows:\n<pre class=\"lang:default decode:true\"> {\r\n   \"taskId\":\"Dialog task ID\",\r\n   \"nodeId\":\"Current node ID in the dialog flow\",\r\n   \"channel\":\"Channel name\",\r\n   \"context\": &lt;context object&gt;\r\n}<\/pre>\n<\/li>\n<\/ul>\n<p><strong>Examples<\/strong><br \/>\nIn 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.<\/p>\n<pre class=\"lang:default decode:true\">function onBookingFailure(requestId) {\r\n    sdk.getSavedData(requestId)\r\n        .then(function(payload) {\r\n            payload.context.successful = false;\r\n            sdk.respondToHook(payload);\r\n        });\r\n}\r\n\/\/call cabBookingService with the requestId. This service is expected to respond asynchronously.\r\n\/\/'requestId' must be passed along all asynchronous flows, to allow the BotKit to respond\r\n\/\/ back to the hook once the async process is completed.\r\nfunction bookTheCab(requestId, cabId, userLoc, destination) {\r\n    cabBookingService(requestId, cabId, userLoc, destination, {\r\n        on_success: onBookingSuccess,\r\n        on_failure: onBookingFailure\r\n    });\r\n}<\/pre>\n<h2 id=\"sdk-registerbot\"><span class=\"ez-toc-section\" id=\"sdkregisterBot\"><em>sdk.registerBot<\/em><\/span><\/h2>\n<p><span style=\"font-weight: 400\">This\u00a0function registers the bot and makes callback events available at runtime.<\/span><br \/>\n<strong>Usage<\/strong><br \/>\nThe BotKit SDK is designed to require you to create one <span style=\"color: #0000ff\">Node.js<\/span> file for each bot. All callbacks for that bot are maintained in the <span style=\"color: #0000ff\">Node.js<\/span> file. To register a bot, you must export the following variables and functions as:<\/p>\n<pre class=\"lang:default decode:true \">module.exports = {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0botId : \u201cxxxxx\u201d,\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0botName : \u201c\u201cxxxxx\u201d,\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0on_user_message : function(requestId, data, callback) {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\/\/code goes here\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0},\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0on_bot_message : function(requestId, data, componentName, callback) {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\/\/code goes here\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0},\r\n\u00a0\u00a0\u00a0\u00a0\u00a0on_webhook : function(requestId, data, componentName, callback) {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\/\/code goes here\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0},\r\n}<\/pre>\n<p><strong>Syntax:<\/strong><br \/>\nTo register the bot, call<\/p>\n<pre class=\"lang:default decode:true\">sdk.registerBot(require('.\/&lt;Bot Name&gt;.js'));<\/pre>\n<p><strong>Parameters:<\/strong><\/p>\n<ul>\n<li><span style=\"font-family: monospace, serif\">Node.js file for the bot to register<\/span><\/li>\n<\/ul>\n<p><strong>Examples<\/strong><br \/>\nThe following code example shows registration of the bot by <code>botId<\/code> and <code>botName<\/code>.<\/p>\n<pre class=\"lang:default decode:true\">module.exports = {\r\n    botId : botId,\r\n    botName : botName,\r\n    on_user_message : function(requestId, payload, callback) {\r\n        debug('on_user_message');\r\n        onUserMessage(requestId, payload, callback);\r\n    },\r\n    on_bot_message : function(requestId, payload, callback) {\r\n        debug('on_bot_message');\r\n        onBotMessage(requestId, payload, callback);\r\n    },\r\n    on_agent_transfer : function(requestId, payload, callback) { console.log(\"on agent transfer event\");\r\n        debug('on_webhook');\r\n        onAgentTransfer(requestId, payload, callback);\r\n    },\r\n    gethistory: gethistory\r\n};<\/pre>\n<h2 id=\"sdk-savedata\"><span class=\"ez-toc-section\" id=\"sdksaveData\"><em>sdk.saveData<\/em><\/span><\/h2>\n<p><span style=\"font-weight: 400\">This\u00a0function saves the data in the <em>Redis<\/em> in-memory data structure store.<\/span><br \/>\n<strong>Usage<\/strong><br \/>\n<span style=\"font-weight: 400\">When you\u00a0respond to an <code>on_webhook<\/code> event call asynchronously, you can store the payload in the <em>Redis<\/em> store by\u00a0<code>requestId<\/code>. After completion of your\u00a0business logic execution, you can read the data using the\u00a0<code>sdk.getSavedData(requestId)function<\/code>\u00a0while preparing the webhook response.<\/span><br \/>\n<strong>Syntax:<\/strong><\/p>\n<pre class=\"lang:default decode:true\">sdk.saveData(requestId, payload)<\/pre>\n<p><strong>Parameters:<\/strong><\/p>\n<ul>\n<li><code>requestId<\/code> &#8211; The\u00a0<code>requestId<\/code>\u00a0from the\u00a0asynchronous\u00a0<code>on_webhook<\/code> event call.<\/li>\n<li><code>payload<\/code> &#8211; A JSON response payload as follows:\n<pre class=\"lang:default decode:true\"> {\r\n   \"taskId\":\"Dialog task ID\",\r\n   \"nodeId\":\"Current node ID in the dialog flow\",\r\n   \"channel\":\"Channel name\",\r\n   \"context\": &lt;context object&gt;\r\n}<\/pre>\n<\/li>\n<\/ul>\n<p><strong>Examples<\/strong><br \/>\nIn this\u00a0<code>on_webhook<\/code> event, the user request to book a cab is saved in the <em>Redis<\/em> store and the asynchronous processing of the booking begins.<\/p>\n<pre class=\"lang:default decode:true\">on_webhook : function(requestId, payload, componentId, callback) {\r\n        var context = data.context;\r\n        if (componentId === 'FindNearbyCabs') {\r\n            findCabs()\r\n                .then(function(cabList) {\r\n                    context.cabList = cabList;\r\n                    callback(null, payload);\r\n                });\r\n        } else if (componentName === 'BookTheCab') {\r\n            sdk.saveData(requestId, payload)\r\n                .then(function() {\r\n                    \/\/Assuming the cab booking was successful. A mock service to book the cab can be called here.\r\n                    payload.successful = 'true';\r\n                    payload.bookedCab = context.entities.selectedCab || {};\r\n                    callback(null, payload);\r\n                });\r\n        }\r\n    }<\/pre>\n<h2 id=\"sdk-getsaveddata\"><span class=\"ez-toc-section\" id=\"sdkgetSavedData\"><em>sdk.getSavedData<\/em><\/span><\/h2>\n<p><span style=\"font-weight: 400\">This\u00a0function reads the data in the <em>Redis<\/em> in-memory data structure store.<\/span><br \/>\n<strong>Usage<\/strong><br \/>\n<span style=\"font-weight: 400\">When you\u00a0respond to an <code>on_webhook<\/code> event call asynchronously, you can store the payload in the <em>Redis<\/em> store by\u00a0<code>requestId<\/code>. After completion of your\u00a0business logic execution, you can read the data using the\u00a0<code>sdk.getSavedData(requestId)function<\/code>\u00a0while preparing the webhook response.<\/span><br \/>\n<strong>Syntax:<\/strong><\/p>\n<pre class=\"lang:default decode:true\">sdk.getSavedData(requestId, payload)<\/pre>\n<p><strong>Parameters:<\/strong><\/p>\n<ul>\n<li><code>requestId<\/code> &#8211; The\u00a0<code>requestId<\/code>\u00a0from the\u00a0asynchronous\u00a0<code>on_webhook<\/code> event call.<\/li>\n<li><code>payload<\/code> &#8211; A JSON response payload as follows:\n<pre class=\"lang:default decode:true\"> {\r\n   \"taskId\":\"Dialog task ID\",\r\n   \"nodeId\":\"Current node ID in the dialog flow\",\r\n   \"channel\":\"Channel name\",\r\n   \"context\": &lt;context object&gt;\r\n}<\/pre>\n<\/li>\n<\/ul>\n<p><strong>Examples<\/strong><br \/>\nIn this code example, the <code>sdk.getSavedData<\/code> 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.<\/p>\n<pre class=\"lang:default decode:true\">\/*\/\r\n * Responds to the webhook asynchronously with the success flag.\r\n *\/\r\nfunction onBookingSuccess(requestId) {\r\n    sdk.getSavedData(requestId)\r\n        .then(function(payload) {\r\n            payload.context.bookedCab = payload.entities.selectedCab;\r\n            payload.context.successful = true;\r\n            sdk.respondToHook(payload);\r\n        });\r\n}\r\nfunction onBookingFailure(requestId) {\r\n    sdk.getSavedData(requestId)\r\n        .then(function(payload) {\r\n            payload.context.successful = false;\r\n            sdk.respondToHook(payload);\r\n        });\r\n}<\/pre>\n<h2 id=\"sdk-getmessages\"><span class=\"ez-toc-section\" id=\"sdkgetMessages\"><em>sdk.getMessages<\/em><\/span><\/h2>\n<p>This\u00a0function is used to get the transcript of previous conversations between the Bot and the user. It works similar to the public API Conversation History (<a href=\"\/docs\/bots\/apis\/conversation-history-api\/\">see here for Conversation History API<\/a>)<br \/>\n<strong>Usage<\/strong><br \/>\nFetches the conversational messages between the bot and user in reverse chronological order. This API supports pagination. You can provide offset\/skip and limit to get a certain number of messages at a time.<br \/>\n<strong>Syntax:<\/strong><\/p>\n<pre class=\"lang:default decode:true\">sdk.getMessages(requestData, callback)<\/pre>\n<p><strong>Parameters:<\/strong><\/p>\n<ul>\n<li><code>requestData<\/code> &#8211; as follows:\n<pre class=\"lang:default decode:true\">requestData.baseUrl + '\/getMessages?' + \"skip=\" + offset + \"&amp;limit=\" + limit + \"&amp;userId=\" + userId+\"&amp;channelType\"=channel-type<\/pre>\n<p>where<\/p>\n<ul>\n<li><code>stream_id<\/code> &#8211; Bot ID accessible from the Config Settings page of the Bot Builder<\/li>\n<li><code>user_id<\/code> &#8211; The ID of the user whose conversation history to access<\/li>\n<li><code>skip<\/code> &#8211; The number of messages to be skipped.<\/li>\n<li><code>limit<\/code> &#8211; The number of messages to be shown on each page.<\/li>\n<li><code>channelType<\/code> &#8211; Optional, the channel where the conversation was hosted.<\/li>\n<\/ul>\n<\/li>\n<li><code>callback<\/code> &#8211; The function to call at event completion used to send the message history back to the Bots Platform.<\/li>\n<\/ul>\n<p><strong>Examples<\/strong><\/p>\n<pre class=\"lang:default decode:true \">\/\/this example is from the LiveChat.js\r\n\/\/where the gethistory() function uses getMessage() to extract the messages\r\n    var userId = req.query.userId;\r\n    var data = userDataMap[userId];\r\n    if(data) {\r\n        data.limit = 100;\r\n        return sdk.getMessages(data, function(err, resp){\r\n            if(err){\r\n                res.status(400);\r\n                return res.json(err);\r\n            }\r\n            var messages = resp.messages;\r\n            res.status(200);\r\n            return res.json(messages);\r\n        });<\/pre>\n<h2 id=\"sdk-clearagentsession\"><span class=\"ez-toc-section\" id=\"sdkclearAgentSession\"><em>sdk.clearAgentSession<\/em><\/span><\/h2>\n<p>This\u00a0function is used to clear the Agent session and reestablish the conversation with the Bot.<br \/>\n<strong>Usage<\/strong><br \/>\nIn an Agent Transfer scenario, when the agent closes the conversation with the user, <code>chat_closed<\/code> event gets triggered from 3rd party provider. In such situations, this function is invoked to re-establish the conversation with the bot<br \/>\n<strong>Syntax:<\/strong><\/p>\n<pre class=\"lang:default decode:true\">sdk.clearAgentSession(requestData, callback)<\/pre>\n<p><strong>Parameters:<\/strong><\/p>\n<ul>\n<li><code>requestData<\/code> &#8211; as follows:\n<pre class=\"lang:default decode:true\">requestData.baseUrl+ '\/clearAgentSession\/' + requestData.requestId<\/pre>\n<p>where<\/p>\n<ul>\n<li><code>requestId<\/code> &#8211; the session id<\/li>\n<\/ul>\n<\/li>\n<li><code>callback<\/code> &#8211; The function to call at event completion.<\/li>\n<\/ul>\n<p><strong>Examples<\/strong><\/p>\n<pre class=\"lang:default decode:true \">\/\/this example is from the LiveChat.js\r\n\/\/where the function is invoked to clear agent session when the chat is closed by the user\r\n    if (event.type===\"chat_closed\"){\r\n       console.log('chat_closed');\r\n       delete userResponseDataMap[visitorId];\r\n       delete _map[visitorId];\r\n       sdk.clearAgentSession(data);\r\n    }\r\n<\/pre>\n<h2 id=\"sdk-startagentsession\"><span class=\"ez-toc-section\" id=\"sdkstartAgentSession\"><em>sdk.startAgentSession<\/em><\/span><\/h2>\n<p>This function is used to notify the platform that an Agent session has started.<br \/>\n<strong>Usage<\/strong><br \/>\nThis function is used when an Agent Transfer is initiated and you want to indicate to the Bot that the agent transfer is in progress. Followed by this, the data object received by BotKit at onMessages(), for instance, would have agent session as true. Further, if the <em>sdk.clearAgentSession<\/em> is called from BotKit, the platform is notified that agent session is completed and the data object received by the BotKit would have the agent session set to false.<br \/>\n<strong>Syntax:<\/strong><\/p>\n<pre class=\"lang:default decode:true\">sdk.startAgentSession(requestData, callback)<\/pre>\n<p><strong>Parameters:<\/strong><\/p>\n<ul>\n<li><code>requestData<\/code> &#8211; as follows:\n<pre class=\"lang:default decode:true\"> requestData.baseUrl + '\/startAgentSession\/' + requestData.requestId<\/pre>\n<p>where<\/p>\n<ul>\n<li><code>requestId<\/code> &#8211; the session id<\/li>\n<\/ul>\n<\/li>\n<li><code>callback<\/code> &#8211; The function to call at event completion.<\/li>\n<\/ul>\n<p><strong>Examples<\/strong><\/p>\n<pre class=\"lang:default decode:true \">\/\/The following function call is used in the LiveChat.js for connectToAgent() function\r\n\/\/Invoking the startAgentSession before invoking the initChat function will ensure that\r\n\/\/ the Bot is aware of the Agent transfer in progress\r\nfunction connectToAgent(requestId, data, cb){\r\n    var formdata = {};\r\n    formdata.licence_id = config.liveagentlicense;\r\n    formdata.welcome_message = \"\";\r\n    var visitorId = _.get(data, 'channel.channelInfos.from');\r\n    if(!visitorId){\r\n       visitorId = _.get(data, 'channel.from');\r\n      }\r\n    userDataMap[visitorId] = data;\r\n     data.message=\"An Agent will be assigned to you shortly!!!\";\r\n     sdk.sendUserMessage(data, cb);\r\n     sdk.startAgentSession(data, cb);\r\n    formdata.welcome_message = \"Link for user Chat history with bot: \"+ config.app.url +\"\/history\/index.html?visitorId=\" + visitorId;\r\n    return api.initChat(visitorId, formdata)\r\n     .then(function(res){\r\n     _map[visitorId] = {\r\n     secured_session_id: res.secured_session_id,\r\n     visitorId: visitorId,\r\n     last_message_id: 0\r\n    };\r\n   });\r\n }<\/pre>\n<h2 id=\"sdk-resetbot\"><span class=\"ez-toc-section\" id=\"sdkresetBot\"><em>sdk.resetBot<\/em><\/span><\/h2>\n<p>This function is used to clear the context and discard the current task silently.<br \/>\n<strong>Usage<\/strong><br \/>\nAt run time, during the execution of dialog, if the user input might want to clear the Bot using &#8220;reset bot&#8221; command. Then the context can be cleared and the task discarded.<br \/>\n<strong>Syntax:<\/strong><\/p>\n<pre class=\"lang:default decode:true\">sdk.resetBot(requestData, callback)<\/pre>\n<p><strong>Parameters:<\/strong><\/p>\n<ul>\n<li><code>requestData<\/code> &#8211; as follows:\n<pre class=\"lang:default decode:true\">requestData.resetBotUrl<\/pre>\n<\/li>\n<li><code>callback<\/code> &#8211; The function to call at event completion.<\/li>\n<\/ul>\n<p><strong>Examples<\/strong><\/p>\n<pre class=\"lang:default decode:true \">on_user_message : function(requestId, data, callback) {\r\n     if (data.message===\"reset bot\"){\r\n\tsdk.resetBot(data, callback);\r\n      }<\/pre>\n<h2 id=\"sdk-extendRequestId\"><span class=\"ez-toc-section\" id=\"sdkextendRequestId\"><em>sdk.extendRequestId<\/em><\/span><\/h2>\n<p>This function is used to extend the time allocated for botKit to send messages to the platform.<br \/>\n<strong>Usage<\/strong><br \/>\nThis function is used when an Agent Transfer is initiated and after sometime platform might not be receiving messages. This can be addressed by extending the time allocated for the botKit to send messages to the platform.<br \/>\n<strong>Syntax:<\/strong><\/p>\n<pre class=\"lang:default decode:true\">sdk.extendRequestId(requestData, callback)<\/pre>\n<p><strong>Examples<\/strong><\/p>\n<pre class=\"lang:default decode:true \">function onBotMessage(requestId, data, cb) {\r\n    console.log(\"bot message\",JSON.stringify(data));\r\n    var visitorId = _.get(data, 'channel.from');\r\n     event =  schedular.scheduleJob(\"*\/4 * * * *\", function() {\r\n                pub.get(visitorId+':data',function(err,reply){\r\n                    if(err) throw err;\r\n                    sdk.extendRequestId(data,cb);\r\n                })\r\n    });\r\n\t}<\/pre>\n<pre> on_user_message: function(requestId, data, callback) { \r\n        var visitorId = _.get(data, 'channel.from');\r\n        registerEvent(visitorId, data);\r\n        if(event){\r\n            event.cancel();\r\n        }else{\r\n            console.log(new Date(),'event not found');\r\n        }\r\n        event =  schedular.scheduleJob(\"*\/4 * * * *\", function() {\r\n            pub.get(visitorId+':data',function(err,reply){\r\n                if(err) throw err;\r\n                    sdk.extendRequestId(data,callback);\r\n            })\r\n        });<\/pre>\n\r\n\t\t<\/div>\r\n\t<\/div>\r\n<div class=\"w-separator size_small with_line width_default thick_1 style_solid color_border align_center\"><div class=\"w-separator-h\"><\/div><\/div><\/div><\/div><\/div><\/div><\/div><\/section>\n","protected":false},"excerpt":{"rendered":"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.resetBot sdk.startAgentSession sdk.clearAgentSession sdk.extendRequestId sdk.sendUserMessage This\u00a0function sends the message to the bot user. Usage Used inside...","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[36],"tags":[],"class_list":["post-17999","post","type-post","status-publish","format-standard","hentry","category-sdks"],"_links":{"self":[{"href":"https:\/\/developer.kore.ai\/v7-0\/wp-json\/wp\/v2\/posts\/17999","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/developer.kore.ai\/v7-0\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/developer.kore.ai\/v7-0\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/developer.kore.ai\/v7-0\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/developer.kore.ai\/v7-0\/wp-json\/wp\/v2\/comments?post=17999"}],"version-history":[{"count":6,"href":"https:\/\/developer.kore.ai\/v7-0\/wp-json\/wp\/v2\/posts\/17999\/revisions"}],"predecessor-version":[{"id":22782,"href":"https:\/\/developer.kore.ai\/v7-0\/wp-json\/wp\/v2\/posts\/17999\/revisions\/22782"}],"wp:attachment":[{"href":"https:\/\/developer.kore.ai\/v7-0\/wp-json\/wp\/v2\/media?parent=17999"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/developer.kore.ai\/v7-0\/wp-json\/wp\/v2\/categories?post=17999"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/developer.kore.ai\/v7-0\/wp-json\/wp\/v2\/tags?post=17999"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}