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