LoginSignup
13
14

More than 3 years have passed since last update.

【Azure】チャットボットをWebサイトに置く

Last updated at Posted at 2019-09-01

前のステップ

Bot Serviceを作る

とりあえず利用する

Azureポータルでチャットボット作成後、Webサイトのチャネルで埋め込み用コードを取得できる。

シークレットを置き換えた後、これを任意のHTMLに貼りつければボットを使えるようになる。

↓先ほどのタグを貼り付けた結果

Webチャットのカスタマイズ色々

先ほどの外観では、自社環境の雰囲気に合わなかったりして、カスタマイズしたくなるかもしれない。その場合、下記のサンプルサイトを参考にカスタマイズできる。

microsoft/BotFramework-WebChat (MS製Webチャットのサンプル集)

JavaScriptを使ってWebチャットを挿入する

JavaScript(またはReact)を使用して、WebサイトにWebチャットを挿入することもできる。

<!DOCTYPE html>
<html>
   <body>
      <div id="webchat" role="main"></div>
      <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
      <script>
         window.WebChat.renderWebChat(
            {
               directLine: window.WebChat.createDirectLine({
                  token: 'YOUR_DIRECT_LINE_TOKEN'
               })
            },
            document.getElementById('webchat')
         );
      </script>
   </body>
</html>

https://github.com/microsoft/botframework-webchat/blob/master/README.md#integrate-with-javascript より。

上記サンプルのYOUR_DIRECT_LINE_TOKENをiframe版で使ったシークレットキーに置き換えれば動作する。YOUR_USER_IDは削除してOKぽい。
ただ、見た目はiframe版と比較するとおそろしくシンプルになる。

スタイルのカスタマイズ

ある程度の見た目は、JavaScriptで呼び出しているrenderWebChatメソッドに、styleOptionsという引数を追加することで変更できる。

カスタマイズのサンプル
const styleOptions = {
    botAvatarImage : 'image/chatbot-avatar2.png' // ボットのアイコン
    ,avatarSize: 60     // アイコンを少し大きく
    ,hideUploadButton: true     // ファイルアップロードを不可にする
};

window.WebChat.renderWebChat(
    {
        directLine: window.WebChat.createDirectLine({
            token: 'xxxx'
        }),
        styleOptions
    },
    document.getElementById('webchat')
);

↓実行結果

参考:スタイルのカスタマイズ
https://github.com/microsoft/BotFramework-WebChat/blob/master/SAMPLES.md

参考:styleOptionsに指定できる値と既定値
https://github.com/microsoft/BotFramework-WebChat/blob/master/packages/component/src/Styles/defaultStyleOptions.js

挨拶をページロード時に表示する

Azureから提供されるサンプルを使ってBot Serviceを作った場合、チャットボットとの会話の最初に挨拶を返す。
01.png

Webチャットで提供されるサンプルでは、チャットボットに話しかけて初めて挨拶が返されるので、これをページロード時に挨拶するように変更する。

// 追加する部分 はじまり
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
  if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
    dispatch({
      type: 'WEB_CHAT/SEND_EVENT',
      payload: {
        name: 'webchat/join',
        value: { language: window.navigator.language }
      }
    });
  }
  return next(action);
});
// 追加する部分 終わり

window.WebChat.renderWebChat({
  directLine: window.WebChat.createDirectLine({ token }),
  store  // 追加。styleOptionsも使用している場合、storeを第2引数にして、styleOptionsは第3引数にする。
}, document.getElementById('webchat'));
13
14
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
14