nadoka/nadoka

View on GitHub
plugins/rss_checkbot.nb

Summary

Maintainability
Test Coverage
# -*-ruby; coding: utf-8 -*- vim:set ft=ruby:
#
# Copyright (c) 2004-2005 SASADA Koichi <ko1 at atdot.net>
#
# This program is free software with ABSOLUTELY NO WARRANTY.
# You can re-distribute and/or modify this program under
# the same terms of the Ruby's license.
#
#
# $Id$
#

=begin
configuration like follows:

BotConfig = [
{
  :name      => :RSS_CheckBot,
  :rss_paths =>
  [
    'http://www.ruby-lang.org/ja/index.rdf',
  ],
  :cache     => "./rss-cache",
  :ch        => '#nadoka_check',
  :tm        => 30     # check interval time(minute)
  :over_message => nil #
}

=end

require 'lib/rss_check'
require 'kconv'

class RSS_CheckBot < Nadoka::NDK_Bot
  def bot_initialize
    @cache = File.expand_path(@bot_config.fetch(:cache, '~/.rss_check'))
    @paths = @bot_config.fetch(:rss_paths, ['http://www.ruby-lang.org/ja/index.rdf'])
    @ch    = @bot_config.fetch(:ch, '#nadoka_check')
    @tm    = @bot_config.fetch(:tm,30)              # min
    @over  = @bot_config.fetch(:over_message, nil)
    @rssc  = RSS_Check.new(@paths, @cache, true)
    @prevtm= Time.now
  end

  def bot_state
    nt = Time.at(@prevtm.to_i + @tm * 60)
    "<#{self.class}: next check at #{nt.asctime}@#{@ch}>" 
  end
  
  def __on_privmsg prefix, ch, msg
    if /^rss> check/ =~ msg && ch == @ch && prefix.nick == @state.nick
      make_notice Time.now
    end
  end
  
  def send_notice(ch, msg)
    if ch.respond_to? :each
      ch.each{|c|
        super(c, msg.tojis)
        sleep 5 # Flood Protection
      }
    else
      super(ch, msg.tojis)
      sleep 5 # Flood Protection
    end
  end

  def on_timer tm
    check
  end

  def check
    tm = Time.now
    if tm.to_i - @tm * 60 > @prevtm.to_i
      make_notice tm
    end
  end

  def make_notice tm
    @prevtm = tm
    begin
      items = @rssc.check
      @rssc.save
    rescue => e
      send_notice(@ch, "rss bot error: #{e}")
      @manager.ndk_error e
      return
    end
    make_notice_thread items
  end
 
  def make_notice_thread items
    Thread.new{
      begin
        items.each{|e|
          if e[:ccode] == 'UTF-8'
            begin
              # convert from U+FF5E FULLWIDTH TILDE to U+301C WAVE DASH
              title = e[:title].gsub(/\357\275\236/u, "\343\200\234")
              title = title.toeuc
            rescue Exception
              # maybe, char code translation error
              next
            end
          else
            title = e[:title]
          end

          send_notice(@ch, "rss bot: #{title} - #{e[:about]}")
        }
      rescue Exception => e
        send_notice(@ch, "rss bot error: #{e}")
        @manager.ndk_error e
      end
      send_notice(@ch, "rss bot: #{@over}") if @over
    }
  end
  
end