Get Started

Sending SMS Messages in Phone Call

Sending text messages during a phone call is a useful way to give users content for offline reference, or even confirm an sms subscription.

In this demonstration, we are going to describe how to build an application that can initiate an SMS message from a phone call.

If you haven't already, take a look through the Twilio SMS Quickstart which explains in further detail all the functionality available in Twilio's SMS API.

This demo is written in Python for Google App Engine. This code can be adapted for other Python web frameworks such as Django.

Concepts

This demo utilizes TwiML, with a focus on the <SMS> verb.

A Caller will dial into a Twilio number and be prompted to confirm their subscription. Once they confirm their sms subscription, a confirmation SMS message will be sent back to them.

If you have further questions about Twilio SMS be sure to check out the faq.

Download

sms-phone.zip

Implementation

  • 1

    • When a call is answered by Twilio, Twilio fetches the '/' page which is configured to query the GatherPage object.

  • 2

    • The GatherPage object contains two methods get() and post() which map to the same function and return a page generated by the template gather.xml

      • howtos/sms-phone/sms-phone.py
        def xml_response(handler, page, templatevalues=None):
            """
            Renders an XML response using a provided template page and values
            """
            path = os.path.join(os.path.dirname(__file__), page)
            handler.response.headers["Content-Type"] = "text/xml"
            handler.response.out.write(template.render(path, templatevalues))
        
        class GatherPage(webapp.RequestHandler):
            """
            Initial user greeting.  Prompts the user to confirm their SMS
            subscription.  Say is wrapped in a Gather verb to collect a digit 
            from the caller.  The Gather will post the results to /confirm
            """
            def get(self):
                self.post()
            
            def post(self):
                templatevalues = {
                    'postprefix': BASE_URL,
                }
                xml_response(self, 'gather.xml', templatevalues)
            

      Here is the template used to render the initial TwiML greeting. Twilio then prompts the caller to confirm their subscription by pressing 1.

      • howtos/sms-phone/gather.xml
        <?xml version="1.0" encoding="UTF-8"?>
        <Response>
            <Gather method="POST" numDigits="5" action="confirm">
                <Say>Please confirm your SMS subscriptiong by pressing 1.</Say>
            </Gather>
        </Response>
            
  • 3

    • When the caller confirms their subscription, Twilio performs an HTTP POST with the results back to the 'action' handler. The 'action' handler is 'http://sms-phone.appspot.com/confirm' in the current application.

      If the caller pressed 1, the phone number is added to the list of subscribed callers.

      • howtos/sms-phone/sms-phone.py
            def post(self):
                tplvars = {}
                confirm = self.request.get('Digits')
                if not confirm:
                    self._error("We could not confirm your subscription.", BASE_URL)
                    return
                
                # strip off extra digits and keys from the Digits we got back
                confirm = confirm.replace('#', '').replace('*', '')[:1]
                if confirm != "1":
                    self._error("We could not confirm your subscription.", BASE_URL)
                    return
        
                subscriber = Subscriber()
                subscriber.number = self.request.get('Caller')
                subscriber.put()
        
                xml_response(self, 'confirm.xml', tplvars)
            
  • 4

    • The final response is generated and sends back a confirmation sms. You can see that an verb can be embedded in the phone call with and other verbs.

      • howtos/sms-phone/confirm.xml
        <?xml version="1.0" encoding="UTF-8"?>
        <Response>
            <Say>Thank you for subscribing, you should receive a confirmation message in a moment.</Say>
            <Sms>
        	Thank you for subscribing.  This message confirms your subscription to http://sms-phone.appspot.com.  
        
        	This is an example SMS response from twilio.com.
            </Sms>
            <Say>Goodbye</Say>
            <Hangup/>
        </Response>
            

      Twilio sends an SMS with the text specified to the caller.

      And that's it! The rest of the code is input validation and error handling.

Other examples

For an overview of all the Twilio SMS API features, take a read through the SMS Quickstart