

 [适用于 JavaScript 的 AWS SDK V3 API 参考指南](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)详细描述了 适用于 JavaScript 的 AWS SDK 版本 3 (V3) 的所有 API 操作。

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 构建 Amazon Lex 聊天机器人
<a name="lex-bot-example"></a>

您可以在 Web 应用程序中创建 Amazon Lex 聊天机器人来吸引您的网站访问者。Amazon Lex 聊天机器人是一种无需与人直接接触即可与用户进行在线聊天对话的功能。例如，下图显示了一个 Amazon Lex 聊天机器人，该聊天机器人针对预订酒店房间与用户进行交流。

![\[Chatbot interface demonstrating a hotel booking conversation with user inputs and bot responses.\]](http://docs.aws.amazon.com/zh_cn/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/zh_cn/sdk-for-javascript/v3/developer-guide/images/lex_example/LanChatBot2.png)


同样，用户可以用意大利语与 Amazon Lex 聊天机器人进行交流。

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


本 AWS 教程将指导你创建 Amazon Lex 聊天机器人并将其集成到 Node.js 网络应用程序中。 适用于 JavaScript 的 AWS SDK (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 聊天机器人](#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 示例，并安装所需的模块 适用于 JavaScript 的 AWS SDK 和第三方模块。按照上的说明进行操作[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/README.md)。
+ 使用用户凭证创建共享配置文件。有关提供共享凭据文件的更多信息，请参阅[和*工具参考指南中的共享配置AWS SDKs 和*凭据文件](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 [AWS CLI 用户指南](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)》中的说明进行安装和配置。

1. 在项目文件夹的根目录`setup.yaml`中创建一个名为的文件，然后将[此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lex-bot/setup.yaml)的内容复制 GitHub到该文件中。
**注意**  
该 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 命令参考指南](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 控制台，选择堆栈，然后选择**资源**选项卡。

## 创建 Amazon Lex 机器人
<a name="lex-bot-example-create-lex-bot"></a>

**重要**  
使用 Amazon Lex 控制台的 V1 创建机器人。此示例不适用于使用 V2 创建的机器人。

第一步是使用 Amazon Web Services 管理控制台创建 Amazon Lex 聊天机器人。在本示例中，使用了 Amazon Lex **BookTrip**示例。有关更多信息，请参阅 [BookTrip](https://docs.aws.amazon.com/lex/latest/dg/ex-book-trip.html)。
+ 在 [Amazon Web Services 控制台](https://console.aws.amazon.com/lex/)上登录 Amazon Web Services 管理控制台并打开 Amazon Lex 控制台。
+ 在“机器人”页面上，选择**创建**。
+ 选择**BookTrip**蓝图（保留默认的机器人名称 **BookTrip**）。  
![\[Interface for creating a chatbot, showing BookTrip sample with conversation flow and components.\]](http://docs.aws.amazon.com/zh_cn/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/zh_cn/sdk-for-javascript/v3/developer-guide/images/lex_example/ChatBotTest.png)
+ 选择 “**发布**” 并指定别名（使用时需要此值 适用于 JavaScript 的 AWS SDK）。

**注意**  
 你需要在 JavaScript 代码中引用**机器人名称****和机器人别名**。

## 创建 HTML
<a name="lex-bot-example-html"></a>

创建一个名为 `index.html`的文件。将以下代码复制并粘贴到 `index.html`。此 HTML 引用 `main.js`。这是 index.js 的捆绑版本，其中包含所需的 适用于 JavaScript 的 AWS SDK 模块。您将在 [创建 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`。导入所需的 适用于 JavaScript 的 AWS SDK 模块和命令。为 Amazon Lex、Amazon Comprehend 和 Amazon Translate 创建客户端。*REGION*替换为 AWS 区域，并*IDENTITY\$1POOL\$1ID*替换为您在中创建的身份池的 ID [创建 AWS 资源](#lex-bot-provision-resources)。要检索此身份池 ID，请在 Amazon Cognito 控制台中打开身份池，选择**编辑身份池**，然后在侧面菜单中选择**示例代码**。身份池 ID 将在控制台中以红色文本显示。

首先，创建一个 `libs` 目录，然后通过创建三个文件 `comprehendClient.js`、`lexClient.js` 和 `translateClient.js` 来创建所需的服务客户端对象。将下面的相应代码粘贴到每个文件中，然后*IDENTITY\$1POOL\$1ID*在每个文件中替换*REGION*和。

**注意**  
使用您在[使用创建 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`和 适用于 JavaScript 的 AWS SDK 模块捆绑到一个文件中`main.js`。

1. 如果您尚未安装 Webpack，请按照本示例中的[先决条件](#lex-bot-example-prerequisites)部分进行安装。
**注意**  
有关 *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>

恭喜您！您创建了一个 Node.js 应用程序，该应用程序使用 Amazon Lex 来创建交互式用户体验。如本教程开头所述，请务必在学习本教程时终止您创建的所有资源，以确保系统不会向您收费。为此，您可以删除在本教程[创建 AWS 资源](#lex-bot-provision-resources)主题中创建的 CloudFormation 堆栈，如下所示：

1. 打开 [CloudFormation 控制台]( https://console.aws.amazon.com/cloudformation/home)。

1. 在**堆栈**页面上，选择堆栈。

1. 选择**删除**。

有关更多 AWS 跨服务示例，请参阅[适用于 JavaScript 的 AWS SDK 跨服务](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/tutorials.html)示例。