In a previous post, I wrote about how to use Twilio to send an SMS message. This time, I'm going to show you how you can use Twilio in conjunction with a web app to answer phone calls made to your Twilio phone number.
First, you will want to have a Twilio developer account. If you did not create one last time, go ahead and create one now.
The Twilio dashboard provides a place for you enter an address to send HTTP POST requests. Using the App.HandleSpecialURL event handler, you can send these requests to a web application running on a publicly available server.
To get started, you need to create a web application. In the App object, go to the HandleSpecialURL event handler. This event handler has one parameter: Request As WebRequest. You can use this parameter to handle the request sent by Twilio and to send information back to Twilio.
Twilio uses something they call TwiML (Twilio Markup Language), which is essentially XML with Twilio-specific commands.
In this case, the special command you want to use is the Say command. This command will speak the provided text to the person that called the number. It is wrapped in a Response, so some simple TwiML looks like this:
<Say>This call was answered by my web application!"</Say>
Going back to the HandleSpecialURL event handler, you just need to return the TwiML as part of the request. This is done using the Print method:
If Request.Path = "twilio" Then
// Use TwiML to say something
Dim now As New Date
Request.Print("<Response>" + EndOfLine)
Request.Print("<Say>This call was answered by my web application!</Say>" + EndOfLine)
Request.Print("<Say>The time is " + Now.LongTime + "</Say>" + EndOfLine)
Notice that I have not created a web page. That's because this web app won't use one as its only purpose is to handle direct requests using HandleSpecial URL.
Give this app a name (TwilioCall), built it as a standalone app (or CGI if you prefer) for your deployment platform.
Now you need to configure Twilio to use this web app. Go back to your Twilio Dashboard and navigate to Dev Tools and select TWIML apps. Click "Create TWiML App" to create a new app.
This opens a screen to specify information about your web app:
In the "Friendly Name" field just give your app a name such as TwilioCall. In the Voice section, you specify the URL for your uploaded web app in the "Request URL" field. The URL of your app will be something like this:
With all this in place, you can now call your Twilio phone number. Twilio will then send a request to your web app which will respond by sending back a request to speak some text and the current time.
You can find more information about TwiML here: https://www.twilio.com/docs/api/twiml
An example project demonstrating this will be included with Xojo and is also available here.