# Konverse AI Developer Hub

Welcome to Konverse AI Developer Hub. Here you can find all documentation to leverage our REST APIs and integrate existing solutions to our Conversational Sales & Marketing AI Platform.

## Reference

The API is organized around REST. All requests should be made over SSL. All request and response bodies, including errors, are encoded in JSON. We have specific language bindings to make integration easier.


# Authentication

Authentication is done via the App ID & API key which you can find in your account settings.

Requests are authenticated using HTTP Basic Auth. Provide your API key as the basic auth username. You do not need to provide a password.

You can also refresh your API keys if you believe that it has been compromised.


# Errors


# Rate Limit

You can make 60 requests per minute to our API. If you think you’ll need a higher rate limit, drop us a line at <support@konverse.ai>.


# Webhook Endpoints

You can use our webhooks to receive notifications & events based on a number of activities done by a lead or user.

Some examples of our webhook endpoints include chat-based activity, buying probability, page exits, engagement score and more.

{% hint style="info" %}
Our webhooks are not limited to the activities mentioned here. If you're looking for a specific outcome, reach out to our support team for further details.
{% endhint %}


# Embedded Functions

Our Platform allows you to send embed functions written in node JS which allows you integrate third-party APIs directly inside your chatbot

```
let { ExtendedLogger } = require("@function-logger");
let logger = new ExtendedLogger("default", "bot_id", "functionNamespace");
module.exports = async (ctx) => {
    let session = ctx.session;
    let config = ctx.config;
    let metadata = ctx.metadata;
    let params = ctx.params;
    let visitor = ctx.visitor;
    return new Promise((resolve, reject) => {
        //...your code goes here
        resolve(ctx);		//Always resolve ctx variable
    })
}
```

Embedded functions as a services pass the conversation context (ctx) into your function allows to to return response, and process information that the chatbot has collected about the visitor and their sessions


# Send Text Message

Embedded functions allows to send a text message from the function. A sample code is mentioned below

```
ctx.sendText("Your Text Here");
```


# Send Quick Reply

Our platform allows you to send quick reply from the embedded functions. A Quick Reply allows you to send a text message with suggestion buttons. Each button can take you to different story point

```
ctx.sendQuickReply("This is a test", 
     [{
       "title" : "<Button Title 1>",
       "jumpTo": "<NODE LABEL>"
      }, {
       "title" : "<Button Title 2>",
       "jumpTo": "<NODE LABEL2>"
      }]
)
```

It is also possible to set variables on click of a buttons. Please refer to the code below

```
ctx.sendQuickReply("This is a test", 
     [{
		"title": "<Button Title 1>",
		"jumpTo": "<NODE LABEL>",
		"variables": [{
			"key": "#service_id",
			"variableType": "Text",
			"value": "value1"
		}]
	}, {
		"title": "<Button Title 2>",
		"jumpTo": "<NODE LABEL2>",
		"variables": [{
			"key": "#service_id",
			"variableType": "Text",
			"value": "value2"
		}]
	}
     }]
)
```

{% content-ref url="/pages/4Y641tEgpTnsYS6v0qYV" %}
[Set Variables](/platform/embedded-functions/set-variables)
{% endcontent-ref %}


# Set Variables

Platform allows you to set variables, which can be used inside your chatbot to check a condition, form a message, or by another embedded function

```
ctx.setVar(variableName, variableType, variableValue)
e.g. ctx.setVar("@visitor_first_name", "Text", "Developer")
```

| Parameters    | Description                                                                                                                                                                                                                                                                                                                                                             |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| variableName  | <p>Name of a variable</p><p></p><p>Variable Name cannot has spaces, and must start with an alphabet</p><p></p><p>@VariableName : Save variable in visitor information (e.g. First Name, Email etc), which almost never changes for a visitor</p><p></p><p>#VariableName : Save variable in session, and will reset automatically when the visitor visits next time </p> |
| variableType  | <p>Allowed Types</p><ul><li>Text</li><li>Boolean</li><li>Date</li><li>Number</li><li>Decimal</li><li>Object</li></ul>                                                                                                                                                                                                                                                   |
| variableValue | Any value as per the variable type                                                                                                                                                                                                                                                                                                                                      |


# Send Choice

Our platform lets you prompt visitor with a set of up-to 10 choices

```
ctx.sendChoice("Your text message", [{
            "title" : "Choice1",
            "value": "Choice1Value"
        }, {
            "title" : "Choice2",
            "value": "Choice2Value"
        }, {
            "title" : "Choice3",
            "value": "Choice3Value"
        }], variableName, requied);
```

| Parameter    | Description                                                                    |
| ------------ | ------------------------------------------------------------------------------ |
| TextMessage  | Text message to prompted                                                       |
| Buttons      | Set of buttons                                                                 |
| VariableName | Name of the variable in which the value will be saved when a button is clicked |
| required     | true or false; default false                                                   |


# Send Cards

Our platform allows to send up-to 10 cards with each card having up-to 3 buttons.&#x20;

```
ctx.sendCards({
	"title": "Card1",
	"subtitle": "Subtitle1",
	"image": "https://path-to-image1",
	"buttons": [{
			"type": "postback",
			"jumpTo": "<Story Label>",
			"title": "Button 1 title"
		},
		{
			"type": "url",
			"url": "https://external-redirec-link",
			"title": "URL BUTTON"
		}, {
			"type": "postback",
			"jumpTo": "<Story Label>",
			"title": "Button 3 Postback with variables",
			"variables": [{
				"key": "#variableName",
				"variableType": "variableType",
				"value": "value"
			}]
		}
	]
})
```


# Stop Propagation

By Default if the function sends a question (QuickReply & Choice), the chatbot automatically stops propagation to next step in your story. However you may force the chatbot to stop propagation to next step by using the following syntax

```
ctx.stopPropagation();
```


# Query a Dataset

Our platform lets you create [Datasets](/platform/datasets), and embedded functions and query a dataset.&#x20;

```
let ds = await ctx.dataset.find("Dataset Name", {id : 1});
```

To fetch all rows from a dataset

```
let ds = await ctx.dataset.find("Dataset Name", {});
```


# Jump To Story

Our Platform lets you jump to a different story based on a logic written inside your embedded function

```
ctx.jumpTo(storyName, options);
```

| Parameter | Description                                                                                                                                                                                                                                                                                          |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| StoryName | Name of the story to which the chatbot will run next                                                                                                                                                                                                                                                 |
| Options   | <p>Set of options to trigger a story</p><p></p><p>delay : time in mill seconds</p><p>time : e.g. 11AM </p><p>timezone : e.g. Asia/Kolkata (moment timezones)</p><p></p><p></p><p>e.g. </p><p></p><p>{ "time": "11AM" ,   "timezone": "Asia/Kolkata"}</p><p></p><p>{ "delay": "5000" } //5 second</p> |


# Query a Google Sheet

Our platform lets you read a write to a google sheet directly.&#x20;

{% hint style="info" %}
Please note it works with only with Google Sheets, and not xlsx files hosted on google
{% endhint %}

#### Package

```
const sheets = require("@googlesheets");
```

#### Reading a sheet

{% hint style="info" %}
To allow reading from a google sheet, please write to <support@konverse.ai>, to get email ID of the chatbot to which you will need to grant permissions
{% endhint %}

```
let rows = await sheets.readSheet(workBookId, sheetId)
rows.map(row => {
  let first_name = row["First Name"]
});
```

| Parameter  | Description                                                                           |
| ---------- | ------------------------------------------------------------------------------------- |
| workbookID | The ID of the google sheet, from its URL                                              |
| sheetID    | Index of your sheet starting from 0. To read first sheet in your google sheet, pass 0 |

#### Append a row in google sheet

```
let sheet = await sheets.getSheet(workbookID, sheetID);
const larryRow = await sheet.addRow({ name: 'Larry Page', email: 'larry@google.com' });
```


# Datasets

Our Platform lets you create datasets or table in an excel like format which can be used in the [Embedded Functions](/platform/embedded-functions)

A dataset can be used when you have an information for which you may not have an API, or is maintained in excel files in your organisation. Some example of the datasets are

* List your your schools
* List of your Hotel Properties
* List of your Courses
* List of your products


# Bot Webhooks

Konverse platform lets you Webhook any session data from the bot to your desired endpoint

![Settings for Web-hook](https://3300248524-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MDd7Ctz3jgnCJLDydlP%2Fuploads%2Fk5A3vD7ZXwu5VQzHrFfg%2FScreenshot_2021-12-24_13-13-42.png?alt=media\&token=f2518fa6-a720-4c26-b912-274a4f895113)

Konverse platform also allows to instruct bot to send text, quick reply or attachment through the Webhook response. Please refer to response formats below. &#x20;

### Text

```json
{
	"konverse": {
		"type": "text",
		"text": ["Hello from webhook"]
	}
}
```

### Attachment

```json
{
	"konverse": {
		"type": "attachment",
		"attachment": {
			"url": "https://cdn.pixabay.com/photo/2020/06/17/12/33/watermelon-5309310_960_720.png",
			"mime": "image/jpeg"
		}
	}
}
```

#### Supported Mime types

| Media      | Supported Content-Types                                                                                                                                                                                                          |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `audio`    | `audio/aac`, `audio/mp4`, `audio/amr`, `audio/mpeg`                                                                                                                                                                              |
| `document` | `application/pdf`                                                                                                                                                                                                                |
| `image`    | `image/jpeg`, `image/png`                                                                                                                                                                                                        |
| `sticker`  | `image/webp`                                                                                                                                                                                                                     |
| `video`    | <p><code>video/mp4</code>, <code>video/3gpp</code><br></p><p><strong>Notes:</strong></p><ul><li>Only H.264 video codec and AAC audio codec is supported.</li><li>Only videos with a single audio stream are supported.</li></ul> |

### Stop Propagation

```json
{
	"konverse": {
		"stopPropagation": true
	}
}
```


# Introduction to Channels

Konverse AI allows you to stay connected with your customers across multiple messaging channels. In this section, get to know about all the channels where you can stay connected with your customers.

{% content-ref url="/pages/-MDdc3NhXgrHqJttZGXc" %}
[Web Chat](/messaging-channels/web-chat)
{% endcontent-ref %}

{% content-ref url="/pages/-MDdcEGW0ijZws-hNs3E" %}
[Facebook Messenger](/messaging-channels/facebook-messenger)
{% endcontent-ref %}

{% content-ref url="/pages/-MDdcFAM8azjUCDC8dNO" %}
[WhatsApp](/messaging-channels/whatsapp)
{% endcontent-ref %}

{% content-ref url="/pages/-MDiKoTPpA7hT1rlnUIx" %}
[Line](/messaging-channels/line)
{% endcontent-ref %}


# Web Chat

### Step 1 - Go to Integration Section on Dashboard <a href="#step-1-go-to-integration-section-on-dashboard" id="step-1-go-to-integration-section-on-dashboard"></a>

Log into your dashboard and go to the **Integrations** section as shown in the image below and click on **Web App**.

![Web App under Integrations](https://3300248524-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MDd7Ctz3jgnCJLDydlP%2F-MERyMrffbtQ9As95xd9%2F-MES21VhaX6MC3lIfC-2%2FScreenshot%202020-08-11%20at%202.46.55%20PM.png?alt=media\&token=627f97a8-6771-4b80-a3c8-80ec83dfb5e8)

### Step 2 - Click on Web App & install

Once you click on Web App, it shows a script. Copy the following sample widget code and paste it inside`<HEAD>`section of your webpage.

![](https://3300248524-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MDd7Ctz3jgnCJLDydlP%2F-MERyMrffbtQ9As95xd9%2F-MES2AJE2oKm3fXyrU8Z%2FScreenshot%202020-08-11%20at%203.48.19%20PM.png?alt=media\&token=8a287ada-3e2f-45ac-b92f-5a68e0cb457b)

```
  <!-- Konverse Chatbot -->
  <a href="https://www.konverse.ai/"
    id="konverse-ref-id" data-bot-id="YOUR-UNIQUE-BOT-ID"
    title="Konverse.ai - Conversational Sales & Marketing Platform"
    style="display:none">AI Chatbot WhatsApp Bot</a>
  <script type="text/javascript" src="https://chat.konverse.ai/konverse.js"></script>
```


# Facebook Messenger

### Step 1 - Go to Integration Section on Dashboard <a href="#step-1-go-to-integration-section-on-dashboard" id="step-1-go-to-integration-section-on-dashboard"></a>

Log into your dashboard and go to the **Integrations** section as shown in the image below and click on **Facebook Messenger**.

![](https://3300248524-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MDd7Ctz3jgnCJLDydlP%2F-MES3QLe0k7ktkp46q7k%2F-MES5zlMVYKIzXcd77pj%2FScreenshot%202020-08-11%20at%204.04.51%20PM.png?alt=media\&token=7c8c2eac-d20f-4b7c-9856-cabd029a5615)

### Step 2 - Login to your Facebook <a href="#step-2-login-to-your-facebook" id="step-2-login-to-your-facebook"></a>

Login to your Facebook account to see the list of all the pages where you are an admin. Select the page and click on connect.

![Login with Facebook](https://3300248524-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MDd7Ctz3jgnCJLDydlP%2F-MES3QLe0k7ktkp46q7k%2F-MES7LC4Be7Bm-Owbozt%2FScreenshot%202020-08-11%20at%204.14.38%20PM.png?alt=media\&token=7a06230b-377d-49d7-98d3-5d3194d5dde3)


# WhatsApp

Our WhatsApp Business API allows you to send WhatsApp based notifications with PDF, Image & Video to your customers through a single API.

{% content-ref url="/pages/-MDdcegtVJEcr2rUxFpb" %}
[Send WhatsApp Notifications](/messaging-channels/whatsapp/whatsapp-template)
{% endcontent-ref %}


# Send WhatsApp Notifications

In this section, you'll learn how to send a new WhatsApp based notification using our programmable APIs.

### Sample Code

```
curl --location --request POST 'https://gateway.konverse.ai/ironman/api/v1/whatsApp/whatsappHSM' \
--header 'x-app-id: your app id' \
--header 'x-api-key: your app key' \
--header 'Content-Type: application/json' \
--data-raw '{
   "message": {
     "to": "919XXXXXXXXX",
     "templateName" : "message1",
     "language" : "<language-code>",
     "parameters": [
         "parameter1",
         "parameter2"
      ],
      "buttons" : []
   }
}'

```

### Step 1 - Authentication

Authentication of our WhatsApp API is done using the two request headers, **`<x-app-id>`** & **`<x-api-key>`.** Connect to our development team for your ID & Key.

### Step 2 - Using the API

Once your template is approved by WhatsApp & you've app ID & key, copy and paste the above cURL request with your credential and start testing.

## WhatsApp Notification Sending API

<mark style="color:green;">`POST`</mark> `https://gateway.konverse.ai/ironman/api/v1/whatsappHSM`

#### Headers

| Name         | Type   | Description             |
| ------------ | ------ | ----------------------- |
| x-app-id     | string | to be shared on request |
| x-api-key    | string | to be shared on request |
| Content-Type | string | application/json        |

#### Request Body

| Name         | Type   | Description                                                                                                                                                                                                                                             |
| ------------ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| to           | string | Mobile number to which WhatsApp notification has to be sent, prefixed with country code without + sign for e.g. "919876543210".                                                                                                                         |
| templateName | string | Name of the template pre-approved by WhatsApp.                                                                                                                                                                                                          |
| parameter    | string | An array of parameters that will replace the placeholder’s in the approved template. The number of parameters in a message template and the length of the array must be equal. Send an empty array if the template doesn't have any parameters e.g. \[] |
| file         | string | This is an object type. Use only if the template has an attachment.                                                                                                                                                                                     |
| file.type    | string | document / video / image                                                                                                                                                                                                                                |
| file.url     | string | Public URL of the attachment                                                                                                                                                                                                                            |
| file.name    | string | Optional caption for the attachment                                                                                                                                                                                                                     |
| buttons      | string | Applicable only if the template has buttons. Send an empty array for Call to Action buttons, e.g. \[].                                                                                                                                                  |
| buttons.type | string | Only if the button in the template is of type URL then type = “url”                                                                                                                                                                                     |
| buttons.url  | string | URL suffix to the pre-approved URL with the template. WhatsApp does not allow completely dynamic URL. A part of URL is pre-approved with the template, and only URL suffix is sent in the API.                                                          |
| language     | String | Language Code (optional). Refer WhatsApp documentation for supported language - [Supported Language](https://developers.facebook.com/docs/whatsapp/api/messages/message-templates#supported-languages)                                                  |

{% tabs %}
{% tab title="200 " %}

```
{
    "status": "success",
    "message": "message sent successfully",
    "messageId": "gBEGkXdgloBAAgluX2iGtsi"
}
```

{% endtab %}

{% tab title="400 The number of parameters sent is not matching with the approved number of parameters in the template." %}

```
{
    "status": "failed",
    "error": {
        "meta": {
            "api_status": "stable",
            "version": "2.27.12"
        },
        "errors": [
            {
                "code": 2000,
                "title": "Number of parameters does not match the expected number of params",
                "details": "number of localizable_params (1) does not match the expected number of params (2)",
                "href": "https://developers.facebook.com/docs/whatsapp/faq#faq_1612022582274564"
            }
        ]
    }
}
```

{% endtab %}

{% tab title="401 Please check your x-app-id & your x-api-key " %}

```
{
    "status": "failed",
    "messaged": "Unauthorized"
}
```

{% endtab %}
{% endtabs %}

### Template with dynamic CTA URL buttons & File

```
curl --location --request POST 'https://gateway.konverse.ai/ironman/api/v1/whatsApp/whatsappHSM' \
--header 'x-app-id: your app id' \
--header 'x-api-key: your app key' \
--header 'Content-Type: application/json' \
--data-raw '{
    "message": {
        "to": "1XXXXXXXX",
        "templateName": "<templatename>",
        "parameters": [
            <parameters>
        ],
        "file": {
            "type": "<document|image|video|audio>",
            "url": "<url - must end with .pdf/.doc/.png/.jpg>"
        },
        "buttons": [
            {
                "type": "url",
                "text": "<url parameter>"
            }
        ]
    }
}'
```


# Send Session Message

To send a session message directly triggered from backend can be sent using the following API

```
curl --location --request POST 'https://gateway.konverse.ai/ironman/api/v1/whatsapp/sessionMessage/text' \
--header 'x-app-id: <your app id>' \
--header 'x-api-key: <your app key>' \
--header 'Content-Type: application/json' \
--data-raw '{
    "to": "91XXXXXXXX",
    "message": {
        "text": "<message>"
    }
}'
```

To send a file/attachment in a session directly triggered from backend can be sent using the following API

```
curl --location --request POST 'https://gateway.konverse.ai/ironman/api/v1/whatsapp/sessionMessage/attachment' \
--header 'x-app-id: <your app id>' \
--header 'x-api-key: <your app key>' \
--header 'Content-Type: application/json' \
--data-raw '{
    "to": "91XXXXXXXX",
    "attachment": {
        "url": "<https://link-url-file>",
        "mime": "<mimetypes>",
        "filename": "<name of your file>",
        "caption": "Caption for your file>"
      }
}'
```

#### Supported Mime-Types <a href="#supported-files" id="supported-files"></a>

| Media      | Supported Content-Types                                                                                                                                                                                                                       |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `audio`    | <p><code>audio/aac</code>, <code>audio/mp4</code>, <code>audio/amr</code>, <code>audio/mpeg</code>,<br><code>audio/ogg; codecs=opus</code></p><p><br></p><p><strong>Note:</strong> The base <code>audio/ogg</code> type is not supported.</p> |
| `document` | Any valid MIME-type.                                                                                                                                                                                                                          |
| `image`    | `image/jpeg`, `image/png`                                                                                                                                                                                                                     |
| `sticker`  | `image/webp`                                                                                                                                                                                                                                  |
| `video`    | <p><code>video/mp4</code>, <code>video/3gpp</code></p><p><br></p><p><strong>Notes:</strong></p><ul><li>Only H.264 video codec and AAC audio codec is supported.</li><li>Only videos with a single audio stream are supported.</li></ul>       |


# Line

Documentation coming soon.


# Android App Integration

## **Step 1: Create App Interface And WebView Element**

Open res -> layout -> activity\_main.xml, create the application interface and add WebView element to it.

![](https://3300248524-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MDd7Ctz3jgnCJLDydlP%2F-MIClkXRGz99gf6XjNoa%2F-MICq6XxKcpJIzvQyHb_%2Fwebview%201.jpg?alt=media\&token=50c605d7-443c-4fdf-bbbf-ab5381bd5fd4)

## **Step 2: Declare A WebView Variable, Add A Link To Your Site**

Go to src -> package -> MainActivity.java. You will need to declare a WebView variable, enable JavaScript and load the link of your website. You can check the below code screenshot. Do not forget to add link of your website in mywebView\.loadUrl().

![](https://3300248524-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MDd7Ctz3jgnCJLDydlP%2F-MIClkXRGz99gf6XjNoa%2F-MICrVcWgT6Izru6xiD7%2Fwebview%202.png?alt=media\&token=1f99e875-6bbc-43be-b93c-efba70fb18cc)

## **Step 3: Set WebView Client**

Next step is to add one line of code in your MainActivity.java class given below. If you do not add this code in your app then clickable links will open in a standard web browser such as Google Chrome. To ensure that the user stays within the app and links open inside your app, you will need to add the below code.

```
mywebView.setWebViewClient(new WebViewClient());
```

## **Step 4: Remove Additional Padding**

If you want to remove the additional spacing, open activity\_main.xml and remove the padding from layouts.


