Search code examples
node.jstwiliowebhookstwilio-twiml

How do I parse the SMS sender's from number and body of what s/he texted to Twilio number via a webhook and node.js?


enter image description hereHello StackOverflow Friends:

The following code works fine, I've tested with nGrok running locally.

Two of the requirements I have left and can't figure out are:

  1. Capture the phone number of the sender (put in variable)
  2. Capture the body of the text the sender sent (put in variable)

Many thanks in advance!

const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const app = express();


});

app.post('/sms', (req, res) => {

// Start our TwiML response.
 const twiml = new MessagingResponse();


// Add a text message.
const msg = twiml.message('some canned response');



res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});

app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});

Solution

  • Twilio developer evangelist here.

    You can get the inbound message from an incoming SMS webhook request with req.body.Body and the inbound phone number with req.body.From.

    To save into a variable, maybe something like const inbMsg = req.body.Body and const inbPhoneNum = req.body.From.

    For more information on parsing an incoming Twilio SMS Webhook with Node.js, I'd recommend this blog post by my teammate Sam Agnew.

    Let me know if this helps at all!