require 'socket' class IrcIdleClient attr_accessor :host, :port, :nick, :uhost, :ipass def initialize(host, port = 6667) @host = host @port = port @nick = 'irc' @uhost= 'rb rb rb :rb' @ipass= 'foo' end def connect @sentping = false @sock = TCPSocket.open @host, @port send "user #@uhost", "nick #@nick" while r = IO.select([@sock], nil, nil, 5).to_a.first raise if not l = @sock.gets puts "#{Time.now.strftime '%H:%M'} #{l}" case l when /^\S* 433 / send "quit" raise 'nick taken' when /^\S* 376 / break end end send "join #nethack-idlerpg", "privmsg juiblex :login #@nick #@ipass" end def run connect loop do r, w, e = IO.select [@sock], nil, nil, 300 if not r handle_timeout elsif r.include? @sock handle_sock @sock.gets.chomp end end end private def send(*l) puts l @sock.write l.map { |ll| ll + "\r\n" }.join end def handle_timeout raise 'server ping timeout' if @sentping send 'ping :stillalive' @sentping = true end def handle_sock l case l when /^ping (.*)/i @sock.write "pong #$1\r\n" else puts "#{Time.now.strftime '%H:%M'} #{l}" end end end if $0 == __FILE__ if ARGV.delete 'loop' loop do exec "ruby #$0 #{ARGV.join(' ')}" if not pid = fork Process.waitpid(pid) sleep 300 end else c = IrcIdleClient.new 'irc.freenode.net' c.nick = ARGV.shift c.ipass= ARGV.shift c.run end end