Skip to content

Instantly share code, notes, and snippets.

@wcheek
Last active March 15, 2022 06:01
Show Gist options
  • Save wcheek/10fe9f33d10156ce1a77ae9e64f6a3f6 to your computer and use it in GitHub Desktop.
Save wcheek/10fe9f33d10156ce1a77ae9e64f6a3f6 to your computer and use it in GitHub Desktop.
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import json
import boto3
import zipfile
import urllib as urllib2
import io
import os
import time
# from botocore.vendored import requests
import requests
SUCCESS = "SUCCESS"
FAILED = "FAILED"
LATEST_ALIAS = "$LATEST"
LEX_SCHEMA = os.environ["LEX_SCHEMA"]
LEX_LAMBDA_ARN = os.environ["LEX_LAMBDA_ARN"]
def lambda_handler(event, context):
responseData = {}
if event["RequestType"] == "Delete":
send(event, context, SUCCESS, responseData)
return {"statusCode": 200, "body": json.dumps("Lambda deleted")}
url = LEX_SCHEMA
response = urllib2.request.urlopen(url)
data = response.read()
data = json.loads(data)
# print(f"data: {data}")
# print(f"LEX_SCHEMA: {LEX_SCHEMA}")
# print(f"LEX_LAMBDA_ARN: {LEX_LAMBDA_ARN}")
data["resource"]["intents"][0]["fulfillmentActivity"]["codeHook"][
"uri"
] = LEX_LAMBDA_ARN
data["resource"]["intents"][0]["dialogCodeHook"]["uri"] = LEX_LAMBDA_ARN
# data["LambdaURI"] = LEX_LAMBDA_ARN
# data = data.replace("LambdaURI", LEX_LAMBDA_ARN)
os.chdir("/tmp")
with open("output.json", "w") as text_file:
text_file.write(json.dumps(data))
os.chdir("/tmp")
zf = zipfile.ZipFile("updatedbot.zip", mode="w")
try:
zf.write("output.json")
finally:
zf.close()
f = open("updatedbot.zip", "rb")
file_content = f.read()
print(file_content)
f.close()
with open("output.json") as bot_def:
bot_schema = json.load(bot_def)
bot_schema_resource = bot_schema["resource"]
lambda_client = boto3.client("lambda")
lambda_client.add_permission(
FunctionName=LEX_LAMBDA_ARN.split(":")[6],
StatementId="{}-intents".format(bot_schema_resource["name"]),
Action="lambda:invokeFunction",
Principal="lex.amazonaws.com",
SourceArn="arn:aws:lex:{}:{}:intent:*".format(
LEX_LAMBDA_ARN.split(":")[3], LEX_LAMBDA_ARN.split(":")[4]
),
)
client = boto3.client("lex-models")
response = client.start_import(
payload=file_content,
resourceType="BOT",
mergeStrategy="OVERWRITE_LATEST",
)
time.sleep(10)
with open("output.json") as lex_schema_file_input:
full_schema = json.load(lex_schema_file_input)
schema_resource = full_schema["resource"]
voice_id = schema_resource["voiceId"]
bot_name = schema_resource["name"]
child_directed = schema_resource["childDirected"]
bot_intents = []
for intent in schema_resource["intents"]:
intent_name = intent["name"]
get_intent_response = client.get_intent(
name=intent_name, version=LATEST_ALIAS
)
bot_intents.append(
{"intentName": intent_name, "intentVersion": LATEST_ALIAS}
)
get_bot_response = client.get_bot(
name=bot_name, versionOrAlias=LATEST_ALIAS
)
client.put_bot(
name=bot_name,
checksum=get_bot_response["checksum"],
childDirected=child_directed,
locale=schema_resource["locale"],
abortStatement=schema_resource["abortStatement"],
clarificationPrompt=schema_resource["clarificationPrompt"],
intents=bot_intents,
processBehavior="BUILD",
voiceId=voice_id,
)
send(event, context, SUCCESS, responseData, context.invoked_function_arn)
return {"statusCode": 200, "body": json.dumps("Lex Bot Deployed")}
def send(
event,
context,
responseStatus,
responseData,
physicalResourceId=None,
noEcho=False,
):
responseUrl = event["ResponseURL"]
print(responseUrl)
responseBody = {}
responseBody["Status"] = responseStatus
responseBody["Reason"] = (
"See the details in CloudWatch Log Stream: " + context.log_stream_name
)
responseBody["PhysicalResourceId"] = (
physicalResourceId or context.log_stream_name
)
responseBody["StackId"] = event["StackId"]
responseBody["RequestId"] = event["RequestId"]
responseBody["LogicalResourceId"] = event["LogicalResourceId"]
responseBody["NoEcho"] = noEcho
responseBody["Data"] = responseData
json_responseBody = json.dumps(responseBody)
print("Response body:\n" + json_responseBody)
headers = {
"content-type": "",
"content-length": str(len(json_responseBody)),
}
try:
response = requests.put(
responseUrl, data=json_responseBody, headers=headers
)
print("Status code: " + response.reason)
except Exception as e:
print("send(..) failed executing requests.put(..): " + str(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment