Skip to main content

Mike Kreuzer

Twitter followers, Ruby redux

July 28, 2017

Today I'm briefly revisiting January's Elixir code, and rewriting that in Ruby.

Apart from dealing with rate limits, being just the one file & easier to read, the Ruby version runs from the command line and doesn't shower me with dependency build warnings…

It's a small update of the original, original Ruby version of this, to deal with the newer cursored lists that are returned by the twitter API, and uses the Twitter gem.

require 'twitter'

client = Twitter::REST::Client.new do |c|
  c.consumer_key        = 'yep'
  c.consumer_secret     = 'yep'
  c.access_token        = 'yep'
  c.access_token_secret = 'yep'
end

def get_array(method)
  cursored_list_of_ids = method
  begin
    cursored_list_of_ids.to_a
  rescue Twitter::Error::TooManyRequests => error
    puts "Rate limited for: #{error.rate_limit.reset_in / 60} minutes"
    sleep error.rate_limit.reset_in + 1
    retry
  end
end

guilty_ids = get_array(client.friend_ids) - get_array(client.follower_ids)

if guilty_ids.empty?
  puts 'Already square'
else
  puts 'Unfollowed:'
  results = client.unfollow guilty_ids
  results.each { |user| puts "#{user.name} (#{user.screen_name})" }
end

That's the whole thing. Just add in your Twitter credentials and you're good to go, "unfollowing back" to your heart's content.

Tags: