Building bots with Microsoft Bot Framework

Microsoft Bot Framework

About
Bots are a kind of program that automates a lot of things. Usually these are repetitive and easy tasks that are time-consuming for humans. Bots are used for trading, auctions, conversations etc., where they can perform tasks much faster than a human being. In this article we will have a closer look at conversational bots.

Every day a lot of people spend time on their jobs answering the same questions and providing the same information for clients. A good example of this type of job can be shopping chats, support services and others alike. No one wants to wait for a free operator to ask something simple. For example, you will always ask the same questions when you would like to order a pizza. These would concern things like type, size, quantity and delivery. This kind of person-to-person conversations can be replaced with bots that can help your company to concentrate human resources on more complex and non-trivial tasks.

Conversational bot is not a new thing, but now their development has become as easy as never before. In 2016, Facebook and Microsoft announced their bot platforms. It means that top companies are interested in this direction and will take a lot of efforts to popularize Conversational User Interfaces (CUI) as an addition of well known Graphical User Interfaces (GUI).

Creating a bot
To demonstrate you how to build a bot we will use Microsoft Bot Framework (MBF). MBF was announced in March on the Microsoft developers conference BUILD 2016. MBF is not just a framework your developers can use to create a bot. It is also a platform that can help you to integrate your bot with other services like Skype, Slack and others. We also expect that in future you will be able to publish your bot and earn on them like now companies make money on stores like AppStore or Google Play.

Right now there are two ways to create a bot on MBF. You can create a new bot with Bot Application Template for Visual Studio(http://aka.ms/bf-bc-vstemplate) or add it to your existing project. We will use the second approach and add a bot to default ASP.NET MVC application.
Steps:

1) To start working with MBF you will need to install Microsoft.Bot.Builder Nuget package that will add all necessary libraries to your project.
Microsoft Bot Builder Nuget Package

2) To take a message from the user and create a reply you will need to create new API controller.

public class MessagesController : ApiController
{
    public async Task Post([FromBody]Message message)
    {
        if (message.ENGINE== "Message")
            return await Conversation.SendAsync(message, () => new MathForKidsDialog());
        return message.CreateReplyMessage($"Message received. Type: {message.Type}");
    }
}

3) For processing dialog, we will use Dialogs model.

Dialogs model a conversational process, where the exchange of messages between a bot and a user is the primary channel for interaction with the outside world. Each dialog is an abstraction that encapsulates its state in a C# class that implements IDialog. Dialogs can be composed with other dialogs to maximize reuse, and a dialog context maintains a stack of dialogs active in the conversation.

Microsoft Bot Framework Documentation

For processing the basic dialog you can use your implementation of Dialog interface. The dialog should be a serializable class because the state of Conversation is transferring every time during conversation through Json. In order to demonstrate how it works we will create a simple dialog for asking users to answer a simple math question.

[Serializable]
public class MathForKidsDialog : IDialog<object>
{
    private QuestionModel _question;
    private bool _sessionStarted;
 
    public async Task StartAsync(IDialogContext context)
    {
        context.Wait(MessageReceivedAsync);
    }
    public async Task MessageReceivedAsync(IDialogContext context, IAwaitable argument)
    {
        var message = await argument;
        if (!_sessionStarted)
        {
            if (string.Equals(message.Text, "Let's study math", StringComparison.OrdinalIgnoreCase))
            {
                _sessionStarted = true;
                await context.PostAsync("Sounds great. Let's start from addiction.");
            }
            else
            {
                await context.PostAsync("Enter \"Let's study math\" to start the conversation.");
                context.Wait(MessageReceivedAsync);
                return;
            }
        }
 
        if (_question == null)
        {
            _question = GetQuestion();
            await context.PostAsync(_question.Question);
        }
        else
        {
            if (_question.Answer == message.Text)
            {
                _question = GetQuestion();
                await context.PostAsync($"Amazing. {_question.Question}");
            }
            else
                await context.PostAsync($"Think one more time. It's easy. {_question.Question}");
        }
        context.Wait(MessageReceivedAsync);
    }
 
    private QuestionModel GetQuestion()
    {
        var random = new Random();
        var number1 = random.Next(20);
        var number2 = random.Next(20);
 
        return new QuestionModel
        {
            Answer = $"{number1 + number2}",
            Question = $"What is the answer for {number1} + {number2}?"
        };
    }
}

4) The Bot Framework also provides an emulator that lets you test your bot. You can download Bot Framework Emulator here.
Microsoft Bot Framework Emulator

Publishing
Let’s publish our bot to Bot Framework developer portal and make it working on Slack.
Steps:
1) Make your website available to direct access. We have deployed our website to Azure.
2) Create your bot on Bot Framework developer portal here.

Microsoft Bot Framework Portal

3) You will have your bot webpage. Here you can change settings, test your bot or integrate it with other platforms. To integrate your bot in Slack just press Add near Slack and follow instruction
Microsoft Bot Framework Portal
Microsoft Bot Framework Portal
4) Congratulations. Your bot is successfully working on Slack
Integration with Slack

Summary
If your company spends a lot of money on talking to clients, you can try to build a bot. Of course it will not replace you a human for non-trivial tasks, but you can use them for a lot of regular tasks. The era of Conversational User Interfaces is near so be one of the first who enter it.

Posted by Andriy Koval

Andriy is a founder and CEO at Westcoup. Contact him anytime at andriy.koval@westcoup.com

Comments