In this tutorial, I’m going to show how to deploy a simple chatbot using the Microsoft bot framework and the Botsociety API. I like the bot framework because it allows me to write the code once and deploy to multiple platforms. I like Botsociety because it allows me to change what the chatbot says without having to deploy my code again. Ready?

You can check out the code used in this tutorial on Github.

First: Design your bot

I have an idea for a simple chatbot that my team may use inside Slack. I would like to come up with a proper design of my chatbot before jumping into development. This approach will allow me to end up with a better user experience. So my chatbot will actually be used! I can come up with the interaction using Botsociety, pen and paper, or even Excel. I prefer to use Botsociety as it gives me an immediate preview. Plus, it’s free!

I signed up here, and then created a new mockup of type “Slack”:

bot framework tutorial

As you see, I typed “ServerUp” as the name of the chatbot. This is because I would like to create a service chatbot that alerts my team if our server is up and other related stuff. I can now simply type in the messages I imagine the chatbot may exchange. I end up with something like this:

bot framework tutorial step 1

This is a very simple user experience. In a real case scenario, I would come up with a more complex interaction, in order to make the chatbot more useful. For the sake of this tutorial, this is going to be enough. If you are interested in learning about how to design more complex Slack chatbot, check out this dedicated tutorial.

Now that I have a skeleton of the interaction, I can move on to the building mode by clicking the yellow “Build” button on the top right corner. I can now access the building mode. It looks like this:

bot framework tutorial fourth step

I can now select the words in my design which are actually variables that depend on my business logic. I just select the words, and type the name of the variable. It takes 3 seconds:

bot framework tutorial part 5

In this case, ‘production-1’ is actually the name of my server. So I select ‘production-1’ and choose ‘server’ as the name of the variable. Then I press enter. Done!

bot framework part 6

We are pretty much with the design part. Let’s move on to the second part: Coding the chatbot using the bot framework

Developing with the Bot framework

In this tutorial, I’m going to use the Microsoft Bot framework SDK for Node.js

I like Node because it allows me to write my backend in Javascript. I can also leverage a lot of useful packages to speed up my work. Let me show what I mean.

First, I will create and move to a new directory on my computer, called “upserver”. I develop on a Mac, so I can use the terminal. To create the directory, I open a terminal and type:
mkdir upserver
Then
cd upserver
So now I created a new dir and moved into it. Now I want to init a Git repository in order to keep my project under version control. In the same terminal, I type:
git init
Always keep stuff in version control! I will then type
npm init
To start a new Node project. You can then follow the instruction prompted and you will end up with a basic package.json file. Among other things, this file keeps track of the dependencies of your project – basically, which other packages it needs to run properly. At the moment, you should have no package needed as you just started!

Let’s start to write some code. Open your favorite text editor – I like Visual Studio Code, by Microsoft. Another cool editor is Atom, by Github. Regardless of your favorite text editor, add a new file to your project directory called ‘.gitignore’. Do not forget the dot at the start! This file tells Git what not to add to your repository. Paste into this file the content of a standard gitignore for Node projects. You can find it here. Save the file.

Ok so now we have a nice starting point for any Node project. I now want to add the packages I need to my project. First, let’s install the bot framework. I go back to my terminal and type:
npm install --save botbuilder
and
npm install --save restify
‘Npm install’ installs a package into your current project directory. The flag ‘–save’ assures that this package is also added to the list of dependencies of your project inside the package.json file. I also want to install the Botsociety package. In my terminal, I type:
npm install --save botsociety
I also would like to install a package named ‘dotenv’. It allows you to manage secret strings that you don’t want to make public or available, such as API keys and other secrets. More on that later. To install it, just type
npm install --save dotenv
Now, back to the text editor. Add a file called app.js and copy paste the following code:

require('dotenv').config();
var restify = require('restify');
var builder = require('botbuilder');
var Botsociety = require('botsociety');

var botsociety = new Botsociety({
  userId: process.env.BOTSOCIETY_USER_ID,
  apiKey: process.env.BOTSOCIETY_API_KEY
});

// 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 connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
  appId: process.env.MICROSOFT_APP_ID,
  appPassword: process.env.MICROSOFT_APP_PASSWORD
});

// Listen for messages from users
server.post('/api/messages', connector.listen());

// Receive messages from the user and respond by sayign the server is down or up
//let's use a fixed variable. You should of course hook this up to your server monitors!
var serverDown = true;
var serverNames = ["production1", "production2", "load_balancer"];
var bot = new builder.UniversalBot(connector, function (session) {
  console.log("connected");
  var messageId;
  if (session.message.text.indexOf("are we down") > -1) {
    if (serverDown) {
      messageId = 3;
      serverDown = false;
      serverName = serverNames[Math.floor(Math.random()*serverNames.length)];
    } else {
      messageId = 5;
      serverDown = true;
    }
    botsociety.getMessageByConversation(process.env.BOTSOCIETY_CONVERSATION_ID, messageId)
    .then(function(response) {
      session.send(response.text_with_variables.replace("${server}", serverName));
    })
    .catch(function(err) {
      console.log("there was an error");
      console.log(err);
    });
  }
});

This is your bot. What it does is:

    • It listens for somebody to say “are we down”
    • If somebody said it, it will say “Server is down” or “Servers are up”, alternatively
    • It replaces the variable in the text ${server} with the name of the server. Since this is an example, the name of the server is chosen randomly between 3 different server names

Note that the content of the messages is not hardcoded in my code! This line is actually grabbing the content of message 3 from Botsociety and using it in my code:

botsociety.getMessageByConversation(process.env.BOTSOCIETY_CONVERSATION_ID, messageId)

You can check out the code used in this tutorial on Github here.

Set the Botsociety API keys

If you take a look at the code above, you will see that you need some environment variables for the code to work. You can set them up manually each time, but it can be daunting. A more elegant way is to use the dotenv npm package. It is used in the first line:
require('dotenv').config();
The dotenv package looks for a file called .env in your application folder and loads those variables into the process. You can find an example of this file in the repository. The file is called ‘.env-example’. I copied it, and renamed the copy simply
.env
Inside this file, I can define all the variables that I need. Let’s start with the API keys:
BOTSOCIETY_USER_ID
and
BOTSOCIETY_API_KEY
In order to generate those, just navigate to the API page inside Botsociety and click on “Generate keys”. Then paste them into your .env file at the right position.
In order to find out the value of
BOTSOCIETY_CONVERSATION_ID
Go into your bot design inside Botsociety. On the top right corner, click on the button ‘Build’. On the right hand side, you will find a button that allows you to copy your conversation id:
Botframework conversation id
Paste this value as well inside your .env file.
You will end up with a .env file similar to this:
BOTSOCIETY_USER_ID=5a782f2f2e3d9e001c6e00f7
BOTSOCIETY_API_KEY=9ee5916bca28700e1a9cba1e1c586f68
BOTSOCIETY_CONVERSATION_ID=5a782f3b2e3d9e001c6e00f8
MICROSOFT_APP_ID=your-microsoft-app-id-here
MICROSOFT_APP_PASSWORD=MICROSOFT_APP_PASSWORD

Note that the keys above are not real, but it should give you the idea!

Testing with the Bot framework emulator

Now that you have your Botsociety keys in, you can test your chatbot in the emulator. To do that, first launch your Node application by typing in your terminal:

node app.js

You should see something like
restify listening to http://[::]:3978
Now, if it’s your first time working with the Microsoft Bot Framework, you to download the Emulator in order to test your bot locally. You can find the installers of the Emulator here. Find the right installer depending on your operative system. Download it and launch it. I’m on MacOS, and to select the default options I just click on the empty dropdown like this:

bot framework part five

The default options are ok in this case, so I click connect. I can now talk with my bot. So if I write “are we down” in the emulator, I will get this response:

bot framework snippet one

Now the cool thing is that if I get back on Botsociety and change the content of my mockup, I will immediately see the result in my working bot. For example, I changed the text so that it also tags the whole Slack channel if a server is down:

bot framework sixth step

Now I just type again in the emulator and I will see the result:

bot framework part 7

Deploy: Microsoft Bot framework keys

Opening an Azure account is not needed if you want to test your bot locally. But you will need to deploy it, right? The procedure is kind of cumbersome, but you will get around $200 credits on Azure. You can do that here.

Now, in order to release your chatbot, you will need to connect to Slack. Assuming you already have a Slack account, the procedure is straightforward. You can find the details in the official guide here.

Once retrieved, you can define the Microsoft variables just like you defined the Botsociety variables. Go back to your .env file and paste those keys in the last two lines:
MICROSOFT_APP_ID=paste your app id here
MICROSOFT_APP_PASSWORD=paste your microsoft password here

That’s it for this tutorial. The deploy on the Azure cloud server still needs some work, but it’s more about Aure than the bot framework, so it’s not covered here. You can check out this tutorial if you are interested.

Feel free to leave any questions in the comments below!

Comments


Vittorio Banfi

Co-founder and CEO botsociety.io