Search code examples
python-3.xtwiliotwilio-apitwilio-click-to-call

How can I fill Twilio Voice url parameter from a predefined variable?


I am using Twilio Programmable Voice and Python. Following documentation on how to make an outbound call, here is my code:

# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client


# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
string = 'Input from a function'
call = client.calls.create(
                        twiml='<Response><Say>string</Say></Response>',
                        to='+15558675310',
                        from_='+15552223214'
                    )

print(call.sid)

How can I include that "string" variable to be spoken via phone? This variable "string" will be the output from a function, so it changes.


Solution

  • In order to have that string input from your function be part of the returning TwiML you would need to use string interpolation. If you're using Python 3.6 or higher you should be able to use the string interpolation function like this:

    twiml=f'<Response><Say>{string}</Say></Response>',
    

    For more information on string interpolation and how it works you can take a look here: Python Literal String Interpolation