pythonamazon-web-servicesaws-lambdacloudamazon-lex

Lambda function can't connect to Lex bot


I want to invoke my Lex bot from my lambda function, by passing an input (utterance) to my bot.

Here is my Python code:

import boto3
import json

def lambda_handler(event, context):
    print(event)
    # Create a new Amazon Lex runtime client
    client = boto3.client('lex-runtime')

    # Send the user's input to the bot
    response = client.post_text(
        botName='BotName',
        botAlias='BotAlias',
        userId='UserID',
        inputText=event['input']
    )

    # Return the bot's response to the caller
    return {
        'output': response['message']
    }

I get the following error:

"errorMessage": "Could not connect to the endpoint URL: "https://runtime.lex.af-south-1.amazonaws.com/bot/BotName/alias/BotAlias/user/UserID/text"", "errorType": "EndpointConnectionError",

My lambda function has the following permissions: AmazonLexFullAccess AmazonLexRunBotsOnly

My Lex bot has the basic Amazon Lex permissions.


Solution

  • So it turns out that I was using 'lex-runtime' instead of 'lexv2-runtime'. The parameters also have to change.

    The corrected code is as follows:

    import boto3
    import json
    
    def lambda_handler(event, context):
        # Create a new Amazon Lex runtime client
        client = boto3.client('lexv2-runtime')
        
        # Send the user's input to the bot
        response = client.recognize_text(
            botId='<botId>',
            botAliasId='<botAliasId>',
            localeId='<localeId>',
            sessionId='<sessionId>',
            text='event['input']
        )
        
        # Return the bot's response to the caller
        return {
            'output': response['messages']
        }