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.
Related
I am using twilio gem for making calls in my rails app. Everything is working fine, now I want to add a conference functionality(adding conference functionality is easy) which should ask for pin before joining call, I don't want to add PIN logic manually. If suppose I will add code for entering PIN, how twilio will work to add all those clients to conference who entered PIN correctly. Does twilio support any thing like this? Any body have any idea about this kind of functionality?
Twilio developer evangelist here.
The URL that usha shared is a good start for adding PIN functionality for conferences. There's no automatic way to do it, you need to use a combination of <Gather> and your own logic for the correct PIN to make this work.
In Rails that might look a bit like this:
Initial webhook for incoming calls to the conference number:
def start_conference
response = Twilio::TwiML::VoiceResponse.new
response.gather(:action => conference_gather_url, :num_digits => 4) do |gather|
gather.say("Please enter the code for the conference", :voice => 'alice')
end
return :xml => response.to_xml
end
In this example, when the user enters 4 digits the call will automatically cause a request to the conference_gather_url with the digits that were entered sent as the Digits parameter in the body of the request.
Then the action needs to check that the PIN is correct and allow access to the conference if it is. I have included a pin_is_correct? method below, it is up to you to implement this.
def conference_gather
pin = params["Digits"]
response = Twilio::TwiML::VoiceResponse.new
if pin_is_correct?(pin)
response.dial do |dial|
dial.conference("CONFERENCE_NAME")
end
else
response.say("Your pin was incorrect. Goodbye.")
response.hangup
end
return :xml => response.to_xml
end
Let me know if that helps at all.
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.
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.
I need to implement messaging feature. When I send message to any user from my rails app then it also goes to users email. But what I need to implement if user who got the email make reply from gmail,yahoo..etc then the reply should also come into rails app. could anyone guide me some way.. so I can search it on google.
For Example:
If I send email to user from this email "mc-6bckm434ls#reply.xyz.com" and user replied on gspq5diedss#reply.xyz.com which I set Reply-To in header. Then I need user's reply in my rails application so that I can add this user's reply into my messaging thread.
By this feature which I want to implement User do not need to login in my application to do message, user can do message on current conversation via email reply also.
Since you tagged the question SendGrid, I'm assuming you're using it. You can use SendGrid's Inbound Parse Webhook to handle parsing incoming messages.
We also have a recent tutorial that goes through using the webhook in a rails app: http://sendgrid.com/blog/two-hacking-santas-present-rails-the-inbound-parse-webhook/
It's possible !
You can use mailman for example.
All you have to do is set a Reply-To header in your e-mail to make it unique, so when you fetch messages you know to what it corresponds.
For example, let's say you own the e-mail address foo#bar.com
You could send e-mails with a reply-to header "foo+content_id#bar.com", so you know what the user is replying to.
Then, mailman can fetch the messages from the mailbox and parse the content id in them.
Some services do that as well, handling all the emailing part and sending you notifications for incoming e-mails, for example, postmark
Ruby on Rails introduced Action Mailbox in version 6.0
With ActionMailbox you can easily configure rules where to route incoming emails (examples from the documentation):
# app/mailboxes/application_mailbox.rb
class ApplicationMailbox < ActionMailbox::Base
routing /^save#/i => :forwards
routing /#replies\./i => :replies
end
And how to handle specific messages in a mailbox:
# app/mailboxes/forwards_mailbox.rb
class ForwardsMailbox < ApplicationMailbox
# Callbacks specify prerequisites to processing
before_processing :require_forward
def process
if forwarder.buckets.one?
record_forward
else
stage_forward_and_request_more_details
end
end
private
def require_forward
unless message.forward?
# Use Action Mailers to bounce incoming emails back to sender – this halts processing
bounce_with Forwards::BounceMailer.missing_forward(
inbound_email, forwarder: forwarder
)
end
end
def forwarder
#forwarder ||= Person.where(email_address: mail.from)
end
def record_forward
forwarder.buckets.first.record \
Forward.new forwarder: forwarder, subject: message.subject, content: mail.content
end
def stage_forward_and_request_more_details
Forwards::RoutingMailer.choose_project(mail).deliver_now
end
end
Find the documentation about how to configure Action Mailbox and some examples in the Rails Guides.
See https://github.com/titanous/mailman/blob/master/USER_GUIDE.md
There is a railscast about using the gem but its pay-only :-/ http://railscasts.com/episodes/313-receiving-email-with-mailman,
however, there is the github repo from the railscast which can showcase you an example app that uses mailman (with before & after so you can track the changes) - https://github.com/railscasts/313-receiving-email-with-mailman
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