Search code examples
ruby-on-railsrubytwitterruby-on-rails-4twitter-gem

Twitter rails gem Update_with_media returns Unauthorized


I'm using the Twitter gem to authenticate and share content to twitter. I need to include an image as well so I'm using the "update_with_media" method, like so:

def tweet
    client = Twitter::REST::Client.new do |config|
      config.consumer_key        = "my consumer key"
      config.consumer_secret     = "my consumer secret"
      config.access_token        = "my access token"
      config.access_token_secret = "my secret access token"
    end
    url = @flip.image_urls[:normal].to_s
    r = open(url)
    bytes = r.read
    img = Magick::Image.from_blob(bytes).first
    fmt = img.format
    data = StringIO.new(bytes)
    data.class.class_eval { attr_accessor :original_filename, :content_type }
    data.original_filename = @flip.slug + "." + fmt unless @flip.slug.nil?
    data.content_type='image.jpg'

    client.update_with_media(personal_message, data)
  end

And I get this response:

Twitter::Error::Unauthorized (Could not authenticate you):

For every other interaction with twitter, get followers, or tweet (update WITHOUT media) it works fine with the same account, so my credentials are correct.

Any thoughts? Is this a bug on Twitter's API or the Twitter Gem?

I apreciate any help, thanks.


Solution

  • I figured out the problem. The error given back by Twitter is very misleading and not accurate.

    The problem with my code is that you can't use the update_with_media method using a StringIO file, it has to be a File object (File class).

    So this is the solution:

    client.update_with_media(message_link, open(url))
    

    Where the url is the image URL from wherever you need. In my case is the image url from my Flip model stored on AWS.