1. Home
  2. Kore.ai Conversational Platform
  3. SDKs & APIs
  4. Web Socket Connect & RTM

Web Socket Connect & RTM

Kore.ai SDK libraries use the web socket channel to communicate with Kore.ai Bots Platform. To initialize a web socket session, the Kore.ai SDKs use the following Bots Platform endpoints. When using the Kore.ai Bots Platform SDKs, only the JWT token must be generated and passed to the client SDK.

Initializing a Web Socket Session

This section describes how the Kore.ai SDKs initialize a web socket session and is for reference only.

Prerequisites:

The client app is registered and Client ID and Secret Key are generated in the Kore.ai Bot Builder tool.

Step1:

The JWT is generated at server side using client app credentials and user information. The JWT is passed to the client app.

Step 2:

The client app exchanges the JWT token for the accessToken on the Bots Platform using the following Bots Platform endpoint. This section describes how to format the request to post a message in a chat with the /api/1.1/oAuth/token/jwtgrant endpoint based on the following JSON syntax.

POST
https://{{APIHost}}/api/1.1/oAuth/token/jwtgrant

{
    "assertion": “{{JWT Token}}”,
    "botInfo": {
        "chatBot": "{{Bot Name}}",
        "taskBotId": "st-f74a3430-3b19-55a3-be41-1ab1a35c4685"
    }
)

Sample cURL

curl 'https://bots.kore.ai/api/1.1/oAuth/token/jwtgrant' -H 'content-type: application/json'  --data-binary '{"assertion":"{JWT Token}}","botInfo":{"chatBot":"{{Bot Name}}","taskBotId":"st-f74a3430-3b19-55a3-be41-1ab1a35c4685"}}

Response

The follow sample JSON response shows the accessToken and user associated with that token.

{
   "authorization": {
	"accessToken": "ZdV2OL_UZ_MvHog-rs8k9KJFNWBICvquSc3jpeaRDE_-",
                 // access token to user at /api/rtm
	"token_type": "bearer",
	"expiresDate": "2019-06-28T06:52:23.160Z",
                //expiry date for access token
	"issuedDate": "2019-02-28T06:52:23.160Z" 
               //access token issuedDate
	},
   "userInfo": {
	"userId": "u-4f6c68e0-551a-5dd9-a33a-1af3dc9cadcc", 
                 // user id which is unique for the user and can be used at bot messages api
	"accountId": "5c66514d09ab3565deb2e30a", 
                 // account id in which the user is present
	"orgId": "o-88aad7f1-0d32-5765-93d7-f40c80402114",
                // organization id of the user
	"identity": "cs-5b08ed1e-5fa7-5aaa-9c21-28bf8c90b739/admin1212@qakore.xyz", 
                //identity of user from the channel perspective
	"enrollType": "free", 
                //Enrollment type (Free/ Paid etc)
	"managedBy": "5c66514d09ab3565deb2e30a", 
                //(The account id)
	"fName": "", 
                //first name of the user
                // (fetched if the user is registered on the platform)
	"lName": "" 
                //last name of the user
                // (fetched if the user is registered on the platform)
	}
}

Step 3:

The client app acquires the web socket URL using the following endpoint. This section describes how to format the request to get the web socket URL with the /api/1.1/rtm/start endpoint based on the following JSON syntax.

Note: This URL is short lived and expires in 30 seconds. You must ensure it is used to connect before expiration.

POST
https://{{APIHost}}/api/1.1/rtm/start

{
    "botInfo": {
        "chatBot": "Twitter",
        "taskBotId": "st-f74a3430-3b19-55a3-be41-1ab1a35c4685"
    }
}

The accessToken is passed in the bearer parameter in the Authorization header.

Sample cURL

curl 'https://bots.kore.ai/api/1.1/rtm/start' -H 'content-type: application/json' -H 'Authorization: bearer {{accessToken}}' --data-binary '{"botInfo":{"chatBot":"{{Bot Name}}","taskBotId":"st-f74a3430-3b19-55a3-be41-1ab1a35c4685"}'

Response

The following sample JSON response shows the web socket URL.

{"url":"wss://bots.kore.com:443/rtm/bot?sid=GhKrtrEC61g7hAnmvKAVnJIHG0DS1Lzv"}

Use Case Example

Below is a demonstration of WS connection from the web SDK provided for integration of chatbot on websites:

  1. Calling the JWT service to fetch the JWT.
    curl 'https://demo.kore.net/users/sts/' -H 'Accept: application/json, text/javascript, */*; q=0.01' -H 'Origin: null' -H 'User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' --data 'clientId=cs-5b08ed1e-5fa7-5aaa-9c21-28bf8c90b739&clientSecret=X324FWQY8d9S%2BDScImtW4ZGObA4J%2BbjTQo0hxnPHfxE%3D&identity=user%40kore.ai&aud=&isAnonymous=true' --compressed

    Response data:

    {
    "jwt":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NTE0MTIwMzI0NDEsImV4cCI6MTU1MTQxMjA5MjQ0MSwiYXVkIjoiIiwiaXNzIjoiY3MtNWIwOGVkMWUtNWZhNy01YWFhLTljMjEtMjhiZjhjOTBiNzM5Iiwic3ViIjoicmVicm9AcWFrb3JlLnh5eiIsImlzQW5vbnltb3VzIjoidHJ1ZSJ9.-1BeEcOe2NddLEdpGXRKD7v9clKCbzgAhopDtNcJgMs"
    }
  2. Calling the JWT grant API to fetch the access token.
    curl 'https://bots.kore.ai/api/oAuth/token/jwtgrant' -H 'accept: application/json' -H 'Origin: null' -H 'User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36' -H 'content-type: application/json' --data-binary '{"assertion":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NTE0MTIwMzI0NDEsImV4cCI6MTU1MTQxMjA5MjQ0MSwiYXVkIjoiIiwiaXNzIjoiY3MtNWIwOGVkMWUtNWZhNy01YWFhLTljMjEtMjhiZjhjOTBiNzM5Iiwic3ViIjoicmVicm9AcWFrb3JlLnh5eiIsImlzQW5vbnltb3VzIjoidHJ1ZSJ9.-1BeEcOe2NddLEdpGXRKD7v9clKCbzgAhopDtNcJgMs","botInfo":{"chatBot":"Sample Bot","taskBotId":"st-eb153221-a10d-51fd-bba1-472f6927dbfb","customData":"test"},"token":{}}' --compressed

    Response data:

    {
       "authorization": {
    	"accessToken": "h3RIbu-9ugOqXhveIVDSm1PPEf2fgREeo8VwQRpUvKahtyFc-9aGTjbL7EoHFuSH",
    	"token_type": "bearer",
    	"expiresDate": "2019-06-29T03:47:12.705Z",
    	"issuedDate": "2019-03-01T03:47:12.705Z"
        },
       "userInfo": {
    	"userId": "u-1ce1e07e-3309-5235-811d-19eaac117e0a",
    	"accountId": "5c655c70b5fdc91b4b7e8df2",
    	"orgId": "o-88aad7f1-0d32-5765-93d7-f40c80402114",
    	"identity": "cs-5b08ed1e-5fa7-5aaa-9c21-28bf8c90b739/user@kore.ai",
    	"enrollType": "paid",
    	"managedBy": "5c655c70b5fdc91b4b7e8df2",
    	"fName": "user",
    	"lName": "user"
        }
    }
  3. Calling the /api/rtm URL to fetch the WebSocket URL.
    curl 'https://bots.kore.ai/api/rtm/start' -H 'accept: application/json' -H 'Origin: null' -H 'User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36' -H 'Authorization: bearer h3RIbu-9ugOqXhveIVDSm1PPEf2fgREeo8VwQRpUvKahtyFc-9aGTjbL7EoHFuSH' -H 'content-type: application/json' --data-binary '{"botInfo":{"chatBot":"Sample bot","taskBotId":"st-eb153221-a10d-51fd-bba1-472f6927dbfb","customData":"test"},"token":{}}' --compressed

    Response data:

    {"url":"wss://rtm.kore.ai:443/rtm/bot?sid=YfGn_0M5KuvZ8AvKkvmXYdE-zEnpXogg"}
  4. Establishing WebSocket by using the WS URL received from the /api/rtm URL.
    curl 'wss://rtm.kore.ai/rtm/bot?sid=Vja5pWtDQDZb_qkBwbFB1lwXUkhw-hOh' -H 'Pragma: no-cache' -H 'Origin: file://' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US,en;q=0.9' -H 'Sec-WebSocket-Key: nmor/hei55hHl9xpOKaAlg==' -H 'User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36' -H 'Upgrade: websocket' -H 'Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits' -H 'Cache-Control: no-cache' -H 'Connection: Upgrade' -H 'Sec-WebSocket-Version: 13' --compressed
  5. Sending message to bot from client via the WebSocket from web SDK channel:
    "clientMessageId": 1551412750498, 
          //unique id of the message sent from bot
    "message": {
    	"body": "Hi" //message sent to bot
       },
    "resourceid": "/bot.message",
    "botInfo": {
    	"chatBot": "Sample Bot", //Bot name
    	"taskBotId": "st-eb153221-a10d-51fd-bba1-472f6927dbfb", // bot id
    	"customData": "test"  //custom data passed as part of bot info
       },
    "client": "sdk", // details of client SDK/ bot builder
    "meta": { //timezone information of the client
    	"timezone": "Asia/Kolkata",
    	"locale": "en-US"
       },
    "id": 1551412750498

    Sample sendMessage construct if developers were to use their own UI with kore.ai chatbot:

      var messageToBot = {};
        messageToBot["message"] = {body:"your message",attachments:[]};
        messageToBot["resourceid"] = '/bot.message';
        // Should be an unique id for each message, 
        // you can use timestamp as well
        messageToBot["clientMessageId"] = 232341234; 
        // Send message to Bot
        bot.sendMessage(messageToBot, function messageSent() {
        });
  6. Acknowledge message received for the message sent from the client
    {
       "ok": true,
       "replyto": 1551412750498, 
           // this is the client message id for the message sent from client
       "type": "ack"
    }
  7. Bot response received for the message sent
    {
       {
    	"type": "bot_response",
    	"from": "bot",
    	"message": [{
    	   "type": "text",
    	   "component": {
    	   	"type": "text", 
                          //type of message received (text/template)
    		"payload": { 
                          // payload changes based on the template received as bot response
    			"text": "Hello "
    			}
    		},
    	"cInfo": {
    		"body": "Hello "
    		}
    	   }],
    	"messageId": "ms-68e77005-ac3c-5e43-8ad6-88125cc37c0b", // unique message id
    		"botInfo": { 
    		"chatBot": "Sample Bot",
    		"taskBotId": "st-eb153221-a10d-51fd-bba1-472f6927dbfb",
    		"customData": "test"
    	},
    	"createdOn": "2019-03-01T03:59:15.209Z",
    	"icon": "http://d1hqmx8kqvpnpa.cloudfront.net/f-ff90111f-9636-5008-8ff2-cf6b2aedcda2.png",                 
                    //bot icon
    	"traceId": "504099843e489092"
    	}
    }

    Sample listen to a message (response) construct if developers were to use their own UI with kore.ai chatbot:

     // Event occurs when you recieve any message from server
        bot.on("message",function(msg){
            console.log("Received Message::",msg.data);
            // Converting JSON string to object
            var dataObj = JSON.parse (msg.data); 
            //differ user message & bot response check message type
            if(dataObj.from === "bot" && dataObj.type === "bot_response") {
                // Bot sends a message to you
            }
            if(tempData.from === "self" && tempData.type === "user_message") {
                // If you are logged in on several devices at the same time 
                // & sent a message to same Bot, it will appear on every device
            }
        });

 

RTM Events Reference

The following real-time events can be exchanged between the client app and the Kore.ai Bots Platform

RTM Client Events

This section describes the RTM Client Event JSON responses sent to the Kore.ai Bots Platform from the client app over a web socket. Event Type: /bot.message Description: Triggered when a user posts a message. The following payload is used to send a user-typed message to the Bots Platform.

{
    "clientMessageId": 1466692440896,
    "message": {
        "body": "Here is the message.",
        "attachments": [

      ]
    },
    "resourceid": "/bot.message",
    "botInfo": {
        "chatBot": "CNN",
        "taskBotId": "st-8aaf0939-c34a-5976-8e2e-5c91e685b2ce"
    },
    "id": 1466692440896
}

RTM Server Events

This section describes the RTM Server Event JSON responses sent to the client app over a web socket.

Event Type: ack

Description: An acknowledgement sent whenever an event is received from the client app. The following payload is used to acknowledge an event from the client app.

{
    "ok": true,
    "replyto": 1466692440896,
    "message": "delivered",
    "type": "ack"
}

Event Type: bot_response

Description: An acknowledgement sent whenever a message is processed from the client app. The following payload is sent when a message from the client app is processed.

{
    "type": "bot_response",
    "from": "bot",
    "message": [
        {
            "type": "text",
            "cInfo": {
                "body": " Hi.  "
            }
      }
   ],
    "botInfo": {
        "chatBot": "CNN",
        "taskBotId": "st-8aaf0939-c34a-5976-8e2e-5c91e685b2ce"
    },
    "createdOn": "2016-06-23T14:34:00.025Z",
    "icon": "https://devbots.kore.com/api/getMediaStream/market/f-683e82be-fc25-5921-bf41-4104780f71c2.png"
}

Event Type: user_message

Description: Sent to the client app when a user enters and sends a message to the server from another simultaneous session. The following sample payload is sent to the client app.

{
    "botInfo": {
        "chatBot": "CNN",
        "taskBotId": "st-8aaf0939-c34a-5976-8e2e-5c91e685b2ce"
    },
    "from": "self",
    "message": {
        "body": "how are you doing ",
        "attachments": []
    },
    "id": 1466692871803,
    "type": "user_message"
}

Next Steps

The Bots Platform API endpoints and RTM events can be used with your client app or Kore.ai Bot SDKs. For more information, see the Kore.ai Bots SDK.

Was this article helpful to you? Yes 2 No 1