Class: Lita::Handlers::Reddit::SubredditPoster

Inherits:
Base
  • Object
show all
Defined in:
lib/lita/handlers/reddit/subreddit_poster.rb

Instance Method Summary collapse

Methods inherited from Base

#client, #poll_interval, #post_limit, #post_text, #reddits, #startup_delay

Instance Method Details

#refresh_posts(_payload) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/lita/handlers/reddit/subreddit_poster.rb', line 30

def refresh_posts(_payload)
  base_redis_key = "seen_list_%s_%s"
  reddits.each do |reddit|
    log.debug("lita-reddit: updating posts for /r/#{reddit[:subreddit]}")
    # new on the left
    redis_key = format(base_redis_key, reddit[:channel], reddit[:subreddit])
    seen_reddits = redis.lrange(redis_key, 0, 10)
    target = Source.new(room: reddit[:channel])
    results = client.get_posts(reddit[:subreddit],
                               redis.lindex(redis_key, 0),
                               post_limit)
    results.reverse.each do |post|
      unless seen_reddits.include?(post[:id])
        robot.send_message(target, post_text % post)
        redis.lpush(redis_key, post[:id])
      end

      # keep a few extra around, 10 is still instantaneous
      redis.ltrim(redis_key, 0, 10)
    end
  end
  rescue Exception => msg
    log.error("lita-reddit: Exception during post update #{msg}")
end

#setup(_payload) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/lita/handlers/reddit/subreddit_poster.rb', line 10

def setup(_payload)
  after startup_delay do
    robot.trigger(:reddit_update_token)
  end
  every poll_interval do
    robot.trigger(:reddit_refresh_posts)
  end
  # update userless token once per hour
  every 3300 do
    robot.trigger(:reddit_update_token)
  end
end

#update_token(_payload) ⇒ Object



23
24
25
26
27
28
# File 'lib/lita/handlers/reddit/subreddit_poster.rb', line 23

def update_token(_payload)
  client.update_token
  robot.trigger(:reddit_refresh_posts)
rescue Exception => msg
  log.error("lita-reddit: Exception during token update: #{msg}")
end