

 [AWS SDK for JavaScript V3 API 참조 안내서](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)는 AWS SDK for JavaScript 버전 3(V3)의 모든 API 작업을 자세히 설명합니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Amazon Lex 챗봇 빌드
<a name="lex-bot-example"></a>

웹 애플리케이션 내에 Amazon Lex 챗봇을 생성하여 웹 사이트 방문자의 참여를 유도할 수 있습니다. Amazon Lex 챗봇은 사람과 직접 접촉하지 않고도 사용자와 온라인 채팅 대화를 수행하는 기능입니다. 예를 들어 다음 그림은 호텔 객실 예약과 관련하여 사용자의 참여를 유도하는 Amazon Lex 챗봇을 보여줍니다.

![\[Chatbot interface demonstrating a hotel booking conversation with user inputs and bot responses.\]](http://docs.aws.amazon.com/ko_kr/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/ko_kr/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/ko_kr/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 챗봇 생성](#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>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ 이러한 노드 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 및 도구 참조 가이드*의 [Shared config and credentials files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) 단원을 참조하세요.

**중요**  
이 예에서는 ECMAScript6(ES6)를 사용합니다. 따라서 Node.js 버전 13.x 이상이 필요합니다. 최신 버전의 Node.js를 다운로드하여 설치하려면 [Node.js downloads](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 인프라 배포를 예측 가능하고 반복적으로 생성하고 프로비저닝할 수 있습니다. 에 대한 자세한 내용은 [AWS CloudFormation 사용 설명서를](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/) CloudFormation참조하세요.

를 사용하여 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 템플릿은 [ 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/)를 AWS CDK참조하세요.

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 Management Console을 사용하여 Amazon Lex 챗봇을 생성하는 것입니다. 이 예에서는 Amazon Lex **BookTrip** 예가 사용됩니다. 자세한 내용은 [Book Trip](https://docs.aws.amazon.com/lex/latest/dg/ex-book-trip.html) 단원을 참조하세요.
+ Amazon Web Services Management Console에 로그인하고 [Amazon Web Services 콘솔](https://console.aws.amazon.com/lex/)에서 Amazon Lex 콘솔을 엽니다.
+ 봇 페이지에서 **생성**을 선택합니다.
+ **BookTrip** 청사진을 선택합니다(기본 봇 이름인 **BookTrip**을 그대로 유지).  
![\[Interface for creating a chatbot, showing BookTrip sample with conversation flow and components.\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/lex_example/pic2.png)
+ 기본 설정을 입력하고 **생성**을 선택합니다(콘솔에 **BookTrip** 봇이 표시됨). 편집기 탭에서 미리 구성된 intent의 세부 정보를 검토합니다.
+ 테스트 창에서 봇을 테스트합니다. *호텔 객실을 예약하고 싶어요*를 입력해 테스트를 시작합니다.  
![\[Chat interface showing a hotel booking conversation with a bot asking for the city.\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/lex_example/ChatBotTest.png)
+ **게시**를 선택하고 별칭 이름을 지정합니다( 사용 시이 값이 필요함 AWS SDK for JavaScript).

**참고**  
 JavaScript 코드에서 **봇 이름**과 **봇 별칭**을 참조해야 합니다.

## HTML 생성
<a name="lex-bot-example-html"></a>

`index.html`이라는 이름의 파일을 만듭니다. 아래 코드를 복사하여 `index.html`에 붙여 넣습니다. 이 HTML은 `main.js`를 참조합니다. 이는 필수 AWS SDK for JavaScript 모듈을 포함하는 index.js의 번들 버전입니다. [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 리전으로 바꾸고 *IDENTITY\$1POOL\$1ID*를에서 생성한 자격 증명 풀의 ID로 바꿉니다[AWS 리소스 생성](#lex-bot-provision-resources). 이 자격 증명 풀 ID를 검색하려면 Amazon Cognito 콘솔에서 자격 증명 풀을 열고 **자격 증명 풀 편집**을 선택한 다음, 측면 메뉴에서 **샘플 코드**를 선택합니다. 자격 증명 풀 ID는 콘솔에 빨간색 텍스트로 표시됩니다.

먼저, `libs` 디렉터리를 생성하고, `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 모듈을 단일 파일 로 번들링합니다`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>

축하합니다\$1 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).