

 [AWS SDK for JavaScript V3 API リファレンスガイド](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)では、 AWS SDK for JavaScript バージョン3 (V3) のすべての API オペレーションについて詳しく説明します。

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Amazon Lex chatbotを構築する
<a name="lex-bot-example"></a>

ウェブアプリケーション内に Amazon Lex chatbotを作成して、ウェブサイトの訪問者に対応することができます。Amazon Lex chatbotは、人と直接連絡することなく、ユーザーとのオンラインチャットの会話を実行する機能です。例えば、次の図は、ホテルの部屋の予約についてユーザーに対応する Amazon Lex chatbotを示しています。

![\[Chatbot interface demonstrating a hotel booking conversation with user inputs and bot responses.\]](http://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v3/developer-guide/images/lex_example/chatintro.png)


この AWS チュートリアルで作成した Amazon Lex チャットボットは、複数の言語を処理できます。例えば、フランス語を話すユーザーは、フランス語のテキストを入力し、フランス語で応答を返すことができます。

![\[Chatbot interface demonstrating Amazon Lex integration with French language support.\]](http://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v3/developer-guide/images/lex_example/LanChatBot2.png)


同様に、ユーザーはイタリア語でAmazon Lex chatbotで通信できます。

![\[Chat interface showing Italian language exchange between user and Amazon Lex chatbot.\]](http://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v3/developer-guide/images/lex_example/LanChatBot3.png)


この AWS チュートリアルでは、Amazon Lex チャットボットを作成し、Node.js ウェブアプリケーションに統合する方法について説明します。 AWS SDK for JavaScript (v3) は、以下の AWS サービスを呼び出すために使用されます。
+ Amazon Lex
+ Amazon Comprehend
+ Amazon Translate

**完了コスト:** このドキュメントに含まれる AWS サービスは、 [AWS 無料利用枠](https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&all-free-tier.sort-order=asc)に含まれています。

**注意:** このチュートリアルを進めるうえで作成したすべてのリソースを終了して、料金が発生しないようにしてください。

**アプリを構築するには**

1. [前提条件](#lex-bot-example-prerequisites)

1. [リソースのプロビジョニング](#lex-bot-provision-resources)

1. [Amazon Lex chatbotの作成する](#lex-bot-example-create-lex-bot)

1. [HTMLを作成する](#lex-bot-example-html)

1. [ブラウザスクリプトを作成](#lex-bot-example-script)

1. [次のステップ](#lex-bot-example-next-steps)

## 前提条件
<a name="lex-bot-example-prerequisites"></a>

この例をセットアップして実行するには、まず次のタスクを完了する必要があります。
+ これらの Node TypeScript の例を実行するようにプロジェクト環境を設定し、必要な AWS SDK for JavaScript モジュールとサードパーティーモジュールをインストールします。「[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/README.md)」の指示に従います。　
+ ユーザーの認証情報を使用して、共有設定ファイルを作成します。共有認証情報ファイルの提供の詳細については、「AWS SDK とツールのリファレンスガイド」の「[共有設定ファイルおよび認証情報ファイル](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)」を参照してください。

**重要**  
この例では、ECMAScript6 (ES6) を使用しています。これには Node.js バージョン13.x以降が必要です。Node.js の最新バージョンをダウンロードしてインストールするには、「[Node.js ダウンロード](https://nodejs.org/en/download)」を参照してください。  
ただし、CommonJS 構文を使用したい場合は、「[JavaScript ES6/CommonJS 構文](sdk-example-javascript-syntax.md)」を参照してください。

## AWS リソースを作成する
<a name="lex-bot-provision-resources"></a>

このチュートリアルでは、以下のリソースが必要です。
+ 次の権限がアタッチされた非認証IAM ロールです。
  + Amazon Comprehend
  + Amazon Translate
  + Amazon Lex

このリソースは手動で作成できますが、このチュートリアルで説明されている AWS CloudFormation ように、 を使用してこれらのリソースをプロビジョニングすることをお勧めします。

### を使用して AWS リソースを作成する CloudFormation
<a name="lex-bot-example-resources-cli"></a>

CloudFormation を使用すると、 AWS インフラストラクチャのデプロイを予測どおりに繰り返し作成およびプロビジョニングできます。詳細については CloudFormation、[AWS CloudFormation 「 ユーザーガイド](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/)」を参照してください。

を使用して CloudFormation スタックを作成するには AWS CLI:

1. [AWS CLI 「 ユーザーガイド](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) AWS CLI 」の手順に従って、 をインストールして設定します。

1. プロジェクトフォルダのルートディレクトリで、`setup.yaml` という名前のファイルを作成し、それに[この GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lex-bot/setup.yaml) にコンテンツをコピーします。
**注記**  
 CloudFormation テンプレートは、 AWS CDK [GitHub にある ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/cdk/lex_bot_example_iam_unauth_role)を使用して生成されました。の詳細については AWS CDK、 [AWS Cloud Development Kit (AWS CDK) デベロッパーガイド](https://docs.aws.amazon.com/cdk/latest/guide/)を参照してください。

1. コマンドラインから以下のコマンドを実行し、「*STACK\$1NAME*」をスタックの一意の名前に置き換えます。
**重要**  
スタック名は、 AWS リージョンと AWS アカウント内で一意である必要があります。最大 128 文字まで指定でき、数字とハイフンを使用できます。

   ```
   aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM
   ```

   `create-stack` コマンドパラメータの詳細については、 [AWS CLI Command Reference guide](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html) (コマンドリファレンスガイド）および「[CloudFormation ユーザーガイド](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-creating-stack.html)」を参照してください。

   作成されたリソースを表示するには、Amazon Lex コンソールを開き、スタックを選択し、**Resources** (リソース)タブを選びます。

## Amazon Lex botを作成します
<a name="lex-bot-example-create-lex-bot"></a>

**重要**  
Amazon Lex V1 コンソールを使用してボットを作成します。この例は V2 を使用して作成されたボットでは機能しません。

最初のステップは、Amazon Web Services マネジメントコンソールを使用して Amazon Lex chatbotを作成することです。この例では、Amazon Lex**BookTrip**の例が使用されます。詳細については「[Book Trip](https://docs.aws.amazon.com/lex/latest/dg/ex-book-trip.html) (出張の予約)」を参照してください。
+ Amazon Web Services マネジメントコンソールにサインインして、[Amazon Web Services Console](https://console.aws.amazon.com/lex/) (Amazon Web Services コンソール)のAmazon Lex コンソールを開きます。
+ Botsページで、**Create**（作成）を選択します。
+ **BookTrip**ブループリント (デフォルトのボット名は**BookTrip**のままにしておきます) を選択します。  
![\[Interface for creating a chatbot, showing BookTrip sample with conversation flow and components.\]](http://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v3/developer-guide/images/lex_example/pic2.png)
+ デフォルト設定を入力し、**作成**(コンソールは **BookTrip**ボットを表示します) を選択します。編集タブで、事前設定されているインテントの詳細を確認します。
+ テストウィンドウでボットをテストします。*ホテルの部屋を予約したい*と入力してテストを開始します。  
![\[Chat interface showing a hotel booking conversation with a bot asking for the city.\]](http://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v3/developer-guide/images/lex_example/ChatBotTest.png)
+ **発行**を選択し、エイリアス名を指定します ( を使用する場合はこの値が必要です AWS SDK for JavaScript)。

**注記**  
 JavaScript コードの **bot name** (ボット名) と **bot alias** (ボットエイリアス) を参照する必要があります。

## HTMLを作成する
<a name="lex-bot-example-html"></a>

`index.html` という名前のファイルを作成します。以下のコードをコピーして、`index.html`に貼り付けます。このHTMLは`main.js`を参照します。これは index.js のバンドルバージョンで、必要な AWS SDK for JavaScript モジュールが含まれています。このファイルは [HTMLを作成する](#lex-bot-example-html) で作成します。`index.html` はスタイルを追加する `style.css` も参照します。

```
<!doctype html>
<head>
  <title>Amazon Lex - Sample Application (BookTrip)</title>
  <link type="text/css" rel="stylesheet" href="style.css" />
</head>

<body>
  <h1 id="title">Amazon Lex - BookTrip</h1>
  <p id="intro">
    This multiple language chatbot shows you how easy it is to incorporate
    <a
      href="https://aws.amazon.com/lex/"
      title="Amazon Lex (product)"
      target="_new"
      >Amazon Lex</a
    >
    into your web apps. Try it out.
  </p>
  <div id="conversation"></div>
  <input
    type="text"
    id="wisdom"
    size="80"
    value=""
    placeholder="J'ai besoin d'une chambre d'hôtel"
  />
  <br />
  <button onclick="createResponse()">Send Text</button>
  <script type="text/javascript" src="./main.js"></script>
</body>
```

このコードも[このGitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/cdk#running-a-cdk-app)で公開されています。

## ブラウザスクリプトを作成する
<a name="lex-bot-example-script"></a>

`index.js` という名前のファイルを作成します。以下のコードをコピーして、`index.js`に貼り付けます。必要な AWS SDK for JavaScript モジュールとコマンドをインポートします。Amazon Lex、Amazon Comprehend、およびAmazon Translate のクライアントを作成します。*REGION* を AWS Region に、*IDENTITY\$1POOL\$1ID* を で作成した ID プールの ID に置き換えます[AWS リソースを作成する](#lex-bot-provision-resources)。このアイデンティティプールのIDを取得するには、Amazon Cognito コンソールでアイデンティティプールを開き、**Edit identity pool** (アイデンティティプールの編集) を選択し、サイドメニューの**Sample code** (サンプルコード)を選択します。アイデンティティプールの IDはコンソールに赤いテキストで表示されます。

まず、`libs`ディレクトリを作成し、3つのファイル、`comprehendClient.js`、`lexClient.js`、`translateClient.js`を作成することで、必要なサービスクライアントオブジェクトを作成します。以下の適切なコードをそれぞれに貼り付け、*REGION* および *IDENTITY\$1POOL\$1ID* を各ファイルで置き換えます。

**注記**  
[を使用して AWS リソースを作成する CloudFormation](#lex-bot-example-resources-cli)で作成したAmazon CognitoアイデンティティプールのIDを使用します。

```
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity";
import { ComprehendClient } from "@aws-sdk/client-comprehend";

const REGION = "REGION";
const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID.

// Create an Amazon Comprehend service client object.
const comprehendClient = new ComprehendClient({
  region: REGION,
  credentials: fromCognitoIdentityPool({
    client: new CognitoIdentityClient({ region: REGION }),
    identityPoolId: IDENTITY_POOL_ID,
  }),
});

export { comprehendClient };
```

```
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity";
import { LexRuntimeServiceClient } from "@aws-sdk/client-lex-runtime-service";

const REGION = "REGION";
const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID.

// Create an Amazon Lex service client object.
const lexClient = new LexRuntimeServiceClient({
  region: REGION,
  credentials: fromCognitoIdentityPool({
    client: new CognitoIdentityClient({ region: REGION }),
    identityPoolId: IDENTITY_POOL_ID,
  }),
});

export { lexClient };
```

```
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity";
import { TranslateClient } from "@aws-sdk/client-translate";

const REGION = "REGION";
const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID.

// Create an Amazon Translate service client object.
const translateClient = new TranslateClient({
  region: REGION,
  credentials: fromCognitoIdentityPool({
    client: new CognitoIdentityClient({ region: REGION }),
    identityPoolId: IDENTITY_POOL_ID,
  }),
});

export { translateClient };
```

このコードは [このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lex-bot/src/libs)で利用可能です。

次に、`index.js`ファイルを作成し、そこへ以下のコードを貼り付けます。

 *BOT\$1ALIAS*と*BOT\$1NAME*をAmazon Lex ボットのエイリアスと名前にそれぞれ置き換え、*USER\$1ID*をユーザー ID に置き換えます。`createResponse`非同期関数は以下を実行します。
+ ユーザーが入力したテキストをブラウザに取り込み、Amazon Comprehend を使用して言語コードを決定します。
+ 言語コードを取得し、Amazon Translate を使用してテキストを英語に翻訳します。
+ 翻訳されたテキストを取得し、Amazon Lex を使用してレスポンスを生成します。
+ レスポンスをブラウザページに投稿します。

```
import { DetectDominantLanguageCommand } from "@aws-sdk/client-comprehend";
import { TranslateTextCommand } from "@aws-sdk/client-translate";
import { PostTextCommand } from "@aws-sdk/client-lex-runtime-service";
import { lexClient } from "./libs/lexClient.js";
import { translateClient } from "./libs/translateClient.js";
import { comprehendClient } from "./libs/comprehendClient.js";

let g_text = "";
// Set the focus to the input box.
document.getElementById("wisdom").focus();

function showRequest() {
  const conversationDiv = document.getElementById("conversation");
  const requestPara = document.createElement("P");
  requestPara.className = "userRequest";
  requestPara.appendChild(document.createTextNode(g_text));
  conversationDiv.appendChild(requestPara);
  conversationDiv.scrollTop = conversationDiv.scrollHeight;
}

function showResponse(lexResponse) {
  const conversationDiv = document.getElementById("conversation");
  const responsePara = document.createElement("P");
  responsePara.className = "lexResponse";

  const lexTextResponse = lexResponse;

  responsePara.appendChild(document.createTextNode(lexTextResponse));
  responsePara.appendChild(document.createElement("br"));
  conversationDiv.appendChild(responsePara);
  conversationDiv.scrollTop = conversationDiv.scrollHeight;
}

function handletext(text) {
  g_text = text;
  const xhr = new XMLHttpRequest();
  xhr.addEventListener("load", loadNewItems, false);
  xhr.open("POST", "../text", true); // A Spring MVC controller
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //necessary
  xhr.send(`text=${text}`);
}

function loadNewItems() {
  showRequest();

  // Re-enable input.
  const wisdomText = document.getElementById("wisdom");
  wisdomText.value = "";
  wisdomText.locked = false;
}

// Respond to user's input.
const createResponse = async () => {
  // Confirm there is text to submit.
  const wisdomText = document.getElementById("wisdom");
  if (wisdomText?.value && wisdomText.value.trim().length > 0) {
    // Disable input to show it is being sent.
    const wisdom = wisdomText.value.trim();
    wisdomText.value = "...";
    wisdomText.locked = true;
    handletext(wisdom);

    const comprehendParams = {
      Text: wisdom,
    };
    try {
      const data = await comprehendClient.send(
        new DetectDominantLanguageCommand(comprehendParams),
      );
      console.log(
        "Success. The language code is: ",
        data.Languages[0].LanguageCode,
      );
      const translateParams = {
        SourceLanguageCode: data.Languages[0].LanguageCode,
        TargetLanguageCode: "en", // For example, "en" for English.
        Text: wisdom,
      };
      try {
        const data = await translateClient.send(
          new TranslateTextCommand(translateParams),
        );
        console.log("Success. Translated text: ", data.TranslatedText);
        const lexParams = {
          botName: "BookTrip",
          botAlias: "mynewalias",
          inputText: data.TranslatedText,
          userId: "chatbot", // For example, 'chatbot-demo'.
        };
        try {
          const data = await lexClient.send(new PostTextCommand(lexParams));
          console.log("Success. Response is: ", data.message);
          const msg = data.message;
          showResponse(msg);
        } catch (err) {
          console.log("Error responding to message. ", err);
        }
      } catch (err) {
        console.log("Error translating text. ", err);
      }
    } catch (err) {
      console.log("Error identifying language. ", err);
    }
  }
};
// Make the function available to the browser.
window.createResponse = createResponse;
```

このコードは [このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lex-bot/src/index.html)で利用可能です。

ここで、webpack を使用して `index.js`および AWS SDK for JavaScript モジュールを 1 つのファイルにバンドルします`main.js`。

1. まだの場合は、この例の[前提条件](#lex-bot-example-prerequisites)に従ってwebpackをインストールしてください。
**注記**  
*Webpack* の詳細については、[Webpack でアプリケーションをバンドルする](webpack.md) を参照してください。

1. コマンドラインで以下を実行して、この例の JavaScriptを`main.js`というファイルにバンドルします。

   ```
   webpack index.js --mode development --target web --devtool false -o main.js
   ```

## 次の手順
<a name="lex-bot-example-next-steps"></a>

お疲れ様でした。Amazon Lex を使用してインタラクティブなユーザーエクスペリエンスを実現する Node.js アプリケーションが作成されました。このチュートリアルの冒頭で説明したように、チュートリアルを進めるうえで作成したすべてのリソースを終了して、料金が発生しないようにしてください。これを行うには、このチュートリアルの [AWS リソースを作成する](#lex-bot-provision-resources)トピックで作成した CloudFormation スタックを次のように削除します。

1. [CloudFormation コンソール]( https://console.aws.amazon.com/cloudformation/home) を開きます。

1. 「**スタック**」ページで、スタックを選択します。

1. **[削除]** を選択します。

 AWS クロスサービスの例については、[AWS SDK for JavaScript 「クロスサービスの例](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/tutorials.html)」を参照してください。