X-Git-Url: https://git.netwichtig.de/gitweb/?a=blobdiff_plain;f=lib%2Frbot%2Fircbot.rb;h=2443ec95d7ae0865423a2b4a4117245c55cb77ea;hb=5a06676cdec9d4b43767f39ef2dea3b735a964a5;hp=f99dd940d5207794d00c486eeb7e9fb13dd38427;hpb=e7558ab501d89ed4d04ff69b58344aec8de50844;p=user%2Fhenk%2Fcode%2Fruby%2Frbot.git diff --git a/lib/rbot/ircbot.rb b/lib/rbot/ircbot.rb index f99dd940..2443ec95 100644 --- a/lib/rbot/ircbot.rb +++ b/lib/rbot/ircbot.rb @@ -51,9 +51,6 @@ class IrcBot # bot's Language data attr_reader :lang - # bot's configured addressing prefixes - attr_reader :addressing_prefixes - # channel info for channels the bot is in attr_reader :channels @@ -112,15 +109,20 @@ class IrcBot :default => 4, :validate => Proc.new{|v| v >= 0}, :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines, with non-burst limits of 512 bytes/2 seconds", :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v }) + BotConfig.register BotConfigIntegerValue.new('server.ping_timeout', + :default => 10, :validate => Proc.new{|v| v >= 0}, + :on_change => Proc.new {|bot, v| bot.start_server_pings}, + :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)") @argv = params[:argv] unless FileTest.directory? Config::datadir - puts "data directory '#{Config::datadir}' not found, did you install.rb?" + puts "data directory '#{Config::datadir}' not found, did you setup.rb?" exit 2 end - botclass = "/home/#{Etc.getlogin}/.rbot" unless botclass + #botclass = "#{Etc.getpwnam(Etc.getlogin).dir}/.rbot" unless botclass + botclass = "#{ENV['HOME']}/.rbot" unless botclass @botclass = botclass.gsub(/\/$/, "") unless FileTest.directory? botclass @@ -134,14 +136,17 @@ class IrcBot Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs") + @ping_timer = nil + @pong_timer = nil + @last_ping = nil @startup_time = Time.new @config = BotConfig.new(self) +# TODO background self after botconfig has a chance to run wizard @timer = Timer::Timer.new(1.0) # only need per-second granularity @registry = BotRegistry.new self @timer.add(@config['core.save_every']) { save } if @config['core.save_every'] @channels = Hash.new @logs = Hash.new - @httputil = Utils::HttpUtil.new(self) @lang = Language::Language.new(@config['core.language']) @keywords = Keywords.new(self) @@ -152,42 +157,41 @@ class IrcBot @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst']) @nick = @config['irc.nick'] - if @config['core.address_prefix'] - @addressing_prefixes = @config['core.address_prefix'].split(" ") - else - @addressing_prefixes = Array.new - end - + @client = IrcClient.new - @client["PRIVMSG"] = proc { |data| - message = PrivMessage.new(self, data["SOURCE"], data["TARGET"], data["MESSAGE"]) + @client[:privmsg] = proc { |data| + message = PrivMessage.new(self, data[:source], data[:target], data[:message]) onprivmsg(message) } - @client["NOTICE"] = proc { |data| - message = NoticeMessage.new(self, data["SOURCE"], data["TARGET"], data["MESSAGE"]) + @client[:notice] = proc { |data| + message = NoticeMessage.new(self, data[:source], data[:target], data[:message]) # pass it off to plugins that want to hear everything @plugins.delegate "listen", message } - @client["MOTD"] = proc { |data| - data['MOTD'].each_line { |line| + @client[:motd] = proc { |data| + data[:motd].each_line { |line| log "MOTD: #{line}", "server" } } - @client["NICKTAKEN"] = proc { |data| - nickchg "#{@nick}_" + @client[:nicktaken] = proc { |data| + nickchg "#{data[:nick]}_" } - @client["BADNICK"] = proc {|data| - puts "WARNING, bad nick (#{data['NICK']})" + @client[:badnick] = proc {|data| + puts "WARNING, bad nick (#{data[:nick]})" } - @client["PING"] = proc {|data| + @client[:ping] = proc {|data| # (jump the queue for pongs) - @socket.puts "PONG #{data['PINGID']}" + @socket.puts "PONG #{data[:pingid]}" } - @client["NICK"] = proc {|data| - sourcenick = data["SOURCENICK"] - nick = data["NICK"] - m = NickMessage.new(self, data["SOURCE"], data["SOURCENICK"], data["NICK"]) + @client[:pong] = proc {|data| + @last_ping = nil + } + @client[:nick] = proc {|data| + sourcenick = data[:sourcenick] + nick = data[:nick] + m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick]) if(sourcenick == @nick) + debug "my nick is now #{nick}" @nick = nick end @channels.each {|k,v| @@ -200,13 +204,13 @@ class IrcBot @plugins.delegate("listen", m) @plugins.delegate("nick", m) } - @client["QUIT"] = proc {|data| - source = data["SOURCE"] - sourcenick = data["SOURCENICK"] - sourceurl = data["SOURCEADDRESS"] - message = data["MESSAGE"] - m = QuitMessage.new(self, data["SOURCE"], data["SOURCENICK"], data["MESSAGE"]) - if(data["SOURCENICK"] =~ /#{@nick}/i) + @client[:quit] = proc {|data| + source = data[:source] + sourcenick = data[:sourcenick] + sourceurl = data[:sourceaddress] + message = data[:message] + m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message]) + if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i) else @channels.each {|k,v| if(v.users.has_key?(sourcenick)) @@ -218,27 +222,24 @@ class IrcBot @plugins.delegate("listen", m) @plugins.delegate("quit", m) } - @client["MODE"] = proc {|data| - source = data["SOURCE"] - sourcenick = data["SOURCENICK"] - sourceurl = data["SOURCEADDRESS"] - channel = data["CHANNEL"] - targets = data["TARGETS"] - modestring = data["MODESTRING"] + @client[:mode] = proc {|data| + source = data[:source] + sourcenick = data[:sourcenick] + sourceurl = data[:sourceaddress] + channel = data[:channel] + targets = data[:targets] + modestring = data[:modestring] log "@ Mode #{modestring} #{targets} by #{sourcenick}", channel } - @client["WELCOME"] = proc {|data| - log "joined server #{data['SOURCE']} as #{data['NICK']}", "server" - debug "I think my nick is #{@nick}, server thinks #{data['NICK']}" - if data['NICK'] && data['NICK'].length > 0 - @nick = data['NICK'] - end - if(@config['irc.quser']) - # TODO move this to a plugin - debug "authing with Q using #{@config['quakenet.user']} #{@config['quakenet.auth']}" - @socket.puts "PRIVMSG Q@CServe.quakenet.org :auth #{@config['quakenet.user']} #{@config['quakenet.auth']}" + @client[:welcome] = proc {|data| + log "joined server #{data[:source]} as #{data[:nick]}", "server" + debug "I think my nick is #{@nick}, server thinks #{data[:nick]}" + if data[:nick] && data[:nick].length > 0 + @nick = data[:nick] end + @plugins.delegate("connect") + @config['irc.join_channels'].each {|c| debug "autojoining channel #{c}" if(c =~ /^(\S+)\s+(\S+)$/i) @@ -248,47 +249,47 @@ class IrcBot end } } - @client["JOIN"] = proc {|data| - m = JoinMessage.new(self, data["SOURCE"], data["CHANNEL"], data["MESSAGE"]) + @client[:join] = proc {|data| + m = JoinMessage.new(self, data[:source], data[:channel], data[:message]) onjoin(m) } - @client["PART"] = proc {|data| - m = PartMessage.new(self, data["SOURCE"], data["CHANNEL"], data["MESSAGE"]) + @client[:part] = proc {|data| + m = PartMessage.new(self, data[:source], data[:channel], data[:message]) onpart(m) } - @client["KICK"] = proc {|data| - m = KickMessage.new(self, data["SOURCE"], data["TARGET"],data["CHANNEL"],data["MESSAGE"]) + @client[:kick] = proc {|data| + m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message]) onkick(m) } - @client["INVITE"] = proc {|data| - if(data["TARGET"] =~ /^#{@nick}$/i) - join data["CHANNEL"] if (@auth.allow?("join", data["SOURCE"], data["SOURCENICK"])) + @client[:invite] = proc {|data| + if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i) + join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick])) end } - @client["CHANGETOPIC"] = proc {|data| - channel = data["CHANNEL"] - sourcenick = data["SOURCENICK"] - topic = data["TOPIC"] - timestamp = data["UNIXTIME"] || Time.now.to_i + @client[:changetopic] = proc {|data| + channel = data[:channel] + sourcenick = data[:sourcenick] + topic = data[:topic] + timestamp = data[:unixtime] || Time.now.to_i if(sourcenick == @nick) log "@ I set topic \"#{topic}\"", channel else log "@ #{sourcenick} set topic \"#{topic}\"", channel end - m = TopicMessage.new(self, data["SOURCE"], data["CHANNEL"], timestamp, data["TOPIC"]) + m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic]) ontopic(m) @plugins.delegate("listen", m) @plugins.delegate("topic", m) } - @client["TOPIC"] = @client["TOPICINFO"] = proc {|data| - channel = data["CHANNEL"] - m = TopicMessage.new(self, data["SOURCE"], data["CHANNEL"], data["UNIXTIME"], data["TOPIC"]) + @client[:topic] = @client[:topicinfo] = proc {|data| + channel = data[:channel] + m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic]) ontopic(m) } - @client["NAMES"] = proc {|data| - channel = data["CHANNEL"] - users = data["USERS"] + @client[:names] = proc {|data| + channel = data[:channel] + users = data[:users] unless(@channels[channel]) puts "bug: got names for channel '#{channel}' I didn't think I was in\n" exit 2 @@ -298,16 +299,21 @@ class IrcBot @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]] } } - @client["UNKNOWN"] = proc {|data| - debug "UNKNOWN: #{data['SERVERSTRING']}" + @client[:unknown] = proc {|data| + #debug "UNKNOWN: #{data[:serverstring]}" + log data[:serverstring], ":unknown" } end # connect the bot to IRC def connect - trap("SIGTERM") { quit } - trap("SIGHUP") { quit } - trap("SIGINT") { quit } + begin + trap("SIGTERM") { quit } + trap("SIGHUP") { quit } + trap("SIGINT") { quit } + rescue + debug "failed to trap signals, probably running on windows?" + end begin @socket.connect rescue => e @@ -315,32 +321,38 @@ class IrcBot end @socket.puts "PASS " + @config['server.password'] if @config['server.password'] @socket.puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert" + start_server_pings end # begin event handling loop def mainloop while true + begin connect @timer.start - begin while true if @socket.select break unless reply = @socket.gets @client.process reply end end - rescue TimeoutError, SocketError => e + # I despair of this. Some of my users get "connection reset by peer" + # exceptions that ARENT SocketError's. How am I supposed to handle + # that? + #rescue TimeoutError, SocketError => e + rescue Exception => e puts "network exception: connection closed: #{e}" puts e.backtrace.join("\n") - @socket.close # now we reconnect - rescue => e # TODO be selective, only grab Network errors - puts "unexpected exception: connection closed: #{e}" + @socket.shutdown # now we reconnect + rescue => e + puts "unexpected exception: connection closed: #{e.inspect}" puts e.backtrace.join("\n") exit 2 end puts "disconnected" + @last_ping = nil @channels.clear @socket.clearq @@ -464,8 +476,9 @@ class IrcBot end # totally shutdown and respawn the bot - def restart - shutdown("restarting, back in #{@config['server.reconnect_wait']}...") + def restart(message = false) + msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..." + shutdown(msg) sleep @config['server.reconnect_wait'] # now we re-exec exec($0, *@argv) @@ -504,11 +517,6 @@ class IrcBot end # attempt to change bot's nick to +name+ - # FIXME - # if rbot is already taken, this happens: - # rbot_, nick rbot - # --- rbot_ is now known as rbot__ - # he should of course just keep his existing nick and report the error :P def nickchg(name) sendq "NICK #{name}" end @@ -555,6 +563,40 @@ class IrcBot return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received." end + # we'll ping the server every 30 seconds or so, and expect a response + # before the next one come around.. + def start_server_pings + @last_ping = nil + # stop existing timers if running + unless @ping_timer.nil? + @timer.remove @ping_timer + @ping_timer = nil + end + unless @pong_timer.nil? + @timer.remove @pong_timer + @pong_timer = nil + end + return unless @config['server.ping_timeout'] > 0 + # we want to respond to a hung server within 30 secs or so + @ping_timer = @timer.add(30) { + @last_ping = Time.now + @socket.puts "PING :rbot" + } + @pong_timer = @timer.add(10) { + unless @last_ping.nil? + diff = Time.now - @last_ping + unless diff < @config['server.ping_timeout'] + debug "no PONG from server for #{diff} seconds, reconnecting" + begin + @socket.shutdown + rescue + debug "couldn't shutdown connection (already shutdown?)" + end + @last_ping = nil + end + end + } + end private @@ -636,8 +678,8 @@ class IrcBot part $1 if(@auth.allow?("join", m.source, m.replyto)) when (/^quit(?:\s+(.*))?$/i) quit $1 if(@auth.allow?("quit", m.source, m.replyto)) - when (/^restart$/i) - restart if(@auth.allow?("quit", m.source, m.replyto)) + when (/^restart(?:\s+(.*))?$/i) + restart $1 if(@auth.allow?("quit", m.source, m.replyto)) when (/^hide$/i) join 0 if(@auth.allow?("join", m.source, m.replyto)) when (/^save$/i) @@ -711,9 +753,9 @@ class IrcBot else # stuff to handle when not addressed case m.message - when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$))[\s,-.]+#{@nick}$/i) + when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i) say m.replyto, @lang.get("hello_X") % m.sourcenick - when (/^#{@nick}!*$/) + when (/^#{Regexp.escape(@nick)}!*$/) say m.replyto, @lang.get("hello_X") % m.sourcenick else @keywords.privmsg(m) @@ -803,7 +845,6 @@ class IrcBot break if m.privmsg(message) } end - end end