Coding a Bing Bot

Bots are becoming increasingly popular, with good reason. Technology has come a very long way; but, there are times when certain technologies seem to reach a point where they cannot go any further. A point where some new "life" is needed—a change, or an improvement. Such is the case with bots.

In the 90s, Web sites became popular. This shifted the software market, or rather, people's market, to a bright and new shiny platform called the "Web." Gone were the days where developers developed software solely for the desktop market. The Web has opened up so many possibilities. People could advertise more and reach more people. New businesses started. E-Commerce started.

In the 2000s, a new player arrived: Mobile applications. The coming of smartphones again changed the technology landscape. Developing for the mobile platform has opened up even more possibilities than its predecessor (the Web) could. Everything has become so easy and convenient. Now, basically ten years on since the start of the mobile age, mobile apps have reached their pinnacle. There is not much more you can do, or invent that hasn't been done or invented on a mobile platform yet.

So, what now?

The answer is: Bots.

Microsoft Bing Bots

A bot is an application that can run automated tasks. These tasks are usually repetitive and bots perform these tasks much faster than humans can. Because of the speed at which bots can perform tasks, they also can be implemented where response speed is faster than how a human can respond and process information.

I have spoken about bots before. You can find those articles here:

Let's delve a bit deeper into bots today and create a Bing Bot.

Microsoft Bot Framework SDK

The first step in creating a Bing Bot is to download the Microsoft Bot Framework SDK. The Microsoft Bot Framework is a communication service that helps connect your bots with different communication channels, such as SMS and e-mail. The Microsoft Bot Framework includes Bot Builder to give you the tools you need to develop bots.

The Bot Builder SDK is hosted on GitHub. If you are not sure how GitHub works, this article will help in understanding GitHub and Visual Studio better.

Bot Builder includes several samples for you to explore and experiment with in Visual Studio.

Bot Framework Template

Step Two involves obtaining the Bot Framework Visual Studio template. You need to install this template to be able to develop any bot. Download the Bot Application template and install the template by extracting the .zip file into your Visual Studio project templates directory, which is located in the following location:

%USERPROFILE%\Documents\Visual Studio VERSION\Templates\ProjectTemplates\Visual C#\

Now, this is where documentation seems a bit lacking as well as the whole process being cumbersome…

By installing the template, you are by no means ready to start developing your bot. You first have to ensure that you have all the Updated ApiController classes. To update all the necessary namespaces and classes, follow these steps:

  1. Create the Bot Framework project. At this point in time, only C# is supported. Name the project anything descriptive. In this example, I have named my project HTGBing.
  2. Once the project skeleton has been created, you will notice that a lot of the classes will potentially produce errors, as shown in Figure 1.

    Solution Explorer before update
    Figure 1: Solution Explorer before update

  3. Right-click the project and select Manage NuGet Packages.
  4. In the Browse tab, type "Microsoft.Bot.Builder."

    NuGet Packages
    Figure 2: NuGet Packages

  5. Locate the Microsoft.Bot.Builder package in the list of search results, and click the Update button for that package.
  6. Preview the changes NuGetwill make.

    Preview NuGet Changes
    Figure 3: Preview NuGet Changes

  7. Follow the prompts to accept the changes and update the package.

    Finished Updating NuGet Packages
    Figure 4: Finished Updating NuGet Packages

Bot Framework Emulator

Step Three involves installing the Bot Framework Emulator. You need to install the Bot Framework Emulator to test your bot properly before publishing it to the Bing portal. Download the Emulator here.

After it has downloaded—it is about 60MB—run the Setup file.

Install Bot Framework Emulator
Figure 5: Install Bot Framework Emulator

Figure 6 shows the Emulator in action.

Emulator in Action
Figure 6: Emulator in Action

Coding Your Microsoft Bing Bot

You will notice how your project is divided and what it consists of in the Solution Explorer. There are three main folders:

  • App_Start
  • Controllers
  • Dialogs

App_Start contains all of the files for your Bing Bot to start. Controllers contain all of the classes that have to interpret and digest the bot's messages being sent and received. Dialogs contain all the graphical windows of your Bing Bot.

Locate and find the Web.Config file. You will have to enter your Bing Bot's credentials in here. Obviously, you have not created the Bing Bot on the Bing Bot Portal yet, but it is good to know where to put it, so that when I cover that (a bit later in this article) you will know what I am talking about.

My Web.Config file that includes my Bing Bot's credentials looks like the following:

Web.Config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
   <appSettings>
      <add key="BotId" value="HTGBing" />
      <add key="MicrosoftAppId"
           value="d8bd90d3-284f-49c7-a33a-bc047dfe7115" />
      <add key="MicrosoftAppPassword"
           value="E1xdHf9dNLRgwV0n9YOTEXw" />
   </appSettings>
   <system.web>
      <customErrors mode="Off" />
      <compilation debug="true" targetFramework="4.6" />
      <httpRuntime targetFramework="4.6" />
   </system.web>
   <system.webServer>
      <defaultDocument>
         <files>
            <clear />
            <add value="default.htm" />
         </files>
      </defaultDocument>

   <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0"
           path="*." verb="*"
           type="System.Web.Handlers.TransferRequestHandler"
           preCondition="integratedMode,runtimeVersionv4.0" />
   </handlers></system.webServer>
   <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         <dependentAssembly>
            <assemblyIdentity name="System.Web.Helpers"
                              publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0"
                             newVersion="3.0.0.0" />
         </dependentAssembly>
         <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc"
                              publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-5.2.3.0"
                             newVersion="5.2.3.0" />
         </dependentAssembly>
         <dependentAssembly>
            <assemblyIdentity name="System.Web.WebPages"
                              publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0"
                             newVersion="3.0.0.0" />
         </dependentAssembly>
         <dependentAssembly>
            <assemblyIdentity name="Newtonsoft.Json"
                              publicKeyToken="30ad4fe6b2a6aeed"
                              culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-8.0.0.0"
                             newVersion="8.0.0.0" />
         </dependentAssembly>
         <dependentAssembly>
            <assemblyIdentity name="System.Net.Http.Primitives"
                              publicKeyToken="b03f5f7f11d50a3a"
                              culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.2.29.0"
                             newVersion="4.2.29.0" />
         </dependentAssembly>
         <dependentAssembly>
            <assemblyIdentity name="System.Net.Http.Formatting"
                              publicKeyToken="31bf3856ad364e35"
                              culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-5.2.3.0"
                             newVersion="5.2.3.0" />
         </dependentAssembly>
      </assemblyBinding>
   </runtime>
</configuration>

The BotID setting must be set to the name of your bot. Once you have registered your bot on the Bing Bot Portal, Bing will supply you with the MicrosoftAppId and MicrosoftAppPassword.

Locate and edit the default.htm file:

Default.htm

<!DOCTYPE html>
<html>
<head>
   <title></title>
   <meta charset="utf-8" />
</head>
<body style="font-family:'Segoe UI'">
   <h1>HTGBing</h1>
   <p>This is simply an Example Bot.</p>
</body>
</html>

Default.htm, in this case, provides the user with a simple message. Locate and edit the WebApiConfig.cs file:

WebApiConfig.cs

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace HTGBing
{
   public static class WebApiConfig
   {
      public static void Register(HttpConfiguration config)
      {
         // JSON settings//
         config.Formatters.JsonFormatter.SerializerSettings
            .NullValueHandling = NullValueHandling.Ignore;
         config.Formatters.JsonFormatter.SerializerSettings
            .ContractResolver = new
            CamelCasePropertyNamesContractResolver();
         config.Formatters.JsonFormatter
            .SerializerSettings.Formatting = Formatting.Indented;
         JsonConvert.DefaultSettings = () => new
            JsonSerializerSettings()
         {
            ContractResolver = new
               CamelCasePropertyNamesContractResolver(),
            Formatting = Newtonsoft.Json.Formatting.Indented,
            NullValueHandling = NullValueHandling.Ignore,
         };

         // Web API configuration and services//

         // Web API routes//
         config.MapHttpAttributeRoutes();

         config.Routes.MapHttpRoute(
            name: "HTGBingMethod",
            routeTemplate: "api/{controller}/HTGBingMethod/{id}",
            defaults: new { id = RouteParameter.Optional }
         );
      }
   }
}

The WebApiConfig class lets you set up the messaging route. This means that here you should specify how the messages should be sent through to the bot. The end EndPoint would resemble the URL of your bot, along with the Route Template. For example: A Route Template such as the one supplied above might end up looking like this once done:

http://localhost(OR SERVERNAME):3979(OR PORT NUMBER)/api/messages/HTGBingMethod/id

Add the MessagesController class:

MessagesController.cs

using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;

namespace HTGBing
{
   [BotAuthentication]
   public class MessagesController : ApiController
   {
      public async Task<HttpResponseMessage>
         Post([FromBody]Activity activity)
      {
         if (activity.Type == ActivityTypes.Message)
         {
            await Conversation.SendAsync(activity, () =>
               new Dialogs.RootDialog());
         }

         var response = Request.CreateResponse(HttpStatusCode.OK);
         return response;
      }
   }
}

If a Message (used to communicate between a user and a bot) was sent, the bot needs to display the Root Dialog, which you will add later. There are various types of Messages that you can send to your bot; these include:

  • Text: The actual text being sent
  • Language: The language of the message that gets sent or should be received.
  • Markdown: This includes the basic formatting of the message as well as an indication of the paragraph markdowns, which is obviously the paragraph marker.
  • Attachments: This is the possible attachment to the message. This also includes the type of content being sent to and from the user and the bot.

Add the RootDialog.cs code:

RootDialog.cs

using System;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;

namespace HTGBing.Dialogs
{
   [Serializable]
   public class RootDialog : IDialog<object>
   {
      public Task StartAsync(IDialogContext context)
      {
         context.Wait(MessageReceivedAsync);

         return Task.CompletedTask;
      }

      private async Task MessageReceivedAsync(IDialogContext
         context, IAwaitable<object> result)
      {
         var activity = await result as Activity;

         if (activity.Text == "Hannes")
         {
            await context.PostAsync($"Welcome Hannes!");
         }
         else
         {
            await context.PostAsync($"Hello there, Stranger!");
         }

         context.Wait(MessageReceivedAsync);
      }
   }
}

If the user entered "Hannes," the bot will reply with a welcoming message. Otherwise, the bot will know I am a stranger and act accordingly.

Registering Your Bing Bot

To register your Bing Bot, follow these steps:

  1. Sign in to the Bot Framework Portal.
  2. After you have signed in, click My Bots.
  3. Click Create a bot.
  4. Click Register.

Register your Bing Bot
Figure 7: Register your Bing Bot

Creating a Bing Bot Profile

  1. Upload an icon that will represent your Bing Bot.
  2. Provide a Display Name for your Bing Bot.
  3. Provide a Handle for your Bing Bot. This value will be used in the URL for your bot and cannot be changed after registration.
  4. Provide a Description of your Bing Bot.

Bing Bot Profile
Figure 8: Bing Bot Profile

Configuring Your Bing Bot

  1. Provide your Bing Bot's HTTPS messaging endpoint. This is the endpoint where your bot will receive HTTP POST messages from the Bot Connector.

    Configuring Bing Bot
    Figure 9: Configuring Bing Bot

  2. Click Create Microsoft App ID and password.
  3. Click Generate an app password to continue.
  4. Copy and securely store the password that is shown, and then click Ok.
  5. Click Finish and go back to Bot Framework.

Bing Bot Generate Application ID and Password
Figure 10: Bing Bot Generate Application ID and Password

The App ID field is now displayed in the Bot Framework Portal.

Providing Analytics for Your Bing Bots

Provide the AppInsights Instrumentation key, AppInsights API key, and AppInsights Application ID from the corresponding resource that you've created.

Adding Owner Information

  1. Specify the email address(es) for the owner(s) of the bot.
  2. Check to indicate that you have read and agree to the Terms of Use, Privacy Statement, and Code of Conduct.
  3. Click Register to complete the registration process.

Owner information
Figure 11: Owner information

Bing Bot created
Figure 12: Bing Bot created

Your Bing Bot is now created. Remember to supply the correct AppID and Password in your Web.Config file. You now can go back to My Bots and you will see your Bing Bot is shown. Clicking your newly created Bing Bot will enable you to connect to more Bing Channels and to fix any outstanding issues for your bot.

Connect to Channels
Figure 13: Connect to Channels

Please feel free to download the accompanying file for this article. It contains the code needed to create your own bot.

Conclusion

The sooner you get acquainted with bots, the better. This article demonstrated how to create your own Bing Bots. As you can see, it is quite easy to do—you just need the right tools.



About the Author

Hannes DuPreez

Hannes du Preez is a Microsoft MVP for Visual Basic for the ninth consecutive year. He loves technology and loves Visual Basic. He loves writing articles and proving that Visual Basic is more powerful than what most believe. You are most welcome to reach him at: ojdupreez1978@gmail.com

Related Articles

Downloads

Comments

  • Locking in to Bing

    Posted by Adrian Waters on 07/17/2017 03:21am

    Why would I want to write software that locks me and my users into a specific search engine?

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date