Class: Ruboty::TwitterTrack::Stream

Inherits:
Object
  • Object
show all
Defined in:
lib/ruboty/twitter_track/stream.rb

Instance Method Summary collapse

Constructor Details

#initialize(robot) ⇒ Stream

Returns a new instance of Stream.



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
# File 'lib/ruboty/twitter_track/stream.rb', line 7

def initialize(robot)
  TweetStream.configure do |config|
    config.consumer_key       = CONSUMER_KEY
    config.consumer_secret    = CONSUMER_SECRET
    config.oauth_token        = ACCESS_TOKEN
    config.oauth_token_secret = ACCESS_TOKEN_SECRET
    config.auth_method        = :oauth
  end

  @robot  = robot
  @client = TweetStream::Client.new

  @client.on_inited do
    log(:info , "Connected to twitter stream.")

    # Every day reconnect the stream to prevent from shutdown.
    EM::PeriodicTimer.new(60 * 60 * 24) do
      @client.stream.immediate_reconnect
    end
  end

  @client.on_reconnect do |timeout, retrial|
    log(:info , "Reconnected to twitter stream: #{timeout} sec.")
  end

  @client.on_error do |message|
    log(:error, message)
  end
end

Instance Method Details

#restart(message, terms) ⇒ Object



48
49
50
51
52
53
# File 'lib/ruboty/twitter_track/stream.rb', line 48

def restart(message, terms)
  return start(message, terms) unless @client.stream

  query = terms.map { |w| w.join(' ') }
  @client.stream.update(params: {:track => query.join(',')})
end

#start(message, terms) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/ruboty/twitter_track/stream.rb', line 37

def start(message, terms)
  return if terms.empty?

  Thread.start do
    query = terms.map { |w| w.join(' ') }
    @client.track(*query) do |object|
      Message.new(message.merge(robot: @robot)).reply(u(object))
    end
  end
end