Giter Site home page Giter Site logo

twilio-ruby's Introduction

twilio-ruby

Tests Gem Version Learn with TwilioQuest

Documentation

The documentation for the Twilio API can be found here.

The individual releases here.

Versions

twilio-ruby uses a modified version of Semantic Versioning for all changes. See this document for details.

Supported Ruby Versions

This library supports the following Ruby implementations:

  • Ruby 2.4

  • Ruby 2.5

  • Ruby 2.6

  • Ruby 2.7

  • Ruby 3.0

  • Ruby 3.1

  • Ruby 3.2

  • JRuby 9.2

  • JRuby 9.3

  • JRuby 9.4

Migrating from 5.x

Upgrade Guide

Installation

To install using Bundler grab the latest stable version:

gem 'twilio-ruby', '~> 7.2.3'

To manually install twilio-ruby via Rubygems simply gem install:

gem install twilio-ruby -v 7.2.3

To build and install the development branch yourself from the latest source:

git clone [email protected]:twilio/twilio-ruby.git
cd twilio-ruby
make install

Info If the command line gives you an error message that says Permission Denied, try running the above commands with sudo.

For example: sudo gem install twilio-ruby

Test your installation

To make sure the installation was successful, try sending yourself an SMS message, like this:

require "twilio-ruby"

# Your Account SID and Auth Token from console.twilio.com
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"

@client = Twilio::REST::Client.new account_sid, auth_token
message = @client.messages.create(
  body: "Hello from Ruby",
  to: "+12345678901",  # Text this number
  from: "+15005550006", # From a valid Twilio number
)

puts message.sid

Warning It's okay to hardcode your credentials when testing locally, but you should use environment variables to keep them secret before committing any code or deploying to production. Check out How to Set Environment Variables for more information.

Usage

Authenticate the Client

require 'twilio-ruby'

# Your Account SID and Auth Token from console.twilio.com
account_sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth_token = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'

# Initialize the Twilio Client with your credentials
@client = Twilio::REST::Client.new account_sid, auth_token

Use An API Key

require 'twilio-ruby'

# Your Account SID from console.twilio.com
account_sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# API Key from twilio.com/console/project/api-keys
api_key_sid = 'zzzzzzzzzzzzzzzzzzzzzz'
api_key_secret = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'

# set up a client to talk to the Twilio REST API using an API Key
@client = Twilio::REST::Client.new api_key_sid, api_key_secret, account_sid

Specify a Region and/or Edge

To take advantage of Twilio's Global Infrastructure, specify the target Region and/or Edge for the client:

# set up a client to talk to the Twilio REST API over a specific region and edge
@client = Twilio::REST::Client.new account_sid, auth_token, nil, 'au1'
@client.edge = 'sydney'

# you may also specify the region and/or edge after client creation
@client = Twilio::REST::Client.new account_sid, auth_token
@client.region = 'au1'
@client.edge = 'sydney'

This will result in the hostname transforming from api.twilio.com to api.sydney.au1.twilio.com.

Make a Call

@client.calls.create(
  from: '+14159341234',
  to: '+16105557069',
  url: 'http://example.com'
)

Send an SMS

@client.messages.create(
  from: '+14159341234',
  to: '+16105557069',
  body: 'Hey there!'
)

List your SMS Messages

@client.messages.list(limit: 20)

Fetch a single SMS message by Sid

# put the message sid you want to retrieve here:
message_sid = 'SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
@client.messages(message_sid).fetch

Iterate through records

The library automatically handles paging for you. Collections, such as calls and messages, have list and stream methods that page under the hood. With both list and stream, you can specify the number of records you want to receive (limit) and the maximum size you want each page fetch to be (page_size). The library will then handle the task for you.

list eagerly fetches all records and returns them as a list, whereas stream returns an enumerator and lazily retrieves pages of records as you iterate over the collection. You can also page manually using the page method.

For more information about these methods, view the auto-generated library docs.

require 'twilio-ruby'

account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'

@client = Twilio::REST::Client.new(account_sid, auth_token)

@client.calls.list
       .each do |call|
         puts call.direction
       end

Enable Debug logging

In order to enable debug logging, pass in a 'logger' instance to the client with the level set to at least 'DEBUG'

@client = Twilio::REST::Client.new account_sid, auth_token
myLogger = Logger.new(STDOUT)
myLogger.level = Logger::DEBUG
@client.logger = myLogger

@client = Twilio::REST::Client.new account_sid, auth_token
myLogger = Logger.new('my_log.log')
myLogger.level = Logger::DEBUG
@client.logger = myLogger

Handle Exceptions {#exceptions}

If the Twilio API returns a 400 or a 500 level HTTP response, the twilio-ruby library will throw a Twilio::REST::RestError. 400-level errors are normal during API operation (“Invalid number”, “Cannot deliver SMS to that number”, for example) and should be handled appropriately.

require 'twilio-ruby'

account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'

@client = Twilio::REST::Client.new account_sid, auth_token

begin
  messages = @client.messages.list(limit: 20)
rescue Twilio::REST::RestError => e
  puts e.message
end

Debug API requests

To assist with debugging, the library allows you to access the underlying request and response objects. This capability is built into the default HTTP client that ships with the library.

For example, you can retrieve the status code of the last response like so:

require 'rubygems' # Not necessary with ruby 1.9 but included for completeness
require 'twilio-ruby'

# Your Account SID and Auth Token from console.twilio.com
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'

@client = Twilio::REST::Client.new(account_sid, auth_token)

@message = @client.messages.create(
  to: '+14158675309',
  from: '+14258675310',
  body: 'Ahoy!'
)

# Retrieve the status code of the last response from the HTTP client
puts @client.http_client.last_response.status_code

Customize your HTTP Client

twilio-ruby uses Faraday to make HTTP requests. You can tell Twilio::REST::Client to use any of the Faraday adapters like so:

@client.http_client.adapter = :typhoeus

To use a custom HTTP client with this helper library, please see the advanced example of how to do so.

To apply customizations such as middleware, you can use the configure_connection method like so:

@client.http_client.configure_connection do |faraday|
  faraday.use SomeMiddleware
end

Get started With Client Capability Tokens

If you just need to generate a Capability Token for use with Twilio Client, you can do this:

require 'twilio-ruby'

# put your own account credentials here:
account_sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth_token = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'

# set up
capability = Twilio::JWT::ClientCapability.new account_sid, auth_token

# allow outgoing calls to an application
outgoing_scope = Twilio::JWT::ClientCapability::OutgoingClientScope.new 'AP11111111111111111111111111111111'
capability.add_scope(outgoing_scope)

# allow incoming calls to 'andrew'
incoming_scope = Twilio::JWT::ClientCapability::IncomingClientScope.new 'andrew'
capability.add_scope(incoming_scope)

# generate the token string
@token = capability.to_s

There is a slightly more detailed document in the Capability section of the wiki.

Generate TwiML

To control phone calls, your application needs to output TwiML.

You can construct a TwiML response like this:

require 'twilio-ruby'

response = Twilio::TwiML::VoiceResponse.new do |r|
  r.say(message: 'hello there', voice: 'alice')
  r.dial(caller_id: '+14159992222') do |d|
    d.client 'jenny'
  end
end

# print the result
puts response.to_s

This will print the following (except for the whitespace):

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Say voice="alice">hello there</Say>
  <Dial callerId="+14159992222">
    <Client>jenny</Client>
  </Dial>
</Response>

Docker Image

The Dockerfile present in this repository and its respective twilio/twilio-ruby Docker image are currently used by Twilio for testing purposes only.

Getting help

If you need help installing or using the library, please check the Twilio Support Help Center first, and file a support ticket if you don't find an answer to your question.

If you've instead found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo!

twilio-ruby's People

Contributors

alexpayment avatar andrewmbenton avatar carlosdp avatar childish-sambino avatar cjcodes avatar claudiachua avatar codejudas avatar dougblack avatar ekarson avatar eshanholtz avatar ilanbiala avatar jennifermah avatar jingming avatar jmctwilio avatar joshbuddy avatar karlfreeman avatar karthiks avatar kridai avatar manisha1997 avatar philnash avatar ryan-rowland avatar sbansla avatar shwetha-manvinkurke avatar skimbrel avatar thinkingserious avatar tiwarishubham635 avatar tmconnors avatar toreyheinz avatar twilio-ci avatar twilio-dx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

twilio-ruby's Issues

ArgumentError in twilio-ruby/rest/client.rb:223

ArgumentError: wrong number of arguments (3 for 2)
...
/gems/multi_json-1.7.2/lib/multi_json/adapter.rb:37:in block in collect_options' /gems/multi_json-1.7.2/lib/multi_json/adapter.rb:37:inmap'
/gems/multi_json-1.7.2/lib/multi_json/adapter.rb:37:in collect_options' /gems/multi_json-1.7.2/lib/multi_json/adapter.rb:29:incollect_load_options'
/gems/multi_json-1.7.2/lib/multi_json/adapter.rb:19:in load' /gems/multi_json-1.7.2/lib/multi_json.rb:120:inload'
/gems/twilio-ruby-3.9.0/lib/twilio-ruby/rest/client.rb:223:in connect_and_send' /gems/twilio-ruby-3.9.0/lib/twilio-ruby/rest/client.rb:165:inblock (2 levels) in class:Client'
/gems/twilio-ruby-3.9.0/lib/twilio-ruby/rest/list_resource.rb:82:in `create'
from (irb):193
...

However, the message is successfully sent.

Handling Call Errors

Is there any way to handle errors during a call? Ideally, I would like to prevent "We're sorry, but an application error has occurred. Goodbye!", and catch it in my application before that happens.

error in example.rb

As-is you'll, get an uninitialized constant Account_SID (NameError)

The fix is near the end of the file:

resp = account.request("/#{API_VERSION}/Accounts/#{Account_SID}/SMS/Messages",
"POST", t)

should be

resp = account.request("/#{API_VERSION}/Accounts/#{ACCOUNT_SID}/SMS/Messages",
"POST", t)

Get (sub)account by friendly name? Returns all accounts

Should it be possible to return only a single sub account for a valid friendly name? Trying to use ruby client (3.9.0) and the web api explorer they both return all my (sub)accounts even when a valid friendly name is passed as below.

client.accounts.list({:friendly_name => "test"}).total

still return 4 in my case.

Weird issue with updating queued calls

I'm trying to update a queued call resource to a different URL. When I fetch the queued call resource using calls.get("C1234") and issue an update or redirect_to on the object, it all works fine and the call is redirected perfectly. No issues there.
The real issue happens when i fetch the call using queues.get(queue_sid).members.get("C1234") and then issue an
update(:url => "http://example.com/new_twiml_now"). I get this

Twilio::REST::RequestError (Bad request):
/Library/Ruby/Gems/1.8/gems/twilio-ruby-3.9.0/lib/twilio-ruby/rest/client.rb:226:in connect_and_send' /Library/Ruby/Gems/1.8/gems/twilio-ruby-3.9.0/lib/twilio-ruby/rest/client.rb:165:inpost'

The same new URL to which I'm trying to redirect worked fine in case of a direct fetch from Call list resource as in the first scenario. Only on queued call update, this issue happens. I even tried alternating between GET and POST.

API Version

I noticed in the upgrade guide https://github.com/twilio/twilio-ruby/wiki/UpgradeGuide

there is no mention of API selection. Is it safe to assume all API calls through the library will use 2010 instead of 2008 API versions?

reason, I ask is our twilio account defaults to 2008, so we've always had to be explicit about it, but I don't see anyway to do so here.

Thanks!

Offer to_json or to_hash. Some way to dump to a database, basically.

Using the rest API through this gem, I can't seem to be able to access any kind of "parameter dump" from the responses.

Specifically I am playing with the SMS API.

message = client.account.sms.messages.create({...})

# Keep the full response so that I can investigate any unexpected data
DatabaseLogModel.create({..., raw_response: message.what?, ...})

I cannot see any support in InstanceResource to get at the params has that is passed in on creation. Is there a way I'm not seeing?

Why am I not content with just calling all known methods to build a hash?

The word known there is significant. Our app supports SMS transactions using around 10 different "aggregators". All with very different APIs and status codes. I therefore parse out and conform Twilio response info into our generic internal format.

But. I want to capture the full response so that I have a record of all that was returned. This helps when I catch an "error-object" from the API that I did not expect. It helps when I, 3 months from now, realize I have been parsing something the wrong way....

Just the raw "params" as an attr_reader would be enough for me, but I guess a de-twillified version would possibly be more generally useful. I forked and made this specific thing to illustrate what I'd like to see.
eimermusic@b087990

I did not make it a pull request because...

  1. I made such a limited change and supporting parameter "dumps" in general will probably require something similar code elsewhere (unfamiliar to me)
  2. This may be completely agains t the spirit and intentions of your client API.

NoMethodError: undefined method `[]' for nil:NilClass

NoMethodError: undefined method `[]' for nil:NilClass
/Users/matthooks/.rbenv/versions/2.0.0-p0/gemsets/prettyquick/gems/twilio-ruby-3.9.0/lib/twilio-ruby/rest/list_resource.rb:83:in `create'
/Users/matthooks/Projects/polymathic/pretty-quick/lib/twilio_interface.rb:9:in `sms'

https://github.com/twilio/twilio-ruby/blob/master/lib/twilio-ruby/rest/list_resource.rb#L83

I'm getting this exception intermittently. It looks like the response is nil?

sms status get in gem?

It's unclear how to view the status of a sent SMS, using the gem. Please update readme or add a method for viewing SMS status. thank you for this gem.

Request for test mode

Great gem, very useful but its hard to put into TDD since its fairly complex. Generally other gems like this (i.e. clickatell's gem) include a method to emulate the API so that one can run tests but not hit there account. Any chance of getting that implemented here?

Iteration using list() doesn't iterate over all items

Hi,

I'm trying to figure out whether I'm using the API wrong or if I've found a bug.

When I use list() on the calls resource and check its total, the API reports 105 items:

2.0.0-p195 :002 > "total items: #{@client.account.calls.list('start_time>' => '2013-10-01').total}"
 => "total items: 105"

However, when I iterate over that list using each, list only returns to me the first 50 items:

count = 0
@client.account.calls.list('start_time>' => '2013-10-01').each do |call|
  count += 1
end
count
 => 50

I can fix this issue by manually setting page_size, but that seems like a hack. Have I done something wrong, or is this expected behavior?

Using twilio-ruby 3.11.4 with ruby 2.0 and rails 3.2.15.

Unitialized Constant Twilio::REST Sending SMS From a model

Hello,
I am having trouble sending an SMS from my Rails app. It works fine locally, but on production I am getting:

unitialized constant Twilio::REST

This is my app/models/alert.rb directory. Obviously putting the sending functionality at the controller level would help, but any ideas on how to have it recognize this in the model? I have some tricky recipient scoping/mapping which is why it is in the model. Thanks!

Generated CapabilityToken is not always valid

I have this in my controller to generate random channel name

class RandomTokensController < ApplicationController
  http_basic_authenticate_with name: ENV["APP_NAME"], password: ENV["APP_SECRET"]

  def create
    account_sid = ENV["TWILIO_SID"]
    auth_token = ENV["TWILIO_TOKEN"]

    capability = Twilio::Util::Capability.new account_sid, auth_token


      @@channel = SecureRandom.hex
      capability.allow_client_incoming @@channel

    @token = capability.generate
    @random_token = {:token => @token, :created_at => "now", :updated_at => "now"}

    respond_to do |format|
      format.json { render action: 'show', status: :created, location: @random_token }
    end
  end
end

The token I get back is not always a valid one. On average 3 out of 10 times, setting up the wait will lead to a failed attempt to listen on the connection of the random channel.

Adding a newline to a text message

Hi,

First of all: thanks for the great gem - it makes our programming lives a lot easier!

I am trying to insert a newline into my text message as per the instructions at http://www.twilio.com/help/faq/sms/how-do-i-add-a-line-break-in-my-sms-message , however, when I insert '%0a' into the body of my message it comes out as exactly that as opposed to generating a new line, e.g. "This is line 1%0aThis is line 2".

I'm wondering if somehow special characters are getting escaped and are appearing intact in the final message (like Rails does for special characters in HTML).

Is that what is happening or am I doing something wrong? Is there a way to get newlines into a text message using your gem?

Thanks,
Larry

error handling documentation

It would be helpful to include documentation for error handling. Specifically, it's not clear what happens when you try to purchase a number that is either not available or no longer available from the API:

@account.incoming_phone_numbers.create(:phone_number => @numbers[0].phone_number)

but what if @numbers[0].phone_number is no longer available or if there is an error and the API fails... does this return nil, and error object or raise an exception...

Thanks!

Deprecate 1.8.7 support

Ruby 1.8.7 has been unsupported for over a year now and is no longer receiving security patches. In the interest of security and moving forward, 1.8.7 should not be supported by this gem.

This means removing 1.8.7 from the Travis build matrix and refactoring code to take advantage of new syntax and features from 1.9+.

@dougblack @skimbrel could someone check the metrics and see if there are a significant amount of 1.8.7 clients hitting the API?

Problem sending messages longer than 160 characters when using this gem

I've got problem sending messages longer than 160 characters when using this gem. The response I get is:

{"status"=>400,
 "message"=>"The message body exceeds the 160 character limit.",
 "code"=>21605,
 "more_info"=>"http://www.twilio.com/docs/errors/21605"}

However error 21605 says that a message cannot be longer than 1600 characters.
I can send long SMSes just fine using curl.
Any ideas?

Newlines in SMS not working

Per this page, the client libraries (including this one) should automatically handle newlines in SMS messages. I am not seeing this correct behavior in gem 'twilio-ruby', tag: '3.11.0'.

What I'd expect to work:

Twilio::TwiML::Response.new do |r|
  r.Message "Do\nnewlines\nwork?\nNope."
end

Any insight? Cheers.

Twilio Documentation Examples Don't Work?

Working with the gem to get usage reporting. However, when using them gem per the example below it doesn't work.

    # twilio-ruby install docs at twilio.com/docs/ruby/install
    require 'rubygems'          # This line not needed for ruby > 1.8
    require 'twilio-ruby'

    # Get your Account Sid and Auth Token from twilio.com/user/account 
    account_sid = 'AC32a3c49700934481addd5ce1659f04d2'
    auth_token = '{{ auth_token }}'
    @client = Twilio::REST::Client.new account_sid, auth_token


    # Loop over records and print out a property for each one
    @client.account.usage.records.today.list({
        :category => "calls"}).each do |record|
        puts record.sid
    end

Results in

NoMethodError: undefined method `sid' for #<Twilio::REST::Record:0x007f9f294e84a8>
    from /Users/BillWatts/.rvm/gems/ruby-1.9.3-p374/gems/twilio-ruby-3.9.0/lib/twilio-ruby/rest/instance_resource.rb:68:in `method_missing'
    from (irb):55:in `block in irb_binding'
    from (irb):54:in `each'
    from (irb):54
    from /Users/BillWatts/.rvm/gems/ruby-1.9.3-p374/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
    from /Users/BillWatts/.rvm/gems/ruby-1.9.3-p374/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
    from /Users/BillWatts/.rvm/gems/ruby-1.9.3-p374/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

Am I missing something or does this thing not worked as advertised?

Twilio::REST::RequestError (The 'To' number _run_process_action_callbacks is not a valid phone number.)

I am having an issue receiving an SMS.
I am trying to send a message back to the FROM number. So the 'To' field of the outgoing sms is the same as the 'From' field of the incoming sms.

I get the following error from twilio on trying to send an sms:

Twilio::REST::RequestError (The 'To' number _run_process_action_callbacks is not a valid phone number.):

I expect the 'To' field to be a phone number (String).

In my controller, 'receive' is what Twilio POSTs to:

def receive
  message_body = params["Body"]
  phone = params["From"]
  send(phone, "verified!")
  render :nothing => true
end

def send(to, message_body)
  twilio_sid = ... 
  twilio_token = ....
  twilio_phone_number = ....
  twilio_client = Twilio::REST::Client.new(twilio_sid, twilio_token)
  twilio_client.account.sms.messages.create( :from => twilio_phone_number, :to => to, :body => message_body)
end

callback not working for outgoing_caller_ids

When trying to validate a new caller id, I am unable to make Twilio issue a callback to our servers.

TWILIO.account.outgoing_caller_ids.create(
  friendly_name: current_administrator.name,
  phone_number: phone_number,
  status_callback: callback_url,
  status_callback_method: 'GET'
)

As per: https://www.twilio.com/docs/api/rest/outgoing-caller-ids#list-post

The number gets validated just fine, but Twilio never issues the callback.

I have also tried:

TWILIO.account.outgoing_caller_ids.create(
  friendly_name: current_administrator.name,
  phone_number: phone_number,
 'StatusCallback' => callback_url,
 'StatusCallbackMethod' => 'GET'
)

I have debugged the call and I can see that callback_url returns the actual expected url that I would like Twilio to call.

Accessing Twilio::REST::Message object -> SmsSid

Hello,

Not sure if this issue is actually addressed in this issue ( #48) already and I'm just missing something.

Anyway, I'm curious if there is already a way that I can access the smss_id which seems to be part of the response from the twilio REST API when I post a new sms to go out.

The return object is an instance of Twilio::REST::Message, but I can't seem to locate any documentation on what methods I can actually call on an instance of that.

In my specific case, I want to pull the smss_id out of the reponse. I can see that it the gem utilizes a path value which contains this. Is there a way to get at this directly already? I need to be able to assign the smss_id in the database when the msg is sent.

Right now I've added the following method to the Twilio::REST::Message class:

def smss_id
  @path.split('/').last
end

Thoughts?

Resource not accessible with Test Credentials when sending SMS Messages

When using the following code with test credentials:

sms = @client.account.sms.messages.create(:body => "Hey Mr Nugget, you the bomb!", :to => "+12078414568", :from => "+15005550006")

an error is raised stating that the Resource is not accessible with Test account credentials. This same error does not occur when trying to make calls with test credentials.

EOFError while making a call

Issue: I am intermittently getting this error while making a call. And this looks like it should be handled at the library level and not at the app level.

twilio-ruby gem version: 3.8.0

  EOFError: "end of file reached"
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/1.8/net/protocol.rb:135:in `sysread'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/1.8/net/protocol.rb:135:in `rbuf_fill'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/1.8/timeout.rb:67:in `timeout'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/1.8/timeout.rb:101:in `timeout'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/1.8/net/protocol.rb:134:in `rbuf_fill'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/1.8/net/protocol.rb:116:in `readuntil'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/1.8/net/protocol.rb:126:in `readline'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/1.8/net/http.rb:2028:in `read_status_line'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/1.8/net/http.rb:2017:in `read_new'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/1.8/net/http.rb:1051:in `request'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/1.8/net/http.rb:1037:in `request'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/1.8/net/http.rb:543:in `start'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/1.8/net/http.rb:1035:in `request'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/twilio-ruby-3.8.0/lib/twilio-ruby/rest/client.rb:213:in `connect_and_send'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/twilio-ruby-3.8.0/lib/twilio-ruby/rest/client.rb:165:in `post'
  /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/twilio-ruby-3.8.0/lib/twilio-ruby/rest/list_resource.rb:82:in `create'
  [RAILS_ROOT]/app/models/customer_call.rb:71:in `call_second_number'

FWIW, the code that is making the call:

@call = @client.account.calls.create(
        :from => from,
        :to   => to,
        :url  => twiml_url,
        'IfMachine' => 'Continue',
        'StatusCallback' => callback_url
)

Ruby version:
ruby 1.8.7 (2011-02-18 patchlevel 334) [x86_64-linux], MBARI 0x6770, Ruby Enterprise Edition 2011.03

Please let me know if you need any more details. I will try to fix and submit a pull request, but if not, can anyone take a look at this?

Show a clearer error message for "Authenticate"

The stack trace you get for an authentication error looks like this:

 /Users/kevin/.rvm/gems/ruby-1.9.3-p194/gems/twilio-ruby-3.8.0/lib/twilio-ruby/rest/client.rb:226:in `connect_and_send': Authenticate (Twilio::REST::RequestError)
from /Users/kevin/.rvm/gems/ruby-1.9.3-p194/gems/twilio-ruby-3.8.0/lib/twilio-ruby/rest/client.rb:165:in `block (2 levels) in <class:Client>'
from /Users/kevin/.rvm/gems/ruby-1.9.3-p194/gems/twilio-ruby-3.8.0/lib/twilio-ruby/rest/list_resource.rb:29:in `list'
from scratch/get_logs.rb:11:in `<main>'

It's not particularly easy to figure out what the problem is (you haven't provided a valid sid and token). It would be nice if we provided a little more guidance in this case.

Using new account messages api can not handle ActiveSupport::TimeWithZone

Similar to Issue 71, DateSent> can not take a time object. When using rails and the deprecated api as it handles the 24.hours.ago time object correctly. The following does not work:

    the_first = 24.hours.ago
    messages = @twilio.account.messages.list("DateSent>" => the_first)
    begin
      messages = messages.next_page
    end while not messages.empty?

But if I change that to @twilio.account.sms.messages.list it works correctly.

I'm using twilio-ruby (3.11.4), rails (3.1.11) and ruby 1.9.3p194.

Segfault: net/http client

There seems to be an issue in the net/http standard library that is causing a segfault. I am more or less interested if their is a work around for this with the twilio gem thanks.

home/ubuntu/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/net/http.rb:920: [BUG] Segmentation fault at 0x007f67a4acc980
ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-linux]

-- Control frame information -----------------------------------------------
c:0042 p:---- s:0198 e:000197 CFUNC :connect
c:0041 p:0008 s:0195 e:000194 BLOCK /home/ubuntu/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/net/http.rb:920
c:0040 p:0036 s:0193 E:000b70 BLOCK /home/ubuntu/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/timeout.rb:91 [FINISH]
c:0039 p:---- s:0188 e:000187 CFUNC :call
c:0038 p:0069 s:0184 E:000a78 METHOD /home/ubuntu/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/timeout.rb:101
c:0037 p:0508 s:0173 E:000d28 METHOD /home/ubuntu/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/net/http.rb:920
c:0036 p:0007 s:0162 e:000161 METHOD /home/ubuntu/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/net/http.rb:863
c:0035 p:0036 s:0159 e:000158 METHOD /home/ubuntu/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/net/http.rb:852
c:0034 p:0017 s:0156 e:000155 METHOD /home/ubuntu/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/net/http.rb:1369
c:0033 p:0031 s:0149 e:000148 METHOD /home/ubuntu/.rvm/gems/ruby-2.1.1/gems/twilio-ruby-3.11.5/lib/twilio-ruby/rest/client.rb:216
c:0032 p:0133 s:0142 e:000141 LAMBDA /home/ubuntu/.rvm/gems/ruby-2.1.1/gems/twilio-ruby-3.11.5/lib/twilio-ruby/rest/client.rb:168 [FINISH]
c:0031 p:0031 s:0136 e:000135 METHOD /home/ubuntu/.rvm/gems/ruby-2.1.1/gems/twilio-ruby-3.11.5/lib/twilio-ruby/rest/list_resource.rb:91

add example for StartTime>=2012-04-01

The API allows you to retrieve all calls with a time greater than or equal to some date by specifying

GET /2010-04-01/Accounts/AC123/Calls?StartTime>=2012-11-05

however this requires the slightly odd and ugly hash format

client.account.calls.list(:"start_time>" => "2012-11-05")

it'd be nice to provide an example of this.

Invalid value for DateSent when using next_page

I'm converting from the old account.sms.messages logic to account.messages. I'm getting an "Invalid value for DateSent" message.

Steps to reproduce:

results = @client.account.messages.list(:date_sent => 24.hours.ago.strftime("%Y-%m-%d"), :page_size => 5)
results.next_page

=> Twilio::REST::RequestError: Invalid value for DateSent

Documentation has not been updated to match new API

If you make breaking changes to your API, you need to update your documentation.

The docs here:
https://www.twilio.com/docs/api/rest/message

Still mention the "old"/"pre-sms" API call:
@client.account.messages.list.each do |message|
puts message.body
end

But now... as far as I can tell... it's been changed to
@client.account.sms.messages.list.each do |message|
puts message.body
end

It'd be nice if we were alerted to breaking changes in the API... or if there were a method of versioning the API...

Thanks.

EOFError still cropping up... rest-client to blame?

Hey guys,

I've been getting a large number of EOF errors using twilio-ruby. Here's an example stack trace:

EOFError: end of file reached
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/openssl/buffering.rb:174:in `sysread_nonblock'
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/openssl/buffering.rb:174:in `read_nonblock'
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/protocol.rb:153:in `rbuf_fill'
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/protocol.rb:134:in `readuntil'
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/protocol.rb:144:in `readline'
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/http/response.rb:39:in `read_status_line'
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/http/response.rb:28:in `read_new'
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/http.rb:1405:in `block in transport_request'
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/http.rb:1402:in `catch'
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/http.rb:1402:in `transport_request'
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/http.rb:1375:in `request'
/app/vendor/bundle/ruby/2.0.0/gems/rest-client-1.6.7/lib/restclient/net_http_ext.rb:51:in `request'
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/http.rb:1368:in `block in request'
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/http.rb:851:in `start'
/app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/http.rb:1366:in `request'
/app/vendor/bundle/ruby/2.0.0/gems/rest-client-1.6.7/lib/restclient/net_http_ext.rb:51:in `request'
/app/vendor/bundle/ruby/2.0.0/gems/twilio-ruby-3.9.0/lib/twilio-ruby/rest/client.rb:213:in `connect_and_send'
/app/vendor/bundle/ruby/2.0.0/gems/twilio-ruby-3.9.0/lib/twilio-ruby/rest/client.rb:165:in `block (2 levels) in '
/app/vendor/bundle/ruby/2.0.0/gems/twilio-ruby-3.9.0/lib/twilio-ruby/rest/list_resource.rb:82:in `create'
/app/lib/twilio_interface.rb:25:in `call'

twilio_interface.rb is just a thin wrapper for the twilio-ruby gem.

class TwilioInterface
  def self.sms(to, body)
    options = {
      from: TWILIO_NUMBER,
      to: to,
      body: body
    }

    message = TWILIO.account.sms.messages.create(options)
    response = TwilioResponse.new(:success, message)

  rescue Twilio::REST::RequestError => e
    Airbrake.notify(e)
    response = TwilioResponse.new(:error, e)
  end

  def self.call(to, url)
    options = {
      format: 'json',
      from: TWILIO_NUMBER,
      to: to,
      url: url
    }

    call = TWILIO.account.calls.create(options)

    response = TwilioResponse.new(:success, call)
  rescue Twilio::REST::RequestError => e
    Airbrake.notify(e)
    response = TwilioResponse.new(:error, e)
  end
end

The calls to TwilioInterface are all made in Sidekiq background workers.

The issue I'm having is that the actual HTTP actions are taking place and calls/texts are completing, but the exceptions that are raised are causing my workers to be retried so I get duplicate calls/texts.

I'm going through today and making my workers idempotent, but any thought as to the root cause of these exceptions would be appreciated.

Theories:

  • rest-client isn't thread-safe, which conflicts with sidekiq.
  • Timeout?

twilio gem 3.0.1 and builder 3.0

Hi,

It seems twilio 3.0.1 requires buidler ~> 2.1.2, but rails 3.1.0.rc4 requires builder ~> 3.0.0. Is it possible to update the dependencies ?

Best regards,

Julien

Twilio::REST::Message does not expose uri property

According to the documentation, "instance resource objects have all the properties that the Twilio REST API returns."

In the case of Twilio::REST::Message, this is true for all properties except uri, which is an instance variable that is not exposed in the interface.

I can construct this URI from the sid, but according to the principles of HATEOAS (which the REST API follows), I should not be forced to do so.

National Number support

Seems like twilio has four types of numbers you can request: local, national, mobile, and toll free. It looks like this gem only supports local, mobile, and toll free? Am I incorrect here, would it be simple to add this functionality?

problem buying numbers

When I buy a number with twilio-ruby, I get a positive response from Twilio, my account gets charged, a sid is returned. But, when I try to retrieve the SID, Twilio responds that no such incoming number exists, and there are no numbers listed on my Twilio dash board. I can buy numbers just fine using the api explorer.

I'm buying my numbers like:

  def self.buy_number subaccount_sid, subaccount_auth_token, number, options={}
     subclient = reteive_client({"account_sid"=>subaccount_sid, "auth_token"=>subaccount_auth_token})
     subaccount = subclient.account
     subaccount.incoming_phone_numbers.create({phone_number:number, sms_method:'GET'}.merge(options))
   end 

  def self.reteive_client credentials=TWILIO_OPTIONS[:credentials]
      return Twilio::REST::Client.new credentials["account_sid"], credentials["auth_token"]
  end 

This is almost verbatum from the API explorer

@client.account.messages doesn't work

So the problem is that there are two Message classes and they're conflicting with each other. The @list_key from the /SMS/Messages version of the class is overwriting the default @list_key of the /Messages version of the class.

This is resulting in a failure to parse responses generated by all

@client.account.messages

calls.

We're working on a fix for this.

Any way to suppress the MultiJson library deprication notice?

What I get when running the latest version:

/Library/Ruby/Gems/1.8/gems/twilio-ruby-3.6.0/lib/twilio-ruby/rest/client.rb:214:in `connect_and_send': [DEPRECATION] MultiJson.decode is deprecated and will be removed in the next major version. Use MultiJson.load instead.

TwiML Gather Method

Is there a way to pass back params in the action callback?

r.Gather :action => "/call/update/"

For example, I want to pass in my local variable @call with it. Something like

r.Gather :action => "/call/update", :params => @call

outbound SMS support

will the twilio gem be updated to support standard outbound sms (not via twiml)

FR: Get the JSON returned from the server after a REST request

Hi,

I'd like access to the actual JSON (or its parsed hash equivalent) returned by the server after making a request, in case I need it for later debugging or whatnot.

I don't think I can get this, as it is -- it looks like the JSON gets parsed in Client#connect_and_send() and then parcellated out in InstanceResource#set_up_properties_from().

Would it be OK to have the hash additionally stored in an instance variable?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.