1
votes

I have followed the instructions at,

https://www.twilio.com/blog/2016/04/receive-and-reply-to-sms-in-rails.html,

to try and send an SMS in rails 4.0. I have a trial account with a simple Rails controller as follows

class MessagesController < ApplicationController
  skip_before_filter :verify_authenticity_token
  # skip_before_filter :authenticate_user!, :only => "reply"

  def reply
    message_body = params["Body"]
    from_number = params["From"]
    boot_twilio
    sms = @client.messages.create(
      from: Rails.application.secrets.twilio_number,
      to: from_number,
      body: "Hello there, thanks for texting me. Your number is #{from_number}."
    )
  end

  private

  def boot_twilio
    account_sid = Rails.application.secrets.twilio_sid
    auth_token = Rails.application.secrets.twilio_token
    @client = Twilio::REST::Client.new account_sid, auth_token
  end
end

In MyAppName/config/secrets.yml, I have defined the SID and token. As per the tutorial, I am using ngrok to expose my application to the world. I have entered the URL from ngrok into Twilio's configuration as shown. I have verified the URL ngrok gave me by copying it into browser's URL. When I do, it opens my rails app at the home page.

The problem is that Twilio never routes the SMS to my rails app. Rather than responding to the SMS in my reply action, I get "Sent from your Twilio trial account - Hello from Twilio!". This is the Twilio response I got before I even wrote my Rails app. I should mention, I have

reply_messages POST /messages/reply(.:format) messages#reply

in my routing table

1

1 Answers

2
votes

Twilio developer evangelist here.

The problem is where you have entered your ngrok URL in the Twilio console. You've actually entered it in the box for a failover URL. If you take a look again you'll see that when a message comes in you are using the TwiML Bin called "SMS Getting Started TwiML" which is why you are still receiving your tutorial response.

You need to change the drop down on the left from "TwiML" to "Webhook" and then enter the URL in the input that appears.

On a second point, you are using the REST API to respond to the incoming message, but you could be doing it with TwiML instead. Just update your action to:

  def reply
    from_number = params["From"]

    resp = Twilio::TwiML::Response.new do |r|
      r.Message "Hello there, thanks for texting me. Your number is #{from_number}."
    end 

    render xml: resp.to_xml
  end

Let me know if that helps.