Text 425-967-8361 to Receive a Compliment: Using Twilio with Webscript

Last year, I built a fun website called The Flatterist (hosted on our web-hosting service, Site44), which delivers compliments to visitors. More recently, a friend and coworker of mine, Wade Wegner, built a phone-based interface to The Flatterist as part of a hackathon. (He won, by the way!) His app allowed someone to send a text message to The Flatterist and receive a compliment over a phone call in return.

Twilio makes it easy to initiate and respond to text messages and phone calls, but most Twilio operations require a web app with a public URL. Building a full web app is often overkill for this sort of thing, and logging and debugging failed operations isn't as easy as it could be (despite Twilio's excellent debugging interface).

This is where Webscript comes in. Webscript lets you write a short script right in the browser, receive web requests right away, and view the full log of every web request and any errors.

With Webscript, I managed to recreate Wade's phone interface for The Flatterist quite easily. Here's the script that receives a text message:

local twilio = require 'twilio'
local PHONENUMBER = '+14259678361'
if twilio.verify(request, AUTHKEY) then
        return 200
        return 403

The script makes use of our Twilio module. It first verifies that the incoming request truly came from Twilio by checking the signature. It then instructs Twilio to make an outbound call back to the sender of the text message. When Twilio makes calls, it needs a URL where it expects to retrieve instructions using an XML-based language called TwiML. The last parameter to twilio.call is that URL.

Here's the script that responds with TwiML:

local response = http.request {
local compliments = json.parse(response.content).compliments
return {['Content-Type']='application/xml'}, string.format(
[[<?xml version="1.0"?>
        compliments[math.random(1, #compliments)][1])

Every time this script is executed, it returns TwiML that instructs Twilio to play the MP3 for a random compliment. (The Flatterist exposes the list of available compliments as JSON.)

Give It a Try

The code for these scripts is also available on our examples page, and you can try it out for yourself by sending a text message to 425-967-8361.