Simple Twilio Applications With Webscript

Wanting to write a simple Twilio app inspired us to create Webscript. We routinely marvel at how well Twilio and Webscript work together.

Today, I will demonstrate how to receive an SMS message and respond with an SMS message, and I will demonstrate how to receive a telephone call and respond with a synthesized voice message.

To start with, you will need a Twilio account. Fortunately, Twilio allows you to sign up for free. Once you sign up, you will get a phone number to use for your Twilio experiments.

Twilio has a very simple webhook-based model for handling an incoming SMS message or an incoming phone call. To handle the incoming event, Twilio will make an HTTP request to your web service. This, of course, is where Webscript comes in—it's trivial to handle these HTTP requests with a simple Lua script hosted on Webscript.

Of course, you must let Twilio know the URL for the webhook. To do this, you will need to click on "Configure your trial number" from the Dashboard. There, you can set the URLs for both voice calls and SMS messages. I've chosen and You also get the choice of whether those HTTP calls will be POSTs or GETs. I chose POSTs.

To start, I will make a simple script for handling an incoming SMS message. In response to the incoming message, my script will echo the message back to the sender:

return request.form.Body

This script makes use of the Twilio convention that the return value to its SMS webhook call can be a simple string to send back to the sender. (request.form.Body contains the SMS message that Twilio received and forwarded to the webhook.)

(You can try this by texting 203-774-5286.)

Twilio and Webscript also make handling incoming voice calls quite simple. As a simple example, we can have Twilio and Webscript work together to answer a call and respond with a synthesized, "Greetings from Webscript!". Unfortunately, this isn't quite as simple as the SMS example, but it's not far off. Twilio has a command language (TwiML) which you use to control its operation. In this case, there's a little boilerplate around a simple <Say> command that will synthesize a voice from text:

        [[<?xml version="1.0"?>
                <Say>Greetings from Webscript!</Say>
        </Response>]], {['Content-Type']='text/xml'}

Note that the script returns two values: the TwiML string, and the appropriate Content-Type header so that this is interpreted as XML.

(You can try this by calling 203-774-5286.)

I hope you agree that it's easy to create SMS and telephone apps with just a little bit of Twilio knowledge and Webscript. In the future, we'll demonstrate some more Twilio+Webscript examples.