Recently Microsoft released “Microsoft Zo” the next generation chatbot. Have you ever felt you want to make it to?

I made a chatbot using a Japanese company’s AI chat service combined with Microsoft Azure Bot Services.

You can try it here: (Japanese only sorry)

You can add it on Skype too!

What to prepare

  • Microsoft Account
  • Skype
  • Azure Bot Service
  • Some chatbot service to link it to. (Japanese version available from here: http://ai.userlocal.jp/document/free/top

 

How to create it.

  • Go to Azure Portal, “New”, “Intelligence + Analytics”, “Bot Service” and click “Create”

  • You can acces what’s created by going to App Service

  • App type is shown as “Bot Service”

  • When you open it, it’ll ask you to create a Microsoft App ID. Click on “Create Microsoft App ID and Password”

  • Fill in the app name. App ID is auto generated. Click on create app password.

  • The password is shown. Make sure you make note of it to use it later and click ok once you’re ready to continue.

  • Go back to Bot Framework to continue.

  • Paste the App ID and password you took note of.

  • Select the programming language. We will use C# this time.

  • Next choose the template. We’ll use the basic template for today.
    Basic – A template with just a simple bot that counts the number of characters you’ve entered.
    Form – A questionnaire not using FormFlow.
    Proactive – A trigger based bot using Azure Functions triggers.
    Language understanding – Uses LUIS for natural language processing.
  • Once selected, the bot service will be deployed with the template.

  • Edit the coding like below to achieve what we want./div>

Run.csx


#r "Newtonsoft.Json"
#load "EchoDialog.csx"

using System;
using System.Net;
using System.Threading;
using Newtonsoft.Json;

using Microsoft.Bot.Builder.Azure;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;

public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info($"Webhook was triggered!");

    // Initialize the azure bot
    using (BotService.Initialize())
    {
        // Deserialize the incoming activity
        string jsonContent = await req.Content.ReadAsStringAsync();
        var activity = JsonConvert.DeserializeObject<Activity>(jsonContent);
        
        // authenticate incoming request and add activity.ServiceUrl to MicrosoftAppCredentials.TrustedHostNames
        // if request is authenticated
        if (!await BotService.Authenticator.TryAuthenticateAsync(req, new [] {activity}, CancellationToken.None))
        {
            return BotAuthenticator.GenerateUnauthorizedResponse(req);
        }
        
        if (activity != null)
        {
            // one of these will have an interface and process it
            switch (activity.GetActivityType())
            {
                case ActivityTypes.Message:
                    await Conversation.SendAsync(activity, () => new EchoDialog());
                    break;
                case ActivityTypes.ConversationUpdate:
                    var client = new ConnectorClient(new Uri(activity.ServiceUrl));
                    IConversationUpdateActivity update = activity;
                    if (update.MembersAdded.Any())
                    {
                        var reply = activity.CreateReply();
                        var newMembers = update.MembersAdded?.Where(t => t.Id != activity.Recipient.Id);
                        foreach (var newMember in newMembers)
                        {
                            reply.Text = "Welcome";
                            if (!string.IsNullOrEmpty(newMember.Name))
                            {
                                reply.Text += $" {newMember.Name}";
                            }
                            reply.Text += "!";
                            await client.Conversations.ReplyToActivityAsync(reply);
                        }
                    }
                    break;
                case ActivityTypes.ContactRelationUpdate:
                case ActivityTypes.Typing:
                case ActivityTypes.DeleteUserData:
                case ActivityTypes.Ping:
                default:
                    log.Error($"Unknown activity type ignored: {activity.GetActivityType()}");
                    break;
            }
        }
        return req.CreateResponse(HttpStatusCode.Accepted);
    }    
}


EchoDialog.csx

次に、EchoDialog.csxのコードも書き換えます。


#r "Newtonsoft.Json"

using System;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using System.Net;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

// For more information about this template visit http://aka.ms/azurebots-csharp-basic
[Serializable]
public class EchoDialog : IDialog<object>
{
    protected int count = 1;

    public Task StartAsync(IDialogContext context)
    {
        try
        {
            context.Wait(MessageReceivedAsync);
        }
        catch (OperationCanceledException error)
        {
            return Task.FromCanceled(error.CancellationToken);
        }
        catch (Exception error)
        {
            return Task.FromException(error);
        }

        return Task.CompletedTask;
    }

    public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
    {
        var message = await argument;
        String chatresponse = null;
        
        //Build the URI
        Uri UriBase = new Uri("https://chatbot-api.userlocal.jp");
        var builder = new UriBuilder($"{UriBase}/api/chat?");

        using (WebClient webclient = new WebClient())
        {
            //Set the encoding to UTF8
            webclient.Encoding = System.Text.Encoding.UTF8;

            //Add the question as part of the body
            var postBody = $"{{\"message\": \"{message.Text}\", \"key\": \"***Change the key here***\"}}";

            //Add the subscription key header
            webclient.Headers.Add("Content-Type", "application/json");
            var responseString = webclient.UploadString(builder.Uri, postBody);
            chatresponse = JObject.Parse(responseString)["result"].ToString();
        }
        await context.PostAsync($"{chatresponse}");
        context.Wait(MessageReceivedAsync);
        
    }
}

That’s it! Happy Bot making!