Syndicated from The Pursuit Of A Life
My last Twilio demo showed how you could call Twilio and retrieve information from a web application you’ve built. This demo shows the reverse scenario: you use a web application that calls out to Twilio, which in turn calls out to a given phone number.
This will be a pretty straightforward translation of Twilio’s existing Appointment Reminder demo, which is written in Ruby.
WARNING: Use this power only for good. For example, you wouldn’t dream of rickrolling anyone, would you? ![]()
Let’s get started. Our web app will be written in ASP.NET/C#, and, unlike the previous example, has no database backend, for simplicity’s sake. In a real-life application, you would pull these reminders from a database on a schedule; but here we’ll bypass that part.
Before you get started, you’ll need to download the C# REST helper library from the Twilio website. This contains some code that wraps the messy network communications.
Add the file twiliorest.cs to your web application project.
You’ll need two ASPX pages: a page that captures the phone number you want Twilio to call, and a page that Twilio uses to decide what to do based on the callee’s responses.
Here’s the web form to capture input. Put this in your <form> tag in a new web form page called default.aspx:
1 2 3 4 5 6 |
<h1>Twilio phone reminder demo</h1> <h2 style="color:#ff0000" id="MessageElement" runat="server"></h2> <h3>Enter your phone number to receive an automated reminder</h3> <asp:TextBox ID="PhoneNumberText" runat="server"></asp:TextBox> <br /> <asp:Button ID="SubmitButton" runat="server" Text="Call Me!" onclick="SubmitButton_Click" /> |
Here’s the code-behind in default.aspx.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
using System; using System.Collections; using TwilioRest; namespace Twilio.Web.appointment { public partial class _default : System.Web.UI.Page { protected const string ACCOUNT_SID = "SSSSSSSSSSSSSSSSSSSSSSSSSSSSS"; protected const string AUTH_TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; protected const string API_VERSION = "2008-08-01"; protected const string CALLER_ID = "NNN-NNN-NNNN"; protected void SubmitButton_Click(object sender, EventArgs e) { string phoneNumber = Server.HtmlEncode(this.PhoneNumberText.Text); this.MakeTwilioCall(phoneNumber); } protected virtual void MakeTwilioCall(string phoneNumber) { TwilioRest.Account account = new Account(ACCOUNT_SID, AUTH_TOKEN); // create the URL at Twilio to post to string postUrl = "/{0}/Accounts/{1}/Calls"; postUrl = string.Format(postUrl, API_VERSION, ACCOUNT_SID); // create the variables to pass in to the POST string reminderUrl = Page.Request.Url.GetLeftPart(UriPartial.Authority) + "/appointment/reminder.aspx"; Hashtable vars = new Hashtable(3); vars.Add("Caller", CALLER_ID); vars.Add("Called", phoneNumber); vars.Add("Url", reminderUrl); try { string response = account.request(postUrl, "POST", vars); } catch (Exception exc) { this.MessageElement.InnerText = exc.Message; } } } } |
What we’re doing here is simply handling the button click event and then using the Twilio helper library to make the RESTful call to the Twilio servers. Of course you need to put your own values in for ACCOUNT_SID, AUTH_TOKEN, and CALLER_ID, which you can get from your Account page on the Twilio website.
Twilio will call the phone number you enter in the text box, and use a new page /appointment/reminder.aspx (which you have to create) as the “controller” for the outbound call.
Your reminder.aspx page should be blank (since you will be writing XML output, not HTML). Here’s the code-behind for reminder.aspx:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
using System; using System.Collections; using System.Xml; namespace Twilio.Web.appointment { public partial class reminder : System.Web.UI.Page { protected string Url = null; protected void Page_Load(object sender, EventArgs e) { Page.Response.ContentType = "text/xml"; this.Url = Page.Request.Url.GetLeftPart(UriPartial.Authority) + "/appointment/reminder.aspx"; if (Request["Digits"] != null) { DoAction(int.Parse(Request["Digits"].ToString())); } else { this.WriteReminder(); } } protected virtual void DoAction(int digit) { switch (digit) { case 3: { WriteGoodbye(); break; } case 2: { WriteDirections(); break; } default: { WriteReminder(); break; } } } protected virtual void WriteGoodbye() { this.WriteXmlToResponse("goodbye.xml", null); } protected virtual void WriteDirections() { this.WriteXmlToResponse("directions.xml", new string[1] { this.Url }); } protected virtual void WriteReminder() { this.WriteXmlToResponse("reminder.xml", new string[1] { this.Url }); } /// <summary> /// XML helper method /// </summary> protected virtual void WriteXmlToResponse(string fileName, string[] values) { System.Xml.XmlDocument doc = new XmlDocument(); string path = Server.MapPath(Page.Request.ApplicationPath) + @"\appointment\" + fileName; doc.Load(path); string xml = doc.OuterXml; xml = string.Format(xml, values); Response.Write(xml); } } } |
We’re using the same WriteXmlToResponse() helper method we created in our last demo. There are three output functions: WriteReminder(), WriteDirections(), and WriteGoodbye(), which correspond to the three choices the user can make when they receive the phone call.
Also note that we set the MIME content-type to “text/xml” in the first line of Page_Load().
Not much to it, is there?
To make this demo work, you’ll also need three XML files that contain the content to read to the user:
reminder.xml
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8" ?> <Response> <Gather action="{0}" numDigits="1"> <Say> Hello this is a call from Crowdify. You have an appointment tomorrow at 9 AM. </Say> <Say> Please press 1 to repeat this menu. Press 2 for directions. Or press 3 if you are done. </Say> </Gather> </Response> |
directions.xml
1 2 3 4 5 |
<?xml version="1.0" encoding="utf-8" ?> <Response> <Say>Your appointment is located on the top of Mount Everest.</Say> <Redirect>{0}</Redirect> </Response> |
goodbye.xml
1 2 3 4 |
<?xml version="1.0" encoding="utf-8" ?> <Response> <Say>Good bye.</Say> </Response> |
Note that in the first two XML files we are using the same String.Format() placeholders as in our previous demo.
That’s it – an end-to-end demo of using the Twilio REST API. The helper library that Twilio provides makes it really easy to get going in no time at all.
