Geeks With Blogs
Joe Mayo

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:


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):

    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)
                 select new string(cleanChars))

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

            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;
                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:


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:


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.



Posted on Friday, April 1, 2016 11:32 PM bots , botframework | Back to top

Copyright © Joe Mayo | Powered by: | Join free