Search code examples
javascriptpythonamazon-web-servicesaws-lambdaamazon-lex

Write a conditional AWS Lambda Function for AWS LEX


I am newbie in AWS Arena. This is my 2nd question regarding AWS Lambda function and AWS LEX. I want to write a lambda function to trigger 2 different intents based on the value of something without any user Utterance. For example

if a >= 90.....Intent-1 will work and say "Messi is the best Footballer" and if a < 90......Intent-2 will work and say "Ronaldo is the best Footballer"


Solution

  • It is not supposed to work like that, intents are triggered based on what user types. For example, you can make an intent BestFootballer and it will be triggered on utterance who is the best footballer.

    Now, once the intent is triggered you can apply some logic to dynamically create a response.

    def build_response(message):
        return {
            "dialogAction":{
                "type":"Close",
                "fulfillmentState":"Fulfilled",
                "message":{
                    "contentType":"PlainText",
                    "content":message
                }
            }
        }
    
    def perform_action(intent_request):
        source = intent_request['invocationSource']
        output_session_attributes = intent_request['sessionAttributes'] if intent_request['sessionAttributes'] is not None else {}
        if source == 'FulfillmentCodeHook':
            a = 100
            if a < 90:
                return build_response('Ronaldo is the best Footballer')
            else:
                return build_response('Messi is the best Footballer')
    
    def dispatch(intent_request):
        intent_name = intent_request['currentIntent']['name']
        if intent_name == 'BestFootballer':
            return perform_action(intent_request)
        raise Exception('Intent with name ' + intent_name + ' not supported')
    
    def lambda_handler(event, context):
        return dispatch(event)
    

    Hope it helps.