Create your first botframework bot in Azure!

At //Build 2016 Microsoft unleashed something known as the Bot Framework; a set of three products to help you build conversational bots and connect them with services, like Slack, Skype, and even Email and SMS.

The Bot Framework has a number of components including the Developer Portal, Bot Builder, and the Bot Directory:

  • Developer Portal is where you wire your bot up to existing services like Skype and Slack
  • Bot Directory is where you publish your bot to so that others can search for and connect it to their Skype and Slack
  • Bot Builder is what you use to implement a more complex and intelligent conversational flow, optionally leveraging the awesome power of some of the Microsoft Research’s Cognitive Services for language interpretation, image recognition, and much more.

In this article I’m going to take you through the process of creating, deploying, and configuring your own Skype bot.

Bots

As far as some people are concerned, “bots” are the new “apps”; before too long every company will have to offer their own bot for some reason or another.

Concept of conversational bots is not new; nerds of my age or similar will no doubt be aware of ELIZA, a conversational bot with no intelligence as such, just giving semi-canned responses to input such as a cheap psychotherapist might do. Great fun though.

This sort of bot paved the way for significantly more complex human language-based interaction, having possibly been the first computer to “pass” the Turing Test!

ChatOps

The term ChatOps has been credited to GitHub following them unleashing Hubot on the tech world; a conversational bot which allowed members of github to interrogate and even update their various systems without leaving their chatroom.

The benefits of this are numerous, such as avoiding a second class citizen “admin” web interface for “backoffice” tasks. These “admin” sites never get as much development and refactoring time as your core product might, falling behind and eventually becoming a hindrance to the team.

Another key feature is the log of the conversation between the team and the bot, allowing for a simple audit log should the conversation include deployment or outage investigations.

Hubot

hubot

Hubot is a nodejs project from GitHub – open source, naturally – with coffeescript (“a little language that compiles into JavaScript”) “commands”, making it extremely simple to extend with your own commands.

I’ve previously deployed a hubot instance (called MrBot..) to heroku, with coffeescript commands to hook into a TeamCity instance’s API to trigger and report on builds and kick off deployments to Azure, through to querying an API in Azure to inspect diagnostic logs and report on system performance.

Being able to implement this all within the context of a conversation in hipchat or Slack was extremely natural and gave a cohesive experience.

botframework

This brings me back to the newly unleashed botframework. Now it’s even easier than ever to create your own conversational bot, deploy it, and connect it to various services.

So that’s what we’re going to do. Get comfy.

Install prerequisite software

In order to use the botframework you’re going to need to make sure you’re running an up to date Visual Studio with all the latest bells and whistles:

  • Visual Studio 2015 Update 3 (if you use Community edition, like me, you may find the Update 3 download actually tries to install Update 2; instead, just go to “Add or Remove Programs”, select Visual Studio > Modify and you’ll be able to install Update 3 from there)
  • Update all VS extensions to their latest versions:
    • Open Visual Studio > Tools > Extensions and Updates > Updates > the lot.
  • Download and install the Bot Application template; this gives you a new project type in Visual Studio:
    • http://aka.ms/bf-bc-vstemplate
    • Save the zip file to your VS templates directory, usually something like: “%USERPROFILE%\Documents\Visual Studio 2015\Templates\ProjectTemplates\Visual C#\”

Create your first bot

Exciting stuff, eh?

  • Open Visual Studio
  • Make sure you have “Create new git repository” selected, since we’ll be deploying to Azure using git
  • Create a new C# project using the new Bot Application template:

bot framework visual studio new project

Take a moment to check out what’s been created in Visual Studio from that new project template. There’s very little code; just a few config files, a mainly blank default.htm page, and a MessagesController class with an interesting using at the top:

using Microsoft.Bot.Connector;

And a nice auth attribute on the controller class:

[BotAuthentication]

Inside that MessagesController class is an interesting method:

public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
    if (activity.Type == ActivityTypes.Message)
    {
        ConnectorClient connector = 
            new ConnectorClient(new Uri(activity.ServiceUrl));

        // calculate something for us to return
        int length = (activity.Text ?? string.Empty).Length;

        // return our reply to the user
        Activity reply = 
            activity.CreateReply($"You sent {activity.Text} which was {length} characters");
        await connector.Conversations.ReplyToActivityAsync(reply);
    }
    else
    {
        HandleSystemMessage(activity);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK);
    return response;
}

The ServiceUrl is the system that’s currently calling the bot endpoint; e.g., Skype or Slack.

Other than that, it’s pretty sparse:

vs new bot framework project

So we’ve created a .Net Web API with some special authorisation implementation, and an endpoint to which all messages (Activitys) are sent.

There are various activity Types, for events such as your bot or another user joining or leaving a conversation, your bot or another user joining or leaving a group conversation (all of which are grouped under the ActivityTypes.ConversationUpdate type, the bot being added to or removed from a user’s contacts list (ActivityTypes.ContactRelationUpdate), knowing that the user is typing (ActivityTypes.Typing – now come on; this is cool!), and a couple of others.

This is where we’ll do all our cleverness; we’ll implement some message parsing logic in a new class and call it in here – we could even have this call a completely different API, using the “bot” merely as a basic web host with authorisation, and single entry point; we could potentially deploy this bot only once and leave it alone.

The botframework SDK allows for some complex conversation models, and I’ll go into this in another article.

Let’s come back to this concept shortly. First up, I’m going to show how to run, test, deploy, and connect to services. Which is really cool.

Locally running and debugging

You’re still in Visual Studio, so let’s hit F5 to run and debug:

Run and debug the bot framework in Visual Studio

Bot Framework Channel Emulator

It’s easy to test this endpoint by using the Bot Framework Channel Emulator; a simple “Click Once” application from Microsoft. Since it’s a Click Once app, it will auto update when necessary. Very handy.

Once your bot/web api is running locally, open up the Bot Framework Emulator, and enter the following details:

  1. Bot Url: this will be localhost:<port>/api/messages – just grab the port from the browser window you launched when F5-ing the project
  2. Microsoft App Id: when testing locally, leave this blank; when testing a remote endpoint, use the Mirosoft App Id you’re given (we’ll get on to this shortly)
  3. Microsoft App Password: same as above; leave blank for local testing, or use the value you’re given from your bot dashboard (later)

If you’ve not made any code changes to the default project you should be able to type in a message at the box at bottom of the emulator and see a response letting you know the length of the message you just entered, along with the JSON for that response in the window on the right of the emulator.

testing locally with the bot emulator

Notice the full JSON response in the right side window; lots of interesting data in there…

Deploying to Azure

Now that we’ve got a “working” bot, it’s time to set it free into the big wide world so we can connect it to other services and start to see the real potential; once this step is done, updating with new functionality will be extremely easy.

The tutorial on the botframework website shows you how to use Visual Studio’s “Publish” functionality to deploy to Azure; I really don’t like this since it’s not supporting anything other than a single developer, with no support for collaboration and no “gates” to deployment – i.e., automated tests.

I’m going to implement a basic separation of these concerns (which I’ll expand on in a subsequent article by introducing a CI server to run tests before allowing us to deploy) using git.

git commit -am “It’s ALIVE!”

I love git. Git git git yum yum yum in my tum. Or something. So I’m going to use this as the deployment initialisation mechanism.

Given .Net Core runs on pretty much OS these days, we could deploy this anywhere; however, the bot requires HTTPS – as any web-based system should – and Azure gives this to you for free (unlike Appharbor, for example), so that’s my host of choice.

Aside: if you try to run your bot over HTTP from a remote endpoint you’ll get an error:

bot running over http gives a warning

Set up Azure

Create the new web app/app service (same thing)

  1. Go to portal.azure.com
  2. If you don’t already have an account, create one; I’ll not go into the detail of doing that here
  3. Select “New Web App” and click “Create”:
    Azure new web app

Configure deployment from git

  1. Once that’s finished creating it, select “Deployment Source” (under Settings > Publishing > Deployment Source) and choose “local git”
  2. Once that’s done, go to the “Essentials” view of your web app, get the git repo endpoint, and set a password for your deployment user (if you haven’t already)
  3. Set up a new git remote either from within Visual Studio’s Team Explorer window, or the command prompt, like:
    • git remote add azure <paste in your azure git repo url here>
    • git push azure master
    • Enter the deployment user’s password and away you go:
remote:   Copying all files to temporary location below for package/publish:
remote:   D:\local\Temp\8d3a8421b0c42a4.
remote: KuduSync.NET from: 'D:\local\Temp\8d3a8421b0c42a4' to: 'D:\home\site\wwwroot'
remote: Copying file: 'Web.config'
remote: Finished successfully.
remote: Running post deployment command(s)...
remote: Deployment successful.
To https://[email protected]:443/rposbo-botframework-demobot.git
   e16b753..9dac446  master -> master

Notice how the git push command is reporting on the actual deployment into Azure? How cool is that?

Testing in Azure
You can’t! At least, you can’t yet. We currently don’t have a valid MicrosoftAppId and MicrosoftAppPassword, remember? They’re still blank in our web.config! Before we can actually use this remotely deployed bot we need to get some valid credentials by registering it with the Microsoft Bot Framework.

Registering with the Microsoft Bot Framework

Head over to https://dev.botframework.com/, click Register a Bot.

Fill in a name and a “bot handle” – this will be your BotId in your web.config – and paste in your Azure endpoint + “/api/messages/” for the “Messaging endpoint” section.

Then click “Create Microsoft App ID and Password” to open up a new tab and log in with your Microsoft (Live/whatever it’s called now) details to see your already configured apps.

Click “Add an app”, give it a name, and on the next screen you’ll see your Microsoft App ID; paste this back in the bot registration page AND in your web.config as the MicrosoftAppId.

Click “Generate new password” and paste this in your web.config as the MicrosoftAppPassword

Finish the rest of this form, click “Register” and whilst you’re waiting for that to finish you can git push your new web.config up to Azure – make sure you’ve filled in your BotId, MicrosoftAppId, and MicrosoftAppPassword! Go on then.. get git pushing!

Say hello to your new friend!

You should now be back in your dev portal with your new bot listed and showing as already being connected to Skype!

Click that “Add to Skype” link..

And have a “chat”:

When you send your first message it may take a few seconds to get a response, but subsequent ones should be quicker.

You just had a chat with your very own Skype Conversational Bot! How cool is that?

Summary

Where do we go from here? You could connect your bot to other services if you have the prerequisites for that service, such as Facebook Messenger, SMS (Twilio) or Slack.

You could start to develop cleverness around parsing the content of the message, and responding appropriately.

You could investigate the various types of responses that are available, such as:

  • attachment – have an inline file or image with your message
  • hero – a “card” with header, subheader, image, and button
  • thumbnail – like a hero, but the image is smaller and to one side
  • receipt – a product listing with images, descriptions, and prices, with a subtotal and total!

You could check out carousels of response cards and combine everything into one giant reply!

Pretty cool, right? Have a go and let me know how you get along.

10 thoughts on “Create your first botframework bot in Azure!

    • Hi Kayode,

      That’s usually due to something else missing on the registration page; scroll around and see if any mandatory text area is highlighted, fill it/them in and try again!

  1. We are getting delay while getting our responses. Sometimes, it happens for the first time sometime it happens randomly. Is this happening from Azure since we have deployed the bot to azure? Is there any solution to this delaying response issue?

    • Hi Rahul,

      This can be due to a couple of things; firstly, you’ll need to configure your Azure app to be “always on”, otherwise it will “go to sleep” if there aren’t many requests in a given period and as such the next request “wakes” it up and can take a while. Secondly, try to host your bot in East US (I think), since this is currently the only location the botframework is hosted – saving on network latency.

      Good luck!

  2. I did exactly what’s described in the article, and when test my bot I get 404. Do you have any idea why is that?

    • Did you remember to append “/api/messages/” to the remote URL when filling in the “Messaging endpoint” section in the botframework connector website?

  3. I could get the chat up and running ,
    But when I click the “test” button , right at the top of the page to “Test Connection to your bot”,
    its giving the following error

    “Unauthorized
    BotAuthenticator failed to authenticate incoming request!”.

    Why is that happening ?

    • Can you check the bot app id and password you’ve used? Usually that error means that the Microsoft App Id and Password (from the Settings screen for your bot) don’t match those in your web.config.

  4. thank you for your post.
    i’ve registered my bot and it’s working on boframework emulator , but with skype i’am having no response. In skype my bot appears online.

Leave a Reply to balkrishna Cancel reply

Your email address will not be published. Required fields are marked *