Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I respond to incoming Twilio calls and SMS messages using node.js?

Tags:

node.js

twilio

In my application I'm using the twilio node.js module to receive an sms, send an sms, receive a call and make an outgoing call. I figured out how to send an sms and make a call. But I don't know how to respond to incoming calls and SMS messages. How can I use node to respond to these?

like image 675
MAAAAANI Avatar asked Jan 28 '13 06:01

MAAAAANI


People also ask

How do I reply to Twilio SMS?

When you send an SMS message to your Twilio phone number, Twilio will send a webhook, an HTTP request with all the details about the message, to a URL you associate with that number. You can reply to the message by responding to the webhook with TwiML (Twilio Markup Language).

How does Twilio handle incoming calls?

Twilio makes answering a phone call as easy as responding to an HTTP request. When a Twilio phone number receives an incoming call, Twilio will send an HTTP request to your web application, asking for instructions on how to handle the call. Your web application will respond with an XML document containing TwiML.

How do I receive a call on my Twilio number?

Configure Your Twilio NumberScroll down to the A CALL COMES IN dropdown in the Voice section and select Studio Flow. Select your new Flow in the Select a Flow dropdown to the right. Hit Save at the bottom, and you'll be all set to test your app!


1 Answers

When Twilio receives a call to your phone number, it will send an HTTP request to a URL you configure in the admin console:

twilio account dashboard

What Twilio expects in return from this HTTP request is a set of XML instructions called TwiML that will tell Twilio what to do in response to the call. For example, let's say that you wanted to respond to a phone call by saying "thank you" and then playing a music file. If you wanted to do this in node, you might consider using this node library and the express framework to send a TwiML response:

var twilio = require('twilio'),
    express = require('express');

// Create express app with middleware to parse POST body
var app = express();
app.use(express.urlencoded());

// Create a route to respond to a call
app.post('/respondToVoiceCall', function(req, res) {
    //Validate that this request really came from Twilio...
    if (twilio.validateExpressRequest(req, 'YOUR_AUTH_TOKEN')) {
        var twiml = new twilio.TwimlResponse();

        twiml.say('Hi!  Thanks for checking out my app!')
            .play('http://myserver.com/mysong.mp3');

        res.type('text/xml');
        res.send(twiml.toString());
    }
    else {
        res.send('you are not twilio.  Buzz off.');
    }
});

app.listen(process.env.PORT || 3000);

Good luck - hope this is what you were looking for.

like image 119
Kevin Whinnery Avatar answered Oct 01 '22 02:10

Kevin Whinnery