Thursday, April 21, 2016

Bot Builder Dialogs


The Bot Framework includes a Bot Builder SDK that helps you manage conversations with users, including Dialogs, Form Flow, and other supporting types. The Bot Builder SDK is open source, supporting both C# and Node.js, and you can visit the source code on GitHub.

This post is an introduction to Dialogs and shows you how to use types that prompt a user, move between questions, and manage state. The example I’m using is a Bug Report Bot. It isn’t very sophisticated, but is designed to show you how to manage a simple conversation, using dialogs.

Project Set-Up

You can get started with the normal Bot Framework template, described on the Bot Framework Getting started page. The template already gives you a reference to the Microsoft.Bot.Connector library and now you’ll need a reference to the Microsoft.Bot.Builder library, which you can load via NuGet. Here’s the Package Manager console command if you prefer:
PM> Install-Package Microsoft.Bot.Builder
With your project set up and configured, you can start building dialogs.

Getting Started

A dialog is a class with state and methods that use Bot Builder types to manage interactions between bot and user. For the Bug Report Bot, I’ll create a class that contains fields and methods. State is important because it holds important information about an ongoing conversation. The following BugReportDialog class shows how to code for managing state.
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;

namespace BugDialogBot
{
    [Serializable]
    class BugReportDialog : IDialog<object>
    {
        ProductOptions productOptions;
        PlatformOptions platformOptions;
        string description;
        
        // other members omitted until later
    }
}
The Bot Framework manages conversations by sending JSON messages through the Bot Connector and to/from user and bot. These messages hold the state of an ongoing conversation. To facilitate managing state with the Bot Framework, your dialog type must be serializable. To support this, the code decorates the BugReportDialog class with the Serializable attribute. Additionally, the class contains fields, representing the state of the conversation. Besides making your dialog class serializable and storing values in serializable fields and/or properties, you don’t have to do anything extra to manage state, because that’s one of the benefits of Bot Framework Dialogs. Both ProductOptions and PlatformOptions are enum types, shown below:
    public enum ProductOptions
    {
        Office,
        SQLServer,
        VisualStudio
    }

    public enum PlatformOptions
    {
        Linux,
        Mac,
        Windows
    }
These enum typess represent options that the user can select when prompted. The fields will hold the user’s response so that we have all of the user’s responses when reaching the end of the conversation/dialog.
Another interesting part of the BugReportDialog is the fact that it implements IDialog<object>, which I’ll discuss next.

The Dialog Entry Point

For IDialog<T>, you implement its single member, StartAsync, which is the entry point for the dialog. Within StartAsync, you’ll specify which dialog method the Bot Framework calls to initiate a conversation. The following code shows the StartAsync implementation for the Bug Report Bot:
    [Serializable]
    class BugReportDialog : IDialog<object>
    {
        ProductOptions productOptions;
        PlatformOptions platformOptions;
        string description;
        
        public async Task StartAsync(IDialogContext context)
        {
            context.Wait(ConversationStartedAsync);
        }
        
        // other members omitted until later

    }
The StartAsync method accepts an IDialogContext parameter, context, which has members to help you manage state and various aspects of a conversation. It’s essentially a convenient hook for various services in the Bot Framework. You’ll see IDialogContext again in later parts of this post because the Bot Framework passes it to every other dialog method. The StartAsync method for BugReportDialog uses the Wait method of context to specify the starting method, ConversationStartedAsync, to call when the user initiates a conversation with the bot. The next section shows how to write that starting method.

Interacting with the User

When the user initiates a conversation with the bot, the StartAsync method specifies which dialog method to start with. In the previous code, that was ConversationStartedAsync, which is shown below:
        public async Task ConversationStartedAsync(IDialogContext context, IAwaitable<Message> argument)
        {
            Message message = await argument;
            await context.PostAsync(message.Text);

            PromptDialog.Choice(
                context: context,
                resume: ResumeAndPromptPlatformAsync,
                options: Enum.GetValues(typeof(ProductOptions)).Cast<ProductOptions>().ToArray(),
                prompt: "Welcome to the Bug Report Bot! Please select the product you're having a problem with (SQLServer or VisualStudio):",
                retry: "I didn't understand. Please try again.");
        }
As mentioned earlier, every dialog method receives a IDialogContext parameter, context. They also receive an IAwaitable<T>, argument. The T is whatever type the method is expecting. Since StartAsync called context.Wait(ConversationStartedAsync), the T will be Message. The T will be specified by the previous method in the dialog chain and you’ll see how that works when covering subsequent methods in this post.
Since argument is awaitable, the code awaits to reference the Message passed by the Bot Framework. This lets you evaluate the value of the argument and build logic to handle the information that the user provided. In this example, we’re interested in the message.Text that the user typed. This is normally “Hi” or “Hello” and the code echoes that back to the user by calling the context.PostAsync method.
PromptDialog is a type in the Bot Builder SDK that manages an interaction with the user. There are different types of prompts, such as Yes/No, string, and number. The Choice prompt lets the user pick one of a number of options. Notice the Enum array passed as the options parameter. The user can choose one of the ProductOption types, mentioned earlier in this post. The prompt dialog uses a convention of breaking the words at capitalized letters in each Enum value – so ProductOptions.VisualStudio becomes “Visual Studio” to the user.
On the other PromptDialog parameters, context is the IDialogContext that I discussed earlier where the Bot Framework passes that to dialog methods. The prompt is the question the bot asks the user and retry is the message the bot uses if it doesn’t understand what the user typed.
What’s interesting here is the resume parameter. When you have a series of interactions, you can specify each of those interactions with a dialog method. The resume parameter specifies which dialog method to call after the user responds. In this case, the next dialog method is ResumeAndPromptPlatformAsync, which I’ll describe in the next section.

Managing Conversation Flow

As the user interacts with a bot, the Bot Framework routes those interactions to the dialog method you specified to handle the next user message. Since the ConversationStartedAsync method called PromptDialog the user’s response goes to the ResumeAndPromptPlatformAsync method as the argument parameter, shown below:
        public async Task ResumeAndPromptPlatformAsync(IDialogContext context, IAwaitable<ProductOptions> argument)
        {
            productOptions = await argument;

            PromptDialog.Choice(
                context: context,
                resume: ResumeAndPromptDescriptionAsync,
                options: Enum.GetValues(typeof(PlatformOptions)).Cast<PlatformOptions>().ToArray(),
                prompt: "Which platform did the problem occur on? (Linux, Mac, or Windows):",
                retry: "I didn't understand. Please try again.");
        }

        public async Task ResumeAndPromptDescriptionAsync(IDialogContext context, IAwaitable<PlatformOptions> argument)
        {
            platformOptions = await argument;

            PromptDialog.Text(
                context: context,
                resume: ResumeAndPromptSummaryAsync,
                prompt: "Please provide a detailed description of the problem:",
                retry: "I didn't understand. Please try again.");
        }
public async Task ResumeAndPromptSummaryAsync(IDialogContext context, IAwaitable<string> argument) { description = await argument; PromptDialog.Confirm( context: context, resume: ResumeAndHandleConfirmAsync, prompt: $"You entered '{productOptions}', '{platformOptions}', and '{description}'. Is that correct?", retry: "I didn't understand. Please try again."); }
There are three dialog methods above, each with their own argument handling and PromptDialog. All three methods store the argument in a class field, which is part of the state of the dialog class, so we can remember the user’s choices. A couple of the PromptDialogs are different from what you’re seen previously. PromptDialog.Text takes a freeform string from the user and PromptDialog.Confirm takes a Yes or No answer. The PromptDialog accepts a certain type and when the user responds, the argument parameter for the resumed dialog method is the type of the previous PromptDialog. Eventually, you’ll reach the end of the report.

Completing the Report

The PromptDialog.Confirm in the previous section summarized the options the user chose and asked them if that was correct. The next dialog method, ResumeAndHandleConfirmAsync, evaluates their response, replies accordingly, and re-starts the Bug Report Bot at the beginning so the user can add another Bug Report, if they like:
        public async Task ResumeAndHandleConfirmAsync(IDialogContext context, IAwaitable<bool> argument)
        {
            bool choicesAreCorrect = await argument;

            if (choicesAreCorrect)
                await context.PostAsync("Your bug report has been submitted. Thanks for the feedback!");
            else
                await context.PostAsync("I see. You're welcome to try again.");

            context.Wait(ConversationStartedAsync);
        }
Here, I’m doing more work with the argument, using an if statement to determine an appropriate response to the user. Since I don’t need a response from the user, I don’t use a PromptDialog. The IDialogContext has a helper method, PostAsync, that lets you send a message to the user. This would have been a good opportunity to put additional logic that submitted the bug report and cleaned up state. The IDialogContext has another method, Wait, which will set which dialog method the Bot Framework sends the next message to, which is the ConversationStartedAsync that you saw at the beginning of this post.

Summary

This post described how to use Bot Framework Dialogs. You saw how to configure dependencies and create a dialog class. The StartAsync method is the entry point to a dialog conversation and you build a chain of dialog methods from there. There are several types of PromptDialog methods, each allowing you to obtain different types of information from a user. You saw how to manage state, which allowed summarizing choices at the end of the dialog to complete the operation. In a later blog post, I’ll build on dialogs with an even more powerful Bot Builder tool named FormFlow.

@JoeMayo

Sunday, April 10, 2016

Using the Bot Framework Chat Control

One of the places you can use a Microsoft Bot Framework bot is on your own Web page. There is a Chat control you can use and this post discusses this and shows an example.
Note: If you had trouble with the chat control earlier, there was a bug, but that is now fixed and the Chat control documentation is updated.
This post shows an implementation with the MVC Web API. Essentially, there are two techniques: insecure and secure, but let’s look at the HTML page setup first.

Setting up the HTML Page

The Bot Framework template includes a default.htm page and this is where I load the Chat control. I’m building on the Pig Latin Bot and the following shows the default.htm implementation:
<!DOCTYPE html>
<html>
<head>
    <title>Pig Latin Bot</title>
    <meta charset="utf-8" />
</head>
<body style="font-family:'Segoe UI'">
    <img src="images/PigLatinBot.png" alt="Pig Latin Bot"/>
    <h1>Pig Latin Bot</h1>
    <p>Translates your text to Pig Latin.</p>

    <div id="webChatControl">

    </div>

    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <script type="text/javascript">
        $("#webChatControl").load("api/WebChat");
    </script>
</body>
</html>
The location of the Chat control is in the div with the webChatControl id. After loading the script from MaxCDN, the next script block loads the chat control via jQuery. Notice the call to the relative api/WebChat endpoint. I’ll explain that next.

Using a Secret Key

The endpoint, the page calls, addresses an MVC Web API. It handles GET requests and returns the <iframe/> HTML for injection into the page. Here’s the implementation:
    public class WebChatController : ApiController
    {
        public async Task<string> Get()
        {
            string webChatSecret = ConfigurationManager.AppSettings["WebChatSecret"];

            return $"<iframe width='400px' height='400px' src='https://webchat.botframework.com/embed/PigLatinBotJoeMayo?s={webChatSecret}'></iframe>";
        }
    }
The WebChatSecret is a key in Web.config appSettings that contains a value for the secret key of the Chat control. You can get this key from your Bot Framework My bots page, edit the Web Chat channel, and generate keys. In the <iframe/> HTML string, replace PigLatinBotJoeMayo with the App ID of your bot. Notice that the parameter is s and it holds your bot’s secret key.
Rather than all of the ceremony for calling the Web API, reading secret key configuration, and injecting the result into the page, I could have coded the HTML directly into the page and been done with it. However, I have a point to make. Earlier, I mentioned that there were two techniques: insecure and secure. This was the insecure technique because whether you paste the HTML into the page or return HTML via a Web API call, the secret key is still part of the page that the user can see, which is insecure.
That said, security is relative. In this case, it depends on whether you intend for anyone in the world to load the Chat control onto their own page and use your key. In that case, this practice isn’t insecure at all. However, if this isn’t your intention, the next section explains a more secure way to handle keys.

Using a Token

If you don’t want to share your secret key with the world, another option is to use a token. It works like this:
  1. Add your secret key as a header value in an HTTP GET request
  2. Send the request and receive a token as a response
  3. Use that token as a parameter in the <iframe/> src URL
Here’s an updated WebChatController that shows how to do this:
    public class WebChatController : ApiController
    {
        public async Task<string> Get()
        {
            string webChatSecret = ConfigurationManager.AppSettings["WebChatSecret"];

            var request = new HttpRequestMessage(HttpMethod.Get, "https://webchat.botframework.com/api/tokens");
            request.Headers.Add("Authorization", "BOTCONNECTOR " + webChatSecret);

            HttpResponseMessage response = await new HttpClient().SendAsync(request);
            string token = await response.Content.ReadAsStringAsync();
            token = token.Replace("\"", "");

            return $"<iframe width='400px' height='400px' src='https://webchat.botframework.com/embed/PigLatinBotJoeMayo?t={token}'></iframe>";
        }
    }
Instantiating an HttpRequestMessage sets up the GET request to the Bot Framework api/tokens endpoint. Set the Authorization with BOTCONNECTOR and your secret key. In this scenario, the only time you’ll use your secret key is to request a token.
The SendAsync method uses that request, makes the call and returns the token. In previous versions, the documentation called for doing a POST that returned JSON. Now, the response contains just a token as a string. In the current implementation, the Bot Framework is returning a quoted token. e.g. “\”<token>\”” That’s the reason for the Replace call, to strip those quotes out. I’m not sure if the token will have those quotes in the future because they feel unnecessary, but you can hit a breakpoint and look at the value  of token in case it changes in the future and you might not need the Replace.
Finally use the token in the <iframe/> src query string parameter. Notice that the parameter is not s, as it was in the previous example for using the secret key, but is now t because you are using a token.
You might say that now anyone can read the token, and that would be true. The reason this is more secure is because that token will expire and can’t be used across sessions.

Summary

The Bot Framework Chat control is a convenient way to add a Bot to your Web site. You have a couple ways to use it via a secret key alone or by exchanging the secret key for a token. The implementation described in this blog post was to use jQuery to call an MVC Web API, return the HTML for the Web Chat control, and inject that control into the page. That is more secure by not exposing your secret key to the world.
@JoeMayo

PC Bot

The PC in PC Bot means Politically Correct – because it reacts to every event. During its lifetime, a (Microsoft Bot Framework) bot can have many different types of messages, in addition to a normal text message from the user. You can know when a user or bot is added or removed, when a conversation ends, and a couple other message types. This post explains PC Bot and discusses a few interesting aspects of message type handling.
Note: PC Bot doesn’t overreact, as you would expect of proper botiquette.

What are the Message Types?

The Bot Framework documents several Message Types. A lot of folks would probably feel like I do that the names are pretty descriptive. To handle these messages, I created a MessageHandler class, containing the following React method:
        public Message React(Message eventMessage)
        {
            Message responseMessage = null;

            BotEvent eventType = GetBotEvent(eventMessage.Type);

            switch (eventType)
            {
                case BotEvent.BotAddedToConversation:
                    responseMessage = ReactToBotAdded(eventMessage);
                    break;
                case BotEvent.BotRemovedFromConversation:
                    responseMessage = ReactToBotRemoved(eventMessage);
                    break;
                case BotEvent.DeleteUserData:
                    responseMessage = ReactToDeleteUser(eventMessage);
                    break;
                case BotEvent.EndOfConversation:
                    responseMessage = ReactToEndConversation(eventMessage);
                    break;
                case BotEvent.Message:
                    responseMessage = ReactToMessage(eventMessage);
                    break;
                case BotEvent.Ping:
                    responseMessage = ReactToPing(eventMessage);
                    break;
                case BotEvent.UserAddedToConversation:
                    responseMessage = ReactToUserAdded(eventMessage);
                    break;
                case BotEvent.UserRemovedFromConversation:
                    responseMessage = ReactToUserRemoved(eventMessage);
                    break;
                case BotEvent.Unknown:
                default:
                    responseMessage = ReactToUnknown(eventMessage);
                    break;
            }

            responseMessage.Text += 
                ", JSON: " + JsonConvert.SerializeObject(eventMessage);

            return responseMessage;
        }
The listing above contains a switch statement with a case for each message type. Although this is a demo, I showed a little bit of defensive programming, by adding the BotEvent.Unknown case with a fall-through to the default case. Each case calls a method, specifically for that message type. I’ll explain the JSON part of the message, at the bottom of the method in an upcoming section.
Notice that each of the cases are an enum member. The BotEvent enum isn’t part of the Bot Framework – I added it myself. That’s why the React method calls the GetBotEvent method, shown below, ahead of the switch statement.
        BotEvent GetBotEvent(string eventType)
        {
            BotEvent botEvent;

            if (!Enum.TryParse<BotEvent>(eventType, out botEvent))
                botEvent = BotEvent.Unknown;

            return botEvent;
        }
The GetBotEvent method above tries to convert the message type from a string to a BotEvent type. If that doesn’t work, it returns BotEvent.Unknown. I could have simply created case statements as strings, but if you prefer a more strongly typed approach, this is one.
You might ask, “Why aren’t the messages already strongly typed?”. The reason has to do with the fact that the Bot Framework is cross-platform. As long as you give it a compatible interface (e.g. Post endpoint with appropriately formatted JSON content and message types), the Bot Framework is okay with that. In other platforms, strongly typed could mean something very different, but strings are well-known. A perfect example of another platform is node.js, for which the Bot Framework already has a Node.js SDK.

Handling Message Types

The messages called in the switch case statements receive a request message and return a response message, containing acknowledgement and some diagnostic details. Here’s an example of methods to handle UserAddedToConversation and UserRemovedFromConversation messages:
        Message ReactToUserAdded(Message eventMessage)
        {
            return eventMessage.CreateReplyMessage(
                $"User Added From - Address: {eventMessage.From.Address}, Name: {eventMessage.From.Name}");
        }

        Message ReactToUserRemoved(Message eventMessage)
        {
            return eventMessage.CreateReplyMessage(
                $"User removed From - Address: {eventMessage.From.Address}, Name: {eventMessage.From.Name}");
        }
Each method uses the CreateReplyMessage method to build a response message, but notice the interpolated string expressions. They’re reading the From property of the eventMessage, which contains additional information. Some bots might want to keep track of who they’re speaking with for proper conversation context and this would be an easy way to do so. There are many other properties of the Message type to obtain information on the particular event.
Additionally, you can also collect state for debugging and diagnostics.

Debugging?

To test your logic on most of these messages, you can use the Bot Framework Emulator, shown below:
image
Tip: When you’re working with multiple bots, it’s convenient to change the bot’s port number. The port number, in the emulator, for PC Bot is 3977 (not the default 3978).
The gray toolbar, above the JSON window, has a drop-down list with various message types. Select the message you want and click the Send button. In the figure, I selected the User Removed From Conversation message type. The chat window shows the response from the bot, which corresponds to the ReactToUserRemoved method response above.
You also see a lot of JSON in the response message, repeated below, which came from the bottom of the React method, before returning the responseMessage:
            responseMessage.Text += 
                ", JSON: " + JsonConvert.SerializeObject(eventMessage);
You see, the Bot Framework Message type serializes to JSON very easily. One problem this solves is when learning how to work with a new channel. There are only a few channels available as I write this blog post, but there will be more in the future. Each channel has it’s own unique characteristics. The Bot Framework accounts for this via a channelData property where you can read meta-data specific to that channel. The emulator doesn’t have this property, but the Slack channel and others do. You need a way to see what the channel is sending your bot. You could say, “Well, I’ll just read the documentation.” and you would be right, until you’re not. Documentation gets old, changes, and sometimes doesn’t exist and being able to inspect those values can be helpful.

Using MessageHandler

Here’s how I use the MessageHandler class:
        public async Task<Message> Post([FromBody]Message message)
        {
            return new MessageHandler().React(message);
        }
Because this bot is PC, it will react to every message.
@JoeMayo

Pig Latin Bot

The blog post, Botiquette, explained how Microsoft released the Bot Framework at the Build conference and referenced how you can find the Bot Framework and associated documentation. It’s easy reading, well organized, and simple to get started.
This post is about my first bot, Pig Latin Bot. As the name suggests, Pig Latin Bot takes everything you say to it and replies with a Pig Latin translation of your message. This post explains how I built Pig Latin Bot.

Setting Up

You need to install a couple bits of software to get started: a Bot Template and the Bot Emulator. The Bot Template lets you start a new bot project with the proper assembly references, configuration, and basic template code. The Bot Emulator is a chat window that helps you test your bot.
  1. Download the Bot Template and save it in “%USERPROFILE%\Documents\Visual Studio 2015\Templates\ProjectTemplates\Visual C#".
  2. Install the Bot Emulator, which is a click-once application that will install and enable easy updates on your computer.
If you need more help, visit the Overview on the Bot Framework site.

Examining the Bot Template

If you placed the Bot Template in the proper location, you can open Visual Studio, start a New Project, and select Bot Template. Name the solution and project – I called my solution BotDemos and the project PigLatinBot. The solution is a typical Web API solution that looks like this:
image
Open MessagesController and you’ll see that it’s a typical controller class. For our demo, clean out the template code so that the MessagesController class only contains an empty Post handler method, like this (and make sure your project builds):
    [BotAuthentication]
    public class MessagesController : ApiController
    {
        public async Task Post([FromBody]Message message)
        {
            return message.CreateReplyMessage("");
        }
    }
By cleaning out the MessagesController class and making CreateReplyMessage send an empty string, this bot effectively does nothing and we’re going to change that soon. The Post method is a REST API endpoint that the Bot Framework uses to communicate with your bot. The Message parameter, message, contains the text that a user types, along with additional metadata and convenience methods. One of those convenience methods is CreateReplyMessage, which constructs a new message that is sent back to the Bot Framework, with the text of your choice.
The Post method is the interface for your bot to the Bot Framework. The user will be communicating on some device that also communicates with the Bot framework. In this blog post, that device is the Bot Emulator, which I’ll discuss later.

Translating English to Pig Latin

This demo could have used one of many translation services off the Web, but that wouldn’t have been as much fun. Instead, I chose to write my own Pig Latin translator. It isn’t as robust as a commercial Pig Latin translator, but I figured it would do the job for this demo. If you aren’t that familiar with Pig Latin, you can get up-to-speed via How to Speak Pig Latin on the wikiHow site. Here’s the code for performing English to Pig Latin translations:
using System;
using System.Collections.Generic;
using System.Linq;

namespace PigLatinBot
{
    public class PigLatin
    {
        readonly char[] alphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
        readonly char[] vowels = "AEIOUaeiou".ToCharArray();
        const string VowelSuffix = "yay";
        const string ConsonantSuffix = "ay";

        public string FromEnglish(string text)
        {
            string[] rawWords = text.Split(' ');

            List<string> cleanedWords =
                (from word in rawWords
                 let wordChars = word.ToLower().ToCharArray()
                 let cleanChars =
                    (from ch in wordChars
                     where alphas.Contains(ch)
                     select ch)
                    .ToArray()
                 select new string(cleanChars))
                .ToList();

            List<string> cookedWords =
                (from word in cleanedWords
                 select ConvertWord(word))
                .ToList();

            return string.Join(" ", cookedWords);
        }

        string ConvertWord(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
                return "";

            char[] textChars = text.ToCharArray();
            char firstChar = textChars[0];

            if (vowels.Contains(firstChar))
            {
                return text + VowelSuffix;
            }
            else
            {
                int newPrefixSize = textChars.Length > 0 ? textChars.Length - 1 : 0;
                var newPrefix = new char[newPrefixSize];
                Array.Copy(textChars, 1, newPrefix, 0, newPrefixSize);

                return new string(newPrefix) + firstChar + ConsonantSuffix;
            }
        }
    }
}
The FromEnglish method takes care of all logic to perform the translation from English to Pig Latin. It first splits a sentence into individual words. Then it cleans the words by eliminating non-alpha characters. This was a simple way to avoid additional work for non-alpha characters – it’s a demo. Then it converts each word into Pig Latin, joins the words together, and returns the translated string. The ConvertWord method is where the actual translation of each word from English to Pig Latin occurs and represents one interpretation of the wikiHow article mentioned earlier.
Create a new PigLatin.cs file in your project and replace its contents with this PigLatin class and make sure your project builds. Now we’re ready to use the new PigLatin class.

Using the PigLatin Class

The logic of the bot is very simple – it reads the message from the user, translates it into Pig Latin, and replies to the user with the translated message. Update the Post method, in MessagesController, like this:
        public async Task Post([FromBody]Message message)
        {
            string pigLatinReply = new PigLatin().FromEnglish(message.Text);

            return message.CreateReplyMessage(pigLatinReply);
        }
The messages parameter has a Text property that contains the message that the user typed and sent via their application. Through an instance of the PigLatin class, the Post method sends message.Text to the FromEnglish method. The returned Pig Latin translation is assigned to pigLatinReply. Then, instead of passing an empty string, the code passes pigLatinReply as an argument to CreateReplyMessage so that the user can see the translated message. Now that the bot is done, you want to see it in action.

Testing Pig Latin Bot

To test your bot, run your project, run the emulator, and make sure the emulator is configured. Start your bot project by typing F5 and you’ll see a screen that looks like this:
image
This launches your bot in a web server where it can be called via it’s REST API. Take note of the address, which is “http://localhost:3978/” on my machine. The address seems to default to port 3978, which could change. e.g. What if you wanted to run multiple bots simultaneously and needed unique addresses?
Now start the Bot Emulator. You can find it in your Start menu under the name, Bot Framework Emulator. It looks like this when it starts:
image
Notice the URL in the top left. This should match the URL of your bot that you launched via Visual Studio with the segments “api/messages” appended. Also, notice the App Id and App Secret boxes on the top right. Their values must match the values that you can find in the appSettings element in the bot project’s Web.config file.
Tip: Don’t check your App Id and App Secret into source control – bad things can happen.
The left side of the screen is where chat takes place and the right screen contains JSON that the server returns. This JSON contains the reply text as well as metadata associated with the Message type returned from your bot. Type in a few sentences to see how it works. What’s great is that you can set breakpoints in your project, handle exceptions, and do all of the debugging tasks you normally do.

In Summary

Now you know how to set up your bot environment and start a new project. You can use the Post method as an interface to manage communication with the Bot framework. The PigLatin class was fun, but also represents a way for you to build and separate your own logic and consume that logic from the Post method of the bot. You can use the Bot Emulator to test your bot, but also remember to check that your URL correctly matches your bot address and that your App Id and App Secret are set properly.
You can find the code on my GitHub Repository, BotDemos.
@JoeMayo

Botiquette

Today, at Build 2016, Microsoft revealed a new AI tool for developers called the Bot Framework. The Bot Framework allows developers to write software bots that interact with people (and other bots). Essentially this makes it easy to create a Conversational User Interface (CUI), ushering in a new era that makes us think more about what a user interface should be.
Beyond a visual interface, User Experience (UX) will take on new meaning. The bot will need to lead the user through a series of steps that make sense, yet be able to adjust so as not to be too rigid and lead them down a path that might not make sense for the situation. Because Bots, written with the Bot Framework, can use Cognitive Services (another new AI product) and other intelligent services, the UX has potential to be even more appealing.
Intelligence is also a two-way sword where checks-and-balances must be maintained to avoid problems. The recent difficulties, as told by the Washington Post and other news media, concerning Microsoft’s @TayAndYou Twitter account highlight what can go wrong with an unconstrained bot. There has been plenty of discussion about how and why this happened, but it does indicate a need for more vigilance by developers. For this, we need something like botiquette:
Botiquette
The customary code of polite behavior among bots and humans - often in social media, but also in apps, the enterprise, or any device where bot to bot and bot to human communication occur.
Neither Bing nor Google revealed a definition of botiquette. I searched Wikipedia too and the closest I came were the Laws of Robotics. The Laws of Robotics, by Asimov et.al., are a valid discussion, but focus on preventing distopian futures. Botiquette, I believe, is a more subtle cultural need for pleasant bot to human experiences.
Do you know of or think there is a better definition for Botiquette?
Bot technology has been around, but is still in it’s early stages. It’s interesting to hear Microsoft and others start the CUI discussion and will be fun to see where it leads.
@JoeMayo