Skip to content

Instantly share code, notes, and snippets.

@mbie
Created April 4, 2017 20:59
Show Gist options
  • Select an option

  • Save mbie/b80d406afabd6da575c9c5c3a6b8b6c5 to your computer and use it in GitHub Desktop.

Select an option

Save mbie/b80d406afabd6da575c9c5c3a6b8b6c5 to your computer and use it in GitHub Desktop.
Simple ruby script for getting stats for tweets
require 'twitter'
class TwitterClient
def self.client
Twitter::REST::Client.new do |config|
config.consumer_key = ""
config.consumer_secret = ""
config.access_token = ""
config.access_token_secret = ""
end
end
end
class TweetsFetcher
def tweets(keyword, exclude_retweets: true)
keyword.concat(" -rt") if exclude_retweets
tweets = client.search(keyword, result_type: :recent).to_a
puts "Fetched #{tweets.size} tweets!"
tweets
end
private
def client
@client ||= TwitterClient.client
end
end
class TwitterStats
attr_reader :tweets
def initialize(tweets)
@tweets = tweets
end
def top_spammers(number = 10)
@most_tweets ||= tweets.each.with_object(Hash.new(0)) do |tweet, hash|
hash[tweet.user.screen_name] += 1
end.sort_by { |_, v| -v }.to_h
@most_tweets.take(number).map.with_index(1) do |(user, count), i|
"#{i}. #{user} - #{count}"
end
end
def top_rewtweeted(number = 5)
@sorted_by_retweet_count ||= tweets.sort_by(&:retweet_count).reverse
@sorted_by_retweet_count.first(number).map.with_index(1) do |tweet, i|
"#{i}. #{tweet.text} by #{tweet.user.screen_name} - #{tweet.retweet_count}"
end
end
def top_favorited(number = 5)
@sorted_by_favorite_count ||= tweets.sort_by(&:favorite_count).reverse
@sorted_by_favorite_count.first(number).map.with_index(1) do |tweet, i|
"#{i}. #{tweet.text} by #{tweet.user.screen_name} - #{tweet.favorite_count}"
end
end
def size
@tweets.size
end
end
fetcher = TweetsFetcher.new
tweets = fetcher.tweets("wrocloverb")
stats = TwitterStats.new(tweets)
puts stats.top_spammers
puts stats.top_rewtweeted
puts stats.top_favorited
@mbie
Copy link
Author

mbie commented Apr 4, 2017

Usage:

  1. Create an application in https://apps.twitter.com
  2. Get the credentials and paste the in the TwitterClient
  3. Install the twitter gem.
  4. Change the default hashtag (only tweets from last 7 days will be fetched - Twitter limits)
  5. Enjoy stats ;)

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