Send SMS text message from your Alexa Skill

One of the best aspects of the Alexa platform is the ability to integrate AWS features seamlessly. Because Alexa uses Lambda functions for handling request/responses, our skills have access to the whole AWS SDK with just a simple package import! In this short tutorial, I will show you how to send a SMS text message with Alexa.

Let’s take a look at a simple code snippet that a feature developer would use to integrate SMS text messaging into their app:

const AWS = require('aws-sdk');

/*
 * Your AWS credentials 
 * - tip: for quick testing, you might be able to use the credentials
 *        stored on your local machine at ~/.aws/credentials
 *        Otherwise, configure the following values as you see fit for 
 *        your project using environment variables.
 */
const aws_access_key_id = 'YOUR ACCESS KEY ID';
const aws_secret_access_key = 'YOUR SECRET ACCESS KEY';

// Configure the AWS SDK
AWS.config.update({
    accessKeyId: aws_access_key_id,
    secretAccessKey: aws_secret_access_key,
    region: 'us-west-2'  // this can be changed to us-west-1, us-east-1, etc.
});

// Create a new SNS object
const sns = new AWS.SNS();

// Send off the SMS 
function sendSMS(to_number, message) {
    return sns.publish({
        Message: message,
        PhoneNumber:to_number
    }).promise();
}

module.exports = {
    sendSMS
}

module.exports = {
    sendSms
};

Pretty straightforward and simple, right? The preceding code sample sends a SMS out to a phone number that we pass as a parameter along with a custom message.

You could include this little snippet of code in a file called utils.js and import it wherever you need to send a SMS text message a user’s phone.

Phone Number Slot Type

Ideally, you would want Alexa to resolve the phone number for you. Use the built-in slot type specifically designed for this use-case, AMAZON.PhoneNumber. This slot type is very useful and available across many of the languages and regions that Alexa supports.

Learn more about this slot type and many more from the official docs: https://developer.amazon.com/docs/custom-skills/slot-type-reference.html#phonenumber

Sample Intent

Here is a sample intent that demonstrates how to add SMS functionality to your IntentHandler.

const SendSmsIntentHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'SendSmsIntent';
    },
    async handle(handlerInput) {
        console.log('handlerInput', JSON.stringify(handlerInput, null, 4));

        let toPhoneNumber = null;
        try {
            const toPhoneNumberSlot = handlerInput.requestEnvelope.request.intent.slots.ToPhoneNumber.value;
            toPhoneNumber = `+1${toPhoneNumberSlot}`;
        } catch (err) {
            throw new Error('Could not resolve the phone number, goodbye!');
        }

        let smsMessage = 'Hello from my Alexa skill!'

        try {
            await sendSMS(toPhoneNumber, smsMessage);
        } catch(err) {
            console.log('Error sending SMS', err);
            throw new Error('There was an error sending the text message');
        }
        return handlerInput.responseBuilder
            .speak(`<speak>Message sent to <say-as interpret-as="telephone">${toPhoneNumber}</say-as><break time="1s" />.  Goodbye!</speak>`)
            .withShouldEndSession(true)
            .getResponse();
    }
};

Quick start model and screenshot

If you are in a hurry, we got you covered. Have a look at the interaction model example JSON and screenshot below. If you decide to use this, make sure to substitute your project’s unique values!

{
  "interactionModel": {
    "languageModel": {
      "invocationName": "some invocation name",
      "intents": [
        // ... other intents
        {
          "name": "SendSmsIntent",
          "slots": [
            {
              "name": "ToPhoneNumber",
              "type": "AMAZON.PhoneNumber",
              "samples": [
                "{ToPhoneNumber}"
              ]
            }
          ],
          "samples": [
            "{ToPhoneNumber}"
          ]
        }
      ],
      "types": []
    },
    "dialog": {
      "intents": [
        {
          "name": "SendSmsIntent",
          "confirmationRequired": false,
          "prompts": {},
          "slots": [
            {
              "name": "ToPhoneNumber",
              "type": "AMAZON.PhoneNumber",
              "elicitationRequired": true,
              "confirmationRequired": true,
              "prompts": {
                "confirmation": "Confirm.Slot.1469534668284.1316031820613",
                "elicitation": "Elicit.Slot.1469534668284.1316031820613"
              }
            }
          ]
        }
      ],
      "delegationStrategy": "ALWAYS"
    },
    "prompts": [
      {
        "id": "Elicit.Slot.1469534668284.1316031820613",
        "variations": [
          {
            "type": "SSML",
            "value": "<speak>What phone number do you want to send a <say-as interpret-as=\"spell-out\">SMS</say-as>?</speak>"
          }
        ]
      },
      {
        "id": "Confirm.Slot.1469534668284.1316031820613",
        "variations": [
          {
            "type": "SSML",
            "value": "<speak>Is the phone number <say-as interpret-as=\"telephone\">{ToPhoneNumber} </say-as> correct?</speak>"
          }
        ]
      }
    ]
  },
  "version": "9999"
}
send SMS text message with Alexa Intents

Further exploration

You may also notice the use of SSML (Speech Synthesis Markup Language) in the models and intent code. Amazon Alexa offers a wide variety of effects and pronunciations that you can add to your skill’s speech output. Check out this link for more information about this feature: https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#say-as

Once your project starts to become a little more complicated, you will definitely need some unit testing to make sure your SMS text messaging is bulletproof. Check out our latest tutorial on how to test IntentHandlers.

Until next time, happy coding!