Skip to main content

Complete On-Premise and Fully Customisable Chat Bot - Part 2 - Agent Building Using Botkit

Welcome back Folks !!

In our part 1 we are reading about the overview of building the chat bot using botkit and the RASA NLU that runs in the premise without having dependency on the cloud services.

Here we will be looking at developing our Chat Bot Agent server using the botkit framework.

Building the Agent

Preparing the environment

We will start with setting up the environment for setting up the agent.

Install the Node. 

  1. You can get the installer from here. Install the node after it gets downloaded. 
  2. Once it gets succesfuly installed, open the command prompt and type.

  1. If the output shows some version number means the installation is success.

Installing the botkit using NPM (Node Package Manager)

  1. Choose some directory and make the following directory structure as follows.

This is going to be the initial directory structure.

  1.  Execute the following commands to move into the Botkit folder
    1. cd Botkit
  2. Initialise the npm package.json using 
    1. npm init
  3. You can see the package.json file created after the wizard.
{
"name": "botkit",
"version": "1.0.0",
"description": "TechSol Chat bot",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Pranav Kumar H M",
"license": "MIT"
}
view raw Package.json hosted with ❤ by GitHub
and the package.json will look like above

  1. Add the botkit package using the command (--save is to save the package to the package.json)
    1. npm install botkit --save
  2. Install the Visual Studio code as the editor for the node js. Download Link
  3. Open the Botkit folder in the visual studio code.
  4. Add a new file named index.js
Now all set for the Agent server. Lets start coding the server.

Once the Visual studio code opens, open the index.js from the file explorer on the left.

1. First lets include the header that is needed to include the needed library.
var Botkit = require("botkit"); // Botkit agent
var debug = require('debug')('botkit:main'); //debug package from Botkit to display the logs
var express = require('express'); // Express package to start the http server
var bodyParser = require('body-parser'); // body-parser to parse the request body
var querystring = require('querystring'); // querystring package to parse the values from the request query string
var debug = require('debug')('botkit:webserver'); // Another debug instance for the BOTKit Webserver
var http = require('http'); // Http module to initialise the http server along with express.
view raw index.js hosted with ❤ by GitHub
The above code have the comments that are self explanatory.


2. Create the express server instance and the HTTP server instance. Express server will act as a web server which uses the http server to run on a particular port. Both can be created as follows.
//Creating the webserver
var webserver = express();
webserver.use(bodyParser.json()); // Including the body parse to the webserver to parse the body
webserver.use(bodyParser.urlencoded({ extended: true })); // making the webserver to have the url encoded requests.
var server = http.createServer(webserver); // creating the actual http server for out BotKit server
server.listen(3000, null, function() { // Listening on port number 3000. Feel free to choose any free port for your bot
debug('Express webserver configured and listening at http://localhost:' + 3000);
});
view raw index.js hosted with ❤ by GitHub


3. Now lets create the Bot kit controller instance by using the Bot kit package that we included as follows. The Bot Kit Controller handles all the incoming and the outgoing connections and also the interfaces to handle the message.

var controller = Botkit.socketbot({ // Creating the type of Bot.Here we use the socketBot which works on the Websocket connection
debug: true,
log: true,
hostname: 'localhost'});
controller.webserver = webserver; // Provide the running server to the Botkit Controller instance
controller.httpserver = server; // Provide the running http server to the Botkit Controller instance
view raw index.js hosted with ❤ by GitHub

Also after creating the controller, let us tell the controller to use the express and the http server as the web server that it needs to use for the communication.

4. Lets now set the bot into action.

  • controller.openSocketServer(controller.httpserver);
    • This will open the websocket server in the http server port that has been specified.
  • controller.startTicking();
    • This will start the initialize the bot and will set the environment ready to work.


5. Next lets make the Bot to hear to the message the user types in. For that we need to use the controller.hear() method to do it. Hear method takes two parameters, one is the 'expression' of the message that needs to be listened up, other is the function(Bot,message) that handles the incoming message.

// Open the web socket server
controller.openSocketServer(controller.httpserver);
// Start the bot brain in motion!!
controller.startTicking();
//Make the bot hear the user message
controller.hears('hello','message_received',function(bot, message) {
// do something!
bot.reply(message, 'Hello human');
});
view raw index.js hosted with ❤ by GitHub

6. You can provide the multiple hear methods with different expression to handle the message. But if no hear matches the message then to have a fall back mechanism we need to add the following code.

// default message if there was no response
controller.on('message_received', function(bot, message) {
bot.reply(message, 'Sorry, I`m not prepared to respond to that message.');
return false;
});
view raw index.js hosted with ❤ by GitHub

All things are done. Combining everything following will be the look of the "index.js"

var Botkit = require("botkit"); // Botkit agent
var debug = require('debug')('botkit:main'); //debug package from Botkit to display the logs
var express = require('express'); // Express package to start the http server
var bodyParser = require('body-parser'); // body-parser to parse the request body
var querystring = require('querystring'); // querystring package to parse the values from the request query string
var debug = require('debug')('botkit:webserver'); // Another debug instance for the BOTKit Webserver
var http = require('http'); // Http module to initialise the http server along with express.
var controller = Botkit.socketbot({ // Creating the type of Bot.Here we use the socketBot which works on the Websocket connection
debug: true,
log: true,
hostname: 'localhost'});
//Creating the webserver
var webserver = express();
webserver.use(bodyParser.json()); // Including the body parse to the webserver to parse the body
webserver.use(bodyParser.urlencoded({ extended: true })); // making the webserver to have the url encoded requests.
var server = http.createServer(webserver); // creating the actual http server for out BotKit server
server.listen(3000, null, function() { // Listening on port number 3000. Feel free to choose any free port for your bot
debug('Express webserver configured and listening at http://localhost:' + 3000);
});
controller.webserver = webserver; // Provide the running server to the Botkit Controller instance
controller.httpserver = server; // Provide the running http server to the Botkit Controller instance
// Open the web socket server
controller.openSocketServer(controller.httpserver);
// Start the bot brain in motion!!
controller.startTicking();
//Make the bot hear the user message
controller.hears('hello','message_received',function(bot, message) {
// do something!
bot.reply(message, 'Hello human');
});
console.log('I AM ONLINE! COME TALK TO ME: http://localhost:' + 3000)
// default message if there was no response
controller.on('message_received', function(bot, message) {
bot.reply(message, 'Sorry, I`m not prepared to respond to that message.');
return false;
});
view raw index.js hosted with ❤ by GitHub


Next our job is to run the bot and talk with the bot. Since we have not created the front end. We will use any web socket client to communicate with our bot.

Start our bot using the following command in the current bot folder.

Command : node index.js

This will start the server in the port 3000.

Lets see how to communicate with the bot in the next post ..Follow the link to communicate with our bot.   :-)

Next >> http://creospiders.blogspot.com/2018/04/CompleteOn-PremiseandFullyCustomisableChatBotpart3.html

Comments

Popular posts from this blog

How to access the each view of item by position in Recycler View in android ?

How to access the each view of item by position in Recycler View in android ? There are some methods to access the view of each item view to change or update the view during the run time. To access the view of the item view , consider the Recycler view as below, RecyclerView mainRecyclerView = (RecyclerView)view.findViewById(R.id.main_recycler_view); RecyclerAdapter adapter = new RecyclerAdapter(mContext); mainRecyclerView.setAdapter(adapter); main.setLayoutManager(new LinearLayoutManager(mContext));  To access the itemView of each position the following functions can be used,  1. View itemView = mainRecyclerView.getChildAt(positionOfItem);  2. View itemView = mainRecyclerView.findViewHolderForAdapterPosition(Position).itemView;  3. View itemView = mainRecyclerView.findViewHolderForPosition(Position).itemView;  4. Long itemId = mainRecyclerView.getAdapter().getItemId(position);       View itemView = mainRecyclerView....

How Machine Learning Works ? - Data Rules the Kingdom

W elcome Back Readers !, For those who have not read the previous post on How Machine Learning works ? Please do read previous one before continuing this so that it would be more easy to understand. You can find the previous post here How Machine Learning Works ? - Mathematics Every Where . For other who are ready to join with me in this journey to understand the Machine Learning, Thank you for being with this post. Till now we are discussing on the the title "How Machine Learning works? " and to understand that we have seen in the first post that there exist the patterns or trends in the data and we try to find that in terms of a mathematical equation called a model and try to fit to the new data that we have not came across for predicting the values. Wow may be we got the entire process complete with this. But there are few thinks that needs to be cared while training the model or creating the model or while processing the data for the model creation. ...

Machine Learning - Types of Learning - Explained

W elcome back readers !! So far we are trying to understand the Machine learning in a simple way, keeping the beginners context in mind ! This is one more post, I thought I would write on explaining the various learning types in the Machine Learning. Obviously the word says "Machine Learning" - means machine learn something. How do machine can learn something is what we understood in our various posts before ( here ). We will see about how many types of learning are possible by the machines. Here when I say types of learning, I say about the various classification of learning procedures (Algorithm - Step by step procedure to solve a problem). Types of Learning: Following types of learning procedures can be identified, Regression Classification Clustering Rule association  Ensemble  Reinforcement Deep Learning I can understand that this sounds Greek and Latin now, trust me I will make you understand all this in easy way. We can't cover all the types...