Placing a call with Twilio and Python 2.7
Introduction
Twilio allows to do many things. Here I'm interested in placing a sample call to a fixed line, using Python 2.7 - alias I cannot used Twilio's helper Python library which is Python 3 only.
So I'm going to rely instead on the excellent requests library.
The first step are to:
- Get a Twilio test account
- Request a test phone number
- Identify my API Secret and Keys
- Whitelist my target phone number
The program bellow will then place a call, and query a number of times for the status of the call.
The code
#!/usr/bin/python
import requests
from requests.auth import HTTPBasicAuth
import time
from xml.etree import ElementTree
API_KEY = 'AC....'
API_SECRET = 'a4...'
CALLING_NUMBER = '+41....'
CALLED_NUMBER = '+41....'
XML_URL = 'http://demo.twilio.com/docs/voice.xml'
BASE_URL = 'https://api.twilio.com/'
POST_URL = '%s/2010-04-01/Accounts/%s/Calls' % (BASE_URL, API_KEY, )
SLEEP_DELAY = 2 # Seconds
NB_POLLS = 10
auth = HTTPBasicAuth(API_KEY, API_SECRET)
r = requests.post(
POST_URL,
auth=auth,
data={
'From': CALLING_NUMBER,
'To': CALLED_NUMBER,
'Url': XML_URL,
},
)
tree = ElementTree.fromstring(r.text)
call_uri = tree.find('.//Uri')
if call_uri is not None:
STATUS_URL = BASE_URL + call_uri.text
for i in range(NB_POLLS):
r = requests.get(STATUS_URL, auth=auth)
tree = ElementTree.fromstring(r.text)
status = tree.find('.//Status')
if status is not None:
print status.text
time.sleep(SLEEP_DELAY)