0
votes

I'm trying to automate call forwarding using Twilio. when the user calls the Twilio number it will play some welcome message then it should call an external API, The API will return a phone number the Twilio should call the number. I'm trying to do with this TwiML. here is my TwiML bin document

<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Pause length="1"/>
    <Say voice="Polly.Joanna"> Welcome
    </Say>
  <Dial> HERE THE NUMBER SHOULD COME THAT API WILL RETURN
  </Dial>

</Response>

for example https://getmynumber/samplenumber is the URL that will return a number. How can I achieve this with TwiML? and is it possible to define a variable inside TwiML? because if i can save the number to that variable using the <Redirect> tag I can achieve this easily. is it possible?

1

1 Answers

1
votes

That'll be difficult with only TwiML Bin but you could try something like:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Pause length="1"/>
    <Say voice="Polly.Joanna">Welcome</Say>
    <Dial>{{Number}}</Dial>
</Response>

And then call it via: https://<your TwiML Bin URL>/...?Number=+123456789

This passes custom values into a TwiML Bin, here Number.

If you really need to call an API to get the number to dial you'll need some kind of endpoint to form the TwiML, e.g. a Twilio Function, or any other endpoint.

A version in Python could look like this:

from twilio.twiml.voice_response import VoiceResponse

response = VoiceResponse()
response.pause(length=1)
response.say('Welcome')
number = '+123456789' # Here you would do an API call
response.dial(number)

print(response)

The above basically creates the TwiML you have in your TwiML Bin but with Python. You would need to wrap this in an endpoint to be able to be called and returned. And of course you would need to add your logic to retrieve the number via the API.