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