UNPKG

@wickr-sample-integrations/wickrio-lex-bot

Version:

Using the AWS SDK for JavaScript V3 to create a Lex chatbot within Wickr.

256 lines (211 loc) 7.57 kB
const WickrIOBotAPI = require('wickrio-bot-api'); const util = require('util') const logger = require('wickrio-bot-api').logger const FileReader = require('filereader') const bot = new WickrIOBotAPI.WickrIOBot(); const WickrIOAPI = bot.apiService().WickrIOAPI; //const RecognizeCelebritiesCommand = require('@aws-sdk/client-rekognition'); //const { RekognitionClient } = require('@aws-sdk/client-rekognition'); const { fromIni } = require('@aws-sdk/credential-providers'); //const { DetectLabelsCommand } = require("@aws-sdk/client-rekognition"); const { ComprehendClient } = require('@aws-sdk/client-comprehend'); const { CognitoIdentityClient } = require('@aws-sdk/client-cognito-identity'); const { TranslateClient } = require('@aws-sdk/client-translate'); const { LexRuntimeV2Client } = require('@aws-sdk/client-lex-runtime-v2'); //const { LexRuntimeServiceClient } = require('@aws-sdk/client-lex-runtime-service'); const { DetectDominantLanguageCommand } = require('@aws-sdk/client-comprehend'); const { TranslateTextCommand } = require('@aws-sdk/client-translate'); const { RecognizeTextCommand } = require('@aws-sdk/client-lex-runtime-v2'); //const { PostTextCommand } = require('@aws-sdk/client-lex-runtime-service'); // snippet-start:[s3.JavaScript.buckets.uploadV3] //const { PutObjectCommand } = require("@aws-sdk/client-s3"); //const { fileURLToPath } = require("url"); console.log = function () { logger.info(util.format.apply(null, arguments)) } console.error = function () { logger.error(util.format.apply(null, arguments)) } var fs = require('fs'); module.exports = WickrIOAPI; process.stdin.resume(); //so the program will not close instantly async function exitHandler(options, err) { try { var closed = await bot.close(); console.log(closed); if (err) { console.log("Exit Error:", err); process.exit(); } if (options.exit) { process.exit(); } else if (options.pid) { process.kill(process.pid); } } catch (err) { console.log(err); } } //catches ctrl+c and stop.sh events process.on('SIGINT', exitHandler.bind(null, { exit: true })); // catches "kill pid" (for example: nodemon restart) process.on('SIGUSR1', exitHandler.bind(null, { pid: true })); process.on('SIGUSR2', exitHandler.bind(null, { pid: true })); //catches uncaught exceptions process.on('uncaughtException', exitHandler.bind(null, { exit: true })); function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // Respond to user's input. async function createResponse(message, vGroupID) { // setup the clients bot.processesJsonToProcessEnv() var tokens = JSON.parse(process.env.tokens) const lex_bot_id = tokens.LEX_ID.value const lex_alias_id = tokens.LEX_ALIAS_ID.value const REGION = tokens.AWS_REGION.value const profileName = tokens.AWS_PROFILENAME.value const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID. not used console.log('lex_alias_id=', lex_alias_id) // botAliasId: "UDSBLAMWWA", // "BotTesting" // botId: "42CIUXUCLR", // "WickrIOTestBot" console.log('entered createResponse') // Create an Amazon Comprehend service client object. const comprehendClient = new ComprehendClient({ region: REGION, credentials: fromIni({profile: profileName,}), }) // Create an Amazon Lex service client object. const lexClient = new LexRuntimeV2Client({ region: REGION, credentials: fromIni({profile: profileName,}), }); // Create an Amazon Translate service client object. const translateClient = new TranslateClient({ region: REGION, credentials: fromIni({profile: profileName,}), }); const comprehendParams = { Text: message, }; 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: message, }; // Save the original language const sourceLanguageCode = data.Languages[0].LanguageCode try { const data = await translateClient.send( new TranslateTextCommand(translateParams) ); console.log("Success. Translated text: ", data.TranslatedText); const lexParams = { botAliasId: lex_alias_id, // "BotTesting" botId: lex_bot_id, // "WickrIOTestBot" localeId: "en_US", sessionId: vGroupID, text: data.TranslatedText }; const command = new RecognizeTextCommand(lexParams); try { const data = await lexClient.send(command); const str = JSON.stringify(data, null, 4); // (Optional) beautiful indented output. console.log(str); // process data... //console.log(JSON.stringify(data)); var sSay = data.messages[0].content; sIntent = data.interpretations[0].intent.name; console.log("To say: " + sSay); console.log("Intent:" + sIntent); // Translate back from english to the original language if (sourceLanguageCode !== 'en') { const translateParams = { SourceLanguageCode: "en", TargetLanguageCode: sourceLanguageCode, Text: sSay, }; const data = await translateClient.send( new TranslateTextCommand(translateParams) ); sSay = data.TranslatedText console.log("Success. Translated text: ", data.TranslatedText); } var sMessage = await WickrIOAPI.cmdSendRoomMessage(vGroupID, sSay); } catch (error) { // error handling. console.log("Error - " + error); } finally { // finally. console.log("Terminated"); } } catch (err) { console.log("Error translating text. ", err); } } catch (err) { console.log("Error identifying language. ", err); } } async function main() { logger.info('entering main') try { var status; if (process.argv[2] === undefined) { var bot_username = fs.readFileSync('client_bot_username.txt', 'utf-8'); bot_username = bot_username.trim(); status = await bot.start(bot_username) } else { status = await bot.start(process.argv[2]) } if (!status) { exitHandler(null, { exit: true, reason: 'Client not able to start' }); } await bot.startListening(listen); //Passes a callback function that will receive incoming messages into the bot client } catch (err) { logger.error(err); } } async function listen(rMessage) { logger.info('entering listen') rMessage = JSON.parse(rMessage); var sender = rMessage.sender; var vGroupID = rMessage.vgroupid; var userArr = []; userArr.push(sender); if (rMessage.message) { var request = rMessage.message; /* var command = '', argument = ''; var parsedData = request.match(/(\/[a-zA-Z]+)(@[a-zA-Z0-9_-]+)?(\s+)?(.*)$/); if (parsedData !== null) { command = parsedData[1]; if (parsedData[4] !== '') { argument = parsedData[4]; } } */ console.log('calling createResponse()') await createResponse(request, vGroupID) } } main();