Protected Skills for SUSI.AI Bot Wizard

The first version of SUSI AI web bot plugin is working like a protected skill. A SUSI.AI skill can be created by someone with minimum base user role USER, or in other words, anyone who is logged in.  Anyone can see this skill or edit it. This is not the case with a protected skill or bot. If a skill is protected it becomes a personal bot and then it can only be used by the SUSI AI web client (chatbot) created by that user. Also, only the person who created this skill will be able to edit it or delete it. This skill won’t be listed with all the other public skills on skills.susi.ai.

How is a skill made private?

To make a skill private, a new parameter is added to SusiSkill.java file. This is a boolean called protected. If this parameter is true (Yes) then the skill is protected else if the parameter is false (No) then the skill is not protected. To add protected parameter, we add the following code to SusiSkill.java:

private Boolean protectedSkill;
boolean protectedSkill = false;

You can see that protectedSkill is a boolean with initial value false.
We need to read the value of this parameter in skill code. This is done by the following code:

if (line.startsWith("::protected"&& (thenpos = line.indexOf(' ')) > 0) {
  if (line.substring(thenpos+ 1).trim().equalsIgnoreCase("yes")) protectedSkill=true;
  json.put("protected",protectedSkill);
}

As you can see that the value of protected is read from the skill code. If it’s ‘Yes’ then protectedSkill is set as true and if it’s ‘No’ then protectedSkill is set as false.
If no protected parameter is given in the skill code, its value remains false.

How to add only protected skills from bot wizard?

Now that protected parameter has been added to the server, we need to add this parameter in the skill code but it should be ‘Yes’ if the user is creating a bot and ‘No’ if user is creating a skill using skill creator. In order to do this, we simply check if the user is creating a bot wizard. This can be done by passing a props in the CreateSkill.js file when the skill creator is being used to create a protected skill. Next, we can determine whether the user is using bot wizard or not simply by an if else statement. The following code will demonstrate it:

if (this.props.botBuilder) {
 code = '::protected Yes\n' + code;
else {
 code = '::protected No\n' + code;
}

References:

Continue ReadingProtected Skills for SUSI.AI Bot Wizard

Different views for SUSI Skill Creator

SUSI Skill Creator is a service provided to easily create skills for SUSI. The skill can be written in the form of code. The coding syntax is described in SUSI skill tutorial. The problem with this is that we can’t expect everyone to be great coders and be able to understand the document and easily create a skill. Hence, we needed some robust alternatives for people who don’t want to write the code. This is where UI View and Tree View comes in.

What is UI View?

UI View or User Interface View shows the skill in form of chat bubbles. This is useful for demonstrating how the actual chat will look like.

Hello
Hi. I’m SUSI.

The following code will be shown as this in conversation view:

What is Tree View?

Tree view shows the conversation in form of a tree with its branching representing the chats.

Hello|Hi
Hi. I'm SUSI.|Hey there!

The following code will be shown as this in tree view:

How are the views synchronised?

We’re basically not making any API calls or performing any major function in any of the views. The components of different views are solely for their own function. All the API calls are made in a parent component named SkillCreator.

The main reason for creating a parent component is that we need the category, language, name and commit message options to appear on all the three views. Hence, it only makes sense to have a parent component for them and different components for the views.

The default code (that appears in code editor by default) is in a state in SkillCreator. We pass this state to the code view component as a props.

<CodeView
  skillCode={this.state.code}
  sendInfoToProps={this.sendInfoToProps}
/>

Now, we need to get any change made in the code in CodeView and change the code state of SkillCreator accordingly. For that, we have a function named sendInfoToProps which is passed as props to CodeView and is then called from CodeView whenever we make some change. This will be more clear after having a look at the function sendInfoToProps:

sendInfoToProps = value => {
 if (value) {
  this.setState(
   {
     code: value.code ? value.code : this.state.code,
     expertValue: value.expertValue
       ? value.expertValue
       : this.state.expertValue,
     groupValue: value.groupValue
       ? value.groupValue
       : this.state.groupValue,
     languageValue: value.languageValue
       ? value.languageValue
       : this.state.groupValue,
   imagUrl: value.imageUrl ? value.imageUrl : this.state.imageUrl,
   },
   () => this.generateSkillData(),
  );
 }
};

You can see that we update the code in SkillCreator and other states required. Also, you can notice the we’re calling generateSkillData function here. This is done to convert the code to skill data which is sent to Conversation view and Tree view as props.
We’re calling generateSkillData as a callback function because setState is an asynchronous function.
This will demonstrate how this is passed to Conversation view:

<ConversationView
  skillData={this.state.skillData}
  handleDeleteNode={this.handleDeleteNode}
/>

Same is the case for this handleDeleteNode function. We have an option in both Conversation view and Tree view to allow the user to delete a conversation (originally written as skill in code view). On delete, handleDeleteNode is called from the props and the conversation is deleted from the code which is then send to all the views (as props) and the views are updated as well.

References:

Continue ReadingDifferent views for SUSI Skill Creator

Code view and UI View in design tab of bot wizard

Design tab is for designing your SUSI AI chatbot. You can change the background colour, add an image as background color, change colour of user text box, bot text box etc. On SUSI AI bot wizard design tab, we have two views. These views show the same thing but in a different way for different people. The code view is mainly for the developers while the UI (User Interface) view is for a non-developer user because we can not expect them to know how to code even if it is easy.

Code View

The current code view of design tab looks like this:

::bodyBackground #ffffff
::bodyBackgroundImage
::userMessageBoxBackground #0077e5
::userMessageTextColor #ffffff
::botMessageBoxBackground #f8f8f8
::botMessageTextColor #455a64
::botIconColor #000000
::botIconImage

For changing colours, you simply have to change the hex codes and for adding images as background, you need to add the url of image. You can also upload an image but that function is provided in the UI View.

UI View

The current UI view of design tab looks like this:

Here, we have colour picker for user to choose a colour for various components of the chatbot. There’s also a small box with the same colour as specified in hex code for previewing.

Switching and Synchronising between Code view and UI view

We have different components for code view and UI view. In order to synchronise both the views, we need to have the same code in state of both components. To do that, we add the code in state of the parent component i.e. design.js and then pass it to code view and UI view as states.

The following code snippet will demonstrate this:

<CodeView
    design={{
        sendInfoToProps: this.sendInfoToProps,
        updateSettings: this.updateSettings,
        code: this.state.code,
    }}
/>

You can see that we pass a whole object as props.
Using this approach, same code is passed to both the views. This solves the first problem. The next problem is that if we do a change in code view then it should happen in the code state of parent file as well. Same goes for UI view.
To do this, whenever we change the code in code view or UI view, we call a function in the parent file (design.js) which was passed as props and we pass the state of code view or UI view as arguments of this function. This function then updates the state accordingly. The name of the function is sendInfoToProps and it is as follows:

sendInfoToProps = values => {
    this.setState({ ...values });
};

You can see that it simply updates the state value as per the parameters passed to it.
So this is how synchronisation works between different views.

References:

Continue ReadingCode view and UI View in design tab of bot wizard

How to receive different types of messages from SUSI Line Bot

In this blog, I will explain how to receive different types of messages responses from LINE Bot. This includes text, sticker, video, audio, location etc types of responses. Follow this tutorial to make SUSI AI LINE Bot.

How does LINE Messaging API work?

The messaging API of LINE allows data to be passed between the server of SUSI AI and the LINE Platform. When a user sends a message to SUSI bot, a webhook is triggered and the LINE Platform sends a request to our webhook URL. SUSI Server then sends a request to the LINE Platform to respond to the user. Requests are sent over HTTPS in JSON format.

Different Message types

  1. Image Messages

To send images, we need two things, the URLs of original image and smaller preview image in the message object. The preview image will be displayed in text and full image is displayed when user clicks on the preview image.
The message object for image message has 3 properties –

Property

Type

Description

type

String

image

originalContentUrl

String

Image URL

previewImageUrl

String

Preview image URL

Sample Message object:

{
   "type": "image",
   "originalContentUrl": "https://susi.ai/original.jpg",
   "previewImageUrl": "https://susi.ai/preview.jpg"
}
  1. Video Messages

To send videos, we need two things, the URL of video file and URL of preview image of video in the message object.
The message object for video messages has 3 properties:

Property

Type

Description

type

String

image

originalContentUrl

String

Video file URL

previewImageUrl

String

Preview image URL

Sample Message object for video type responses:

{
   "type": "video",
   "originalContentUrl": "https://susi.ai/original.mp4",
   "previewImageUrl": "https://susi.ai/preview.jpg"
}
  1. Audio Messages

To send an audio message, you have to include the URL to audio file and the duration in the message object.
The message object for audio messages has 3 properties:

Property

Type

Description

type

String

image

originalContentUrl

String

Audio file URL

duration

Number

Length of the Audio file in milliseconds

Sample Message object for audio type responses:

{
   "type": "audio",
   "originalContentUrl": "https://susi.ai/original.m4a",
   "duration": 10000
}
  1. Location Messages

To send location information to users, you need to include title, address, latitude and longitude of the location.
The message object needs to include 5 properties:

Property

Type

Required

Description

type

String

Required

location

title

String

Required

Title

address

String

Required

Address

latitude

Decimal

Required

Latitude

longitude

Decimal

Required

Longitude

Sample Message object for location type responses:

{
   "type": "location",
   "title": "singapore",
   "address": "address",
   "latitude": 1.2896698812440377,
   "longitude": 103.85006683126556
}

How to use these Message objects?

You have to send the response that you got from SUSI server to LINE platform. Now this response is sent in the form of an object. This object tells the LINE platform about the type of this message. So simply sending this object to reply API of LINE sends the message to user.
It looks like this:

return client.replyMessage(event.replyToken, answer);

References:

Continue ReadingHow to receive different types of messages from SUSI Line Bot

How to make SUSI AI Twitch Bot

In this blog post, we’ll learn how to make SUSI AI Twitch botSUSI.AI is an intelligent Open Source personal assistant. SUSI AI Bots are built to enable users to chat with SUSI on different clients. Twitch is a live streaming video platform. We can integrate SUSI AI to the live chat on any of its channels.

Pre-requisites:

  1. A Main Twitch account (This is the account on whose channel users would be able to talk to SUSI)
  2. A separate Twitch account for SUSI.
  3. GitHub Account

Create a GitHub from here – Sign up on GitHub

  1. Heroku Account

To create Heroku account, go to Heroku and click on Sign Up.

  1. Node.js

Install Node.js from https://nodejs.org/en/ if it isn’t installed already on your computer.

To check if node is already installed or not, open terminal and type the command:

node -v

If you see something like this – (version can be different)

v9.4.0

Then Node.js is installed on your computer and you can follow along.

Procedure:

You can either fork susi_twitchbot repository and then simply deploy it on Heroku to create SUSI AI Twitch bot or you can create a new repository on your account then deploy it. The following section will describe how to create a new repository for SUSI AI Twitch bot. If you want to deploy susi_twitchbot directly then skip this section and directly move on to the deployment section.

Creating the SUSI AI Twitch codebase:

1. Create a folder on your computer with any name. Open terminal and change your current directory to the new folder that you just created.

2. Type npm init command and enter details like name, version etc. (preferably just keep pressing enter key and let the values stay default)

3. Create a file with the same name that you wrote in entry point (index.js by default). NOTE – It should be in the same folder that you created earlier.

4. In the same folder, type the following commands in command line –

npm i -s tmi.js

We need tmi.js module to easily interact with Twitch messaging interface. For more details, visit https://www.tmijs.org/.

npm i -s request

We need request module to make a GET request to the SUSI API and retrieve JSON data for a particular query.

npm i -s express

We need express module to create successful connection with Heroku through the port provided by it.

5. Open package.json file. It should look like this:

(Adding “start” script is necessary for deploying the app on Heroku)

{
  "name": "susi_twitchbot",
  "version": "1.0.0",
  "description": "SUSI.AI Twitchbot",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "request": "^2.86.0",
    "tmi.js": "^1.2.1"
  }
}

6. Copy the following code into the file that you created i.e. index.js

var tmi = require('tmi.js');
var request = require('request');
const express = require('express');
const app = express();
const userChannel = process.env.CHANNEL;

var ans;
var options = {
        options: {
                debug: true
        },
        connection: {
                reconnect: true
        },
        identity: {
                username: process.env.USERNAME,
                password: process.env.OAUTH_TOKEN
        },
        channels: [userChannel]
};

var client = new tmi.client(options);
// Connect the client to the server
client.connect();
client.on('chat', function(channel, userstate, message, self){
        if(message.includes("@"+process.env.USERNAME)){ // checking if SUSI is tagged
                var u = message.split("@" + process.env.USERNAME + " ");
                // Setting options to make a successful call to SUSI API
                var options1 = {
                        method: 'GET',
                        url: 'http://api.susi.ai/susi/chat.json',
                        qs:
                        {
                                timezoneOffset: '-300',
                                q: u[1]
                        }
                };
                request(options1, function(error, response, body) {
                        if (error) throw new Error(error);
                        if((JSON.parse(body)).answers[0])
                                ans = userstate['display-name'] + " " + (JSON.parse(body)).answers[0].actions[0].expression;
                        else
                                ans = userstate['display-name'] + " Sorry, I could not understand what you just said."
                
                        client.action(userChannel, ans);
                });
        }
});

client.on('connected', function(address, port){
        client.action(userChannel, `Hi, I'm SUSI. Mention me using @${process.env.USERNAME} to chat with me.`);
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
   console.log(`Listening on ${port}`);
});

7. Before we can deploy this bot to Heroku, we have to make a GitHub repository for it. For making a github repository for the chatbot, follow these steps:

In the command line, change current directory to the folder we created above for the bot and type in the following commands.

git init
git add .
git commit -"initial"

Now, you have to create a Github repository, follow these steps to do that –

  1. Go to https://github.com/ and login.
  2. Create a new repository. Choose any name.
  3. Get the URL for remote repository and copy it.

Again go to the command line, change current directory to the folder we created above for the bot and type in the following commands.

git remote add origin <URL for remote repository that you just copied>
git remote -v
git push -u origin master

Setting up SUSI bot account on Twitch:

In order to set up SUSI AI bot on Twitch, go to http://twitchapps.com/tmiclick on “Connect with Twitch” and login to the account that will be used as SUSI AI bot. This will generate an OAuth tokenSave it for later use.

Deploying the Bot on Heroku:

  1. Got to Heroku and login.
  2. Go to dashboard and create a new app.
  3. After creating an app, go to Deploy and choose “GitHub” for Deployment method.

  1. Search for the repository that you created on GitHub or select susi_twitchbot after forking it. Connect to it in “App connected to GitHub”.
  2. Enable Automatic deployment.

  1. Now go to Settings and add the following config vars “CHANNEL”, “OAUTH_TOKEN”, “USERNAME” and “HEROKU_URL”.
  • The key of “CHANNEL” is the channel name on which you’d like to talk to SUSI.
  • The key of “OAUTH_TOKEN” is the OAuth key that you generated earlier. (Remember to include “oauth:” in the key)
  • The key of “USERNAME” is the username of the Twitch account you created for SUSI AI.
  • The key of “HEROKU_URL” is “http://<your_app_name>.herokuapp.com” (write ‘http’ and not ‘https’).

  1. Go to Deploy, Press “Deploy Branch” under “Manual Deployment”.

Now your SUSI AI Twitch bot is successfully deployed on Heroku. Go to your Twitch channel and mention your SUSI account using ‘@’ and start talking to SUSI!

Here, ‘dns4044′ is the owner of channel, ‘testdns’ is some user on the channel and ‘susiaibot’ is SUSI AI Twitch bot.

References:

Continue ReadingHow to make SUSI AI Twitch Bot

How does live preview work on SUSI AI chatbot wizard

Live preview is an important feature for the chatbot building process in SUSI.AI botbuilder. It tells the bot creator how the bot looks and behaves at any time.

We use iframe for creating a live preview.

What is iframe?

Frames allow browser window to be split into separate segments. All these segments can be used for displaying a different webpage within the browser window.

is an HTML tag. iframe stands for “inline frame”. It places another HTML document in a frame. The content of the element is used as an alternative text to be displayed if the browser does not support inline frames.

This was first introduced by Microsoft Internet Explorer in 1997, standardized in HTML 4.0 transitional and allowed in HTML5.

Syntax:

<iframe src=”URL”></iframe>

Some attributes:

  • Height
  • Width
  • Name
  • Id

Code used for preview of chatbot screen:

<iframe title="botPreview" name="frame-1" id="frame-1" src={locationBot} height="600px" style={styles.iframe}></iframe>

Code used for preview of chatbot avatar:

<iframe title="botAvatarPreview" name="frame-2" id="frame-2" src={locationAvatar} height="100px" style={styles.iframe}></iframe>

Preview bot fetches the current theme status and skill status from SUSI server and then applies it to the chatbot. Now, this details will be unique to the user logged in. Hence, we need to somehow identify the person logged in. This is done using access token stored in the cookies which is accessed through cookies.get(‘loggedIn’).

How to pass access token to iframe?

This is the major issue faced when creating preview using iframe because even though the HTML window in iframe is rendered on the same parent page, we can not access the elements of HTML page inside iframe. This is because iframe loads dynamically. There are few solutions for this problem.

One of them is to create a script in iframe that would run when iframe is loaded. Now this script can access the elements of parent window (the one containing iframe) using window.parent.document.getElementById(‘#target’)

The best solution is however to pass the access token in the URL of the source of iframe. Then this can be accessed by HTML page in frame using location.href .

Code sample to pass access token in url:

src = '/BotPreview.html?access='+cookies.get('loggedIn')

Now, we have to split this URL and get the access token. This can be easily done using the following script.

var url = location.href.split(‘?’)[1].split(‘=’);
var access_token = url[1];

Here in this example, the url variable firstly splits the URL at ‘?’. This creates an array with two elements.

[‘url.com/BotPreview.html’, ‘access=abcdef123’]

Then we access the element on index 1, i.e. ‘access=abcdef123’ and split it at the ‘=’. This further creates an array of two elements.

[‘access’, ‘abcdef123’]

Now, we can access the access token which is at index 1 in this array.

References

Continue ReadingHow does live preview work on SUSI AI chatbot wizard

How to deploy SUSI AI bots on ngrok for debugging

For production purposes, bots can be deployed in cloud services such as HerokuGoogle App Engine or Amazon Web Services – or in their own data center infrastructure.

However, for development purposes you can use ngrok to provide access to your bot running in your local network. Ngrok is easy to setup and use. To learn more about it, you can refer to its documentation.

Ngrok is a handy tool and service that allows you tunnel requests from the wide open Internet to your local machine when it’s behind a NAT or firewall. It’s commonly used to develop web services and webhooks.

In this blog, you’ll learn how to deploy SUSI AI bots on ngrok. We’re going to demonstrate the process for SUSI AI Kik bot. However it is the same for rest of the bots as well.

First of all, you need to configure a bot on Kik. To configure a Kik bot, follow the first few steps of this blog post till you get an API key for the bot that you created using Botsworth. Now, follow these steps:

  1. In order to run SUSI AI kik bot on ngrok, you have to make some changes to the index.js file after forking susi_kikbot repository and cloning it to your local machine.
  2. Open index.js and change the information in ‘bot’ object. Write username of your kik bot in front of username and api key that you got for your bot in front of apiKey in quotations and leave the baseUrl blank for now. It will look like this: (Don’t copy the API key shown below. It’s invalid and only for demonstration purposes.)
var bot = new Bot({
    username: 'susi.ai',
    apiKey: 'b5a5238b-b764-45fe-a4c5-629fsd1851bd',
    baseUrl: ''
});
  1. Now save the file. No need to commit it.
  2. Go to https://ngrok.com/ and sign up.
  3. Next, you’ll be redirected to the setup and installation page. Follow the instructions there to setup ngrok on your local machine.
  4. Now open terminal and use ‘cd’ command to go to the susi_kikbot directory.
  5. While deploying on ngrok, we set the port for listening to http requests. Hence remove “process.env.PORT” from index.js or else this will cause an error in the next step. After removing, it should look like this: (Now save the index.js file)
http.createServer(bot.incoming()).listen(8080);

Also, comment out setInterval function in index.js.

  1. Now type the command ngrok http 8080 in terminal. In case ‘ngrok’ command doesn’t run, copy the ngrok file that you downloaded in step 5 and paste it in the susi_kikbot directory. Then enter ./ngrok http 8080 in terminal.
  2. When it launches, you’ll see a screen similar to the following:

  1. Copy the “forwarding” address (https://d36f0add.ngrok.io), and paste it in front of ‘baseUrl’ in the ‘bot’ object in index.js file. Add “/incoming” after it and save it. Now the ‘bot’ object should look similar to this:
var bot = new Bot({
    username: 'susi.ai',
    apiKey: 'b5a5238b-b764-45fe-a4c5-629fsd1851bd',
    baseUrl: 'https://d36f0add.ngrok.io/incoming'
});
  1. Launch another terminal window and cd into the susi_kikbot directory in your local machine. Then type node index.js command.

Congratulations! You’ve successfully deployed SUSI AI Kik bot on ngrok. Now try sending a message to your SUSI AI Kik bot.

References

Continue ReadingHow to deploy SUSI AI bots on ngrok for debugging

How to make SUSI AI LINE Bot

 

(The blog previously written for “How to make SUSI AI Line Bot” is no longer valid as a lot has changed since then. SUSI API, LINE developer menu etc has changed. This blog post describes the updated procedure for creating SUSI AI LINE Bot. The previous blog can be found here – https://blog.fossasia.org/how-to-make-susi-ai-line-bot/)

Susi AI is an intelligent Open Source personal assistant. SUSI AI Bots are built to enable users to chat with SUSI on different clients.

Pre-requisites –

1. In order to integrate SUSI’s API with Line bot, you will need to have a Line account first.

Download LINE Messenger app from here –

Google Play Store

Apple App Store

2. GitHub Account

Create a GitHub from here – Sign up on GitHub

3. Heroku Account

To create Heroku account, go to Heroku and click on Sign Up.

4. Node.js

Install Node.js from https://nodejs.org/en/ if it isn’t installed already on your computer.

To check if node is already installed or not, open terminal and type the command –

node -v

If you see something like this – (version can be different)

v9.4.0

Then Node.js is installed on your computer and you can follow along.

Procedure:

Now that you have created a LINE account, GitHub account, Heroku account and installed Node.js, we can move to the creating the SUSI AI bot.

You can either deploy susi_linebot repository to create SUSI AI LINE bot or you can create a new repository on your account then deploy it to Heroku. The next section will describe how to create a new repository for deploying SUSI AI Line bot. If you want to just deploy susi_linebot then skip the next section.

Creating the SUSI AI LINE bot codebase:

1. Create a folder on your computer with any name. Open terminal and change your current directory to the new folder you just created.

2. Type npm init command and enter details like name, version etc. (preferably just keep pressing enter key and let the values stay default)

3. Create a file with the same name that you wrote in entry point (index.js by default). NOTE – It should be in the same folder that you created earlier.

4. Type the following commands in command line –

npm i -s @line/bot-sdk
npm i -s express
npm i -s request

5. Open package.json file. It should look like this:

{
  "name": "susi_linebot",
  "version": "1.0.0",
  "description": "SUSI AI LINE bot",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@line/bot-sdk": "^6.0.1",
    "express": "^4.16.3",
    "request": "^2.85.0"
  }
}

You should see “@line/bot-sdk”, “express” and “request” under dependencies. Versions can change. Make sure to add “start” under scripts or else deploying on Heroku will cause an error.

6. Copy the following code into the file that you created i.e. index.js

'use strict';
const line = require('@line/bot-sdk');
const express = require('express');
var request = require("request");

// create LINE SDK config from env variables
const config = {
   channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
   channelSecret: process.env.CHANNEL_SECRET,
};

// create LINE SDK client
const client = new line.Client(config);

// create Express app
// about Express: https://expressjs.com/
const app = express();

// register a webhook handler with middleware
app.post('/webhook', line.middleware(config), (req, res) => {
   Promise
       .all(req.body.events.map(handleEvent))
       .then((result) => res.json(result))
       .catch((err) => {
        console.error(err);
        res.status(500).end();
      });
});

// event handler
function handleEvent(event) {
   if (event.type !== 'message' || event.message.type !== 'text') {
       // ignore non-text-message event
       return Promise.resolve(null);
   }
   var options = {
       method: 'GET',
       url: 'https://api.susi.ai/susi/chat.json',
       qs: {
           timezoneOffset: '-330',
           q: event.message.text
       }
   };
   request(options, function(error, response, body) {
       if (error) throw new Error(error);
       // answer fetched from susi
       var ans = (JSON.parse(body)).answers[0].actions[0].expression;
       // create a echoing text message
       const answer = {
           type: 'text',
           text: ans
       };
       // use reply API
       return client.replyMessage(event.replyToken, answer);
   })
}

// listen on port

const port = process.env.PORT || 3000;
app.listen(port, () => {
   console.log(`listening on ${port}`);
});

7. In order to deploy this bot on Heroku, we have to make a github repository for it. For making a github repository for the chatbot, follow these steps:

In the command line, change current directory to the folder we created above for the bot and type in the following commands.

git init
git add .
git commit -m "initial"

Now, you have to create a Github repository, follow these steps to do that –

  1. Go to https://github.com/ and login.
  2. Create a new repository. Choose any name.
  3. Get the URL for remote repository and copy it.

Again go to the command line, change current directory to the folder we created above for the bot and type in the following commands.

git remote add origin <URL for remote repository that you just copied>
git remote -v
git push -u origin master

Creating SUSI AI bot on LINE:

1. Go to LINE Developers and click on “Start using Messaging API”.

2. Login through the email ID you used for creating LINE account on LINE app. (If you didn’t enter an email address while creating LINE account then go to “Settings” on LINE app and click on “Account”. Now enter an email address.)

3. Now you have to create a new channel. For that, first of all select a provider or create a new one. You can name it anything.

4. Enter the information for Messaging API. Write all details like App name, description etc. Choose “Developer Trial” under Plan option.

5. Choose any category, subcategory, type in your email address and click Confirm.

6. Now click on your channel to open channel settings.

7. Under “Messaging settings”, click on Issue to issue a channel access token. Choose any number of hours and then issue it. Copy it and save it somewhere. We’ll need it later on.

8. Copy Channel secret given on the same page.

Deploying the Bot on Heroku:

1. Go to Heroku and login.

2. Go to dashboard and create a new app.

3. After creating an app, go to Deploy and choose “GitHub” for Deployment method.

4. Search the repository that you created on GitHub or select susi_linebot after forking it and connect to it in “App connected to GitHub”.

5. Enable Automatic deployment.

6. Now go to Settings and setup Config Variables.

Add the channel access token which you copied earlier as value of “CHANNEL_ACCESS_TOKEN” and the channel secret as value of “CHANNEL_SECRET”. After saving, click on Hide Config Vars.

Now, your bot is deployed on Heroku.

Final Steps:

Finally, go back to LINE Developers website. In settings of SUSI AI app, under “Messaging settings”, enable webhooks and add webhook URL. It will look like this:

https://<your_heroku_app_name>.herokuapp.com/webhook

Clicking on “verify” should show success as shown.

Congratulations! Your SUSI AI LINE bot is ready! Add it as a friend by scanning the QR code provided in the same settings menu and start chatting with SUSI.

References:

Continue ReadingHow to make SUSI AI LINE Bot

Maintaining Extension State in SUSI.AI Chrome Bot Using Chrome Storage API

SUSI Chrome Bot is a browser action chrome extension which is used to communicate with SUSI AI.The browser action extension in chrome is like any other web app that you visit. It will store all your preferences like theme settings and speech synthesis settings and data till you are interacting with it, but once you close it, it forgets all of your data unless you are saving it in some database or you are using cookies for the session. We want to be able to save the chats and other preferences like theme settings the user makes when interacting with SUSI AI through Susi Chrome Bot. In this blog, we’ll explore Chrome’s chrome.storage API for storing data.

What options do we have for storing data offline?

IndexedDB: IndexedDB is a low-level API for client-side storage of data. IndexedDB allows us to store a large amount of data and works like RDBMS but IndexedDB is javascript based Object-oriented database.

localStorage API: localStorage allows us to store data in key/value pairs which is much more effective than storing data in cookies. localStorage data persists even if the user closes and reopens the browser.

Chrome.storage: Chrome provides us with chrome.storage. It provides the same storage capabilities as localStorage API with some advantages.

For susi_chromebot we will use chrome.storage because of the following advantages it has over the localstorage API:

  1. User data can be automatically synced with Chrome sync if the user is logged in.
  2. The extension’s content scripts can directly access user data without the need for a background page.
  3. A user’s extension settings can be persisted even when using incognito mode.
  4. It’s asynchronous so bulk read and write operations are faster than the serial and blocking localStorage API.
  5. User data can be stored as objects whereas the localStorage API stores data in strings.

Integrating chrome.storage to susi_chromebot for storing chat data

To use chrome.storage we first need to declare the necessary permission in the extension’s manifest file. Add “storage” in the permissions key inside the manifest file.

"permissions": [
         "storage"
       ]

 

We want to store the chat user has made with SUSI. We will use a Javascript object to store the chat data.

var storageObj = {
senderClass: "",
content: ""
};

The storageObj object has two keys namely senderClass and content. The senderClass key represents the sender of the message(user or susi) whereas the content key holds the actual content of the message.

We will use chrome.storage.get and chrome.storage.set methods to store and retrieve data.

var susimessage = newDiv.innerHTML;
storageObj.content = susimessage;
storageObj.senderClass = "susinewmessage";
chrome.storage.sync.get("message",(items) => {
if(items.message){
storageArr = items.message;
}
storageArr.push(storageObj);
chrome.storage.sync.set({"message":storageArr},() => {
console.log("saved");
});
});

 

In the above code snippet, susimessage contains the actual message content sent by the SUSI server. We then set the correct properties of the storageObj object that we declared earlier. Now we can use chrome.storage.set to save the storageObj object but that would overwrite the current data that we have inside chrome’s StorageArea. To prevent the old message data from getting overwritten, we’ll first get all the message content in our storage using chrome.storage.sync.get. Notice how we are passing the “message” string as the first perimeter to the function. This is done because we only want our message content which was saved in the StorageArea. If we pass null instead, it will return all the content inside storageArea. Once we have our messages (which will be an array of objects that we store as storageObj), we will store that into a new array storageArr. We will then push our new storageObj that contains the message and the sender into the array. Finally, we use chrome.storage.sync.set to save the message content in chrome’s StorageArea which can later be retrieved using the “message” key.

storageArr.push(storageObj);
chrome.storage.sync.set({"message":storageArr},() => {
console.log("saved");
});

We use the same procedure to save messages sent by the user.

Note: chrome.storage is not very large, so we need to be careful about what we store or we may run out of storage space. Also, we should not store confidential data in storage since the storage area is not encrypted.

Resources:

Tags:

  • FOSSASIA, codeheat, Chrome extensions, Javascript, Chrome Storage, Chrome Sync, Susi Chrome Bot, SUSI AI, Bot Development
Continue ReadingMaintaining Extension State in SUSI.AI Chrome Bot Using Chrome Storage API

How to make SUSI kik bot

To make SUSI kik bot first you have to configure a bot. To configure bot go to https://dev.kik.com/ and make your bot by scanning code from your kik mobile app.You have to answer following questions from botsworth and make your bot.

 

After logging in to your dashboard get your api key by going to configuration menu on top.

After your bot is setup follow given steps to create your first susi kik bot.

Steps:

  1. Install Node.js from the link below on your computer if you haven’t installed it already.
    https://nodejs.org/en/
  2. Create a folder with any name and open shell and change your current directory to the new folder you created.
  3. Type npm init in command line and enter details like name, version and entry point.
  4. Create a file with the same name that you wrote in entry point in above given step. i.e index.js and it should be in same folder you created.
  5. Type following commands in command line  npm install –save @kikinteractive/kik. After @kikinteractive/kik is installed type npm install –save http after http is installed type npm install –save request when all the modules are installed check your package.json these modules will be included within dependencies portion.

  6. Your package.json file should look like this.

     
    {
     "name": "susi_kikbot",
       "version": "1.0.0",
     "description": "susi kik bot",
     "main": "index.js",
     "scripts": {
       "test": "node tests/sample.js"
     },
     "license": "MIT",
     "dependencies": {
       "@kikinteractive/kik": "^2.0.11",
       "request": "^2.75.0"
     }
    }
    
    
  7. Copy following code into file you created i.e index.js and add your bot name to it in place of username.

    var http = require('http');
    var Bot = require('@kikinteractive/kik');
    var request = require('request')
    var answer;
     
    var bot = new Bot({
     
        username: '<your-bot-name>',
        apiKey: process.env.API_KEY,
        baseUrl: process.env.HEROKU_URL
     
    });
     
    bot.updateBotConfiguration();
     
    bot.onTextMessage((message) => {
     
        request('http://api.asksusi.com/susi/chat.json?q=' + encodeURI(query), function(error, response, body) {
     
            if (!error && response.statusCode == 200) {
     
                answer = JSON.parse(body).answers[0].actions[0].expression;
     
            } else {
     
                answer = "Oops, Looks like Susi is taking a
                break, She will be back soon";
     
            }
     
        });
     
        message.reply(answer)
    });
     
    http.createServer(bot.incoming()).listen(process.env.PORT || 5000)
    
    
  8. Before deploying our bot to heroku so that it can be active we have to make a github repository for chatbot to make github repository follow these steps.In shell change current directory to folder we created above and  write
    git init
    git add .
    git commit -m”initial”
    git remote add origin <URL for remote repository>
    git remote -v
    git push -u origin master

    You will get URL for remote repository by making repository on your github and copying this link of your repository.

  9. To deploy your bot to heroku you need an account on Heroku and after making an account make an app.

     

  10. Deploy app using github deployment method.
  11. Select Automatic deployment method.
  12. Go to settings of your app and config variables and paste your API key for bot to this and name it as API_KEY and get your heroku app url and make a variable for it named HEROKU_URL.
  13. Your susi bot is ready now test it by massaging it.

If you want to learn more about kik API then refer to https://dev.kik.com/#/docs/messaging

 

Resources:

Github Repository: https://github.com/fossasia/susi_kikbot
KIK bot API: https://dev.kik.com/#/docs/messaging

Continue ReadingHow to make SUSI kik bot