Search code examples
twiliotwilio-apitwilio-programmable-chat

How do I delay sending responses to Twilio SMS webhook


router.post('/sms', (req, res)=>{
    main();   
    res.sendStatus(200);    
})

res.sendStatus(200) responds with a 'OK' text message instantly. How do I delay responding back to the post request by 10 minutes? Is it possible to acknowledge the post request and then send the message later?

I'm trying to use https://www.twilio.com/docs/sms/api/message-resource#create-a-message-resource


Solution

  • The trick is returning an empty TwiML response on the incoming http call. This means that no message should be send as a response.

    <?xml version="1.0" encoding="UTF-8"?>
    <Response>
    </Response>
    

    In parallel, you need to trigger an API call to manually send another message 10 minutes later. For this, you can use a timeout()

    app.post('/sms', (req, res) => {
      const twiml = new MessagingResponse();
      // Don't add a message twiml.message('');
      res.writeHead(200, {'Content-Type': 'text/xml'});
      res.end(twiml.toString());
    
    
      setTimeout(function(){
        client.messages.create({
          from: req.body.To,
          to: req.body.From,
          body: "Response in here",
        });
      }, 10 * 60 * 1000);
    
    });