Applicable when
- You need to automate the process of importing a Lex Bot to AWS.
Implementation
As of this writing there is no means to build and / or publish a Lex chatbot programmatically. However, we can leverage the AWS SDK to import both the bot and an alias to AWS which will reduce the time it takes to deploy a chatbot from scratch.
We're assuming you already have a well-formed AWS Lex chatbot definition in a JSON file. At this point we need to create a zip file containing only the JSON file.
For this we can use archiver (MIT-licensed) to easily take the JSON representation of the chatbot and write a zip file which we can use to import the chatbot to AWS. If the chatbot already exists, this strategy will overwrite according to the parameters which you can change depending on your needs
...
const output = createWriteStream(chatBotPath);
output.on('close', async () => {
const buffer = readFileSync(chatBotPath);
const lex = new LexModelBuildingService();
const importResponse = await lex.startImport({
mergeStrategy: 'OVERWRITE_LATEST',
payload: buffer,
resourceType: 'BOT'
}).promise();
// Wait for import to finish before putting alias
let botCreated = false;
let i = 0;
do {
delay(waitingTime);
const params = await lex.getImport({
importId: importResponse.importId
}).promise();
botCreated = params.importStatus === 'COMPLETE';
i++;
} while (!botCreated && i < maxWaitingIterations);
try {
await lex.putBotAlias({
botName: 'myChatBot',
botVersion: '$LATEST',
name: 'myChatBot'
}).promise();
} catch(e) {
if (e.statusCode !== 412) {
throw e;
}
}
});
archive.on('error', err => {
throw err;
});
archive.pipe(output);
archive.directory('../path/to/chatbot/json/file/subdirectory', false);
archive.finalize();
As can be noted, first we use archiver to start the zip creation. Upon completion, we read the bytes from the newly created zip file and pass them to the startImport method as payload. Since this import may take a couple of seconds, we wait and call getImport with the corresponding importId until we are sure the bot has been imported fully (or after a timeout occurs). Finally, we call putAlias to create an alias for the latest version of the bot which we can reuse in other resources such as Amazon Connect. In case the alias was created already, we simply ignore the error and terminate the script.
Comments
0 comments
Please sign in to leave a comment.