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