Responding to Incoming SMS

To make your Sinatra application respond to incoming SMS commands is pretty easy. Earlier you mapped your Twilio number to an endpoint GET /sms/incoming. Now we just need to add information to hook that up.

Create or modify the route definition to look like the following:

get "/sms/incoming" do 
	# sessions work with Twilio 
	session["counter"] ||= 1
	# Get the incoming SMS message content i.e. Body
	# and the who the SMS is From 
  body = params[:Body] || ""
  sender = params[:From] || ""

	# respond with a Media URL 
	# only if it's the first message 
  if session["counter"] == 1
    message = "Thanks for your first message. From #{sender} saying #{body}"
    media = "" 
    message = "Thanks for message number #{ session["counter"] }. From #{sender} saying #{body}"
    media = nil
  # Build a twilio response object 
	# This will be sent back in XML 
  twiml = do |r|
    r.message do |m|

      # add the text of the response
      m.body( message )
      # add media if it is defined
      unless media.nil? media )
  # increment the session counter
  session["counter"] += 1
  # send a response to twilio 
  content_type 'text/xml'



The latest tutorials sent straight to your inbox.