How to use <Say> multiple times in one call?

37 Views Asked by At

How can I use <Say> multiple times in one call? I have come up with an example for my question:

exports.handler = async function (context, event, callback) {
  try {
    const twiml = new Twilio.twiml.VoiceResponse();
    const client = context.getTwilioClient();
    console.log("The call is " + JSON.stringify(event.CallSid));
    var i = 0;
    const sentences = ['Ahoy there', 'How are you today?', 'Nice to meet you', 'Hope you have a great day', 'Goodbye'];

    const intervalId = setInterval(async () => {
      if (i < sentences.length) {
        const resp = await client.calls(event.CallSid).update({
          twiml: `<Response><Say>${sentences[i]}</Say></Response>`
        });
        i += 1;
      } else {
        clearInterval(intervalId);
        return callback(null, twiml);
      }
    }, 3000); // update every 3 seconds
  } catch (err) {
    console.error(err);
  }
};

Here, there are a set of four sentences that I would like to say separately every three seconds. I am following the update documentation here.

But, this doesn't seem to work. It just leads to a Twilio timeout. Is there a way to do this without having to recursively return a callback and redirect each time?

1

There are 1 best solutions below

0
Keyboard Corporation On

Try to construct a single TwiML instruction that includes all the <Say> and use <Pause> to introduce the delays between the sentences.

exports.handler = async function (context, event, callback) {
 try {
    const twiml = new Twilio.twiml.VoiceResponse();
    const client = context.getTwilioClient();
    console.log("The call is " + JSON.stringify(event.CallSid));
    const sentences = ['Ahoy there', 'How are you today?', 'Nice to meet you', 'Hope you have a great day', 'Goodbye'];

    // Create a single TwiML instruction with all the <Say> tags and <Pause> tags
    let twimlInstruction = '<Response>';
    for (let sentence of sentences) {
      twimlInstruction += `<Say>${sentence}</Say><Pause length="3"/>`;
    }
    twimlInstruction += '</Response>';

    const resp = await client.calls(event.CallSid).update({
      twiml: twimlInstruction
    });
    return callback(null, twiml);
 } catch (err) {
    console.error(err);
 }
};