Kore.ai BotKit SDK를 사용하여 봇 플랫폼에서 이벤트를 캡처하고 처리하여 사용자의 봇 경험을 더 잘 통제하고 사용자 정의할 수 있습니다. BotKit SDK는 다음 이벤트를 지원합니다.
onMessage
본 이벤트는 다음 두 가지 구성 요소로 구성됩니다.
- 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 엔진이 대화 흐름에서 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 이벤트의 다음 예시에서, 두 호텔 이름은 사용자 입력에 대한 응답의 결과로 반환됩니다.
    //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 : function (requestId, data, callback) 매개변수:
- requestId – 각 메시지 이벤트에 대한 고유 ID.
 - data– 아래 예시와 같은 JSON 응답 페이로드.
 - callback – 이벤트 완료 후 호출하는 함수이며, 업데이트된 메시지와 컨텍스트를 봇 플랫폼으로 다시 전송하는 데 사용됩니다.
 
예:
on_event : function (requestId, data, callback)
{
return sdk.sendAlertMessage(data, callback);
}
이벤트는 kit에 전송된 데이터 개체에 다음 코드를 추가합니다.
"event":
{
"event Type": "endDialog"/ “endFAQ”
}
		OnAlert
본 이벤트는 봇 사용자가 알림을 수신할 때 실행됩니다. 구문: on_alert : function (requestId, data, callback) 매개변수:
requestId– 각 메시지 이벤트에 대한 고유 ID.data– JSON 응답 페이로드.callback– 이벤트 호출 시 호출하는 함수이며, 업데이트된 메시지와 컨텍스트를 봇 플랫폼으로 다시 전송하는 데 사용됩니다.
예:
on_alert: function(requestId, data, callback)
{
 return sdk.sendAlertMessage(data, callback);
}
알림 응답 데이터는 kit로 전송된 데이터 개체에서 찾을 수 있습니다.
OnVariableUpdate
본 이벤트는 봇이 게시될 때 variable_update에서 실행됩니다. 구문: variable_update : function (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 : function (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”}