Sha256: 343bcd9d1ea14c78e6755a93e9e4b8ee571a14def403f0b0315ef247ab339708

Contents?: true

Size: 1.28 KB

Versions: 1

Compression:

Stored size: 1.28 KB

Contents

class QwtfDiscordBotWatcher < QwtfDiscordBot
  THIRTY_SECONDS = 30
  TEN_MINUTES = 10 * 60

  def run
    every(THIRTY_SECONDS) do
      @endpoints.each do |endpoint, channel_ids|
        request = QstatRequest.new(endpoint)
        next if request.is_empty?

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

          history[endpoint] ||= {}
          history[endpoint][name] = Time.now
        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?(endpoint:, name:)
    last_seen = history[endpoint] && history[endpoint][name]
    last_seen && (Time.now - last_seen < TEN_MINUTES)
  end

  def report_joined(name:, channel_id:, server_summary:)
    Discordrb::API::Channel.create_message(
      "Bot #{TOKEN}",
      channel_id,
      "#{name} has joined #{server_summary}"
    )
  end

  def history
    @history ||= {}
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
qwtf_discord_bot-3.0.0 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb