]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
51f323b37d83c15fb6fe49b8a481f03237796ccb
[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 "data directory '#{Config::DATADIR}' not found, did you 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") unless File.exist?("#{botclass}/logs")
101
102     @startup_time = Time.new
103     @config = Irc::BotConfig.new(self)
104     @timer = Timer::Timer.new(1.0) # only need per-second granularity
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
115     Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
116     @plugins = Irc::Plugins.new(self, ["#{botclass}/plugins"])
117
118     @socket = Irc::IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
119     @nick = @config['irc.nick']
120     if @config['core.address_prefix']
121       @addressing_prefixes = @config['core.address_prefix'].split(" ")
122     else
123       @addressing_prefixes = Array.new
124     end
125     
126     @client = Irc::IrcClient.new
127     @client["PRIVMSG"] = proc { |data|
128       message = PrivMessage.new(self, data["SOURCE"], data["TARGET"], data["MESSAGE"])
129       onprivmsg(message)
130     }
131     @client["NOTICE"] = proc { |data|
132       message = NoticeMessage.new(self, data["SOURCE"], data["TARGET"], data["MESSAGE"])
133       # pass it off to plugins that want to hear everything
134       @plugins.delegate "listen", message
135     }
136     @client["MOTD"] = proc { |data|
137       data['MOTD'].each_line { |line|
138         log "MOTD: #{line}", "server"
139       }
140     }
141     @client["NICKTAKEN"] = proc { |data| 
142       nickchg "#{@nick}_"
143     }
144     @client["BADNICK"] = proc {|data| 
145       puts "WARNING, bad nick (#{data['NICK']})"
146     }
147     @client["PING"] = proc {|data|
148       # (jump the queue for pongs)
149       @socket.puts "PONG #{data['PINGID']}"
150     }
151     @client["NICK"] = proc {|data|
152       sourcenick = data["SOURCENICK"]
153       nick = data["NICK"]
154       m = NickMessage.new(self, data["SOURCE"], data["SOURCENICK"], data["NICK"])
155       if(sourcenick == @nick)
156         @nick = nick
157       end
158       @channels.each {|k,v|
159         if(v.users.has_key?(sourcenick))
160           log "@ #{sourcenick} is now known as #{nick}", k
161           v.users[nick] = v.users[sourcenick]
162           v.users.delete(sourcenick)
163         end
164       }
165       @plugins.delegate("listen", m)
166       @plugins.delegate("nick", m)
167     }
168     @client["QUIT"] = proc {|data|
169       source = data["SOURCE"]
170       sourcenick = data["SOURCENICK"]
171       sourceurl = data["SOURCEADDRESS"]
172       message = data["MESSAGE"]
173       m = QuitMessage.new(self, data["SOURCE"], data["SOURCENICK"], data["MESSAGE"])
174       if(data["SOURCENICK"] =~ /#{@nick}/i)
175       else
176         @channels.each {|k,v|
177           if(v.users.has_key?(sourcenick))
178             log "@ Quit: #{sourcenick}: #{message}", k
179             v.users.delete(sourcenick)
180           end
181         }
182       end
183       @plugins.delegate("listen", m)
184       @plugins.delegate("quit", m)
185     }
186     @client["MODE"] = proc {|data|
187       source = data["SOURCE"]
188       sourcenick = data["SOURCENICK"]
189       sourceurl = data["SOURCEADDRESS"]
190       channel = data["CHANNEL"]
191       targets = data["TARGETS"]
192       modestring = data["MODESTRING"]
193       log "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
194     }
195     @client["WELCOME"] = proc {|data|
196       log "joined server #{data['SOURCE']} as #{data['NICK']}", "server"
197       debug "I think my nick is #{@nick}, server thinks #{data['NICK']}"
198       if data['NICK'] && data['NICK'].length > 0
199         @nick = data['NICK']
200       end
201       if(@config['irc.quser'])
202         puts "authing with Q using  #{@config['quakenet.user']} #{@config['quakenet.auth']}"
203         @socket.puts "PRIVMSG Q@CServe.quakenet.org :auth #{@config['quakenet.user']} #{@config['quakenet.auth']}"
204       end
205
206       if(@config['irc.join_channels'])
207         @config['irc.join_channels'].split(", ").each {|c|
208           debug "autojoining channel #{c}"
209           if(c =~ /^(\S+)\s+(\S+)$/i)
210             join $1, $2
211           else
212             join c if(c)
213           end
214         }
215       end
216     }
217     @client["JOIN"] = proc {|data|
218       m = JoinMessage.new(self, data["SOURCE"], data["CHANNEL"], data["MESSAGE"])
219       onjoin(m)
220     }
221     @client["PART"] = proc {|data|
222       m = PartMessage.new(self, data["SOURCE"], data["CHANNEL"], data["MESSAGE"])
223       onpart(m)
224     }
225     @client["KICK"] = proc {|data|
226       m = KickMessage.new(self, data["SOURCE"], data["TARGET"],data["CHANNEL"],data["MESSAGE"]) 
227       onkick(m)
228     }
229     @client["INVITE"] = proc {|data|
230       if(data["TARGET"] =~ /^#{@nick}$/i)
231         join data["CHANNEL"] if (@auth.allow?("join", data["SOURCE"], data["SOURCENICK"]))
232       end
233     }
234     @client["CHANGETOPIC"] = proc {|data|
235       channel = data["CHANNEL"]
236       sourcenick = data["SOURCENICK"]
237       topic = data["TOPIC"]
238       timestamp = data["UNIXTIME"] || Time.now.to_i
239       if(sourcenick == @nick)
240         log "@ I set topic \"#{topic}\"", channel
241       else
242         log "@ #{sourcenick} set topic \"#{topic}\"", channel
243       end
244       m = TopicMessage.new(self, data["SOURCE"], data["CHANNEL"], timestamp, data["TOPIC"])
245
246       ontopic(m)
247       @plugins.delegate("listen", m)
248       @plugins.delegate("topic", m)
249     }
250     @client["TOPIC"] = @client["TOPICINFO"] = proc {|data|
251       channel = data["CHANNEL"]
252       m = TopicMessage.new(self, data["SOURCE"], data["CHANNEL"], data["UNIXTIME"], data["TOPIC"])
253         ontopic(m)
254     }
255     @client["NAMES"] = proc {|data|
256       channel = data["CHANNEL"]
257       users = data["USERS"]
258       unless(@channels[channel])
259         puts "bug: got names for channel '#{channel}' I didn't think I was in\n"
260         exit 2
261       end
262       @channels[channel].users.clear
263       users.each {|u|
264         @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
265       }
266     }
267     @client["UNKNOWN"] = proc {|data|
268       debug "UNKNOWN: #{data['SERVERSTRING']}"
269     }
270   end
271
272   # connect the bot to IRC
273   def connect
274     trap("SIGTERM") { quit }
275     trap("SIGHUP") { quit }
276     trap("SIGINT") { quit }
277     begin
278       @socket.connect
279       rescue => e
280       raise "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
281     end
282     @socket.puts "PASS " + @config['server.password'] if @config['server.password']
283     @socket.puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
284   end
285
286   # begin event handling loop
287   def mainloop
288     while true
289       connect
290       @timer.start
291       
292       begin
293         while true
294           if @socket.select
295             break unless reply = @socket.gets
296             @client.process reply
297           end
298         end
299       rescue => e
300         puts "connection closed: #{e}"
301         puts e.backtrace.join("\n")
302       end
303       
304       puts "disconnected"
305       @channels.clear
306       @socket.clearq
307       
308       puts "waiting to reconnect"
309       sleep @config['server.reconnect_wait']
310     end
311   end
312   
313   # type:: message type
314   # where:: message target
315   # message:: message text
316   # send message +message+ of type +type+ to target +where+
317   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
318   # relevant say() or notice() methods. This one should be used for IRCd
319   # extensions you want to use in modules.
320   def sendmsg(type, where, message)
321     # limit it 440 chars + CRLF.. so we have to split long lines
322     left = 440 - type.length - where.length - 3
323     begin
324       if(left >= message.length)
325         sendq("#{type} #{where} :#{message}")
326         log_sent(type, where, message)
327         return
328       end
329       line = message.slice!(0, left)
330       lastspace = line.rindex(/\s+/)
331       if(lastspace)
332         message = line.slice!(lastspace, line.length) + message
333         message.gsub!(/^\s+/, "")
334       end
335       sendq("#{type} #{where} :#{line}")
336       log_sent(type, where, line)
337     end while(message.length > 0)
338   end
339
340   def sendq(message="")
341     # temporary
342     @socket.queue(message)
343   end
344
345   # send a notice message to channel/nick +where+
346   def notice(where, message)
347     message.each_line { |line|
348       line.chomp!
349       next unless(line.length > 0)
350       sendmsg("NOTICE", where, line)
351     }
352   end
353
354   # say something (PRIVMSG) to channel/nick +where+
355   def say(where, message)
356     message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
357       line.chomp!
358       next unless(line.length > 0)
359       unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
360         sendmsg("PRIVMSG", where, line)
361       end
362     }
363   end
364
365   # perform a CTCP action with message +message+ to channel/nick +where+
366   def action(where, message)
367     sendq("PRIVMSG #{where} :\001ACTION #{message}\001")
368     if(where =~ /^#/)
369       log "* #{@nick} #{message}", where
370     elsif (where =~ /^(\S*)!.*$/)
371          log "* #{@nick}[#{where}] #{message}", $1
372     else
373          log "* #{@nick}[#{where}] #{message}", where
374     end
375   end
376
377   # quick way to say "okay" (or equivalent) to +where+
378   def okay(where)
379     say where, @lang.get("okay")
380   end
381
382   # log message +message+ to a file determined by +where+. +where+ can be a
383   # channel name, or a nick for private message logging
384   def log(message, where="server")
385     message.chomp!
386     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
387     unless(@logs.has_key?(where))
388       @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
389       @logs[where].sync = true
390     end
391     @logs[where].puts "[#{stamp}] #{message}"
392     #debug "[#{stamp}] <#{where}> #{message}"
393   end
394   
395   # set topic of channel +where+ to +topic+
396   def topic(where, topic)
397     sendq "TOPIC #{where} :#{topic}"
398   end
399   
400   # message:: optional IRC quit message
401   # quit IRC, shutdown the bot
402   def quit(message=nil)
403     trap("SIGTERM", "DEFAULT")
404     trap("SIGHUP", "DEFAULT")
405     trap("SIGINT", "DEFAULT")
406     message = @lang.get("quit") if (!message || message.length < 1)
407     @socket.clearq
408     save
409     @plugins.cleanup
410     @channels.each_value {|v|
411       log "@ quit (#{message})", v.name
412     }
413     @socket.puts "QUIT :#{message}"
414     @socket.flush
415     @socket.shutdown
416     @registry.close
417     puts "rbot quit (#{message})"
418     exit 0
419   end
420
421   # call the save method for bot's config, keywords, auth and all plugins
422   def save
423     @registry.flush
424     @config.save
425     @keywords.save
426     @auth.save
427     @plugins.save
428   end
429
430   # call the rescan method for the bot's lang, keywords and all plugins
431   def rescan
432     @lang.rescan
433     @plugins.rescan
434     @keywords.rescan
435   end
436   
437   # channel:: channel to join
438   # key::     optional channel key if channel is +s
439   # join a channel
440   def join(channel, key=nil)
441     if(key)
442       sendq "JOIN #{channel} :#{key}"
443     else
444       sendq "JOIN #{channel}"
445     end
446   end
447
448   # part a channel
449   def part(channel, message="")
450     sendq "PART #{channel} :#{message}"
451   end
452
453   # attempt to change bot's nick to +name+
454   def nickchg(name)
455       sendq "NICK #{name}"
456   end
457
458   # changing mode
459   def mode(channel, mode, target)
460       sendq "MODE #{channel} #{mode} #{target}"
461   end
462   
463   # m::     message asking for help
464   # topic:: optional topic help is requested for
465   # respond to online help requests
466   def help(topic=nil)
467     topic = nil if topic == ""
468     case topic
469     when nil
470       helpstr = "help topics: core, auth, keywords"
471       helpstr += @plugins.helptopics
472       helpstr += " (help <topic> for more info)"
473     when /^core$/i
474       helpstr = corehelp
475     when /^core\s+(.+)$/i
476       helpstr = corehelp $1
477     when /^auth$/i
478       helpstr = @auth.help
479     when /^auth\s+(.+)$/i
480       helpstr = @auth.help $1
481     when /^keywords$/i
482       helpstr = @keywords.help
483     when /^keywords\s+(.+)$/i
484       helpstr = @keywords.help $1
485     else
486       unless(helpstr = @plugins.help(topic))
487         helpstr = "no help for topic #{topic}"
488       end
489     end
490     return helpstr
491   end
492
493   def status
494     secs_up = Time.new - @startup_time
495     uptime = Utils.secs_to_string secs_up
496     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
497   end
498
499
500   private
501
502   # handle help requests for "core" topics
503   def corehelp(topic="")
504     case topic
505       when "quit"
506         return "quit [<message>] => quit IRC with message <message>"
507       when "join"
508         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"
509       when "part"
510         return "part <channel> => part channel <channel>"
511       when "hide"
512         return "hide => part all channels"
513       when "save"
514         return "save => save current dynamic data and configuration"
515       when "rescan"
516         return "rescan => reload modules and static facts"
517       when "nick"
518         return "nick <nick> => attempt to change nick to <nick>"
519       when "say"
520         return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
521       when "action"
522         return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
523       when "topic"
524         return "topic <channel> <message> => set topic of <channel> to <message>"
525       when "quiet"
526         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>"
527       when "talk"
528         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>"
529       when "version"
530         return "version => describes software version"
531       when "botsnack"
532         return "botsnack => reward #{@nick} for being good"
533       when "hello"
534         return "hello|hi|hey|yo [#{@nick}] => greet the bot"
535       else
536         return "Core help topics: quit, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
537     end
538   end
539
540   # handle incoming IRC PRIVMSG +m+
541   def onprivmsg(m)
542     # log it first
543     if(m.action?)
544       if(m.private?)
545         log "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
546       else
547         log "* #{m.sourcenick} #{m.message}", m.target
548       end
549     else
550       if(m.public?)
551         log "<#{m.sourcenick}> #{m.message}", m.target
552       else
553         log "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
554       end
555     end
556
557     # pass it off to plugins that want to hear everything
558     @plugins.delegate "listen", m
559
560     if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
561       notice m.sourcenick, "\001PING #$1\001"
562       log "@ #{m.sourcenick} pinged me"
563       return
564     end
565
566     if(m.address?)
567       case m.message
568         when (/^join\s+(\S+)\s+(\S+)$/i)
569           join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
570         when (/^join\s+(\S+)$/i)
571           join $1 if(@auth.allow?("join", m.source, m.replyto))
572         when (/^part$/i)
573           part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
574         when (/^part\s+(\S+)$/i)
575           part $1 if(@auth.allow?("join", m.source, m.replyto))
576         when (/^quit(?:\s+(.*))?$/i)
577           quit $1 if(@auth.allow?("quit", m.source, m.replyto))
578         when (/^hide$/i)
579           join 0 if(@auth.allow?("join", m.source, m.replyto))
580         when (/^save$/i)
581           if(@auth.allow?("config", m.source, m.replyto))
582             save
583             m.okay
584           end
585         when (/^nick\s+(\S+)$/i)
586           nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
587         when (/^say\s+(\S+)\s+(.*)$/i)
588           say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
589         when (/^action\s+(\S+)\s+(.*)$/i)
590           action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
591         when (/^topic\s+(\S+)\s+(.*)$/i)
592           topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
593         when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
594           mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
595         when (/^ping$/i)
596           say m.replyto, "pong"
597         when (/^rescan$/i)
598           if(@auth.allow?("config", m.source, m.replyto))
599             m.okay
600             rescan
601           end
602         when (/^quiet$/i)
603           if(auth.allow?("talk", m.source, m.replyto))
604             m.okay
605             @channels.each_value {|c| c.quiet = true }
606           end
607         when (/^quiet in (\S+)$/i)
608           where = $1
609           if(auth.allow?("talk", m.source, m.replyto))
610             m.okay
611             where.gsub!(/^here$/, m.target) if m.public?
612             @channels[where].quiet = true if(@channels.has_key?(where))
613           end
614         when (/^talk$/i)
615           if(auth.allow?("talk", m.source, m.replyto))
616             @channels.each_value {|c| c.quiet = false }
617             m.okay
618           end
619         when (/^talk in (\S+)$/i)
620           where = $1
621           if(auth.allow?("talk", m.source, m.replyto))
622             where.gsub!(/^here$/, m.target) if m.public?
623             @channels[where].quiet = false if(@channels.has_key?(where))
624             m.okay
625           end
626         # TODO break this out into a config module
627         when (/^options get sendq_delay$/i)
628           if auth.allow?("config", m.source, m.replyto)
629             m.reply "options->sendq_delay = #{@socket.sendq_delay}"
630           end
631         when (/^options get sendq_burst$/i)
632           if auth.allow?("config", m.source, m.replyto)
633             m.reply "options->sendq_burst = #{@socket.sendq_burst}"
634           end
635         when (/^options set sendq_burst (.*)$/i)
636           num = $1.to_i
637           if auth.allow?("config", m.source, m.replyto)
638             @socket.sendq_burst = num
639             @config['irc.sendq_burst'] = num
640             m.okay
641           end
642         when (/^options set sendq_delay (.*)$/i)
643           freq = $1.to_f
644           if auth.allow?("config", m.source, m.replyto)
645             @socket.sendq_delay = freq
646             @config['irc.sendq_delay'] = freq
647             m.okay
648           end
649         when (/^status$/i)
650           m.reply status if auth.allow?("status", m.source, m.replyto)
651         when (/^registry stats$/i)
652           if auth.allow?("config", m.source, m.replyto)
653             m.reply @registry.stat.inspect
654           end
655         when (/^(version)|(introduce yourself)$/i)
656           say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
657         when (/^help(?:\s+(.*))?$/i)
658           say m.replyto, help($1)
659         when (/^(botsnack|ciggie)$/i)
660           say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
661           say m.replyto, @lang.get("thanks") if(m.private?)
662         when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
663           say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
664           say m.replyto, @lang.get("hello") if(m.private?)
665         else
666           delegate_privmsg(m)
667       end
668     else
669       # stuff to handle when not addressed
670       case m.message
671         when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$))\s+#{@nick}$/i)
672           say m.replyto, @lang.get("hello_X") % m.sourcenick
673         when (/^#{@nick}!*$/)
674           say m.replyto, @lang.get("hello_X") % m.sourcenick
675         else
676           @keywords.privmsg(m)
677       end
678     end
679   end
680
681   # log a message. Internal use only.
682   def log_sent(type, where, message)
683     case type
684       when "NOTICE"
685         if(where =~ /^#/)
686           log "-=#{@nick}=- #{message}", where
687         elsif (where =~ /(\S*)!.*/)
688              log "[-=#{where}=-] #{message}", $1
689         else
690              log "[-=#{where}=-] #{message}"
691         end
692       when "PRIVMSG"
693         if(where =~ /^#/)
694           log "<#{@nick}> #{message}", where
695         elsif (where =~ /^(\S*)!.*$/)
696           log "[msg(#{where})] #{message}", $1
697         else
698           log "[msg(#{where})] #{message}", where
699         end
700     end
701   end
702
703   def onjoin(m)
704     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
705     if(m.address?)
706       log "@ Joined channel #{m.channel}", m.channel
707       puts "joined channel #{m.channel}"
708     else
709       log "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
710       @channels[m.channel].users[m.sourcenick] = Hash.new
711       @channels[m.channel].users[m.sourcenick]["mode"] = ""
712     end
713
714     @plugins.delegate("listen", m)
715     @plugins.delegate("join", m)
716   end
717
718   def onpart(m)
719     if(m.address?)
720       log "@ Left channel #{m.channel} (#{m.message})", m.channel
721       @channels.delete(m.channel)
722       puts "left channel #{m.channel}"
723     else
724       log "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
725       @channels[m.channel].users.delete(m.sourcenick)
726     end
727     
728     # delegate to plugins
729     @plugins.delegate("listen", m)
730     @plugins.delegate("part", m)
731   end
732
733   # respond to being kicked from a channel
734   def onkick(m)
735     if(m.address?)
736       @channels.delete(m.channel)
737       log "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
738       puts "kicked from channel #{m.channel}"
739     else
740       @channels[m.channel].users.delete(m.sourcenick)
741       log "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
742     end
743
744     @plugins.delegate("listen", m)
745     @plugins.delegate("kick", m)
746   end
747
748   def ontopic(m)
749     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
750     @channels[m.channel].topic = m.topic if !m.topic.nil?
751     @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
752     @channels[m.channel].topic.by = m.source if !m.source.nil?
753
754           debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
755   end
756
757   # delegate a privmsg to auth, keyword or plugin handlers
758   def delegate_privmsg(message)
759     [@auth, @plugins, @keywords].each {|m|
760       break if m.privmsg(message)
761     }
762   end
763
764 end
765
766 end