Make sure to replace YOUR_NUMBER_HERE
with the phone number you want the incoming SMS forwarded to.
In Twilio Functions we can access webhook data such as the From
number or the message Body
using event.
. The new twiml.message
line will now return the TwiML needed to forward an SMS to the specified number, containing the number of the person who sent it and the original message body.
Save the code by clicking the "Save" button. Head to the Phone Numbers section in the Twilio Console and pick the number that you want to use for SMS forwarding or buy a new one.
Once you are in the configuration screen, scroll to the bottom of the page, and under 'A message comes in' select the value "Function", and then the name of your Function. In my case that's "My SMS Forwarder".
Afterwards click "Save" and grab your phone to text any message to it. You should see a reply with your phone number and the message you sent:
If you want to see if it properly works, ask a friend or colleague to text your Twilio number and you should see their message. Alternatively get a second Twilio number and use the API Explorer's "Message Create" functionality to send an SMS to your forwarding number.
Responding to Messages
Now that we have the message forwarding solved, how do we reply to those messages? If you want to respond with your actual number, that's easy, copy the number from the SMS and write them from your phone. If you want to keep on using your masked number it's not quite that easy.
Right now if you reply to any SMS it will trigger the same SMS webhook and basically just echo to you. We'll modify this behavior by adding the following logic to this:
Check if the message came from our own number:
- Came from someone else -> Forward the SMS like we previously did
- Message is from us -> Parse message to receive intended recipient and forward the message
In order to find out the intended recipient, we'll establish a certain pattern that all of our responses have to follow. It will be the same way that we are currently forwarding messages:
RECIPIENT_NUMBER: MESSAGE_BODY
.
Update your Twilio Function code to apply this logic: