AWS Messaging & Targeting Blog

Create an SMS Chatbot with Amazon Pinpoint and Lex

Note: This post was written by Ilya Pupko, Senior Consultant for the AWS Digital User Engagement team, and by Gopinath Srinivasan, an AWS Enterprise Solution Architect.


A major advantage of using Amazon Pinpoint for your customer engagement workflows is its ability to tightly integrate with other AWS services. These integrations make it possible to engage in deeper conversations with your customers, as opposed to simply sending one-directional, one-size-fits-all messages.

In this tutorial, we look at the process of creating an SMS-based chatbot using Amazon Lex. This chatbot will help our customers schedule appointments. We’ll use Amazon Pinpoint to send responses from the chatbot over the SMS channel, and we’ll use AWS Lambda to connect the two services together. The following image illustrates the architecture that we’ll create in this tutorial.

The steps in this post are intended to provide general guidance, rather than specific procedures. If you’ve used other AWS services in the past, most of the concepts here will be familiar. If not, don’t worry—we’ve included links to the documentation to make things easier.

Step 1: Set up a project in Amazon Pinpoint

The first step in setting up the chatbot is to create a new Amazon Pinpoint project that can send and receive SMS messages. To be able to receive incoming SMS messages, you also need to obtain a dedicated phone number.

To create a new SMS project

  1. Sign in to the Amazon Pinpoint console at https://console.aws.amazon.com/pinpoint.
  2. Create a new Amazon Pinpoint project, and enable the SMS channel for the project. For more information, see https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-setup.html.
  3. Request a long code for your country. For more information, see https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-voice-manage.html#channels-voice-manage-request-phone-numbers.
  4. Enable the two-way SMS feature for the dedicated long code that you just purchased. Under Incoming message destination, choose Create a new SNS topic, and name it LexPinpointIntegrationDemo. For more information about setting up two-way SMS, see https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-two-way.html.

Step 2: Create a Lex chatbot

Now it’s time to create your bot. For the purposes of this example, we’ll use a bot that’s pre-configured to handle appointment requests. Later, you can customize this bot to fit your needs by specifying additional intents.

To create your bot

  1. Sign in to the Lex console at https://console.aws.amazon.com/lex.
  2. Create a new bot. On the Create your bot page, choose the ScheduleAppointment sample. Use the default IAM role. For COPPA, choose No. Note the name that you specified for the bot—you need to refer to this name in the Lambda function that you create later. For more information about creating bots in Lex, see https://docs.aws.amazon.com/lex/latest/dg/gs-console.html.
  3. When the bot finishes building, choose Publish. For Create an alias, enter Latest. Choose Publish.

Step 3: Set up the Lambda backend

After you create your Lex bot, you have to create a Lambda function that allows your Lex bot to send messages through Amazon Pinpoint.

To create the Lambda function

  1. Sign in to the Lambda console at https://console.aws.amazon.com/lambda.
  2. Create a new Node.js 10.x function from scratch. Create a new IAM role with the default permissions. For more information about creating functions, see https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html.
  3. In the Designer section, choose Add trigger. Add a new SNS trigger, and then choose the LexPinpointIntegrationDemo topic that you created earlier.
  4. In the Lambda code editor, paste the following code:
    "use strict";
    
    const AWS = require('aws-sdk');
    AWS.config.update({
        region: process.env.Region
    });
    const pinpoint = new AWS.Pinpoint();
    const lex = new AWS.LexRuntime();
    
    var AppId = process.env.PinpointApplicationId;
    var BotName = process.env.BotName;
    var BotAlias = process.env.BotAlias;
    
    exports.handler = (event, context)  => {
        /*
        * Event info is sent via the SNS subscription: https://console.aws.amazon.com/sns/home
        * 
        * - PinpointApplicationId is your Pinpoint Project ID.
        * - BotName is your Lex Bot name.
        * - BotAlias is your Lex Bot alias (aka Lex function/flow).
        */
        console.log('Received event: ' + event.Records[0].Sns.Message);
        var message = JSON.parse(event.Records[0].Sns.Message);
        var customerPhoneNumber = message.originationNumber;
        var chatbotPhoneNumber = message.destinationNumber;
        var response = message.messageBody.toLowerCase();
        var userId = customerPhoneNumber.replace("+1", "");
    
        var params = {
            botName: BotName,
            botAlias: BotAlias,
            inputText: response,
            userId: userId
        };
        response = lex.postText(params, function (err, data) {
            if (err) {
                console.log(err, err.stack);
                //return null;
            }
            else if (data != null && data.message != null) {
                console.log("Lex response: " + data.message);
                sendResponse(customerPhoneNumber, chatbotPhoneNumber, response.response.data.message);
            }
            else {
                console.log("Lex did not send a message back!");
            }
        });
    }
    
    function sendResponse(custPhone, botPhone, response) {
        var paramsSMS = {
            ApplicationId: AppId,
            MessageRequest: {
                Addresses: {
                    [custPhone]: {
                        ChannelType: 'SMS'
                    }
                },
                MessageConfiguration: {
                    SMSMessage: {
                        Body: response,
                        MessageType: "TRANSACTIONAL",
                        OriginationNumber: botPhone
                    }
                }
            }
        };
        pinpoint.sendMessages(paramsSMS, function (err, data) {
            if (err) {
                console.log("An error occurred.\n");
                console.log(err, err.stack);
            }
            else if (data['MessageResponse']['Result'][custPhone]['DeliveryStatus'] != "SUCCESSFUL") {
                console.log("Failed to send SMS response:");
                console.log(data['MessageResponse']['Result']);
            }
            else {
                console.log("Successfully sent response via SMS from " + botPhone + " to " + custPhone);
            }
        });
    }
  5. In the Environment variables section, add the following variables:
    Key Value
    PinpointApplicationId The ID of the Pinpoint project that you created earlier.
    BotName The name of the Lex bot that you created earlier.
    BotAlias Latest
    Region The AWS Region that you created the Amazon Pinpoint project and Lex bot in.
  6. Under Execution role, choose View the LexPinpointIntegrationDemoLambda role.
  7. In the IAM console, add an inline policy. Paste the following into the policy editor:
    {
       "Version":"2012-10-17",
       "Statement":[
          {
             "Sid":"Logs",
             "Effect":"Allow",
             "Action":[
                "logs:CreateLogStream",
                "logs:CreateLogGroup",
                "logs:PutLogEvents"
             ],
             "Resource":[
                "arn:aws:logs:*:*:*"
             ]
          },
          {
             "Sid":"Pinpoint",
             "Effect":"Allow",
             "Action":[
                "mobiletargeting:SendMessages"
             ],
             "Resource":[
                "arn:aws:mobiletargeting:<REGION>:<ACCOUNTID>:apps/*"
             ]
          },
          {
             "Sid":"Lex",
             "Effect":"Allow",
             "Action":[
                "lex:PostContent",
                "lex:PostText"
             ],
             "Resource":[
                "arn:aws:lex:<REGION>:<ACCOUNTID>:bot/<BOTNAME>"
             ]
          }
       ]
    }

    In the preceding code, make the following changes:

    • Replace <REGION> with the name of the AWS Region that you created the Amazon Pinpoint project and the Lex bot in (such as us-east-1).
    • Replace <ACCOUNTID> with your AWS account ID.
    • Replace <BOTNAME> with the name of your Lex bot.
  8. When you finish, save the policy as PinpointLexFunctionRole.

Step 4: Test the chatbot

Your SMS chatbot is now set up and ready to use! You can test it by sending a message (such as “Schedule an appointment”) to the long code that you obtained earlier. The chatbot responds, asking what type of appointment you want to book, and at what time.

Conclusion

Now that you’ve created your chatbot, you can start to customize it to fit your specific use case. For example, you can enhance the chatbot’s conversational abilities by adding intents, or you could expand on the Lambda function to integrate it with a third-party scheduling tool.

To learn more about configuring Amazon Lex, see the Amazon Lex Developer Guide.

Finally, you can find the latest updates to the code that’s associated with this tutorial in the amazon-pinpoint-lex-bot repository on Github.

Brent Meyer

Brent Meyer