sferik / twitter-ruby

A Ruby interface to the Twitter API.
http://www.rubydoc.info/gems/twitter
MIT License
4.58k stars 1.31k forks source link

The error occurs when twitter: image and twitter: text shared to twitter OAuth api #907

Closed Rybots closed 1 year ago

Rybots commented 6 years ago

Dear, I have the website which user can share some own image with text to Twitter by using Twitter OAuth API. (Ruby:2.3.6,Rails: 5.1.4,‘omniauth-twitter’ gem,Amazon Linux AMI)

and, when User is trying to tweet with an image, (using this)

client.update_with_media(
  comment,
  image_path
 )

sometimes the error occurs with following messages

[DEPRECATED] :mime_type option deprecated, use :content_type Twitter::Error::Unauthorized (Invalid or expired token.): Completed 500 Internal Server Error

Then, I searched and I found out that If the image is smaller than 10 kb, image path is recognized as Twitter as a character string. So I wrote monkey patch like this.

module Twitter::Image
    def self.open_from_url(image_path)                                                                                          
         image_file = open(image_path)
         return image_file unless image_file.is_a?(StringIO)
         file_name = File.basename(image_path)
         temp_file = Tempfile.new(file_name)
         temp_file.binmode
         temp_file.write(image_file.read)
         temp_file.close
         open(temp_file.path)
    end       
  end  

 image_path = Twitter::Image.open_from_url(image_path)
 client.update_with_media(
     comment + "\nhhbox.net/#{user.screen_name}",
     image_path
 )

However, it doesn't work well.Sometimes errors occur yet. Could you please help??

Thanks

vladfreel commented 5 years ago

update_with_media deprecated. My code:

> def send_to_twitter social_pictures, content
>     pictures = []
>     social_pictures.each do |picture|
>       pictures << picture.image.file.path
>     end
>     media_ids = pictures.map do |filename|
>       twitter_client.upload(File.new(filename))
>     end.map(&:value)
>     twitter_client.update(content, :media_ids => media_ids)
> end

But I have same error

PashaLVWD commented 5 years ago

@Rybots I think you need to copy metadata from image_file (StringIO) to your temp_file (Tempfile) as suggested here: https://gist.github.com/janko-m/7cd94b8b4dd113c2c193#file-02-safe-download-commented-rb-L58