Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

file 68 lines (51 sloc) 1.578 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
require 'rubygems'
require 'em-websocket'
require 'twitter/json_stream'
require 'yaml'
require 'yajl'

credentials = YAML.load(File.open('credentials.yml'))
username = credentials['username']
password = credentials['password']
terms = ['yankees', 'kobe', 'ruby', 'jquery']

puts "Connecting to twitter stream as #{username}"

def post?(status)
  post = true
  
  parsed_status = Yajl::Parser.parse(status)
  post = (parsed_status['text'].downcase =~ /suck/)

  post
end

EventMachine.run {
  @channel = EM::Channel.new

  @twitter = Twitter::JSONStream.connect(
    :path => '/1/statuses/filter.json',
    :auth => "#{username}:#{password}",
    :method => 'POST',
    :content => "track=#{terms.join(',')}"
  )

  @twitter.each_item do |status|
    parsed_status = Yajl::Parser.parse(status)
    
    @channel.push status unless (parsed_status['text'].downcase =~ /suck/)
  end

  @twitter.on_error do |message|
    puts message
      # No need to worry here. It might be an issue with Twitter.
      # Log message for future reference. JSONStream will try to reconnect after a timeout.
  end

  EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8080, :debug => true) do |ws|

    ws.onopen {
      sid = @channel.subscribe { |msg| ws.send msg }
      # @channel.push "#{sid} connected!"

      ws.onmessage { |msg|
        @channel.push "<#{sid}>: #{msg}"
      }

      ws.onclose {
        @channel.unsubscribe(sid)
      }

    }
  end

  trap('TERM') {
    @twitter.stop
    EventMachine.stop if EventMachine.reactor_running?
  }

  puts "Server started"
}
Something went wrong with that request. Please try again.