Creating a Hello World! Bot (MS Bot Framework V4)

Oct 2

Written by:
10/2/2018 9:31 PM  RssIcon

image

The Microsoft Bot Framework V4 allows you to create intelligent bots that interact naturally wherever your users are (text/SMS to Skype, Slack, Office 365 mail and other popular services). The Bot Builder V4 SDK offers new features and is extensible with a pluggable middleware model.

In this article we will create a simple Hello World! Bot and deploy it.

Tutorial Series

Other articles in this series:

Requirements

 

Create The Project

image

Open Visual Studio and select File, then New, then Project.

image

In the New Project dialog, select the Bot Builder Template, name the project HelloWorldBot and click OK.

image

The project will be created.

Hit F5 to run the project.

image

Your web browser will open.

Connect Using The Bot Framework Emulator

image

Open the Bot Framework Emulator.

image

Select Open Bot.

image

Select the .Bot file that is in the root directory of the project you just created.

image

You can now chat with the Bot.

Update The Code

image

Return to Visual Studio and press Shift+F5 to stop debugging.

image

Open the CounterState.cs file and change the class so it adds a SaidHello property:

 

    public class CounterState
    {
        /// <summary>
        /// Gets or sets the number of turns in the conversation.
        /// </summary>
        /// <value>The number of turns in the conversation.</value>
        public int TurnCount { get; set; } = 0;
        public bool SaidHello { get; set; }
    }

 

image

Next, open the EchoWithCounterBot.cs file (this is the main file for the bot), and alter the OnTurnAsync method to the following:

 

        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken 
            cancellationToken = default(CancellationToken))
        {
            // Handle Message activity type, which is the main activity 
            // type for shown within a conversational interface
            // Message activities may contain text, speech, interactive cards, 
            // and binary or unknown attachments.
            // see https://aka.ms/about-bot-activity-message to learn more about 
            // the message and other activity types
            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                // Get the conversation state from the turn context.
                var state = await _accessors.CounterState.GetAsync(turnContext, () => new CounterState());
                // Bump the turn count for this conversation.
                state.TurnCount++;
                if (!state.SaidHello)
                {
                    // Handle the Greeting
                    string strMessage = $"Hello World! {System.Environment.NewLine}";
                    strMessage += "Talk to me and I will repeat it back!";
                    await turnContext.SendActivityAsync(strMessage);
                    // Set SaidHello
                    state.SaidHello = true;
                }
                else
                {
                    // Echo back to the user whatever they typed.
                    var responseMessage = $"Turn {state.TurnCount}: You sent '{turnContext.Activity.Text}'\n";
                    await turnContext.SendActivityAsync(responseMessage);
                }
                // Set the property using the accessor.
                await _accessors.CounterState.SetAsync(turnContext, state);
                // Save the new turn count into the conversation state.
                await _accessors.ConversationState.SaveChangesAsync(turnContext);
            }
            else
            {
                await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected");
            }
        }

 

This checks the status of the boolSaidHello property, and if it is false, sends a “Hello World!” message.

It then sets the property to true so it wont say it again.

image

Rebuild the project in Visual Studio and press F5 to run it.

image

In the Bot Emulator, click the Start Over button to re-start the conversation.

 

image

The greeting message will now only show once during the conversation.

Deploy The Bot

image

To deploy your Bot, the first step is to create a Production endpoint in the .bot file.

(if you don’t do this you may get the error: Application startup exception: System.InvalidOperationException: The .bot file does not contain an endpoint with name 'production'.)

In the Emulator, click the + icon next to ENDPOINT.

image

In the Add a Endpoint for your bot dialog that appears:

  • Enter Production for Name
  • Enter the address you plan to publish the bot to for the Endpoint url

Press Submit.

image

When you look in the .bot configuration file, you will see a new endpoint has been added.

image

Update the file so the Production end point is listed first.

image

In Visual Studio, right-click on the project and select Publish.

image

  1. Select App Service (this is an Azure website)
  2. Select Create New
  3. Click Create Profile

image

  1. Log into your Azure account
  2. Put in the settings to create the new App Service
  3. Click the Create button

image

It may take several minutes for it to deploy.

At this point it is only creating the resources on Azure.

image

Click the Publish button to publish the application to Azure.

image

The application will publish.

Your web browser will open on the site.

Connect The Bot To The Azure Bot Service

image

At this point we only have a web application deployed. To enable it to connect to the various channels such as Skype, we need to create an Azure Bot Service and connect it to it.

Open a web browser and navigate to: https://portal.azure.com and log in.

Then select Create a resource.

image

Search for Bot Channels and press the Enter key to perform the search.

When Bot Channels Registration appears, click on it.

image

On the edit screen for Bot Channels Registration, click the Create button.

image

  1. Fill in the details for the registration
  2. Click the Auto create App ID and password button…

image

A new blade will open

Click the Auto create App ID and password button

The blade will then close

image

This returns you to the Bot Channels Registration blade.

Click the Create button.

image

It may take several minutes for it to deploy.

image

Click the Go to resource button when it displays.

image

You can also find the Bot Channels Registration you created by selecting All resources (in the Azure portal) and then searching for it.

image

Select Settings then the Manage link for Microsoft App ID.

image

This will take you to the app registration site at: https://apps.dev.microsoft.com

Click on the Generate New Password button.

image

A password will display.

Copy down the password

Click OK.

image

Return to the portal.azure.com site and copy the Microsoft App ID.

image

In Visual Studio, open the BotConfiguration.bot file and update it:

Add the following keys (and the coordinating values you copied down earlier):

  • appId (for value use the Microsoft App ID you copied earlier)
  • id (the name of the app registration site at: https://apps.dev.microsoft.com)
  • appPassword (for value use the password you copied earlier)

Re-publish the application.

image

Return to the Bot Channels Registration

image

You can now click the Test in Web Chat button and communicate with the Bot.

image

You can click on the Channels button to set up more channels for the Bot.

image

For example, you can click the Skype button…

image

Then click Publish.

image

Fill in the required information and click the Save button.

image

Agree to Microsoft’s Terms of Service.

image

Click the Cancel button.

image

This takes you back to the Connect to channels page.

Click on the Skype link.

image

This will take you to page that allows you to add the bot to your Skype contacts.

Click the Add to Contacts button.

image

Click the button to Open Skype (if you have it installed on your computer).

Otherwise click the button to Download Skype.

image

Skype will open.

You can now chat with the Bot in Skype.

 

Connect In The Emulator

image

You can also open the Bot Framework Emulator

Select create a new bot configuration.

image

Enter the connection information to the bot App Service on Azure

Click Save and connect.

 

Links

Azure Bot Service Documentation for the v4 SDK

Azure Bot Service

Conversational AI: Best Practices for Building Bots

Find Your Azure Bot’s AppID and AppSecret

Download

You can download the code from the Download page