alexr101
alexr101

Reputation: 598

How to use Twilio to send SMS, and wait for response from phone to finish request in NodeJS

I know how to send an SMS via Twilio to a phone number specified in the request body, however I need a way for this route to wait for the user to respond with a text message. I need to capture that messages body and send it as a response.

router.post('/', function(req, res){

    var customerNumber = req.body.mobileNumber;
    var twilioNumber = process.env.TWILIO_NUMBER;

    client.messages
        .create({
           to: '+1' + customerNumber,
           from: twilioNumber,
           body: 'message to user',
           provideFeedback: 'true',
        }, function(err, message){
           if(err) res.send('message err: ' + err);
           else{
             // wait 10-20 seconds for user to respond
             res.send("A response from the user");
           }
        })      
});

I also know how to listen to responses with Twilio, but this doesn't work because I need the above route to respond with the message I get from the user in the route below.

router.post('/sms-response', function(req, res){
  var twilio = require('twilio');
  var twiml = new twilio.twiml.MessagingResponse();
  twiml.message('thanks for your feedback');
  res.writeHead(200, {'Content-Type':'text/xml'});
  res.end(twiml.toString());
});

I've been looking for a way to do this all day with no success at all. I appreciate your help!

Upvotes: 1

Views: 1258

Answers (2)

philnash
philnash

Reputation: 73075

Twilio developer evangelist here.

While this could technically be possible I strongly recommend against it. You mention that you might be waiting for 10-20 seconds, but users are much more fickle than that, as are mobile networks. So getting a response may take much longer that that or even never happen. Then you'd be left with a long running connection to your server waiting for a response that might never come.

As Hammer suggested, it would be better to return a response to the user straight away, saying something like "We're waiting for your response", then connecting that user's browser to your server via a websocket or server sent event stream. When you receive the incoming message on your webhook endpoint, you can then send the information down the websocket or event source and react to that in the front end.

Let me know if that helps at all.

Upvotes: 1

Lucas Hendren
Lucas Hendren

Reputation: 2826

I dont know if that is possible yet, I went through their documentation and didnt see that feature yet. I would suggest using a web socket like socket.io. When message comes in you can just pass the response in through the socket to the user.

Upvotes: 1

Related Questions