Skip to content

Instantly share code, notes, and snippets.

@jalcantarab
Last active May 8, 2023 13:33
Show Gist options
  • Save jalcantarab/0550eb938456c5d91cb28e2db4784eb1 to your computer and use it in GitHub Desktop.
Save jalcantarab/0550eb938456c5d91cb28e2db4784eb1 to your computer and use it in GitHub Desktop.
Google App Script Examples of some of the Inbenta API endpoints

Inbenta API - Google Apps Script Examples (~JavaScript)

Check out the official documentation of the Inbenta API at Getting Started. This gist is done for API version v1. To check out SDK examples in JavaScript, check this out

Overview

All the API access is over HTTPS. The response format for all requests is a JSON object. Whether a request succeeded is indicated by the HTTP status code. A 2xx status code indicates success, otherwise failure. When a request fails, the response body is still JSON.

Authentication

Authentication is done via HTTP headers, more information in the Authorization section. The calls in this gist all authenticate doing a call to getApiData(), which retrieves a token from POST /auth, and the list of api endpoints from GET /apis.

Request Format

The request parameters must be sent through the request body using a JSON string in POST methods or through query string in GET methods. Authentication is done via HTTP headers. The Authorization header authenticates the endpoint (using the format Bearer your_access_token).

Error Codes

Check inbenta errors documentation to know about the error codes and their format.

Rate limit

Global Rate Limits

Global rate limits are applied inclusive of all API calls made by an app over the 30-minutes sliding window, regardless of the particular endpoint. Rate limits also apply to invalid or malformed requests. We also applied a limit of requests per second that may change depending on the use.

Endpoint-Specific Rate Limits

Endpoints used to publish (POST or DELETE) have rate limits that are applied on an per-endpoint basis.

Rate Limit Response Codes

If your app exceeds any of these rate limits, you will receive a response with an HTTP response code of 429 (Too Many Requests).

/* (POST /auth || POST /refreshToken) && POST /apis
* Returns tokens and API endpoints.
*
* output: data{inbenta_key, inbenta_secret, bearerToken, baseURL{search, knowledge, chatbot, ticketing}}
*/
function getApiData(){
var clientName = "Inbenta";
var inbenta_key = "<your-inbenta-api-key>";
var inbenta_secret = "<your-inbenta-api-secret>";
var bearerToken = authPOST(inbenta_key, inbenta_secret);
var baseURL = endpointsGET(inbenta_key, bearerToken);
var data = {
'inbenta_key' : inbenta_key,
'inbenta_secret' : inbenta_secret,
'bearerToken' : bearerToken,
'baseURL' : baseURL,
'clientName' : clientName
};//Logger.log(data)
return data
}
/* POST /auth || POST /refreshToken
* Returns Bearer token
* input: {inbenta_key, inbenta_secret}
* output: bearerToken
*/
function authPOST(inbenta_key, inbenta_secret) {
var url = "https://api.inbenta.io/v1/auth";
var bearerToken = "";
var payload ={"secret":inbenta_secret};
var headers = {'x-inbenta-key':inbenta_key};
var options = {
"method" : "POST",
"headers": headers,
contentType:"application/x-www-form-urlencoded",
payload: payload,
followRedirects : true,
muteHttpExceptions: true};
var result = UrlFetchApp.fetch(url, options);
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
bearerToken = params.accessToken;
return bearerToken
}else{Logger.log("Error in POST /auth");return undefined}
}
/* GET /apis
* Returns API endpoints.
* input: {inbenta_key, bearerToken}
* output: data{search, km, chatbot, ticketing}}
*/
function endpointsGET(inbenta_key, bearerToken) {
var url = "https://api.inbenta.io/v1/apis";
var bearerToken = "Bearer "+ bearerToken;
var headers = {
'x-inbenta-key':inbenta_key,
Authorization: bearerToken
};
var options = {
method:"GET",
"headers": headers,
followRedirects : true,
muteHttpExceptions: true
};
var content = UrlFetchApp.fetch(url, options);
if (content.getResponseCode() == 200) {
var params = JSON.parse(content.getContentText());
var apis = params.apis;
apis.search = apis.search+"/v1";
apis.knowledge = apis.knowledge+"/v1";
apis.chatbot = apis.chatbot+"/v1";
apis.ticketing = apis.ticketing+"/v1";
return apis
}
Logger.log("Error in GET /apis");return undefined
}
/* POST /conversation
* Creates a new conversation by starting a session and retrieving a token to maintain it.
* This method can also send all the project configuration to overwrite the default values.
* input: {answers{sideBubbleAttributes,answerAttributes,maxOptions},forms{allowUserToAbandonForm, errorRetries}}
* output: {sessionToken}
*/
function conversationPOST() {
var credentials = getApiData();
var url = credentials.baseURL.chatbot + "/conversation";
var BearerToken = "Bearer "+ credentials.bearerToken;
var payload ={
// Custom configuration about the answers to be returned by the API
"answers": {
"sideBubbleAttributes": ["Answer"],
"answerAttributes": ["Answer"],
"maxOptions": 3
},
// Custom configuration about the bot forms behaviour
"forms": {
// Whether or not a user is allowed to abandon the form after a number of consecutive failed answers. Defaults to true
"allowUserToAbandonForm": true,
// The number of times a user can fail a form field before being asked if he wants to leave the form. Defaults to 3
"errorRetries": 3
}
};
var headers = {
'x-inbenta-key': credentials.inbenta_key,
'x-inbenta-env': '0',
Authorization : BearerToken
};
var options = {
method : "POST",
headers : headers,
payload : payload,
followRedirects : true,
muteHttpExceptions : true
};
var result = UrlFetchApp.fetch(url, options);//Logger.log(result.getContentText())
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());Logger.log(result.getContentText())
credentials['inbentaSession'] = params.sessionToken;
return credentials
}else{Logger.log("Error in POST /conversation")}
}
/* POST /conversation/message
* Main function to have a conversation with the bot, which will send a message through the message parameter in body, and the bot will return the best possible matched answer.
* input: {message, option}
* output: {message,type,options[{value,label}],parameters{contents{title,id,attributes,tracking{clickCode,rateCode}}}}
*/
function conversationMessagePOST(message, option) {
var credentials = conversationPOST();
var url = credentials.baseURL.chatbot + "/conversation/message";
var bearerToken = "Bearer " + credentials.bearerToken;
var inbentaSession = "Bearer " + credentials.inbentaSession;
if (message==undefined){var message="standards";}
if (option==undefined){var option="10";}
var payload={
"message": message,
"option": option
};/*
var headers ={
'x-inbenta-key': credentials.inbenta_key,
'x-inbenta-session': inbentaSession,
Authorization : bearerToken,
};*/Logger.log(inbentaSession); inbentaSession="Bearer eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJzZXNzaW9uSWQiOiJyNXNuY2pzcHZrc2ozOXBjNXM1dGpmZTgyMSJ9.MjhiYjBhZjQ4ZjE0NzYyMWIzNmNjODI5NTg3NDIwNmQ0Yzc4NDE5ZjRhYzA0MjQ3OWViN2YyZmI3YTI1MDkxMQ";
var headers ={
'x-inbenta-key': credentials.inbenta_key,
'x-inbenta-session': inbentaSession,
Authorization : bearerToken,
}
Logger.log(headers)
var options = {
method : "POST",
headers : headers,
payload : payload,//{"message":"standards","option":"10"},
followRedirects : true,
muteHttpExceptions : true
};
var result = UrlFetchApp.fetch("https://api-gcu1.inbenta.io/prod/chatbot/v1/conversation/message", options);Logger.log(result)
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());Logger.log(params)
return params
}else{Logger.log("Error in POST /conversation/message")}
}
/* GET /contents/{content_id}
* Returns a content by ID
* input: {id}
* {hasRelated, hasDecisionTree, attributes{Answer}, id, categories, title, tracking={clickCode, rateCode}}
*/
function contentsGET(id) {
var credentials = getApiData();
var url = credentials.baseURL.knowledge + "/contents";
var bearerToken = "Bearer "+ credentials.bearerToken;
if (id==undefined){var id="317";}else{id=id.replace('"','');}
url= url+ "/"+ id;Logger.log(url);
var headers = {
'x-inbenta-key':credentials.inbenta_key,
'x-inbenta-env':'production',
'x-inbenta-user-type': '0',
Authorization: bearerToken
};
var options = {
method:'GET',
'headers': headers,
followRedirects : true,
muteHttpExceptions: true
};
var content = UrlFetchApp.fetch(url, options);Logger.log(content)
if (content.getResponseCode() == 200) {
var params = JSON.parse(content.getContentText());
return params.results
}else{Logger.log("Error in GET /contents/{content_id}")}Logger.log(content)
}
/* GET /categories/{category_id}
* Returns one category's attributes
* input: {id, depth}
* output {id, parent, depth, name, numContents, numContentsDescendants, children}
*/
function categoryGET(id, depth) {
var credentials = getApiData();
var url = credentials.baseURL.knowledge + "/categories";
var bearerToken = "Bearer "+ credentials.bearerToken;
if (id==undefined){var id="18";}else{id=id.replace('"','');}
if (depth==undefined){depth="1";}
url= url+ "/"+ id+ '?maxDepth='+depth;
var headers = {
'x-inbenta-key':credentials.inbenta_key,
'x-inbenta-env':'production',
'x-inbenta-user-type': '0',
authority:'api-gcu1.inbenta.io',
Authorization: bearerToken
};
var options = {
method:"GET",
"headers": headers,
followRedirects : true,
muteHttpExceptions: true
};
var content = UrlFetchApp.fetch(url, options);
if (content.getResponseCode() == 200) {
var params = JSON.parse(content.getContentText());
Logger.log(params.results);
return params.results
}else{Logger.log("Error in GET /categories/{category_id}")}Logger.log(content)
}
/* GET /categories
* Returns all categories with specified depth
* input: {depth}
* output {int parent, int numContents, int depth, int numContentsDescendants, array children, string name, int id}
*/
function categoryGET(depth) {
var credentials = getApiData();
var url = credentials.baseURL.knowledge + "/categories";
var bearerToken = "Bearer "+ credentials.bearerToken;
if (depth=="undefined"){depth="9";}
url= url+'?maxDepth='+depth;
var headers = {
'x-inbenta-key':credentials.inbenta_key,
'x-inbenta-env':'production',
'x-inbenta-user-type': '0',
authority:'api-gcu1.inbenta.io',
Authorization: bearerToken
};
var options = {
method:"GET",
"headers": headers,
followRedirects : true,
muteHttpExceptions: true
};
var content = UrlFetchApp.fetch(url, options);
if (content.getResponseCode() == 200) {
var params = JSON.parse(content.getContentText());
Logger.log(params.results)
return params.results
}else{Logger.log("Error in GET /categories")}Logger.log(content)
}
/* POST /federated-search
* Returns the JSON of a defined number of results for an input query and defined filters
* @param {string} query - Query from UI.
* @param {array}{string} filters - List of filters to apply
* @param {string} length - Number of results to return
* @returns {json}{processingTimeMs, results{attributes{Answer}, id, title, tracking{clickCode, rateCode} - A JSON objevt with the search results
*/
function searchPOST(query, filters, length) {
if (query==undefined){query="support";}
if (query!=undefined){
var credentials = getApiData();
var url = credentials.baseURL.search + "/federated-search";
var BearerToken = "Bearer "+ credentials.bearerToken;
if (filters==undefined){filters='';}
if (length==undefined){length='6';}
var payload ={
"query":encodeURIComponent(query), //encodeURIComponent escapes all characters except A-Z a-z 0-9 - _ . ! ~ * ' ( )
"length": length
};Logger.log(payload.query)
var headers = {
'x-inbenta-key': credentials.inbenta_key,
'x-inbenta-env': '0',
Authorization : BearerToken
};
var options = {
method : "POST",
"headers" : headers,
contentType : "application/x-www-form-urlencoded",
payload : payload,
followRedirects : true,
muteHttpExceptions : true
};
var result = UrlFetchApp.fetch(url, options);Logger.log(result.getContentText())
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());for (var i =0;i<params.results.length;i++){ Logger.log(params.results[i]);}
return result.getContentText()
}else{Logger.log("Error in POST /federated-search")}
}else{Logger.log("query missing in searchPOST");return undefined}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment