Home > Net >  How do I initiate a conversation with AWS LEX from node js?
How do I initiate a conversation with AWS LEX from node js?

Time:01-30

My context is this: I am attempting to build a chat bot into my Mozilla Hubs client, which is a node js / React project. I have a lex bot created on AWS, and I have installed the client-lex-runtime-v2 package and can import it successfully, but I have no idea how to set up a StartConversationCommand, give it credentials, etc. Most of the javascript examples seem to go the other way, where Lex calls a lambda function after processing a request, but I have user input in my app and I need to send it to Lex, and then deliver the resulting text back to the user inside my application.

This seems like very basic Lex usage - if anyone could point me to a code example I would be most grateful.

CodePudding user response:

John,

You need to make use of the LexRuntimeV2Client in the SDK as demonstrated here.

From the linked documentation, the below is how you import and instantiate a new client:

import { LexRuntimeV2Client, DeleteSessionCommand } from "@aws-sdk/client-lex-runtime-v2";
const client = new LexRuntimeV2Client({ region: "REGION" });

Once configured with your respective AWS environment details, credentials etc you will be able to invoke your Lex bot (again, from the linked documentation):

try {
  const data = await client.send(command);
  // process data.
} catch (error) {
  // error handling.
} finally {
  // finally.
}

Take a look at this sample repo on GitHub as well: aws-lex-web-ui

CodePudding user response:

So for anyone else stuck where I was, I cannot say this is the right way to do it, because I never did get it working, but the closest I got to at least forming up my credentials and trying to make a connection was this:

const client = new LexRuntimeV2Client({ 
  region: "us-east-1",
  credentials: new AWS.Credentials({
    accessKeyId: "my_IAM_access_key_id", 
    secretAccessKey: "my_secret_access_key" 
  })     
});
const lexparams = {
  "botAliasId": "my alias_id",
  "botId": "bot_id_from_lex",
  "localeId": "en_US",
  "inputText": "hello, this is a test sample",
  "sessionId": "some_session_id"
};
let cmd = new StartConversationCommand(lexparams);
try {
  const data = await client.send(cmd);
  console.log("Success. Response is: ", data.message);
} catch (err) {
  console.log("Error responding to message. ", err);
}

As said, buyer beware, and best of luck out there! I hope this might help somebody in some slight way. We taking a momentary break on this problem until a member of our team with better aws fu can take a look at it. :-)

  •  Tags:  
  • Related