Search code examples
twittersinatrastringio

Sinatra, Twitter, and StringIO


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.


Solution

  • 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