Tracking Which Twilio Users Make Which Calls - ruby-on-rails

Problem: I'm unable to determine which of my Rails app's users are making which browser-to-browser calls using Twilio.
I am able to make browser to browser calls with Twilio and I am able to store the #call object in the Calls table like this:
def start_conference
#call = Call.create_from_twilio_params(params)
#call.user_id = current_user.id #current_user doesn't work in this Twilio request even when the user is signed into the Rails app
#call.save
end
Here are the parameters that Twilo app returns in the log when it processes a user's call:
TwilioController#start_conference as HTML
Parameters: {"AccountSid"=>"AC123", "ApplicationSid"=>"AP234", "Caller"=>"client:test", "CallStatus"=>"ringing", "Called"=>"", "To"=>"", "CallSid"=>"CAxyz", "From"=>"client:test", "Direction"=>"inbound", "ApiVersion"=>"2010-04-01"}
Is it possible to add my own parameters such as user_id? Or maybe there is another way for me to connect the call to the user?
From this StackOverflow question, it seems possible to attach parameters to the callback URL, but where is the Twilio documentation about specifying a custom callback URL?
Thank you!

Twilio developer evangelist here.
You can indeed pass more parameters around when making a call with Twilio Client.
When you call Twilio.Device.connect() to make the call you can pass an object with parameters in that will get POSTed to your controller. For example:
// In your front end code
Twilio.Device.connect({ userId: '<%= current_user.id %>' });
And then, in your controller code, you will receive that userId in the params and you could use it like this:
def start_conference
user_id = params.delete('userId')
#call = Call.create_from_twilio_params(params)
#call.user_id = user_id
#call.save
end
Let me know if this helps!

Related

Twilio security PIN for conference call

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.

instagram api ruby subscription tag post access object_id

the problem that i have is that when i post a picture on Instagram with the good hastag# of my subscription, i receive the notification in my callback but i can't access the object_id in the params. Here is the line that i receive :
Parameters: {"_json"=>[{"changed_aspect"=>"media", "object"=>"tag", "object_id"=>"mytag", "time"=>1439341303, "subscription_id"=>19499294, "data"=>{}}], "subscription"=>{}}
Here's my ruby code :
def process_subscription
if params["hub.challenge"]
render :text => params["hub.challenge"]
else
#test_tag_name = params["object_id"]
end
end
But the #test_tag_name is always to null.
Thank you very much
For those exact params, this would work: params["_json"][0]["object_id"]
But you'll probably need to adjust based on what params["_json"] will return in the general case (I'm not familiar with that API). For example, you should probably iterate over the array it returns rather than grabbing the first element.

Twilio API - getting the child call SID after Status Callback

I am using a TwiML App to establish a phone call via the browser.
I have a Status Callback URL in the APp that post the details of the child call.
The problem is, in the POST I only have the Parent Call ID, not the actual child call ID. How can I get it?
The post looks something like:
post: ApiVersion=2010-04-01&Called=&CallStatus=completed&Duration=1&From=client%3Akaren_calls&CallDuration=20&Timestamp=Mon%2C%2025%20May%202015%2020%3A48%3A22%20%2B0000&Direction=inbound&CallbackSource=call-progress-events&AccountSid=ACfxxxxxxxxxxxxxxxxxxx&ApplicationSid=xxxxxxxxxxxx&Caller=client%3Akaren_calls&SequenceNumber=0&To=&CallSid=CAxxxxxxxxxxxxxxxxxx
The "CallSid" above is for the parent call, not the child.
Twilio developer evangelist here.
You can get the child calls of a call by retrieving a list of calls from the REST API and filtering it by the parent call SID. You can see how you can filter calls in the documentation.
If you were doing this with the Ruby library, you would do the following:
require 'twilio-ruby'
# Fill in your account SID and auth token below
client = Twilio::REST::Client.new "ACxxxx", "XYzzzzz"
# Fill in the call SID below
child_calls = client.calls.list parent_call_sid: "CAxxxxx"
Let me know if this helps.

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

Resources