Class: QwtfDiscordBotWatcher

Inherits:
Object
  • Object
show all
Includes:
QwtfDiscordBot
Defined in:
lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb

Constant Summary collapse

THIRTY_SECONDS =
30
TEN_MINUTES =
10 * 60

Constants included from QwtfDiscordBot

QwtfDiscordBot::VERSION

Instance Method Summary collapse

Methods included from QwtfDiscordBot

config, config_file, #redis

Instance Method Details

#every(n_seconds) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb', line 33

def every(n_seconds)
  loop do
    before = Time.now
    yield
    interval = n_seconds - (Time.now - before)
    sleep(interval) if interval > 0
  end
end

#report_joined(name:, channel_id:, server_summary:) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb', line 51

def report_joined(name:, channel_id:, server_summary:)
  message = "#{name} joins #{server_summary}"

  Discordrb::API::Channel.create_message(
    "Bot #{QwtfDiscordBot.config.token}",
    channel_id,
    message
  )

  puts message
end

#runObject



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
# File 'lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb', line 7

def run
  every(THIRTY_SECONDS) do
    QwtfDiscordBot.config.endpoints.each do |endpoint|
      address = endpoint.address
      request = QstatRequest.new(address)
      next if request.is_empty?

      request.player_names.each do |name|
        redis_key = ['watcher', address, name].join(':')

        unless seen_recently?(redis_key)
          endpoint.channel_ids.each do |channel_id|
            report_joined(
              name: name,
              channel_id: channel_id,
              server_summary: request.server_summary
            )
          end
        end

        update_last_seen_at(redis_key)
      end
    end
  end
end

#seen_recently?(redis_key) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb', line 42

def seen_recently?(redis_key)
  redis.get(redis_key)
end

#update_last_seen_at(redis_key) ⇒ Object



46
47
48
49
# File 'lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb', line 46

def update_last_seen_at(redis_key)
  redis.set(redis_key, Time.now)
  redis.expire(redis_key, TEN_MINUTES)
end