]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
d513cb714a1e88ed9404cad8371839e2e5ffe536
[user/henk/code/ruby/rbot.git] / lib / rbot / ircbot.rb
1 require 'thread'
2 require 'etc'
3 require 'fileutils'
4
5 $debug = false unless $debug
6 # print +message+ if debugging is enabled
7 def debug(message=nil)
8   if ($debug && message)
9     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
10     message.to_s.each_line { |l|
11       $stdout.puts "D: [#{stamp}] #{l}"
12     }
13     $stdout.flush
14   end
15   #yield
16 end
17
18 # The following global is used for the improved signal handling.
19 $interrupted = 0
20
21 # these first
22 require 'rbot/rbotconfig'
23 require 'rbot/config'
24 require 'rbot/utils'
25
26 require 'rbot/rfc2812'
27 require 'rbot/keywords'
28 require 'rbot/ircsocket'
29 require 'rbot/auth'
30 require 'rbot/timer'
31 require 'rbot/plugins'
32 require 'rbot/channel'
33 require 'rbot/message'
34 require 'rbot/language'
35 require 'rbot/dbhash'
36 require 'rbot/registry'
37 require 'rbot/httputil'
38
39 module Irc
40
41 # Main bot class, which manages the various components, receives messages,
42 # handles them or passes them to plugins, and contains core functionality.
43 class IrcBot
44   # the bot's current nickname
45   attr_reader :nick
46
47   # the bot's IrcAuth data
48   attr_reader :auth
49
50   # the bot's BotConfig data
51   attr_reader :config
52
53   # the botclass for this bot (determines configdir among other things)
54   attr_reader :botclass
55
56   # used to perform actions periodically (saves configuration once per minute
57   # by default)
58   attr_reader :timer
59
60   # bot's Language data
61   attr_reader :lang
62
63   # channel info for channels the bot is in
64   attr_reader :channels
65
66   # bot's irc socket
67   attr_reader :socket
68
69   # bot's object registry, plugins get an interface to this for persistant
70   # storage (hash interface tied to a bdb file, plugins use Accessors to store
71   # and restore objects in their own namespaces.)
72   attr_reader :registry
73
74   # bot's httputil help object, for fetching resources via http. Sets up
75   # proxies etc as defined by the bot configuration/environment
76   attr_reader :httputil
77
78   # create a new IrcBot with botclass +botclass+
79   def initialize(botclass, params = {})
80     # BotConfig for the core bot
81     # TODO should we split socket stuff into ircsocket, etc?
82     BotConfig.register BotConfigStringValue.new('server.name',
83       :default => "localhost", :requires_restart => true,
84       :desc => "What server should the bot connect to?",
85       :wizard => true)
86     BotConfig.register BotConfigIntegerValue.new('server.port',
87       :default => 6667, :type => :integer, :requires_restart => true,
88       :desc => "What port should the bot connect to?",
89       :validate => Proc.new {|v| v > 0}, :wizard => true)
90     BotConfig.register BotConfigStringValue.new('server.password',
91       :default => false, :requires_restart => true,
92       :desc => "Password for connecting to this server (if required)",
93       :wizard => true)
94     BotConfig.register BotConfigStringValue.new('server.bindhost',
95       :default => false, :requires_restart => true,
96       :desc => "Specific local host or IP for the bot to bind to (if required)",
97       :wizard => true)
98     BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
99       :default => 5, :validate => Proc.new{|v| v >= 0},
100       :desc => "Seconds to wait before attempting to reconnect, on disconnect")
101     BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
102       :desc => "IRC nickname the bot should attempt to use", :wizard => true,
103       :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
104     BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
105       :requires_restart => true,
106       :desc => "local user the bot should appear to be", :wizard => true)
107     BotConfig.register BotConfigArrayValue.new('irc.join_channels',
108       :default => [], :wizard => true,
109       :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'")
110     BotConfig.register BotConfigIntegerValue.new('core.save_every',
111       :default => 60, :validate => Proc.new{|v| v >= 0},
112       # TODO change timer via on_change proc
113       :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example")
114     BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
115       :default => 2.0, :validate => Proc.new{|v| v >= 0},
116       :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
117       :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
118     BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
119       :default => 4, :validate => Proc.new{|v| v >= 0},
120       :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
121       :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
122     BotConfig.register BotConfigStringValue.new('server.byterate',
123       :default => "400/2", :validate => Proc.new{|v| v.match(/\d+\/\d/)},
124       :desc => "(flood prevention) max bytes/seconds rate to send the server. Most ircd's have limits of 512 bytes/2 seconds",
125       :on_change => Proc.new {|bot, v| bot.socket.byterate = v })
126     BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
127       :default => 10, :validate => Proc.new{|v| v >= 0},
128       :on_change => Proc.new {|bot, v| bot.start_server_pings},
129       :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
130
131     @argv = params[:argv]
132
133     unless FileTest.directory? Config::datadir
134       puts "data directory '#{Config::datadir}' not found, did you setup.rb?"
135       exit 2
136     end
137
138     botclass = "#{Etc.getpwuid(Process::Sys.geteuid)[:dir]}/.rbot" unless botclass
139     #botclass = "#{ENV['HOME']}/.rbot" unless botclass
140     botclass = File.expand_path(botclass)
141     @botclass = botclass.gsub(/\/$/, "")
142
143     unless FileTest.directory? botclass
144       puts "no #{botclass} directory found, creating from templates.."
145       if FileTest.exist? botclass
146         puts "Error: file #{botclass} exists but isn't a directory"
147         exit 2
148       end
149       FileUtils.cp_r Config::datadir+'/templates', botclass
150     end
151
152     Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
153     Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
154
155     @ping_timer = nil
156     @pong_timer = nil
157     @last_ping = nil
158     @startup_time = Time.new
159     @config = BotConfig.new(self)
160 # TODO background self after botconfig has a chance to run wizard
161     @timer = Timer::Timer.new(1.0) # only need per-second granularity
162     @registry = BotRegistry.new self
163     @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
164     @channels = Hash.new
165     @logs = Hash.new
166     @httputil = Utils::HttpUtil.new(self)
167     @lang = Language::Language.new(@config['core.language'])
168     @keywords = Keywords.new(self)
169     @auth = IrcAuth.new(self)
170
171     Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
172     @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
173
174     @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
175     @nick = @config['irc.nick']
176
177     @client = IrcClient.new
178     @client[:privmsg] = proc { |data|
179       message = PrivMessage.new(self, data[:source], data[:target], data[:message])
180       onprivmsg(message)
181     }
182     @client[:notice] = proc { |data|
183       message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
184       # pass it off to plugins that want to hear everything
185       @plugins.delegate "listen", message
186     }
187     @client[:motd] = proc { |data|
188       data[:motd].each_line { |line|
189         log "MOTD: #{line}", "server"
190       }
191     }
192     @client[:nicktaken] = proc { |data|
193       nickchg "#{data[:nick]}_"
194       @plugins.delegate "nicktaken", data[:nick]
195     }
196     @client[:badnick] = proc {|data|
197       puts "WARNING, bad nick (#{data[:nick]})"
198     }
199     @client[:ping] = proc {|data|
200       # (jump the queue for pongs)
201       @socket.puts "PONG #{data[:pingid]}"
202     }
203     @client[:pong] = proc {|data|
204       @last_ping = nil
205     }
206     @client[:nick] = proc {|data|
207       sourcenick = data[:sourcenick]
208       nick = data[:nick]
209       m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
210       if(sourcenick == @nick)
211         debug "my nick is now #{nick}"
212         @nick = nick
213       end
214       @channels.each {|k,v|
215         if(v.users.has_key?(sourcenick))
216           log "@ #{sourcenick} is now known as #{nick}", k
217           v.users[nick] = v.users[sourcenick]
218           v.users.delete(sourcenick)
219         end
220       }
221       @plugins.delegate("listen", m)
222       @plugins.delegate("nick", m)
223     }
224     @client[:quit] = proc {|data|
225       source = data[:source]
226       sourcenick = data[:sourcenick]
227       sourceurl = data[:sourceaddress]
228       message = data[:message]
229       m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
230       if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i)
231       else
232         @channels.each {|k,v|
233           if(v.users.has_key?(sourcenick))
234             log "@ Quit: #{sourcenick}: #{message}", k
235             v.users.delete(sourcenick)
236           end
237         }
238       end
239       @plugins.delegate("listen", m)
240       @plugins.delegate("quit", m)
241     }
242     @client[:mode] = proc {|data|
243       source = data[:source]
244       sourcenick = data[:sourcenick]
245       sourceurl = data[:sourceaddress]
246       channel = data[:channel]
247       targets = data[:targets]
248       modestring = data[:modestring]
249       log "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
250     }
251     @client[:welcome] = proc {|data|
252       log "joined server #{data[:source]} as #{data[:nick]}", "server"
253       debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
254       if data[:nick] && data[:nick].length > 0
255         @nick = data[:nick]
256       end
257
258       @plugins.delegate("connect")
259
260       @config['irc.join_channels'].each {|c|
261         debug "autojoining channel #{c}"
262         if(c =~ /^(\S+)\s+(\S+)$/i)
263           join $1, $2
264         else
265           join c if(c)
266         end
267       }
268     }
269     @client[:join] = proc {|data|
270       m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
271       onjoin(m)
272     }
273     @client[:part] = proc {|data|
274       m = PartMessage.new(self, data[:source], data[:channel], data[:message])
275       onpart(m)
276     }
277     @client[:kick] = proc {|data|
278       m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message])
279       onkick(m)
280     }
281     @client[:invite] = proc {|data|
282       if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i)
283         join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
284       end
285     }
286     @client[:changetopic] = proc {|data|
287       channel = data[:channel]
288       sourcenick = data[:sourcenick]
289       topic = data[:topic]
290       timestamp = data[:unixtime] || Time.now.to_i
291       if(sourcenick == @nick)
292         log "@ I set topic \"#{topic}\"", channel
293       else
294         log "@ #{sourcenick} set topic \"#{topic}\"", channel
295       end
296       m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
297
298       ontopic(m)
299       @plugins.delegate("listen", m)
300       @plugins.delegate("topic", m)
301     }
302     @client[:topic] = @client[:topicinfo] = proc {|data|
303       channel = data[:channel]
304       m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
305         ontopic(m)
306     }
307     @client[:names] = proc {|data|
308       channel = data[:channel]
309       users = data[:users]
310       unless(@channels[channel])
311         puts "bug: got names for channel '#{channel}' I didn't think I was in\n"
312         # exit 2
313       end
314       @channels[channel].users.clear
315       users.each {|u|
316         @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
317       }
318       @plugins.delegate "names", data[:channel], data[:users]
319     }
320     @client[:unknown] = proc {|data|
321       #debug "UNKNOWN: #{data[:serverstring]}"
322       log data[:serverstring], ".unknown"
323     }
324   end
325
326   def got_sig(sig)
327     debug "received #{sig}, queueing quit"
328     $interrupted += 1
329     debug "interrupted #{$interrupted} times"
330     if $interrupted >= 5
331       debug "drastic!"
332       exit 2
333     elsif $interrupted >= 3
334       debug "quitting"
335       quit
336     end
337   end
338
339   # connect the bot to IRC
340   def connect
341     begin
342       trap("SIGINT") { got_sig("SIGINT") }
343       trap("SIGTERM") { got_sig("SIGTERM") }
344       trap("SIGHUP") { got_sig("SIGHUP") }
345     rescue => e
346       debug "failed to trap signals: #{e.inspect}\nProbably running on windows?"
347     end
348     begin
349       @socket.connect
350     rescue => e
351       raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
352     end
353     @socket.puts "PASS " + @config['server.password'] if @config['server.password']
354     @socket.puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
355     start_server_pings
356   end
357
358   # begin event handling loop
359   def mainloop
360     while true
361       begin
362         connect
363         @timer.start
364
365         while @socket.connected?
366           if @socket.select
367             break unless reply = @socket.gets
368             @client.process reply
369           end
370           quit if $interrupted > 0
371         end
372
373       # I despair of this. Some of my users get "connection reset by peer"
374       # exceptions that ARENT SocketError's. How am I supposed to handle
375       # that?
376       rescue SystemExit
377         exit 0
378       rescue TimeoutError, SocketError => e
379         puts "#{e.class}: #{e}"
380         debug e.backtrace.join("\n")
381       rescue Exception => e
382         puts "network exception: #{e.inspect}"
383         puts e.backtrace.join("\n")
384         @socket.shutdown # now we reconnect
385       rescue => e
386         puts "unexpected exception: connection closed: #{e.inspect}"
387         puts e.backtrace.join("\n")
388         exit 2
389       end
390
391       puts "disconnected"
392
393       stop_server_pings
394       @channels.clear
395       @socket.clearq
396
397       puts "waiting to reconnect"
398       sleep @config['server.reconnect_wait']
399     end
400   end
401
402   # type:: message type
403   # where:: message target
404   # message:: message text
405   # send message +message+ of type +type+ to target +where+
406   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
407   # relevant say() or notice() methods. This one should be used for IRCd
408   # extensions you want to use in modules.
409   def sendmsg(type, where, message)
410     # limit it according to the byterate, splitting the message
411     # taking into consideration the actual message length
412     # and all the extra stuff
413     # TODO allow something to do for commands that produce too many messages
414     # TODO example: math 10**10000
415     left = @socket.bytes_per - type.length - where.length - 4
416     begin
417       if(left >= message.length)
418         sendq("#{type} #{where} :#{message}")
419         log_sent(type, where, message)
420         return
421       end
422       line = message.slice!(0, left)
423       lastspace = line.rindex(/\s+/)
424       if(lastspace)
425         message = line.slice!(lastspace, line.length) + message
426         message.gsub!(/^\s+/, "")
427       end
428       sendq("#{type} #{where} :#{line}")
429       log_sent(type, where, line)
430     end while(message.length > 0)
431   end
432
433   # queue an arbitraty message for the server
434   def sendq(message="")
435     # temporary
436     @socket.queue(message)
437   end
438
439   # send a notice message to channel/nick +where+
440   def notice(where, message)
441     message.each_line { |line|
442       line.chomp!
443       next unless(line.length > 0)
444       sendmsg("NOTICE", where, line)
445     }
446   end
447
448   # say something (PRIVMSG) to channel/nick +where+
449   def say(where, message)
450     message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
451       line.chomp!
452       next unless(line.length > 0)
453       unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
454         sendmsg("PRIVMSG", where, line)
455       end
456     }
457   end
458
459   # perform a CTCP action with message +message+ to channel/nick +where+
460   def action(where, message)
461     sendq("PRIVMSG #{where} :\001ACTION #{message}\001")
462     if(where =~ /^#/)
463       log "* #{@nick} #{message}", where
464     elsif (where =~ /^(\S*)!.*$/)
465          log "* #{@nick}[#{where}] #{message}", $1
466     else
467          log "* #{@nick}[#{where}] #{message}", where
468     end
469   end
470
471   # quick way to say "okay" (or equivalent) to +where+
472   def okay(where)
473     say where, @lang.get("okay")
474   end
475
476   # log message +message+ to a file determined by +where+. +where+ can be a
477   # channel name, or a nick for private message logging
478   def log(message, where="server")
479     message = message.chomp
480     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
481     where = where.gsub(/[:!?$*()\/\\<>|"']/, "_")
482     unless(@logs.has_key?(where))
483       @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
484       @logs[where].sync = true
485     end
486     @logs[where].puts "[#{stamp}] #{message}"
487     #debug "[#{stamp}] <#{where}> #{message}"
488   end
489
490   # set topic of channel +where+ to +topic+
491   def topic(where, topic)
492     sendq "TOPIC #{where} :#{topic}"
493   end
494
495   # disconnect from the server and cleanup all plugins and modules
496   def shutdown(message = nil)
497     debug "Shutting down ..."
498     ## No we don't restore them ... let everything run through
499     # begin
500     #   trap("SIGINT", "DEFAULT")
501     #   trap("SIGTERM", "DEFAULT")
502     #   trap("SIGHUP", "DEFAULT")
503     # rescue => e
504     #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
505     # end
506     message = @lang.get("quit") if (message.nil? || message.empty?)
507     if @socket.connected?
508       debug "Clearing socket"
509       @socket.clearq
510       debug "Sending quit message"
511       @socket.puts "QUIT :#{message}"
512       debug "Flushing socket"
513       @socket.flush
514       debug "Shutting down socket"
515       @socket.shutdown
516     end
517     debug "Logging quits"
518     @channels.each_value {|v|
519       log "@ quit (#{message})", v.name
520     }
521     debug "Saving"
522     save
523     debug "Cleaning up"
524     @plugins.cleanup
525     # debug "Closing registries"
526     # @registry.close
527     debug "Cleaning up the db environment"
528     DBTree.cleanup_env
529     puts "rbot quit (#{message})"
530   end
531
532   # message:: optional IRC quit message
533   # quit IRC, shutdown the bot
534   def quit(message=nil)
535     begin
536       shutdown(message)
537     ensure
538       exit 0
539     end
540   end
541
542   # totally shutdown and respawn the bot
543   def restart(message = false)
544     msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
545     shutdown(msg)
546     sleep @config['server.reconnect_wait']
547     # now we re-exec
548     exec($0, *@argv)
549   end
550
551   # call the save method for bot's config, keywords, auth and all plugins
552   def save
553     @config.save
554     @keywords.save
555     @auth.save
556     @plugins.save
557     DBTree.cleanup_logs
558   end
559
560   # call the rescan method for the bot's lang, keywords and all plugins
561   def rescan
562     @lang.rescan
563     @plugins.rescan
564     @keywords.rescan
565   end
566
567   # channel:: channel to join
568   # key::     optional channel key if channel is +s
569   # join a channel
570   def join(channel, key=nil)
571     if(key)
572       sendq "JOIN #{channel} :#{key}"
573     else
574       sendq "JOIN #{channel}"
575     end
576   end
577
578   # part a channel
579   def part(channel, message="")
580     sendq "PART #{channel} :#{message}"
581   end
582
583   # attempt to change bot's nick to +name+
584   def nickchg(name)
585       sendq "NICK #{name}"
586   end
587
588   # changing mode
589   def mode(channel, mode, target)
590       sendq "MODE #{channel} #{mode} #{target}"
591   end
592
593   # m::     message asking for help
594   # topic:: optional topic help is requested for
595   # respond to online help requests
596   def help(topic=nil)
597     topic = nil if topic == ""
598     case topic
599     when nil
600       helpstr = "help topics: core, auth, keywords"
601       helpstr += @plugins.helptopics
602       helpstr += " (help <topic> for more info)"
603     when /^core$/i
604       helpstr = corehelp
605     when /^core\s+(.+)$/i
606       helpstr = corehelp $1
607     when /^auth$/i
608       helpstr = @auth.help
609     when /^auth\s+(.+)$/i
610       helpstr = @auth.help $1
611     when /^keywords$/i
612       helpstr = @keywords.help
613     when /^keywords\s+(.+)$/i
614       helpstr = @keywords.help $1
615     else
616       unless(helpstr = @plugins.help(topic))
617         helpstr = "no help for topic #{topic}"
618       end
619     end
620     return helpstr
621   end
622
623   # returns a string describing the current status of the bot (uptime etc)
624   def status
625     secs_up = Time.new - @startup_time
626     uptime = Utils.secs_to_string secs_up
627     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
628     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
629   end
630
631   # we'll ping the server every 30 seconds or so, and expect a response
632   # before the next one come around..
633   def start_server_pings
634     stop_server_pings
635     return unless @config['server.ping_timeout'] > 0
636     # we want to respond to a hung server within 30 secs or so
637     @ping_timer = @timer.add(30) {
638       @last_ping = Time.now
639       @socket.puts "PING :rbot"
640     }
641     @pong_timer = @timer.add(10) {
642       unless @last_ping.nil?
643         diff = Time.now - @last_ping
644         unless diff < @config['server.ping_timeout']
645           debug "no PONG from server for #{diff} seconds, reconnecting"
646           begin
647             @socket.shutdown
648           rescue
649             debug "couldn't shutdown connection (already shutdown?)"
650           end
651           @last_ping = nil
652           raise TimeoutError, "no PONG from server in #{diff} seconds"
653         end
654       end
655     }
656   end
657
658   def stop_server_pings
659     @last_ping = nil
660     # stop existing timers if running
661     unless @ping_timer.nil?
662       @timer.remove @ping_timer
663       @ping_timer = nil
664     end
665     unless @pong_timer.nil?
666       @timer.remove @pong_timer
667       @pong_timer = nil
668     end
669   end
670
671   private
672
673   # handle help requests for "core" topics
674   def corehelp(topic="")
675     case topic
676       when "quit"
677         return "quit [<message>] => quit IRC with message <message>"
678       when "restart"
679         return "restart => completely stop and restart the bot (including reconnect)"
680       when "join"
681         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"
682       when "part"
683         return "part <channel> => part channel <channel>"
684       when "hide"
685         return "hide => part all channels"
686       when "save"
687         return "save => save current dynamic data and configuration"
688       when "rescan"
689         return "rescan => reload modules and static facts"
690       when "nick"
691         return "nick <nick> => attempt to change nick to <nick>"
692       when "say"
693         return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
694       when "action"
695         return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
696         #       when "topic"
697         #         return "topic <channel> <message> => set topic of <channel> to <message>"
698       when "quiet"
699         return "quiet [in here|<channel>] => with no arguments, stop speaking in all channels, if \"in here\", stop speaking in this channel, or stop speaking in <channel>"
700       when "talk"
701         return "talk [in here|<channel>] => with no arguments, resume speaking in all channels, if \"in here\", resume speaking in this channel, or resume speaking in <channel>"
702       when "version"
703         return "version => describes software version"
704       when "botsnack"
705         return "botsnack => reward #{@nick} for being good"
706       when "hello"
707         return "hello|hi|hey|yo [#{@nick}] => greet the bot"
708       else
709         return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
710     end
711   end
712
713   # handle incoming IRC PRIVMSG +m+
714   def onprivmsg(m)
715     # log it first
716     if(m.action?)
717       if(m.private?)
718         log "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
719       else
720         log "* #{m.sourcenick} #{m.message}", m.target
721       end
722     else
723       if(m.public?)
724         log "<#{m.sourcenick}> #{m.message}", m.target
725       else
726         log "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
727       end
728     end
729
730     # pass it off to plugins that want to hear everything
731     @plugins.delegate "listen", m
732
733     if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
734       notice m.sourcenick, "\001PING #$1\001"
735       log "@ #{m.sourcenick} pinged me"
736       return
737     end
738
739     if(m.address?)
740       delegate_privmsg(m)
741       case m.message
742         when (/^join\s+(\S+)\s+(\S+)$/i)
743           join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
744         when (/^join\s+(\S+)$/i)
745           join $1 if(@auth.allow?("join", m.source, m.replyto))
746         when (/^part$/i)
747           part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
748         when (/^part\s+(\S+)$/i)
749           part $1 if(@auth.allow?("join", m.source, m.replyto))
750         when (/^quit(?:\s+(.*))?$/i)
751           quit $1 if(@auth.allow?("quit", m.source, m.replyto))
752         when (/^restart(?:\s+(.*))?$/i)
753           restart $1 if(@auth.allow?("quit", m.source, m.replyto))
754         when (/^hide$/i)
755           join 0 if(@auth.allow?("join", m.source, m.replyto))
756         when (/^save$/i)
757           if(@auth.allow?("config", m.source, m.replyto))
758             save
759             m.okay
760           end
761         when (/^nick\s+(\S+)$/i)
762           nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
763         when (/^say\s+(\S+)\s+(.*)$/i)
764           say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
765         when (/^action\s+(\S+)\s+(.*)$/i)
766           action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
767           # when (/^topic\s+(\S+)\s+(.*)$/i)
768           #   topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
769         when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
770           mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
771         when (/^ping$/i)
772           say m.replyto, "pong"
773         when (/^rescan$/i)
774           if(@auth.allow?("config", m.source, m.replyto))
775             m.reply "Saving ..."
776             save
777             m.reply "Rescanning ..."
778             rescan
779             m.okay
780           end
781         when (/^quiet$/i)
782           if(auth.allow?("talk", m.source, m.replyto))
783             m.okay
784             @channels.each_value {|c| c.quiet = true }
785           end
786         when (/^quiet in (\S+)$/i)
787           where = $1
788           if(auth.allow?("talk", m.source, m.replyto))
789             m.okay
790             where.gsub!(/^here$/, m.target) if m.public?
791             @channels[where].quiet = true if(@channels.has_key?(where))
792           end
793         when (/^talk$/i)
794           if(auth.allow?("talk", m.source, m.replyto))
795             @channels.each_value {|c| c.quiet = false }
796             m.okay
797           end
798         when (/^talk in (\S+)$/i)
799           where = $1
800           if(auth.allow?("talk", m.source, m.replyto))
801             where.gsub!(/^here$/, m.target) if m.public?
802             @channels[where].quiet = false if(@channels.has_key?(where))
803             m.okay
804           end
805         when (/^status\??$/i)
806           m.reply status if auth.allow?("status", m.source, m.replyto)
807         when (/^registry stats$/i)
808           if auth.allow?("config", m.source, m.replyto)
809             m.reply @registry.stat.inspect
810           end
811         when (/^(help\s+)?config(\s+|$)/)
812           @config.privmsg(m)
813         when (/^(version)|(introduce yourself)$/i)
814           say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
815         when (/^help(?:\s+(.*))?$/i)
816           say m.replyto, help($1)
817           #TODO move these to a "chatback" plugin
818         when (/^(botsnack|ciggie)$/i)
819           say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
820           say m.replyto, @lang.get("thanks") if(m.private?)
821         when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
822           say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
823           say m.replyto, @lang.get("hello") if(m.private?)
824       end
825     else
826       # stuff to handle when not addressed
827       case m.message
828         when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
829           say m.replyto, @lang.get("hello_X") % m.sourcenick
830         when (/^#{Regexp.escape(@nick)}!*$/)
831           say m.replyto, @lang.get("hello_X") % m.sourcenick
832         else
833           @keywords.privmsg(m)
834       end
835     end
836   end
837
838   # log a message. Internal use only.
839   def log_sent(type, where, message)
840     case type
841       when "NOTICE"
842         if(where =~ /^#/)
843           log "-=#{@nick}=- #{message}", where
844         elsif (where =~ /(\S*)!.*/)
845              log "[-=#{where}=-] #{message}", $1
846         else
847              log "[-=#{where}=-] #{message}"
848         end
849       when "PRIVMSG"
850         if(where =~ /^#/)
851           log "<#{@nick}> #{message}", where
852         elsif (where =~ /^(\S*)!.*$/)
853           log "[msg(#{where})] #{message}", $1
854         else
855           log "[msg(#{where})] #{message}", where
856         end
857     end
858   end
859
860   def onjoin(m)
861     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
862     if(m.address?)
863       debug "joined channel #{m.channel}"
864       log "@ Joined channel #{m.channel}", m.channel
865     else
866       log "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
867       @channels[m.channel].users[m.sourcenick] = Hash.new
868       @channels[m.channel].users[m.sourcenick]["mode"] = ""
869     end
870
871     @plugins.delegate("listen", m)
872     @plugins.delegate("join", m)
873   end
874
875   def onpart(m)
876     if(m.address?)
877       debug "left channel #{m.channel}"
878       log "@ Left channel #{m.channel} (#{m.message})", m.channel
879       @channels.delete(m.channel)
880     else
881       log "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
882       if @channels.has_key?(m.channel)
883         @channels[m.channel].users.delete(m.sourcenick)
884       else
885         puts "bug: got part for channel '#{channel}' I didn't think I was in\n"
886         # exit 2
887       end
888     end
889
890     # delegate to plugins
891     @plugins.delegate("listen", m)
892     @plugins.delegate("part", m)
893   end
894
895   # respond to being kicked from a channel
896   def onkick(m)
897     if(m.address?)
898       debug "kicked from channel #{m.channel}"
899       @channels.delete(m.channel)
900       log "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
901     else
902       @channels[m.channel].users.delete(m.sourcenick)
903       log "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
904     end
905
906     @plugins.delegate("listen", m)
907     @plugins.delegate("kick", m)
908   end
909
910   def ontopic(m)
911     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
912     @channels[m.channel].topic = m.topic if !m.topic.nil?
913     @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
914     @channels[m.channel].topic.by = m.source if !m.source.nil?
915
916           debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
917   end
918
919   # delegate a privmsg to auth, keyword or plugin handlers
920   def delegate_privmsg(message)
921     [@auth, @plugins, @keywords].each {|m|
922       break if m.privmsg(message)
923     }
924   end
925 end
926
927 end