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 = "https://media.giphy.com/media/13ZHjidRzoi7n2/giphy.gif" 
  else
    message = "Thanks for message number #{ session["counter"] }. From #{sender} saying #{body}"
    media = nil
  end
	
  # Build a twilio response object 
	# This will be sent back in XML 
  twiml = Twilio::TwiML::MessagingResponse.new do |r|
    r.message do |m|

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

×

Subscribe

The latest tutorials sent straight to your inbox.