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