2

The Twitter API allows you to add media to your tweet via their update_with_tweet method.

I am using Sinatra and have my Twitter configurations all set up. I am able to succesfully post tweets with my app.

My app reads a webpage, extracts the photos from that page, and then is supposed to individually post them to Twitter. I am successfully extracting the photos from the page using Nokogiri.

But, I am having trouble converting those photos into a media type that Twitter will allow. Because I am also using the uri gem, given this example: photo_url = "placekitten.com/300/300", I am able to call media = open(photo_url) and this returns a StringIO.

But, when I try posting that newly stored media with my post to Twitter I am given the error that The IO object for media must respond to to_io (Twitter::Error::UnacceptableIO).

I am trying to figure out how to correctly format/call the image so that I can successfully post it to Twitter.

2 Answers 2

6

I faced with same issue but using Rails.

Problem is in size of image: if size of image is less than 10kb then open(photo_url) will give you StringIO object, if size is more then 10kb then - File object which is saved in tmp/ folder. File object respond's to to_io method and StringIO object doesn't.

What you can do - create file in tmp folder from your file, and then use this this file for posting to TW. For example:

  img = open(url)
  if img.is_a?(StringIO)
    ext = File.extname(url)
    name = File.basename(url, ext)
    Tempfile.new([name, ext])
  else
    img
  end
1
0

One way to solve the above problem is to force a File to be created. And don't allow downloaded files to be created as StringIO.

Just include the following code into the top of the file with :update_with_media call.

require 'open-uri'

OpenURI::Buffer.send :remove_const, 'StringMax' if OpenURI::Buffer.const_defined?('StringMax')
OpenURI::Buffer.const_set 'StringMax', 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.