Search code examples
rubyapitwitter

How To Scrape More Than One Account Automatically With Twitter API Using Ruby


I use this Ruby script and Twitter API to scrape followers of twitter usernames. It works as it should, but it can only scrape followers of one account, then I need to manually change the username and start it again. I have almost no experience with Ruby, so I would like to know if there is a away how to fetch the usernames from text file, one line after another, or any other way how to to do this. This is how my code looks now:

def fetch_all_followers(twitter_username)
  fname = "#{twitter_username}_friends_list.txt"
  @client.follower_ids(twitter_username)
         .each_slice(5000)
         .with_index do |slice, i|
    @client.users(slice)
           .each_with_index do |f, j|
              File.open(fname, "a+") do |file|
      file.write [i * 5000 + j + 1, f.screen_name, "\n"].join(',')
      sleep 0.06
    end
  end
end
end

fetch_all_followers("sometwiiteraccount")

Solution

  • Try this

    usernames = %w{
      alice
      bob
      charlie
      ...
    }
    
    usernames.each { |username| fetch_all_followers(username) }