Sha256: 162ba901194751cb439599bfacb179732afcb3a70c3c28b0ae2eb90ea431f9f7

Contents?: true

Size: 1.37 KB

Versions: 14

Compression:

Stored size: 1.37 KB

Contents

class QwtfDiscordBotWatcher
  include QwtfDiscordBot

  THIRTY_SECONDS = 30
  TEN_MINUTES = 10 * 60

  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

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

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

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

  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
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
qwtf_discord_bot-5.1.11 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-5.1.9 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-5.1.8 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-5.1.6 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-5.1.5 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-5.1.4 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-5.1.3 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-5.1.2 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-5.1.1 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-5.1.0 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-5.0.4 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-5.0.3 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-5.0.2 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-5.0.1 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb