Last active
August 29, 2015 14:10
-
-
Save Emerson/c7d1638c2525464d3275 to your computer and use it in GitHub Desktop.
Pulling Down a User's Twitter Feed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'twitter' | |
class AllTweets | |
attr_accessor :tweets | |
def initialize(username, config) | |
@username = username | |
@config = config | |
@tweets = [] | |
@max_id = nil | |
end | |
def client | |
Twitter::REST::Client.new do |config| | |
config.consumer_key = @config[:consumer_key] | |
config.consumer_secret = @config[:consumer_secret] | |
config.access_token = @config[:access_token] | |
config.access_token_secret = @config[:access_token_secret] | |
end | |
end | |
def fetch | |
options = {count: 200} | |
options[:max_id] = @max_id if @max_id | |
fetched_tweets = client.user_timeline(@username, options) | |
fetched_tweets.each do |tweet| | |
if @max_id.nil? || @max_id >= tweet.id | |
@max_id = tweet.id - 1 | |
end | |
@tweets.push(tweet.attrs.to_json) | |
end | |
if fetched_tweets.length == 0 | |
puts "Done, fetched #{@tweets.length} tweets" | |
return @tweets | |
else | |
puts "Tweet Count: #{@tweets.length}" | |
fetch | |
end | |
end | |
end | |
#-- Usage ----------------------------------------------------------------- | |
config = { | |
consumer_key: "YOUR_CONSUMER_KEY", | |
consumer_secret: "YOUR_CONSUMER_SECRET", | |
access_token: "YOUR_ACCESS_TOKEN", | |
access_token_secret: "YOUR_ACCESS_TOKEN_SECRET" | |
} | |
all_tweets = AllTweets.new('twg', config) | |
all_tweets.fetch | |
all_tweets.tweets | |
#=> Returns an array of ~3200 JSON encoded tweets |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment