Luigi
Luigi

Reputation: 5603

Twilio post to url with params[:text_response] and params[:phone_number]

I am using ruby 2.0.0 and Rails 4.0.

I am sending a text message out via my rails app to my end user.

When they respond, I want to redirect them to an api call:

www.myapp.com/api/verify_text_response

Within that API call, I want to see what the text message sent from the end user to my url is. Ideally, I would receive a param of "text_response" that I could then do what I wanted to with.

How can I redirect a reply from my end_user to the above url, and capture the phone number it came from as well as the message sent to me in my params? If this isn't possible, how can I use TwiML to do something similar?

End Goal

For what it's worth, this is what I'm trying to accomplish:

  1. I send a text message out - "Would you like to subscribe?"
  2. The end user responds "Yes" or "No".
  3. I change the subscribed attribute on my subscription model to true or false.
  4. I send another text message saying either "You are subscribed." or "You are not subscribed.".

Item's #3 and #4 are based on the user responding "Yes" or "No" in item #2.

Upvotes: 0

Views: 147

Answers (1)

jvperrin
jvperrin

Reputation: 3368

The twilio guide here for Ruby is the most useful documentation out there. They recommend using the Twilio gem in your Rails application by adding the twilio-ruby gem to your Gemfile.

All you need to do to is add the following code to one of your controller's actions (the one that is routed to by www.myapp.com/api/verify_text_response:

def receive_text
  # Not exactly sure this is the right parameter, but it's easy to test
  sender_message = params[:Body]

  response = if (sender_message == "Yes")
    "You are subscribed."
  else
    "You are not subscribed."
  end

  twiml = Twilio::TwiML::Response.new do |r|
    r.Message(response)
  end
  twiml.text
end

To make your Rails application accessible to Twilio, follow the directions found on this page:

Copy and paste the URL of your server into the "SMS" URL of a number on the Numbers page of your Twilio Account. On the page for that number, change the Method from "POST" to "GET".

I wasn't exactly sure from looking at the documentation which parameter holds the user's response (I thought it was probably params[:Body]), but the best way to figure out is simply by printing out the parameters that the controller receives when you send a text message to your Twilio number.

Upvotes: 1

Related Questions