-
-
Save csamuel/1180547 to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/env ruby | |
# twail.rb | |
# Twitter stream tail | |
# Copyright 2010 Jonathan Rudenberg | |
# Licensed under the MIT License | |
# | |
# Prerequisites: gem install json twitter-stream | |
require 'optparse' | |
require 'json' | |
require 'open-uri' | |
require 'cgi' | |
require 'twitter/json_stream' | |
@options = {} | |
@opts = OptionParser.new do |opts| | |
opts.banner = "Usage: #$0 options" | |
opts.on('-u', '--user=USER', String, 'Twitter username') { |v| @options[:username] = v } | |
opts.on('-p', '--password=PASSWORD', String, 'Twitter password') { |v| @options[:password] = v } | |
opts.on('-t', '--track=KEYWORDS', Array, 'Comma separated list of keywords to track') { |v| @options[:keywords] = v } | |
opts.on('-f', '--follow=USERS', Array, 'Comma separated list of usernames to track') do |v| | |
@options[:userids] = v.map do |u| | |
res = open("http://api.twitter.com/1/users/show.json?screen_name=#{u}").read | |
JSON.parse(res)['id'] | |
end | |
end | |
opts.on('-s', '--sample', 'Show a random sample of the firehose. Overrides -t and -f') { |v| @options[:sample] = true } | |
opts.on_tail('-h', '--help', 'Display this message') do | |
puts opts | |
exit | |
end | |
if !ARGV.first | |
puts opts | |
exit | |
end | |
end | |
@opts.parse! | |
@options[:username] ||= ENV['TWITTER_USER'] | |
@options[:password] ||= ENV['TWITTER_PASS'] | |
raise ArgumentError, "Username or password not specified\n" + @opts.help unless @options[:username] && @options[:password] | |
def stream_options | |
if @options[:sample] | |
'sample.json' | |
else | |
raise ArgumentError, "At least one of -t,-f,-s must be specified\n" + @opts.help unless @options[:keywords] || @options[:userids] | |
path = 'filter.json?' | |
path += "track=#{CGI.escape(@options[:keywords].join(','))}" if @options[:keywords] | |
path += "&follow=#{@options[:userids].join(',')}" if @options[:userids] | |
path | |
end | |
end | |
EventMachine.run do | |
stream = Twitter::JSONStream.connect( | |
:path => '/1/statuses/' + stream_options, | |
:auth => "#{@options[:username]}:#{@options[:password]}", | |
:ssl => true | |
) | |
stream.each_item do |item| | |
status = JSON.parse(item) | |
status['text'].gsub! /(#{@options[:keywords].join('|')})/i, "\e[4m#{$1}\e[0m" if @options[:keywords] | |
puts "\e[1m#{status['user']['screen_name']}:\e[0m #{status['text']}" if status['user'] | |
end | |
stream.on_error { |message| puts message } | |
trap('INT') { EM.stop_event_loop } # Ctrl-C | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment