Connect Azure Bot to Google Assistant Action Channel | Prepare your Code

Connect Microsoft Bot Framework Azure Bot to Google Assistant Action as a channel. We will use Actions SDK and DialogFlow Adapter for Bot Builder v4 .NET SDK.

I will be working on the Core Bot template considering the sequential conversation and testing it on Google Actions Console. Many other demos use the Echo bot for its simplicity.

This is the bot series on Connecting Microsoft Azure Bot to Google Assistant Action Channel and in this first part, we will prepare our code for the deployment.

Prerequisites

  • Visual Studio

Visual Studio link can be found on the Downloads page.

Prepare your Code

I have created the project using the Core Bot template which is also called the Flight Booking Bot. Go to the controller folder and add a new controller with the name GoogleController.

Create a new GoogleController for Google Assistant integration with Azure Bot

Add the following code to the GoogleController.cs. Make sure to change the namespace according to your project name and the location.

using System.Threading.Tasks;
using Bot.Builder.Community.Adapters.Google;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Builder;

namespace FlightBot.Controllers
{
    // This ASP Controller is created to handle a request. Dependency Injection will provide the Adapter and IBot
    // implementation at runtime. Multiple different IBot implementations running at different endpoints can be
    // achieved by specifying a more specific type for the bot constructor argument.
    [Route("api/google")]
    [ApiController]
    public class GoogleController : ControllerBase
    {
        private readonly GoogleAdapter Adapter;
        private readonly IBot Bot;

        public GoogleController(GoogleAdapter adapter, IBot bot)
        {
            Adapter = adapter;
            Bot = bot;
        }

        [HttpPost]
        public async Task PostAsync()
        {
            // Delegate the processing of the HTTP POST to the adapter.
            // The adapter will invoke the bot.
            await Adapter.ProcessAsync(Request, Response, Bot);
        }
    }
}

Install the Bot.Builder.Community.Adapters.Google NuGet package.

Install the Google Adaptor NuGet package

For Error handling with respect to Google Adaptor, create a new class file with the name GoogleAdapterWithErrorHandler at the root location of the project.

Create the Error Handler class for Google Adaptor

Add the following code to GoogleAdaptorWithErrorHandler.cs class file. Make sure to change the namespace according to your project name and the location.

using Bot.Builder.Community.Adapters.Google;
using Microsoft.Extensions.Logging;

namespace FlightBot
{
    public class GoogleAdapterWithErrorHandler : GoogleAdapter
    {
        public GoogleAdapterWithErrorHandler(ILogger<GoogleAdapter> logger, GoogleAdapterOptions adapterOptions)
            : base(adapterOptions, logger)
        {
            OnTurnError = async (turnContext, exception) =>
            {
                // Log any leaked exception from the application.
                logger.LogError($"Exception caught : {exception.Message}");

                // Send a catch-all apology to the user.
                await turnContext.SendActivityAsync("Sorry, it looks like something went wrong.");
            };
        }
    }
}

The last thing is to add is the Google Adaptor services in the Startup.cs file. Add the following code inside ConfigureServices method.

services.AddSingleton(sp =>
            {
                return new GoogleAdapterOptions()
                {
                    ActionInvocationName = "<ACTION_INVOCATION_NAME>",
                    ActionProjectId = "<ACTION_PROJECT_ID>",
                    DialogFlowAuthorizationHeader = "<DIALOG_FLOW_AUTHORIZATION_HEADER_SECRET_KEY>",
                    ValidateIncomingRequests = true,
                    WebhookType = GoogleWebhookType.Conversation
                };
            });

            services.AddSingleton<GoogleAdapter, GoogleAdapterWithErrorHandler>();

For more details about these properties, visit the Bot builder community GitHub repo where the Adaptor is hosted. Don’t worry about the values of the above properties, we will fill it out later. Below is the complete code of how your Startup.cs file will look like.

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// Generated with Bot Builder V4 SDK Template for Visual Studio CoreBot v4.14.0

using Bot.Builder.Community.Adapters.Google;
using Bot.Builder.Community.Adapters.Google.Core.Model.Request;
using FlightBot.Bots;
using FlightBot.Dialogs;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace FlightBot
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpClient().AddControllers().AddNewtonsoftJson();

            // Create the Bot Framework Adapter with error handling enabled.
            services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();

            services.AddSingleton(sp =>
            {
                return new GoogleAdapterOptions()
                {
                    ActionInvocationName = "<ACTION_INVOCATION_NAME>",
                    ActionProjectId = "<ACTION_PROJECT_ID>",
                    DialogFlowAuthorizationHeader = "<DIALOG_FLOW_AUTHORIZATION_HEADER_SECRET_KEY>",
                    ValidateIncomingRequests = true,
                    WebhookType = GoogleWebhookType.Conversation
                };
            });

            services.AddSingleton<GoogleAdapter, GoogleAdapterWithErrorHandler>();

            // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.)
            services.AddSingleton<IStorage, MemoryStorage>();

            // Create the User state. (Used in this bot's Dialog implementation.)
            services.AddSingleton<UserState>();

            // Create the Conversation state. (Used by the Dialog system itself.)
            services.AddSingleton<ConversationState>();

            // Register LUIS recognizer
            services.AddSingleton<FlightBookingRecognizer>();

            // Register the BookingDialog.
            services.AddSingleton<BookingDialog>();

            // The MainDialog that will be run by the bot.
            services.AddSingleton<MainDialog>();

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            services.AddTransient<IBot, DialogAndWelcomeBot<MainDialog>>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseDefaultFiles()
                .UseStaticFiles()
                .UseWebSockets()
                .UseRouting()
                .UseAuthorization()
                .UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });

            // app.UseHttpsRedirection();
        }
    }
}

Thank you All!!! Hope you find this useful.


One thought on “Connect Azure Bot to Google Assistant Action Channel | Prepare your Code

Add yours

Up ↑

%d bloggers like this: