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.

kittyminky
  • 478
  • 6
  • 27

2 Answers2

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
kaleb4eg
  • 2,255
  • 1
  • 18
  • 13
  • 1
    This is indeed the problem. A different solution is http://stackoverflow.com/questions/10496874/why-does-openuri-treat-files-under-10kb-in-size-as-stringio – Bill Barnes Aug 19 '15 at 20:15
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
Sagar Ranglani
  • 5,491
  • 4
  • 34
  • 47