Friday, July 15, 2016

Microsoft Bot Framework: Getting Started

Required Software:

1) Visual Studio 2015
2) Bot builder template - save the zip to your Visual Studio 2015 templates directory (%USERPROFILE%\Documents\Visual Studio 2015\Templates\ProjectTemplates\Visual C#\)

Creating your app

Create your app by going to File->New->Project in Visual Studio. Select Bot Application.



Let's take a look at some of the code that comes with the template. The interesting part is going to be in MessagesController.cs:
You'll notice that this looks very similar to an ASP.NET WebApi project -- that's because it is. This is a WebApi Controller with a simple POST method. The post takes an Activity object and return an HttpResponseMessage.

This Activity object is simply the message that the user is sending to the bot. The message that the user is sending is contained in the Text property. You will also notice that there is a check on activity.Type. We'll get more into this later, but this is simply a check as to whether this message is a message from the user, or a system message (such as an alert that the user is typing).

The next line of code creates a ConnectorClient. This is an object representing the connection between the bot and a particular user. This connection can hold multiple conversations, each consisting of multiple activities.

Once we have the user's message and the connection, a reply is generated for the user. This reply simply returns a string containing the user's message and the length of that message. This reply is generated with "activity.CreateReply()," and it is sent back to the user via "connector.Conversations.ReplyToActivityAsync()."

Let's get this application running and test it out. Launch the application using your browser of choice. I am using Google Chrome for this example.



The browser window should look similar to this:


Note the port used at the end of the url. After the bot is running, we want to connect a chat client to it. The easiest way to test it is to use the Microsoft Bot Emulator. Change the "Bot Url" value to use the port that your bot is running on. In this case, mine was running on 3979. The full url should be "http://localhost:XXXX/api/messages."



Once this is finished, type a message at the bottom of the emulator, and send it to your bot!
You should quickly get a response.



When you send the message, you can see the json on the right side. Note that this json can be hard to see sometimes since it is quickly replaced by the reply.





















Notice that this json is the same Activity object that we use in the POST method in MessagesController.cs. The Type and Text are easily visible.





















Now we have a fully working bot! Move on to uploading your app to Azure, or integrate luis into your bot.

No comments:

Post a Comment