]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blobdiff - lib/rbot/ircbot.rb
windows hates logging to files with : in them :p
[user/henk/code/ruby/rbot.git] / lib / rbot / ircbot.rb
index 51f323b37d83c15fb6fe49b8a481f03237796ccb..d07c4977aa9542cd94867446950a3e9b65257d95 100644 (file)
@@ -1,48 +1,37 @@
-# Copyright (C) 2002 Tom Gilbert.
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to
-# deal in the Software without restriction, including without limitation the
-# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-# sell copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies of the Software and its documentation and acknowledgment shall be
-# given in the documentation and software packages that this Software was
-# used.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
-# THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
 require 'thread'
 require 'etc'
 require 'fileutils'
 
+$debug = false unless $debug
+# print +message+ if debugging is enabled
+def debug(message=nil)
+  stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
+  print "D: [#{stamp}] #{message}\n" if($debug && message)
+  #yield
+end
+
+# these first
+require 'rbot/rbotconfig'
+require 'rbot/config'
+require 'rbot/utils'
+
 require 'rbot/rfc2812'
 require 'rbot/keywords'
-require 'rbot/config'
 require 'rbot/ircsocket'
 require 'rbot/auth'
 require 'rbot/timer'
 require 'rbot/plugins'
 require 'rbot/channel'
-require 'rbot/utils'
 require 'rbot/message'
 require 'rbot/language'
 require 'rbot/dbhash'
 require 'rbot/registry'
 require 'rbot/httputil'
-require 'rbot/rbotconfig'
 
 module Irc
 
-# Main bot class, which receives messages, handles them or passes them to
-# plugins, and stores runtime data
+# Main bot class, which manages the various components, receives messages,
+# handles them or passes them to plugins, and contains core functionality.
 class IrcBot
   # the bot's current nickname
   attr_reader :nick
@@ -63,12 +52,12 @@ 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
 
+  # bot's irc socket
+  attr_reader :socket
+
   # bot's object registry, plugins get an interface to this for persistant
   # storage (hash interface tied to a bdb file, plugins use Accessors to store
   # and restore objects in their own namespaces.)
@@ -79,13 +68,62 @@ class IrcBot
   attr_reader :httputil
 
   # create a new IrcBot with botclass +botclass+
-  def initialize(botclass)
-    unless FileTest.directory? Config::DATADIR
-      puts "data directory '#{Config::DATADIR}' not found, did you install.rb?"
+  def initialize(botclass, params = {})
+    # BotConfig for the core bot
+    BotConfig.register BotConfigStringValue.new('server.name',
+      :default => "localhost", :requires_restart => true,
+      :desc => "What server should the bot connect to?",
+      :wizard => true)
+    BotConfig.register BotConfigIntegerValue.new('server.port',
+      :default => 6667, :type => :integer, :requires_restart => true,
+      :desc => "What port should the bot connect to?", 
+      :validate => Proc.new {|v| v > 0}, :wizard => true)
+    BotConfig.register BotConfigStringValue.new('server.password',
+      :default => false, :requires_restart => true,
+      :desc => "Password for connecting to this server (if required)",
+      :wizard => true)
+    BotConfig.register BotConfigStringValue.new('server.bindhost',
+      :default => false, :requires_restart => true,
+      :desc => "Specific local host or IP for the bot to bind to (if required)",
+      :wizard => true)
+    BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
+      :default => 5, :validate => Proc.new{|v| v >= 0},
+      :desc => "Seconds to wait before attempting to reconnect, on disconnect")
+    BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
+      :desc => "IRC nickname the bot should attempt to use", :wizard => true,
+      :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
+    BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
+      :requires_restart => true,
+      :desc => "local user the bot should appear to be", :wizard => true)
+    BotConfig.register BotConfigArrayValue.new('irc.join_channels',
+      :default => [], :wizard => true,
+      :desc => "What channels the bot should always join at startup. List multiple channels using commas to separate. If a channel requires a password, use a space after the channel name. e.g: '#chan1, #chan2, #secretchan secritpass, #chan3'")
+    BotConfig.register BotConfigIntegerValue.new('core.save_every',
+      :default => 60, :validate => Proc.new{|v| v >= 0},
+      # TODO change timer via on_change proc
+      :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example")
+    BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
+      :default => 2.0, :validate => Proc.new{|v| v >= 0},
+      :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
+      :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
+    BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
+      :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 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
@@ -94,65 +132,67 @@ class IrcBot
         puts "Error: file #{botclass} exists but isn't a directory"
         exit 2
       end
-      FileUtils.cp_r Config::DATADIR+'/templates', botclass
+      FileUtils.cp_r Config::datadir+'/templates', botclass
     end
     
     Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
 
+    @ping_timer = nil
+    @pong_timer = nil
+    @last_ping = nil
     @startup_time = Time.new
-    @config = Irc::BotConfig.new(self)
+    @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 = Irc::HttpUtil.new(self)
-    @lang = Irc::Language.new(@config['core.language'])
-    @keywords = Irc::Keywords.new(self)
-    @auth = Irc::IrcAuth.new(self)
+    @httputil = Utils::HttpUtil.new(self)
+    @lang = Language::Language.new(@config['core.language'])
+    @keywords = Keywords.new(self)
+    @auth = IrcAuth.new(self)
 
     Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
-    @plugins = Irc::Plugins.new(self, ["#{botclass}/plugins"])
+    @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
 
-    @socket = Irc::IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
+    @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 = Irc::IrcClient.new
-    @client["PRIVMSG"] = proc { |data|
-      message = PrivMessage.new(self, data["SOURCE"], data["TARGET"], data["MESSAGE"])
+
+    @client = IrcClient.new
+    @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[: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"])
+    @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|
@@ -165,13 +205,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))
@@ -183,78 +223,74 @@ 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'])
-        puts "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
 
-      if(@config['irc.join_channels'])
-        @config['irc.join_channels'].split(", ").each {|c|
-          debug "autojoining channel #{c}"
-          if(c =~ /^(\S+)\s+(\S+)$/i)
-            join $1, $2
-          else
-            join c if(c)
-          end
-        }
-      end
+      @plugins.delegate("connect")
+
+      @config['irc.join_channels'].each {|c|
+        debug "autojoining channel #{c}"
+        if(c =~ /^(\S+)\s+(\S+)$/i)
+          join $1, $2
+        else
+          join c if(c)
+        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
@@ -264,44 +300,62 @@ 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("SIGINT") { quit }
+      trap("SIGTERM") { quit }
+      trap("SIGHUP") { quit }
+    rescue
+      debug "failed to trap signals, probably running on windows?"
+    end
     begin
       @socket.connect
-      rescue => e
+    rescue => e
       raise "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
     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
+      # 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 SystemExit
+        exit 0
+      rescue Exception => e
+        puts "network exception: connection closed: #{e.inspect}"
+        puts e.backtrace.join("\n")
+        @socket.shutdown # now we reconnect
       rescue => e
-        puts "connection closed: #{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
       
@@ -337,6 +391,7 @@ class IrcBot
     end while(message.length > 0)
   end
 
+  # queue an arbitraty message for the server
   def sendq(message="")
     # temporary
     @socket.queue(message)
@@ -396,26 +451,47 @@ class IrcBot
   def topic(where, topic)
     sendq "TOPIC #{where} :#{topic}"
   end
-  
-  # message:: optional IRC quit message
-  # quit IRC, shutdown the bot
-  def quit(message=nil)
-    trap("SIGTERM", "DEFAULT")
-    trap("SIGHUP", "DEFAULT")
-    trap("SIGINT", "DEFAULT")
-    message = @lang.get("quit") if (!message || message.length < 1)
+
+  # disconnect from the server and cleanup all plugins and modules
+  def shutdown(message = nil)
+    begin
+      trap("SIGINT", "DEFAULT")
+      trap("SIGTERM", "DEFAULT")
+      trap("SIGHUP", "DEFAULT")
+    rescue
+      debug "failed to trap signals, probably running on windows?"
+    end
+    message = @lang.get("quit") if (message.nil? || message.empty?)
     @socket.clearq
     save
     @plugins.cleanup
     @channels.each_value {|v|
       log "@ quit (#{message})", v.name
     }
+    @registry.close
     @socket.puts "QUIT :#{message}"
     @socket.flush
     @socket.shutdown
-    @registry.close
     puts "rbot quit (#{message})"
-    exit 0
+  end
+  
+  # message:: optional IRC quit message
+  # quit IRC, shutdown the bot
+  def quit(message=nil)
+    begin
+      shutdown(message)
+    ensure
+      exit 0
+    end
+  end
+
+  # totally shutdown and respawn the bot
+  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)
   end
 
   # call the save method for bot's config, keywords, auth and all plugins
@@ -490,12 +566,49 @@ class IrcBot
     return helpstr
   end
 
+  # returns a string describing the current status of the bot (uptime etc)
   def status
     secs_up = Time.new - @startup_time
     uptime = Utils.secs_to_string secs_up
     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
+            # TODO
+            # raise an exception to get back to the mainloop
+          rescue
+            debug "couldn't shutdown connection (already shutdown?)"
+          end
+          @last_ping = nil
+        end
+      end
+    }
+  end
 
   private
 
@@ -504,6 +617,8 @@ class IrcBot
     case topic
       when "quit"
         return "quit [<message>] => quit IRC with message <message>"
+      when "restart"
+        return "restart => completely stop and restart the bot (including reconnect)"
       when "join"
         return "join <channel> [<key>] => join channel <channel> with secret key <key> if specified. #{@nick} also responds to invites if you have the required access level"
       when "part"
@@ -533,7 +648,7 @@ class IrcBot
       when "hello"
         return "hello|hi|hey|yo [#{@nick}] => greet the bot"
       else
-        return "Core help topics: quit, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
+        return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
     end
   end
 
@@ -575,6 +690,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(?:\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)
@@ -623,39 +740,19 @@ class IrcBot
             @channels[where].quiet = false if(@channels.has_key?(where))
             m.okay
           end
-        # TODO break this out into a config module
-        when (/^options get sendq_delay$/i)
-          if auth.allow?("config", m.source, m.replyto)
-            m.reply "options->sendq_delay = #{@socket.sendq_delay}"
-          end
-        when (/^options get sendq_burst$/i)
-          if auth.allow?("config", m.source, m.replyto)
-            m.reply "options->sendq_burst = #{@socket.sendq_burst}"
-          end
-        when (/^options set sendq_burst (.*)$/i)
-          num = $1.to_i
-          if auth.allow?("config", m.source, m.replyto)
-            @socket.sendq_burst = num
-            @config['irc.sendq_burst'] = num
-            m.okay
-          end
-        when (/^options set sendq_delay (.*)$/i)
-          freq = $1.to_f
-          if auth.allow?("config", m.source, m.replyto)
-            @socket.sendq_delay = freq
-            @config['irc.sendq_delay'] = freq
-            m.okay
-          end
-        when (/^status$/i)
+        when (/^status\??$/i)
           m.reply status if auth.allow?("status", m.source, m.replyto)
         when (/^registry stats$/i)
           if auth.allow?("config", m.source, m.replyto)
             m.reply @registry.stat.inspect
           end
+        when (/^(help\s+)?config(\s+|$)/)
+          @config.privmsg(m)
         when (/^(version)|(introduce yourself)$/i)
           say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
         when (/^help(?:\s+(.*))?$/i)
           say m.replyto, help($1)
+          #TODO move these to a "chatback" plugin
         when (/^(botsnack|ciggie)$/i)
           say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
           say m.replyto, @lang.get("thanks") if(m.private?)
@@ -668,9 +765,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)
@@ -703,8 +800,8 @@ class IrcBot
   def onjoin(m)
     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
     if(m.address?)
+      debug "joined channel #{m.channel}"
       log "@ Joined channel #{m.channel}", m.channel
-      puts "joined channel #{m.channel}"
     else
       log "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
       @channels[m.channel].users[m.sourcenick] = Hash.new
@@ -717,9 +814,9 @@ class IrcBot
 
   def onpart(m)
     if(m.address?)
+      debug "left channel #{m.channel}"
       log "@ Left channel #{m.channel} (#{m.message})", m.channel
       @channels.delete(m.channel)
-      puts "left channel #{m.channel}"
     else
       log "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
       @channels[m.channel].users.delete(m.sourcenick)
@@ -733,9 +830,9 @@ class IrcBot
   # respond to being kicked from a channel
   def onkick(m)
     if(m.address?)
+      debug "kicked from channel #{m.channel}"
       @channels.delete(m.channel)
       log "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
-      puts "kicked from channel #{m.channel}"
     else
       @channels[m.channel].users.delete(m.sourcenick)
       log "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
@@ -760,7 +857,6 @@ class IrcBot
       break if m.privmsg(message)
     }
   end
-
 end
 
 end