javascriptfunctiontwiliotwilio-functionstwilio-programmable-voice

How to use Twilio function to repeat the message?


Here is my code

exports.handler = function(context, event, callback) {
  let twiml = new Twilio.twiml.VoiceResponse();
  twiml.gather({ numdigit:"1", tiemout:"5"}).say("some message , press 9 to repeat");

  if(event.numdigit === 9)
  {
      twiml.repeat;
  }
  else if(event.numdigit != 9){
      twiml.say("soory");
  }
  callback(null, twiml);
};

I am new to twilio functions. I have gone through the docs but cannot find anything regarding this.

When ever I am calling to the number "some message, press 9 to repeat" this is said but I want to repeat the message when 9 is pressed and should play sorry when number other then 9 is pressed

Currently if I pressed number other then 9 then also the same message is playing. If i do press any thing then it goes to "sorry"

Can anyone suggest the solution


Solution

  • Twilio developer evangelist here.

    What may be confusing here is that this Function is actually called twice as part of your call.

    <Gather> works like this: when the user enters the digit Twilio makes a new HTTP request with the Digits parameter to either the <Gather> action attribute or by default to the same URL as the current response. In your case, this means it will request the same Twilio function again.

    There is no TwiML to repeat, so we need to say the same thing again. Here's an example of how to achieve that, by returning the same TwiML for the initial request and for any request where the Digits parameter is not "9":

    exports.handler = function(context, event, callback) {
      const message = "some message , press 9 to repeat";
      const gatherOptions = { numDigits:"1", timeout:"5"};
      let twiml = new Twilio.twiml.VoiceResponse();
    
      if (event.Digits) {
        if(event.Digits === '9') {
          twiml.gather(gatherOptions).say(message);
        } else {
          twiml.say("sorry");
        }
      } else {
        twiml.gather(gatherOptions).say(message);
      }
      callback(null, twiml);
    };
    

    Let me know if that helps.