Sha256: 7174c9d221afd75c1ea7caf1ee6158c114ed1d9f4340396b94bf749581cdabc6

Contents?: true

Size: 1.43 KB

Versions: 2

Compression:

Stored size: 1.43 KB

Contents

require "redis"

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 = "#{address}:#{name}"

          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} has joined #{server_summary}"

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

    puts message
  end

  private

  def redis
    @redis ||= Redis.new
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
qwtf_discord_bot-4.2.6 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb
qwtf_discord_bot-4.2.5 lib/qwtf_discord_bot/qwtf_discord_bot_watcher.rb