Replying to SMS via Twilio API with Ruby on Rails 4.0 - ruby-on-rails

I'm having a tough time understanding Twilio. I've read the docs many many times and still couldn't get my app run. I'm writing a web app in Ruby on Rails (4.0) to get an SMS text from students and print them out on the website.
In the Gemfile I put
gem 'twilio-ruby'
Then I have a controller like this
class TwilioController < ApplicationController
def index
end
def sent_sms
account_sid = "I put my ID here"
auth_token = "I put my auth token here"
twilio_phone_number = "xxxxxxxxx"
message_body = params["Body"]
from_number = params["From"]
#client = Twilio::REST::Client.new(account_sid, auth_token)
#client.account.sms.messages.create(
from: "+1#{twilio_phone_number}",
to: "+1#{from_number}",
body: "Hey there! I got a text from you"
)
end
Now I don't know how to print out those messages gotten from students to the webpage. I spent 2 days on this and still can't figure it out. Also, I don't know what to put in the URL in Twilio account in this screenshot below. I deploy my app to Heroku though. Any advice is appreciated.
https://www.dropbox.com/s/zxbyw6j5te8ipgp/Screen%20Shot%202014-04-12%20at%203.43.18%20PM.png

Twilio evangelist here.
Let me start clarify whats your trying to do. From the code above it looks like you want to receive a text message from your students and then send them back a simple response. You also want to print out the text messages that you've received? Hopefully I've got that right. If I do, lets start with receiving messages and sending a reply.
When a student sends a text message to your Twilio phone number, Twilio will receive that message and make an HTTP request to whatever URL you have set in the Messaging URL. Based on the Rails code in your post, it looks like that URL is going to be something like:
http://[yourdomain].com/Twilio/send_sms
Now, if you want to send a SMS message the student who sent you a message, you just need to generate and return some TwiML containing the <Message> verb from the send_sms function. That would look something like this:
twiml = Twilio::TwiML::Response.new do |r|
r.Message "Hey there! I got a text from you."
end
twiml.text
If you loaded the send_sms route in a browser you should see that your Rails app outputs some TwiML that looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Message>Hey there! I got a text from you.</Message>
</Response>
This code came from the "Replying to an SMS" quickstart which has a ton of great info in it. Another great resource for getting started with receiving text messages using Rails is this fantastic blog post.
OK, so now you've had a bunch of students send some text messages to you and you want to create a page in your Rails app to display them. For this you're going to need to use the REST API. This sample from the docs shows how to use the Ruby helper library to get a list of messages from Twilio. You can pass the list you get back from Twilio to your Rails view where you can loop over it outputting whatever HTML elements you want to use to display the SMS attributes.
Hop that helps.

Related

How do I dynamically generate TwiML from my Rails app?

I have integrated Twilio through twilio-ruby
with my Rails app. The basic SMS and voice capabilities are working as expected, but now I want to extend my functionality. I would like to be able to generate TwiML in my controller dynamically, save it somewhere (either locally or to a service), and then have Twilio access this XML. For example, a customer makes an order through my app, TwiML is generated and saved, and then Twilio makes a voice call to my supplier with the new order data. Keeping concurrent orders in mind, what might the solution look like for this? What is the best solution for storing the TwiML/XML and then having Twilio access it? Thank you.
Dynamically generating the TwiML during the call does seem like it would be the preferred method.
An example of generating TwimL content dynamically from the docs where we greet a caller by name:
https://www.twilio.com/docs/quickstart/ruby/twiml/greet-caller-by-name#twiml-quickstartrb
require 'rubygems'
require 'sinatra'
require 'twilio-ruby'
get '/hello-monkey' do
people = {
'+14158675309' => 'Curious George',
'+14158675310' => 'Boots',
'+14158675311' => 'Virgil',
'+14158675312' => 'Marcel',
}
name = people[params['From']] || 'Monkey'
Twilio::TwiML::Response.new do |r|
r.Say "Hello #{name}"
end.text
end
Instead of a people array your application would have to parse incoming message bodies (if using SMS) for the order and then make the appropriate call to the supplier.
If however, your use case truly requires creating hosted TwiML on the fly, TwiML Bins in the Twilio Console will soon allow you to do this with interpolation.
That means you would be able to do something like:
curl -X POST api.twilio.com/..../Calls -d 'Url=https://hander.twilio.com/EHxxx?message=hello+world' -u Cxxx:yyyy
And your TwiML Bin would contain the necessary TwiML:
<Response><Say>{{message}}</Say></Response>
This way, you would not need to make two rest calls and wouldn't amass thousands (or more) of redundant bins that will be unwieldy to maintain or clean up.

RoR Twilio Texting App - Cannot get Twilio to send SMS. No error message

Update: Thanks to everyone for their suggestions. I tried everything, but nothing worked until I updated my credentials (my API, token, and phone number) to be the production credentials. And now I can receive text messages, even though the text messages confusingly say they have been sent from trial account. I'm happy the app is working, but bewildered as to why production credentials work when test credentials do not. If anyone has an idea, let me know.
I'm using RoR to create a web app that sends a text message to a phone number, using the Twilio API. Because I don't know what I'm doing, I'm following the instructions here:
https://www.sitepoint.com/adding-sms-capabilities-to-your-rails-app/
which are super great, but also written 4 years ago. I noticed that Twilio uses a different resource URI (Messages vs SMS/Messages), and I've tried to adjust the code to reflect this update, but I think I'm still missing something, because I'm not receiving any text messages. And yes, the phone number I'm using is 100% verified.
Even more perplexing, neither my console nor the Twilio SMS logs are giving me any error messages. The console output looks something like this:
(42.6ms) commit transaction
Rendered text template (0.0ms)
Completed 200 OK in 710ms (Views: 0.4ms | ActiveRecord: 42.9ms)
which looks pretty chill to me. And there's not even an entry in the log. Here's what my controller looks like:
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(params[:user])
if #user.save
render text: "Thank you! You will receive an SMS shortly with verification instructions."
# Instantiate a Twilio client
client = Twilio::REST::Client.new(TWILIO_CONFIG['sid'], TWILIO_CONFIG['token'])
# Create and send an SMS message
client.account.messages.create(
from: TWILIO_CONFIG['from'],
to: #user.phone,
body: "Thanks for signing up. To verify your account, please reply HELLO to this message."
)
else
render :new
end
end
end
Specifically, I tried changing client.account.messages.create() from client.account.sms.messages.create(), to no avail. I also tried changing it to client.account.sms.messages.sendMessage(), but I got an error telling me the method was undefined.
Anywayyyy, can anyone give me a hint as to how to troubleshoot? This is the only piece of code I've changed, so maybe I have to alter something else?
Thanks in advance. :)
P.S. Why do the ends at the end of my code look so screwy? They don't look like that in Sublime.
what happens if you do something like:
#config/initializers/twilio.rb
#move your TWILIO_CONFIG initialization here
TwilioClient = Twilio::REST::Client.new(TWILIO_CONFIG['sid'], TWILIO_CONFIG['token'])
#models/user.rb
class User
after_create :send_verification_message #best done with a background worker
def send_verification_message
TwilioClient.account.messages.create(
from: TWILIO_CONFIG['from'],
to: phone,
body: "Thanks for signing up. To verify your account, please reply HELLO to this message."
)
end
end
end
You can then remove the one defined in the controller. I believe with this, you should either be able to send the messages or see the errors returned
try this:
paste it into your controller
def twilio_client
Twilio::REST::Client.new(ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN'])
end
    def send_otp
      twilio_client.messages.create(to: 'phone_number', from: 'twilio_phone_no', body: "temporary identification code when prompted." )
    end
set from field as per your twilio account and set to fild to client phone no "+4563217892"
and call controller send_otp method.
for more information check this link:
http://rubyonrailsdocs.blogspot.com/2016/05/twilio-application-step-by-step-process.html
Kira,
Take a look at Why aren't my test credentials working? regarding your update.
With the proper credentials, I'd suggest trying an updated tutorial SMS notifications in Ruby and Rails where the send_message function looks like this:
def send_message(phone_number, alert_message, image_url)
#twilio_number = ENV['TWILIO_NUMBER']
#client = Twilio::REST::Client.new ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN']
message = #client.account.messages.create(
:from => #twilio_number,
:to => phone_number,
:body => alert_message,
# US phone numbers can make use of an image as well.
# :media_url => image_url
)
puts message.to
end
Take a look at the full code in the tutorial and let me know if it helps at all.
I just wanted to follow up on this - I authored the question. It turns out that you can't test in this manner with Twilio's test credentials. As outlined in the Twilio documentation, https://support.twilio.com/hc/en-us/articles/223183808-Why-aren-t-my-test-credentials-working-:
Although Twilio will provide test credentials for users to exercise parts of the Twilio REST API, these cannot be used to send messages or make a phone call. This is why my app worked when I used production credentials. I wasn't charged for using these production credentials (I think you must get a couple of freebies).
For the record, the code I followed from that tutorial is correct, with the exception of the deprecated .sms endpoint mentioned in the original question. That did have to be altered.

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:
I send a text message out - "Would you like to subscribe?"
The end user responds "Yes" or "No".
I change the subscribed attribute on my subscription model to true or false.
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.
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.

Rails 3 and Twilio to do phone verification

I am building an app in Rails 3, using twilio to verify a businesses existance. Basically, when you create a new buisiness I randomly generate a 6 digit number and then call the business phone number with this verification code and the user needs to enter it back in the system to finish the signup process. I am having trouble finding any relevant examples as to how to get this set up. I've found this, but it seems horribly outdated and doesn't work with Rails 3 seemingly. The documentation for the twilio-rb gem is confusing as well.
Does anyone know of any examples or have any code samples that could point me in the right direction?
As I said in the comment on your question itself, I am the author of the twilio-rb gem you mention. Off the top of my head, I would implement a verifications resource that you post a telephone number to.
POST /verifications.voice { telephone_number: '+12125551234' }
In the create action use Twilio::Call.create to create a new call with Twilio
def create
#verification = Verification.new params[:verification]
if #verification.save
Twilio::Call.create to: #verification.telephone_number,
from: YOUR_CALLER_ID, url: verification_url(#verification, format: :voice)
# 201 created and return verification code etc
else
# Handle errors
end
end
You will also want to rescue any API errors that twilio-rb might raise. The url refers to the show action of the verification resource instance. Twilio will then dial the supplied telephone number, and when the call is connected will request the url, e.g. GET /verifications/1.voice so you'll need a show view that asks for the verification code and collects the digits with the <Gather> verb:
res.gather num_digits: 4, action: twilio_hack_verification_url(#verification, :format => :voice), method: 'POST' do |form|
form.say 'Please enter the your 4 digit verification code'
end
Since Twilio currently does not implement the PUT verb, you'll to add a member to your resource
resources :verifications do
member { post 'twilio_hack' }
end
Then in your controller update the object with the user input:
def twilio_hack
#verification = Verification.find(params[:id]).tap do |v|
v.user_input params['Digits']
v.save
end
if #verification.confirmed?
# handle success
else
# handle failure
end
end
Finally in your model you'll need code that generates the verification code, and verifies if it is confirmed
class Verification < ActiveRecord::Base
before_save -> { self[:confirmed] = true if user_input == verification_code }, if: user_input
before_create -> { self[:verification_code] = rand.to_s[2..5] }
end
This is all untested and off the top of my head with about 2 minutes thought, but it should get you started.
When you wish to verify a Business:
Generate a verification code.
Use the Twilio REST API to initiate an outbound call, passing a URL for a callback to a controller which will handle the verification logic. Docs at Twilio are here and an example is here.
This means that you need to pass the verification code into your controller via the callback URL. Use a non-resourceful route with a bound parameter. See here.
Write a controller that handles the call and processes the verification:
Emit TwiML that challenges the user to enter the verification code. I have found using Nokogiri to build the TwiML myself to be the most straightforward approach. (See the method phone_greeting in this simple app I wrote: here.)
If it's correct, flag the Business as verified, congratulate the user, and hang up.
If not, loop.
Hopefully that's enough information to point you in the right direction.
Have you considered using Twilio's Outgoing Caller IDs to help solve this problem?
When calling Twilio over REST to add a new caller id to your account, Twilio will return a 6 digit verification code (property ValidationCode) for you to display in your UI, and then Twilio will automatically call the number and prompt for the code. When the user verifies the number over the phone, their number will be added to your account's caller ids. You can then query Twilio for their phone number over REST (parameter PhoneNumber) to ensure the verification was successful.
See here for documentation:
Add a caller id: http://www.twilio.com/docs/api/rest/outgoing-caller-ids#list-post
Find a caller id: http://www.twilio.com/docs/api/rest/outgoing-caller-ids#list

How do I visit a url in rails

Im working on a small project which I need to send a couple of parameters to another server which has a web service for sending of SMS messages. I'm constructing the URL by calling a method on my controller like so,
...
send_sms(number,message)
sms_url = "http://sms-machine.xx.xx/sendsms/" + number + "/" + message
#go to the url above
end
The resulting page will be a delivery message from the server with either a "NO" or "YES" to show if the message was sent. It is important for the users to know if the sms message was sent or not. So my question is how do I visit the sms url. Is there such a go_to_url function in rails?
You can use Ruby's Net::HTTP or the much simpler open-uri functionality, eg:
require 'open-uri'
status = open("http://sms-machine.xx.xx/sendsms/#{number}/#{message}").read
Net:HTTP is loaded by default.
You can use the standard net/http library to make your own HTTP requests: http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/index.html

Resources