创建浏览器脚本 - Amazon SDK for JavaScript
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

帮助我们改进Amazon SDK for JavaScript版本 3 (V3) 文档,方法是使用反馈链接,或者在上创建议题或拉取请求GitHub.

这些区域有:Amazon SDK for JavaScriptV3 API 参考指南详细描述了Amazon SDK for JavaScript版本 3 (V3)。

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

创建浏览器脚本

本主题是教程的一部分,该教程在 Web 应用程序中创建 Amazon Lex 聊天机器人以吸引您的网站访问者。要开始使用本教程,请参阅构建 Amazon Lex 聊天机器人

创建一个名为 index.js 的文件。将以下代码复制并粘贴到index.js. 导入必需的Amazon SDK for JavaScript模块和命令。为 Amazon Lex、Amazon Comprehend 和 Amazon Translate 创建客户端。Replace领域和Amazon地区,以及IDENTITY_POOL_ID使用您在创建Amazon资源 . 要检索此身份池 ID,请在 Amazon Cognito 控制台中打开身份池,选择编辑身份池,然后选择示例代码在侧面菜单中。控制台中的身份池 ID 以红色文本显示。

首先,创建一个libs目录通过创建三个文件来创建所需的服务客户端对象,comprehendClient.jslexClient.js, 和transcribeClient.js. 将下面适当的代码粘贴到每个代码中,然后替换领域IDENTITY_POOL_ID在每个中。

注意

使用您在中创建的 Amazon Cognito 身份池的 ID创建Amazon使用的资源Amazon CloudFormation.

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"; //e.g. "us-east-1" const IdentityPoolId = "IDENTITY_POOL_ID"; const comprehendClient = new ComprehendClient({ region: REGION, credentials: fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region: REGION }), identityPoolId: IdentityPoolId }), });
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity"; import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity"; import { LexClient } from "@aws-sdk/client-lex"; const REGION = "REGION"; //e.g. "us-east-1" const IdentityPoolId = "IDENTITY_POOL_ID"; const lexClient = new LexRuntimeServiceClient({ region: REGION, credentials: fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region: REGION }), identityPoolId: IdentityPoolId }), });
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"; //e.g. "us-east-1" const IdentityPoolId = "IDENTITY_POOL_ID"; const translateClient = new TranslateClient({ region: REGION, credentials: fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region: REGION }), identityPoolId: IdentityPoolId }), });

这个代码是可用的此处GitHub..

接下来,创建一个index.html文件,然后将以下代码粘贴到其中。

ReplaceBOT_ALIASBOT_NAME分别使用 Amazon Lex 机器人的别名和名称,以及USER_ID带有用户 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 {comprehendClient} from ".libs/comprehendClient.js"; import {translateClient} from ".libs/translateClient.js"; var g_text = ""; // set the focus to the input box document.getElementById("wisdom").focus(); function showRequest(daText) { var conversationDiv = document.getElementById("conversation"); var requestPara = document.createElement("P"); requestPara.className = "userRequest"; requestPara.appendChild(document.createTextNode(g_text)); conversationDiv.appendChild(requestPara); conversationDiv.scrollTop = conversationDiv.scrollHeight; }; function showResponse(lexResponse) { var conversationDiv = document.getElementById("conversation"); var responsePara = document.createElement("P"); responsePara.className = "lexResponse"; var 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; var 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(event) { var msg = event.target.responseText; showRequest(); showResponse(msg); // re-enable input var wisdomText = document.getElementById("wisdom"); wisdomText.value = ""; wisdomText.locked = false; }; // Respond to user's input. const createResponse = async () => { // Confirm there is text to submit. var wisdomText = document.getElementById("wisdom"); if (wisdomText && wisdomText.value && wisdomText.value.trim().length > 0) { // Disable input to show it is being sent. var wisdom = wisdomText.value.trim(); wisdomText.value = "..."; wisdomText.locked = true; 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 = { botAlias: "BOT_ALIAS", botName: "BOT_NAME", inputText: data.TranslatedText, userId: "USER_ID" // For example, 'chatbot-demo'. }; try { const data = await lexClient.send(new PostTextCommand(lexParams)); console.log("Success. Response is: ", data.message); document.getElementById("conversation").innerHTML = data.message; } 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); } } }; window.createResponse = createResponse;

这个代码是可用的此处GitHub..

现在使用 webpack 来捆绑index.js和Amazon SDK for JavaScript模块到单个文件中,main.js.

  1. 如果您尚不了解,请按照先决条件对于这个例子来安装 webpack。

    注意

    有关的信息有关webpack,请参阅使用 webpack 捆绑应用程序.

  2. 在命令行中运行以下命令以捆绑JavaScript对于这个例子到一个名为的文件<index.js>

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