Skip to content

Instantly share code, notes, and snippets.

@hyuki
Created May 18, 2018 04:23
Show Gist options
  • Save hyuki/163340e4f5924c9ab8fb66c84f378132 to your computer and use it in GitHub Desktop.
Save hyuki/163340e4f5924c9ab8fb66c84f378132 to your computer and use it in GitHub Desktop.
twitter-get-image.rb - ツイートのURLを与えると添付画像をダウンロードするRubyスクリプト
#!/usr/bin/env ruby
# encoding: utf-8
# cf. https://qiita.com/mataneko_boy/items/852ca5484b80d2530560
require 'twitter'
require 'open-uri'
CLIENT = Twitter::REST::Client.new do |config|
config.consumer_key = "XXXXXXXXXXXXXXXXXXXXXXXXX"
config.consumer_secret = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"
config.access_token = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
config.access_token_secret = "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"
end
def fetch_media(url)
p url
html = open(url)
img = html.read
mime = html.content_type
ext = if mime.include?('jpeg')
'.jpg'
elsif mime.include?('png')
'.png'
elsif mime.include?('gif')
'.gif'
else
''
end
return img, ext
end
def get_all_images(url)
tweet = CLIENT.status(url)
p tweet.full_text
p tweet.media?
if not tweet.media?
puts "No media."
rerun
end
counter = 1
tweet.media.each do |media|
media_url = media.media_url.to_s
img,ext = fetch_media(media_url)
filename = "#{counter}#{ext}"
puts filename
open(filename, 'w') do |f|
f.puts(img)
end
counter += 1
end
end
if ARGV.length == 0
puts "ruby twitter-get-image.rb https://twitter.com/hyuki/status/995912906477731840"
abort
else
url = ARGV[0]
get_all_images(url)
end
# vim: set filetype=ruby:
@hyuki
Copy link
Author

hyuki commented May 18, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment