Build universal bot using NodeJs

Build universal bot using NodeJs

 

 

Microsoft has recently released Bot framework: it is a very useful framework to build and connect intelligent bots to interact with your users naturally wherever they are, from Telegram to Skype, Slack, Facebook and other popular services.

This article shows how to build universal bot using NodeJs and Bot framework. The purpose is to build an bot which can recognise and describe an image using  Microsoft Cognitive Services.

I have already wrote about bot framework in the following article:  Developing artificial intelligence using .NET.

The demo code is available on Github.

Setup node project

First of all, create a folder for your bot and initialize the node project using:

npm init

Next, you need to install the project dependencies by running:

npm install --save botbuilder
npm install --save restify

Restify is a is a node.js module built specifically to enable you to build correct REST web services and botbuilder contains the Bot framework.

Diagram

Here’s a simple diagram of the node project. It illustrates the architecture or the project:

Universal bot development using NodeJs

Code

ConfigurationHelper.js

The ConfigurationHelper.js contains an object which represents the configurations of the bot:

var _config = {
CHAT_CONNECTOR: {
APP_ID: "", //You can obtain an APP ID and PASSWORD here: https://dev.botframework.com/bots/new
APP_PASSWORD: ""
},
COMPUTER_VISION_SERVICE: {
API_URL: "https://api.projectoxford.ai/vision/v1.0/",
API_KEY: "" //You can obtain an COGNITIVE SERVICE API KEY: https://www.microsoft.com/cognitive-services/en-us/pricing
}
};
exports.CONFIGURATIONS = _config;

In particular:

  • CHAT_CONNECTOR contains the ID and Password of your bot, which can be obtained here.
  • COMPUTER_VISION_SERVICE contains the Url and the API Key of the Cognitive Services which can be obtained here.

BotHelper.js

The BotHelper.js contains some utils methods to extract Urls from incoming messages:

exports.extractUrl = function _extractUrl(message) {
if (message.type !== "message") return;
if (typeof message.attachments !== "undefined"
&& message.attachments.length > 0) {
return message.attachments[0].contentUrl;
}
if (typeof message.text !== "") {
return _findUrl(message.text);
}
return "";
};
function _findUrl(text) {
var source = (text || '').toString();
var matchArray;
// Regular expression to find FTP, HTTP(S) and email URLs.
var regexToken = /(((http|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)/g;
// Iterate through any URLs in the text.
if ((matchArray = regexToken.exec(source)) !== null) {
var token = matchArray[0];
return token;
}
return "";
}

VisionService.js

The VisionService.js contains some methods to retrieve information from Microsoft Cognitive services and to extract the response sent by the bot:

var request = require("request");
var config = require("./../Helpers/ConfigurationHelper");
exports.describeImage = function _describeImage(url, callback) {
var options = {
method: 'POST',
url: config.CONFIGURATIONS.COMPUTER_VISION_SERVICE.API_URL + "describe/",
headers: {
'ocp-apim-subscription-key': config.CONFIGURATIONS.COMPUTER_VISION_SERVICE.API_KEY,
'content-type': 'application/json'
},
body: {url: url},
json: true
};
request(options, callback);
};
exports.extractCaption = function _extractCaption(bodyMessage) {
if (typeof bodyMessage.description === "undefined") return "";
var desc = bodyMessage.description;
if (typeof desc.captions !== "undefined" &&
desc.captions.length > 0) {
return desc.captions[0].text;
}
return "Oops, I can't recognize it :( !";
};

app.js (Entry point)

app.js is the main entry point of the node server, it runs all processes used by the bot:

var restify = require('restify');
var builder = require('botbuilder');
var config = require('./Helpers/ConfigurationHelper');
var botHelper = require("./Helpers/BotHelper");
var visionService = require("./Services/VisionService");
//=========================================================
// Bot Setup
//=========================================================
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
// Create chat bot
var connector = new builder.ChatConnector({
appId: config.CONFIGURATIONS.CHAT_CONNECTOR.APP_ID,
appPassword: config.CONFIGURATIONS.CHAT_CONNECTOR.APP_PASSWORD
});
var bot = new builder.UniversalBot(connector);
server.post('/api/messages', connector.listen());
//=========================================================
// Bots Dialogs
//=========================================================
bot.dialog('/', function (session) {
console.log(session.message);
var extractedUrl = botHelper.extractUrl(session.message);
if (extractedUrl === "") {
session.send("Please, send me an image or link");
}
visionService.describeImage(extractedUrl, function (error, response, body) {
session.send(visionService.extractCaption(body));
})
});
view raw app.js hosted with ❤ by GitHub

Deploy the project

In order to use the bot on the messaging platforms, is necessary to deploy the node project on an hosting provider. There are a lot of options, for example: AWS, Microsoft Azure or Heroku.

In case of a simple demo, I think Heroku is the best choice: it’s very immediate and simple. You can connect your Heroku app with github repository, or upload the source code on server.

Setup bot using bot framework

Once you have deployed the node app on server, you need to register the bot  at the following page: https://dev.botframework.com/bots/new, in order to distribute the bot on all messaging platform supported.

Final Result

Universal bot development using NodeJs

 

Final thoughts

Bot framework allows developers to build universal bot using Node.js or .NET framework.

Why chat bots are important to your business?

  • Available anytime: consumers are often annoyed when businesses only seem to keep banker’s hours. Consumers don’t all work banker’s hours and need to be able to contact a company any time of the day or night for assistance;
  • Converting Data to Personalized Advertisements: a bot can send you shoppable looks. Depending on which photos and products you have liked or previously purchased, it can send you product recommendations or deliver coupons for in-store purchases;
  • Natural Language Communication: consumers need to believe they are speaking to a real person. Chatbots are programmed to react specifically to direct responses from consumers, and offer the right products for their needs;

The demo code is available on Github.

Cheers 🙂