Oct 27 2009

Download Twitter Profile Images Using Ruby

Recently, I gave myself the small task of going through all my Twitter retries and downloading each profile image from each Twitter user that replied to me. To access my Twitter replies I used the Twitter Ruby Gem. I am using Twitter gem version 0.4.1.

The script is small and pretty concise that it can speak for itself. I use my Twitter credential to log on and query for the 40 most recent replies. For each reply download the user’s profile image.

require 'rubygems'

gem 'twitter', '=0.4.1'

require 'twitter'
require 'open-uri'
require 'find'

twitter = Twitter::Base.new(username, password)
replies = twitter.replies(:count => 40)

replies.each do |status|
  user = status.user
  image_url = user.profile_image_url
  image_name = image_url.match(/([\w_]+).(\w\w\w)$/)
  file_path = "profile/#{image_name[1]}.#{image_name[2]}"

  # Did I already download this image?
  unless File.exists?(file_path)
    File.open(file_path, 'w') do |output|
      # Download image
      open(image_url) do |input|
        output << input.read
      end
    end
  end  
end