Create a bot that runs on a web browser with Microsoft’s Direct Line API × jQuery

Create a bot that runs on a web browser with Microsoft’s Direct Line API × jQuery

Create a bot that runs on a web browser with Microsoft's Direct Line API × jQuery

Good morning, this is Okada.

This time, we will use jQuery, which everyone is familiar with, to interact with a bot on a web browser!

Microsoft Bot Framework that allows you to create bots on so many channels. In fact, there is a mechanism that allows you to handle bots as REST APIs.that is“Direct Line API”is.

By combining Direct Line API and jQuery, you can not only talk with bots in a web browser, but also interact with bots.Flexible UII think I can give you

Since it is a REST API, as long as HTTP communication is possible, regardless of programming language or device,Bot can be called in various scenesThere is an advantage. It doesn’t hurt to remember.

At the end of the article, there is also a demo and sample code that you can try immediately, so please refer to it.

Click here for the previous article using MS Bot Framework
>> Surprisingly easy. I tried embedding my own bot in a web page using Microsoft Bot Framework

Preparation for using Direct Line API

Now, let’s get ready to use the Direct Line API!

First, sign in to the official website of Microsoft Bot Framework and open “My Bots”.

01

Next, click on the bot you want to use Direct Line API to go to the bot management screen.

02

The channels that can be added are displayed in Add another channel, so click Add of Direct Line from among them.

03

On the next screen, click the “Generate Direct Line secret” button to issue a secret key.

04

A secret key will be issued, so copy this and keep it.

Click the “I’m done configuring Direct Line” button and you’re all set!

Three basic operations of Direct Line API

Now that the preparations are complete, let’s start using the Direct Line API.

The Direct Line API has three basic operations.

  • Issue conversionId
  • Send message to bot
  • Get bot’s message

With the above three operations, we will interact with the bot. I will explain in order.

Issue conversationId

In order to interact with the bot with the Direct Line API, it is necessary to issue a conversationId.

This is the ID for the Direct Line API to record the conversation log between you and the bot. Without this ID, you cannot interact with the bot.

To send a request to the server, use the $.ajax() function.

$.ajax({
  method: "POST",
  contentType: "application/json",
  headers: {
    Authorization: "Botconnector xkyR6XSfVQM.cwA.qUw.KBdFH5UtudREtKq4_pfF8EMzvxL592q7OH9ltpreOFY"
  },
  url: "https://directline.botframework.com/api/conversations",
  success: function(data){
    console.log(data);
  }
});

with the POST method

https://directline.botframework.com/api/conversations

When sending a request to , the header contains

Authorization: “Botconnector YOUR_SECRET_KEY”

Specify

Executing the above code will return the following object to the browser’s console.

{
  conversationId: "2y7YRcZAx4f",
  token: "xkyR6XSfVQM.dAA.MgB5ADcAWQBSAGMAWgBBAHgANABmAA.O1R3HwvL0QE.-2L97p8XuRA.XpyptkBFriShOOg_ujewf9hD2kxi0rpwp-xClpwSIpI"
}

The “conversationId” in this is required to exchange messages with the bot.

By the way, this ID is automatically deleted after 30 minutes, so you need to create it every 30 minutes.

Send a message to your bot

Now it’s time to send a message to the bot.

function sendMessage (convId, msg) {

  var user = "user_" + convId; // from用のユーザー名を作成します

  $.ajax({
    method: "POST",
    contentType: "application/json",
    headers: {
      Authorization: "Botconnector xkyR6XSfVQM.cwA.qUw.KBdFH5UtudREtKq4_pfF8EMzvxL592q7OH9ltpreOFY"
    },
    url: 'https://directline.botframework.com/api/conversations/' + convId + '/messages',
    data: JSON.stringify({
      "text": msg, // 送信するメッセージ内容です
     "from": user // 同じユーザーからのメッセージであることを認識させるために、fromを入れます
    }),
    success: function (obj) {
      console.log("メッセージを送りました!");
    }
  });

}

sendMessage("2y7YRcZAx4f", "自己紹介して");

In the code above, we have created a function called sendMessage that takes as arguments the conversationId and the message to send.

As before, send a request using the POST method.

To send a message, to the endpoint

https://directline.botframework.com/api/conversations/{conversationId}/messages

and send the data { text: “Message to send”, from: “User name” }. There are other data that can be sent, but please refer to the official documentation for details.

By specifying from,“It’s a message from the same user.”You can tell the bot that. Conversely, if from is not specified,“This is a message from a different user.”Please note that the bot will misunderstand and the answer and conversation with the bot will not be established correctly.

If the above code is executed and the message is successfully sent, the message “Message sent!” should be displayed in the browser console.

Receive bot messages

Now, it’s time to get the message from the bot.

In the code above, we created a function called getMessage that takes a conversationId and a watermark as arguments.

To get the message from the bot, to the endpoint

https://directline.botframework.com/api/conversations/{conversationId}/messages

and send a request with the GET method.

This time, just the headers for authentication are fine. A sample code is below.

function getMessage(convId, watermark) {

  var url;

  // ウォーターマークの有無により、URLの分岐
  if (watermark) {
    url = "https://directline.botframework.com/api/conversations/" + convId + "/messages?watermark=" + watermark;
  } else {
    url = "https://directline.botframework.com/api/conversations/" + convId + "/messages";
  }

  return $.ajax({
    method: "GET",
    contentType: "application/json",
    headers: {
      Authorization: "Botconnector xkyR6XSfVQM.cwA.qUw.KBdFH5UtudREtKq4_pfF8EMzvxL592q7OH9ltpreOFY"
    },
    url: url,
    success: function (data) {

      console.log(JSON.stringify(data));

    }
  });
}

getMessage("2y7YRcZAx4f");

Running the above code will return the following object:

{
  messages: [{
      id: "2y7YRcZAx4f|131113209232385773",
      conversationId: "2y7YRcZAx4f",
      created: "2016-06-25T09:35:23.2385773Z",
      from: "user_2y7YRcZAx4f",
      text: "自己紹介して",
      images: [],
      attachments: [],
      eTag: "W/"datetime'2016-06-25T09%3A35%3A24.2168782Z'""
    },
    {
      id: "2y7YRcZAx4f|131113209266579021",
      conversationId: "2y7YRcZAx4f",
      created: "2016-06-25T09:35:26.2873792Z",
      from: "qavppytestbot",
      text: "こんにちは!ぼくの名前は、かぶっぴー。よろしくね(๑•̀ㅁ•́๑)✧",
      images: [],
      attachments: [],
      eTag: "W/"datetime'2016-06-25T09%3A35%3A27.1026598Z'""
    }]
  ,
  watermark: "131113209945100859"
}

After that, you can create your favorite UI by extracting messages from this object.

A little explanation of objects

// ウォーターマークの有無により、URLの分岐
if (watermark) {
  url = "https://directline.botframework.com/api/conversations/" + convId + "/messages?watermark=" + watermark;
} else {
  url = "https://directline.botframework.com/api/conversations/" + convId + "/messages";
}

There is.

If you attach this watermark to the endpoint and make a request, you can get only messages after that watermark. In other words, you can get only “new messages”.

demo

We have prepared an actual demo that combines these three functions! >> here
In the demo, once a conversionId is created, it is also saved in a cookie for 30 minutes.

demo

The source code is also available on GitHub, so please take a look!

lastly

This time, we were able to use the Direct Line API to interact with the bot.

As long as you can communicate with HTTP, you can use any program, not just jQuery, so please give it a try.

Next time, I would like to create a full-fledged chat UI using the Direct Line API.

Well then!