Search code examples
twiliotwilio-apitwilio-twiml

Twilio: Responding to a caller after transcript for previous response is received


I'm trying to get the following flow to work:

  1. Caller dials twilio #
  2. We ask a question of the caller and they respond by speaking
  3. Once the transcript is received (not the audio file), we respond by asking them another question... this goes on for 2-3 questions

The problem I'm having is the separation of the calls to the main webhook handler, and the transcript handler.

I have the primary call handler responding with the first question, as follows:

<!-- [/ handler] initial response, with the first question -->
<Response>
    <Say voice="alice">What is your favorite color? Press any key when done.</Say>
    <Record transcribe="true" transcribeCallback="/transcript" maxLength="60"/>
</Response>

Then we receive a second request to the primary call handler when the recording is completed. I can't respond with another question yet (business requirements), so we respond with a vague confirmation:

<!-- [/ handler] vague confirmation response
<Response>
    <Say voice="alice">Got it. Give me a couple seconds to write that down.</Say>
</Response>

Then I receive a hit on the /transcript handler with the transcript, to which I respond with:

<!-- [/transcript handler] Second question -->
<Response>
    <Say voice="alice">What is the air-speed velocity of an unladen swallow? Press any key when done.</Say>
    <Record transcribe="true" transcribeCallback="/transcription" maxLength="60"/>
</Response>

But apparently you can't respond to that handler with TWiML? The caller is hung up on after the second response from the / handler.

Any ideas on how I can implement this? I don't think I can really have the user wait in silence before responding to the second / handler request...


Solution

  • When you receive a hit on your /transcript handler you have in the request the callSid (CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX) among other parameters.

    With this callSid you can modify the "in progress call" my making a request to Twilio and passing a new TwiML.

    Not sure what language are you using on your server side but in Node.js would look something like this:

    const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
    const authToken = 'your_auth_token';
    const client = require('twilio')(accountSid, authToken);
    
    client.calls('CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
          .update({twiml: '<Response>
        <Say voice="alice">What is the air-speed velocity of an unladen swallow? Press any key when done.</Say>
        <Record transcribe="true" transcribeCallback="/transcription" maxLength="60"/>
    </Response>'})
          .then(call => console.log(call.to));
    

    Docs: (https://www.twilio.com/docs/voice/tutorials/how-to-modify-calls-in-progress-node-js)