Your Twilio account needs to be configured so that it can handle inbound SMS message and inbound phone calls. The simplest handling method is simply to have inbound SMS or calls forwarded to your real phone number.
The code snippets below need to be configured as functions within your Twilio account. Once the function is created, you can assign the function as a handler for your Twilio phone number.
When you configure each function in Twilio, you will assign a path for the function. The path must not contain spaces or other special characters. In the example bwlow, we have assigned the path "forward-sms":
Here is the function that will forward inbound SMS messages to your Twilio number to your real phone number:
const MY_NUMBER = "+12074515191"; // Number to which inbound SMS are forwarded
exports.handler = (context, event, callback) => {
// Create a new messaging response object
const twiml = new Twilio.twiml.MessagingResponse();
// Use any of the Node.js SDK methods, such as `message`, to compose a response
// Access incoming text information like the from number and contents off of `event`
// Note: providing a `to` parameter like so will forward this text instead of responding to the sender
twiml.message({ to: MY_NUMBER }, `${event.From}: ${event.Body}`);
// Return the TwiML as the second argument to `callback`
// This will render the response as XML in reply to the webhook request
return callback(null, twiml);
};
Once the function is created, we then assign the new function to handle inbound SMS message for our Twilio phone number. Note how the last field specifies the path that we created when we created the function:
Here is the function that will forward inbound phone calls to your Twilio number to your real phone number. This script allows you to configure a voice message that the caller will hear as the call is being forwarded:
const NEW_NUMBER = "+16035709255"; // The number to which inbound calls will be forwarded
exports.handler = (context, event, callback) => {
// Create a new voice response object
const twiml = new Twilio.twiml.VoiceResponse();
twiml.say('Hello! Forwarding you to our new phone number now!'); // Voice message callers hear prior to forwarding
// The `dial` method will forward the call to the provided E.164 phone number
twiml.dial(NEW_NUMBER);
// Return the TwiML as the second argument to `callback`
// This will render the response as XML in reply to the webhook request
return callback(null, twiml);
};
Once the function is created, we then assign the new function to handle inbound phone calls to our Twilio phone number. Note how the last field specifies the path that we created when we created the function: