Create WhatsApp Bot | Connect WhatsApp with QnA Maker | Create Azure Functions using Visual Studio

In this post, we will Create a WhatsApp Bot that will connect to the QnA Maker Service using the Azure Functions in C#. We will create the Azure Function in Visual Studio.

Pre-Requisites:

  1. QnA Maker Knowledge Base
  2. Twilio Account
  3. Cloud Templates in Visual Studio

Creating Azure Function in Visual Studio

Launch Visual Studio and Create a new project. Select Cloud as Project Type and choose Azure Function.

Give the name of the project “WhatsAppBotFunction” and save it to desired location. Select checkbox place solution and project in same directory. Select Azure Functions v1 (.Net Framework) and HTTP Trigger.

Replace the existing code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using Twilio.TwiML;

namespace FunctionApp1
{
    public static class Function1
    {
        private static readonly HttpClient httpClient = new HttpClient();
        private const string endpointURL = "";
        private const string endpointKey = "";
        private const string kbId = "";

        [FunctionName("whatsapp-message")]
        public static async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            var data = await req.Content.ReadAsStringAsync();

            var formValues = data.Split('&')
                .Select(value => value.Split('='))
                .ToDictionary(pair => Uri.UnescapeDataString(pair[0]).Replace("+", " "),
                              pair => Uri.UnescapeDataString(pair[1]).Replace("+", " "));

            var text = formValues["Body"].ToString();
            var message = await evaluateMessage(text);
            var response = new MessagingResponse().Message(message);

            var twiml = response.ToString();
            twiml = twiml.Replace("utf-16", "utf-8");

            return new HttpResponseMessage
            {
                Content = new StringContent(twiml, Encoding.UTF8, "application/xml")
            };
        }

        private static async Task evaluateMessage(string text)
        {
            var uri = endpointURL + "/qnamaker/knowledgebases/" + kbId + "/generateAnswer";

            // JSON format for passing question to service
            string question = @"{'question': '" + text + "'}";

            // Create http client
            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                // POST method
                request.Method = HttpMethod.Post;

                // Add host + service to get full URI
                request.RequestUri = new Uri(uri);

                // set question
                request.Content = new StringContent(question, Encoding.UTF8, "application/json");

                // set authorization
                request.Headers.Add("Authorization", "EndpointKey " + endpointKey );

                // Send request to Azure service, get response
                var response = client.SendAsync(request).Result;
                var jsonResponse = response.Content.ReadAsStringAsync().Result;

                // Output JSON response
                Console.WriteLine(jsonResponse);
                var qnaModel = JsonConvert.DeserializeObject<QnAModel>(jsonResponse);


                return qnaModel.answers[0].answer;

            }
        }
    }
    public class QnAModel
    {
        public List answers { get; set; }
    }

    public class Answers
    {
        public string answer { get; set; }
    }


}

Build the solution – Cntrl + Shift + B

Publishing Azure Function to Azure

Right-click on project – Click Publish

Select Target – Azure. Make sure you are logged in to Visual Studio with your Azure credentials.

Under Functions Instance – Select your Subscription, Resource group, and function (if already created in Azure). If you have not created Function in Azure click “Create a new Azure Function” with the following data. Change accordingly.

Configure storage you created and Publish.

After publishing is done. Go to Azure Portal. Under your resource group, find the function app created.

Click Functions

Click on your function.

Go to Code + Test -> Get function URL -> Store the URL at some location. We will be using it as a Webhook in Twilio.

Configuring Twilio Channel

Login to Twilio and go to Console. Click all products and services and select Programmable SMS.

Select WhatsApp and start learning. Follow the instructions to create Sandbox.

Configure sandbox by giving the function URL in “When a message comes in” and Save.

Test your bot in WhatsApp by joining the conversation using code you have been given by Sandbox.

Thank you All. I hope you find this useful.

If you liked our content and it was helpful, you can buy us a coffee or a pizza. Thank you so much.


3 thoughts on “Create WhatsApp Bot | Connect WhatsApp with QnA Maker | Create Azure Functions using Visual Studio

Add yours

Up ↑

%d bloggers like this: