Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Receive an inbound SMS


When someone sends a text message to your Twilio number, Twilio can invoke a webhook that you've created to determine what reply to send back using TwiML. On this page, we will be providing some examples of Functions that can serve as the webhook of your Twilio number.

A Function that responds to webhook requests will receive details about the incoming message as properties on the event parameter. These include the incoming number (event.From), the recipient number (event.To), the text body of the message (event.Body), and other relevant data such as the number of media sent and/or geographic metadata about the phone numbers involved. You can view a full list of potential values at Twilio's Request to your Webhook URL.

Once a Function has been invoked on an inbound SMS, any number of actions can be taken. Below are some examples to inspire what you will build.


Create and host a Function

create-and-host-a-function page anchor

In order to run any of the following examples, you will first need to create a Function into which you can paste the example code. You can create a Function using the Twilio Console or the Serverless Toolkit as explained below:

ConsoleServerless Toolkit

If you prefer a UI-driven approach, creating and deploying a Function can be done entirely using the Twilio Console and the following steps:

  1. Log in to the Twilio Console and navigate to the Functions tab(link takes you to an external page) . If you need an account, you can sign up for a free Twilio account here(link takes you to an external page) !
  2. Functions are contained within Services . Create a Service by clicking the Create Service(link takes you to an external page) button and providing a name such as test-function .
  3. Once you've been redirected to the new Service, click the Add + button and select Add Function from the dropdown.
  4. This will create a new Protected Function for you with the option to rename it. The name of the file will be path it is accessed from.
  5. Copy any one of the example code snippets from this page that you want to experiment with, and paste the code into your newly created Function. You can quickly switch examples by using the dropdown menu of the code rail.
  6. Click Save to save your Function's contents.
  7. Click Deploy All to build and deploy the Function. After a short delay, your Function will be accessible from: https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>
    For example: test-function-3548.twil.io/hello-world .

Your Function is now ready to be invoked by HTTP requests, set as the webhook of a Twilio phone number, invoked by a Twilio Studio Run Function Widget, and more!


Set a Function as a webhook

set-a-function-as-a-webhook page anchor

In order for your Function to react to incoming SMS and/or voice calls, it must be set as a webhook for your Twilio number. There are a variety of methods to set a Function as a webhook, as detailed below:

Twilio ConsoleTwilio CLITwilio SDKs

You can use the Twilio Console(link takes you to an external page) UI as a straightforward way of connecting your Function as a webhook:

  1. Log in to the Twilio Console's Phone Numbers page(link takes you to an external page) .
  2. Click on the phone number you'd like to have connected to your Function.
  3. If you want the Function to respond to incoming SMS, find the A Message Comes In option under Messaging . If you want the Function to respond to Voice, find the A Call Comes In option under Voice & Fax .
  4. Select Function from the A Message Comes In or A Call Comes In dropdown.
  5. Select the Service that you are using, then the Environment (this will default to ui unless you have created custom domains ), and finally Function Path of your Function from the respective dropdown menus.
    Connect a Function as a Messaging webhook using the Function dropdowns.
  • Alternatively, you could select Webhook instead of Function, and directly paste in the full URL of the Function.
    Setting a Function as a Messaging webhook using the webhook dropdown option.
  1. Click the Save button.

Respond with a static message

respond-with-a-static-message page anchor

For the most basic possible example, one can reply to the incoming SMS with a hardcoded message. To do so, you can create a new MessagingResponse and declare the intended message contents. Once your message content has been set, you can return the generated TwiML by passing it to the callback function as shown and signaling a successful end to the Function.

Respond to an inbound SMS

respond-to-an-inbound-sms page anchor

_10
exports.handler = (context, event, callback) => {
_10
// Create a new messaging response object
_10
const twiml = new Twilio.twiml.MessagingResponse();
_10
// Use any of the Node.js SDK methods, such as `message`, to compose a response
_10
twiml.message('Hello, World!');
_10
// Return the TwiML as the second argument to `callback`
_10
// This will render the response as XML in reply to the webhook request
_10
return callback(null, twiml);
_10
};


Respond dynamically to an inbound SMS

respond-dynamically-to-an-inbound-sms page anchor

Because the contents of the incoming message are accessible from event.Body, it's also possible to tailor the response based on the contents of the message. For example, you could respond with "Hello, there!" to an incoming message that includes the text "hello", say "Goodbye" to any message including "bye", and have a fallback response if neither of those conditions is met.

Dynamically respond to an inbound SMS

dynamically-respond-to-an-inbound-sms page anchor

_20
exports.handler = (context, event, callback) => {
_20
// Create a new messaging response object
_20
const twiml = new Twilio.twiml.MessagingResponse();
_20
_20
// Access the incoming text content from `event.Body`
_20
const incomingMessage = event.Body.toLowerCase();
_20
_20
// Use any of the Node.js SDK methods, such as `message`, to compose a response
_20
if (incomingMessage.includes('hello')) {
_20
twiml.message('Hello, there!');
_20
} else if (incomingMessage.includes('bye')) {
_20
twiml.message('Goodbye!');
_20
} else {
_20
twiml.message('Not sure what you meant! Please say hello or bye!');
_20
}
_20
_20
// Return the TwiML as the second argument to `callback`
_20
// This will render the response as XML in reply to the webhook request
_20
return callback(null, twiml);
_20
};


Another example that uses even more event properties would be a Function that forwards SMS messages from your Twilio phone number to your personal cell phone. This could be handy in a situation where perhaps you don't want to share your real number while selling an item online, you are suspicious of the stranger that just asked for your number, or for any other reason.

This Function will accept an incoming SMS and generate a new TwiML response that contains the number that sent the message followed by the contents of the SMS. Because the TwiML's to property is set to your personal phone number, this new message will be forwarded to you instead of creating a response directly to the sender.

For more information and a more detailed example, please reference this blog post(link takes you to an external page) on the subject.


_13
const MY_NUMBER = "+15095550100";
_13
_13
exports.handler = (context, event, callback) => {
_13
// Create a new messaging response object
_13
const twiml = new Twilio.twiml.MessagingResponse();
_13
// Use any of the Node.js SDK methods, such as `message`, to compose a response
_13
// Access incoming text information like the from number and contents off of `event`
_13
// Note: providing a `to` parameter like so will forward this text instead of responding to the sender
_13
twiml.message({ to: MY_NUMBER }, `${event.From}: ${event.Body}`);
_13
// Return the TwiML as the second argument to `callback`
_13
// This will render the response as XML in reply to the webhook request
_13
return callback(null, twiml);
_13
};

(information)

Info

In this example, your personal number is hardcoded as a string in the Function for convenience. For a more secure approach, consider setting MY_NUMBER as an Environment Variable in the Functions UI instead. It could then be referenced in your code as context.MY_NUMBER, as shown in the following example.

Using an environment variable to store sensitive data


_11
exports.handler = (context, event, callback) => {
_11
// Create a new messaging response object
_11
const twiml = new Twilio.twiml.MessagingResponse();
_11
// Use any of the Node.js SDK methods, such as `message`, to compose a response
_11
// Access incoming text information like the from number and contents off of `event`
_11
// Access environment variables and other runtime data from `context`
_11
twiml.message({ to: context.MY_NUMBER }, `${event.From}: ${event.Body}`);
_11
// Return the TwiML as the second argument to `callback`
_11
// This will render the response as XML in reply to the webhook request
_11
return callback(null, twiml);
_11
};


Respond with MMS media from an HTTP request

respond-with-mms-media-from-an-http-request page anchor

All the Function examples so far are fully synchronous and only rely on data from the inbound message. Functions can also request data from other services with the ability to rely on modern async/await syntax(link takes you to an external page).

For example, in response to an incoming SMS, it's possible for a Function to request an online resource (such as a fun image of a doge), and reply back to the sender with an MMS containing said image.

Respond to an inbound SMS with an asynchronously generated MMS

respond-to-an-inbound-sms-with-an-asynchronously-generated-mms page anchor

_30
const axios = require('axios');
_30
_30
// Note that the function must be `async` to enable the use of the `await` keyword
_30
exports.handler = async (context, event, callback) => {
_30
// Create a new messaging response object
_30
const twiml = new Twilio.twiml.MessagingResponse();
_30
_30
// You can do anything in a Function, including making async requests for data
_30
const response = await axios
_30
.get('https://dog.ceo/api/breed/shiba/images/random')
_30
.catch((error) => {
_30
// Be sure to handle any async errors, and return them in a callback to end
_30
// Function execution if it makes sense for your application logic
_30
console.error(error);
_30
return callback(error);
_30
});
_30
_30
const imageUrl = response.data.message;
_30
_30
// Use any of the Node.js SDK methods, such as `message`, to compose a response
_30
// In this case we're also including the doge image as a media attachment
_30
// Note: access incoming text details such as the from number on `event`
_30
twiml
_30
.message(`Hello, ${event.From}! Enjoy this doge!`)
_30
.media(imageUrl);
_30
_30
// Return the TwiML as the second argument to `callback`
_30
// This will render the response as XML in reply to the webhook request
_30
return callback(null, twiml);
_30
};

(warning)

Warning

In order to use an npm module such as axios to create HTTP requests, you will need to add it as a Dependency.


Rate this page: