Partager via


Build a chat bot in under 10 minutes using Node.js and the Microsoft Bot Framework

Chat bots are a great way to engage your customers with the ability to provide a truly personalised experience. They are easy to build and provide huge business impact and thanks to the extensive SDKs provided by Microsoft, you don't have to use C#/.NET.

As Microsoft continues to transform and embrace open source and support cross platform development, we continue to build SDKs for languages other than .NET creating an open ecosystem that welcomes anyone with any development skillset to adopt our services. As an employee, C# was my go to language for demos and prototypes, however building a simple API or Web App for demo purposes could prove to be time consuming.

Hello Node.js.

It's no secret that javascript is gaining momentum as the web development language of choice. With the ability to quickly knock up prototypes to prove value and the plethora of community modules available, it easy to see why we are embracing Node.js and providing first class support for many of our Azure and online services through the availability of Node.js SDKs.

In this blog I will show you how to quickly build a chat bot in Node.js and if you don't have a copy yet, I recommend you download our free cross platform source code editor Visual Studio Code which coincidently is built on Node.js.

As a pre-requisite, this blog assumes you have a basic understanding of javascript and Node.js. If not head over to one of the many Node.js tutorial sites and build yourself a "hello world" application, preferably with the express module.

It also assumes you have knowledge of the basic components required to build a bot including dialogs, prompts, cards. If not you can familiar yourself with these key concepts here: https://docs.botframework.com/en-us/node/builder/overview/

Finally you must register your bot on the Bot Framework portal which can be done here: https://dev.botframework.com/bots/new. This will provide you with the AppId and AppPassword required to register your bot against the portal as well as the ability to publish your bot through multiple consumer channels including Skype and Facebook.

Begin you chat bot application by downloading via npm and including the following modules :

var restify = require("restify"); var builder = require("botbuilder"); var url = require("url");

We use the restify module to build the REST Apis required, although express could be used as an alternative.

While the url module is not required, I use this as a dynamic way of parsing out the host from the http request to build a URL endpoint for the images used by our cards.

Next we setup the service.

Create your server object:

var server = restify.createServer();

Insert your middleware if required, here we intercept the http request to retrieve the host name:

server.use(function (req, res, next) { serverUrl = "https://"+req.header('Host'); next(); });

and insert a custom route to handle image retrieval:

server.get(/\/images\/?.*/, restify.serveStatic({ directory: __dirname }));

Finally we invoke the listen method to begin listening to our requests:
server.listen(process.env.port || process.env.PORT || 3978, function () { console.log('Chatbot listening to %s', server.url); });

Next we create a connector and bot object which manages communications between the bot app itself and the bot framework service.

var connector = new builder.ChatConnector({ appId: "your registered app id", appPassword: "your registered password" }); var bot = new builder.UniversalBot(connector);

and finally we set up a route which forwards API requests to the connector object.

server.post('/api/messages', connector.listen());

Once this is complete your events will be managed by the bot object.

To present a card when someone joins your bot channel i simply use the bot.on('conversationUpdate') event as per the following example:

bot.on('conversationUpdate', function (activity) { if (activity.membersAdded && activity.membersAdded.length > 0) { bot.send(new builder.Message() .address(activity.address) .textFormat(builder.TextFormat.xml) .attachments([ new builder.HeroCard() .title("Welcome to my chat bot!") .subtitle("I am written in node.js!") .text("Hello. Please tell me how I can assist.") .images([ builder.CardImage.create(activity.address, serverUrl+"/images/mylogo.png") ]) ]) ); } });

I can then create an IntentDialog object to manage conversation with the bot.dialog method and use standard Regex to match an intent as in the example below:

var intents = new builder.IntentDialog() bot.dialog('/', intents); intents.matches(/^hello|hola|kio ara/i, function(session){ session.send(`${session.message.text}! Please let me know how I can help!`); });

I hope this helps you get started on your chat bot journey. In a second blog post, I will show you how to integrating with other services such as LUIS and QnA Maker to truly make your chat bot awesome!

Happy coding!