]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
3881771d37a659d190020642ccd52eb90b8c1f8b
[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     BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
116       :default => 10, :validate => Proc.new{|v| v >= 0},
117       :on_change => Proc.new {|bot, v| bot.start_server_pings},
118       :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
119
120     @argv = params[:argv]
121
122     unless FileTest.directory? Config::datadir
123       puts "data directory '#{Config::datadir}' not found, did you setup.rb?"
124       exit 2
125     end
126     
127     #botclass = "#{Etc.getpwnam(Etc.getlogin).dir}/.rbot" unless botclass
128     botclass = "#{ENV['HOME']}/.rbot" unless botclass
129     @botclass = botclass.gsub(/\/$/, "")
130
131     unless FileTest.directory? botclass
132       puts "no #{botclass} directory found, creating from templates.."
133       if FileTest.exist? botclass
134         puts "Error: file #{botclass} exists but isn't a directory"
135         exit 2
136       end
137       FileUtils.cp_r Config::datadir+'/templates', botclass
138     end
139     
140     Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
141
142     @ping_timer = nil
143     @timeout_timer = nil
144     @startup_time = Time.new
145     @config = BotConfig.new(self)
146 # TODO background self after botconfig has a chance to run wizard
147     @timer = Timer::Timer.new(1.0) # only need per-second granularity
148     @registry = BotRegistry.new self
149     @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
150     @channels = Hash.new
151     @logs = Hash.new
152     @httputil = Utils::HttpUtil.new(self)
153     @lang = Language::Language.new(@config['core.language'])
154     @keywords = Keywords.new(self)
155     @auth = IrcAuth.new(self)
156
157     Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
158     @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
159
160     @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
161     @nick = @config['irc.nick']
162
163     @client = IrcClient.new
164     @client[:privmsg] = proc { |data|
165       message = PrivMessage.new(self, data[:source], data[:target], data[:message])
166       onprivmsg(message)
167     }
168     @client[:notice] = proc { |data|
169       message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
170       # pass it off to plugins that want to hear everything
171       @plugins.delegate "listen", message
172     }
173     @client[:motd] = proc { |data|
174       data[:motd].each_line { |line|
175         log "MOTD: #{line}", "server"
176       }
177     }
178     @client[:nicktaken] = proc { |data| 
179       nickchg "#{data[:nick]}_"
180     }
181     @client[:badnick] = proc {|data| 
182       puts "WARNING, bad nick (#{data[:nick]})"
183     }
184     @client[:ping] = proc {|data|
185       # (jump the queue for pongs)
186       @socket.puts "PONG #{data[:pingid]}"
187     }
188     @client[:pong] = proc {|data|
189       # cancel the timeout timer
190       debug "got a pong from the server, cancelling timeout"
191       remove_timeout_timer
192     }
193     @client[:nick] = proc {|data|
194       sourcenick = data[:sourcenick]
195       nick = data[:nick]
196       m = NickMessage.new(self, data[:source], data[:sourcenick], data[:nick])
197       if(sourcenick == @nick)
198         debug "my nick is now #{nick}"
199         @nick = nick
200       end
201       @channels.each {|k,v|
202         if(v.users.has_key?(sourcenick))
203           log "@ #{sourcenick} is now known as #{nick}", k
204           v.users[nick] = v.users[sourcenick]
205           v.users.delete(sourcenick)
206         end
207       }
208       @plugins.delegate("listen", m)
209       @plugins.delegate("nick", m)
210     }
211     @client[:quit] = proc {|data|
212       source = data[:source]
213       sourcenick = data[:sourcenick]
214       sourceurl = data[:sourceaddress]
215       message = data[:message]
216       m = QuitMessage.new(self, data[:source], data[:sourcenick], data[:message])
217       if(data[:sourcenick] =~ /#{Regexp.escape(@nick)}/i)
218       else
219         @channels.each {|k,v|
220           if(v.users.has_key?(sourcenick))
221             log "@ Quit: #{sourcenick}: #{message}", k
222             v.users.delete(sourcenick)
223           end
224         }
225       end
226       @plugins.delegate("listen", m)
227       @plugins.delegate("quit", m)
228     }
229     @client[:mode] = proc {|data|
230       source = data[:source]
231       sourcenick = data[:sourcenick]
232       sourceurl = data[:sourceaddress]
233       channel = data[:channel]
234       targets = data[:targets]
235       modestring = data[:modestring]
236       log "@ Mode #{modestring} #{targets} by #{sourcenick}", channel
237     }
238     @client[:welcome] = proc {|data|
239       log "joined server #{data[:source]} as #{data[:nick]}", "server"
240       debug "I think my nick is #{@nick}, server thinks #{data[:nick]}"
241       if data[:nick] && data[:nick].length > 0
242         @nick = data[:nick]
243       end
244
245       @plugins.delegate("connect")
246
247       @config['irc.join_channels'].each {|c|
248         debug "autojoining channel #{c}"
249         if(c =~ /^(\S+)\s+(\S+)$/i)
250           join $1, $2
251         else
252           join c if(c)
253         end
254       }
255     }
256     @client[:join] = proc {|data|
257       m = JoinMessage.new(self, data[:source], data[:channel], data[:message])
258       onjoin(m)
259     }
260     @client[:part] = proc {|data|
261       m = PartMessage.new(self, data[:source], data[:channel], data[:message])
262       onpart(m)
263     }
264     @client[:kick] = proc {|data|
265       m = KickMessage.new(self, data[:source], data[:target],data[:channel],data[:message]) 
266       onkick(m)
267     }
268     @client[:invite] = proc {|data|
269       if(data[:target] =~ /^#{Regexp.escape(@nick)}$/i)
270         join data[:channel] if (@auth.allow?("join", data[:source], data[:sourcenick]))
271       end
272     }
273     @client[:changetopic] = proc {|data|
274       channel = data[:channel]
275       sourcenick = data[:sourcenick]
276       topic = data[:topic]
277       timestamp = data[:unixtime] || Time.now.to_i
278       if(sourcenick == @nick)
279         log "@ I set topic \"#{topic}\"", channel
280       else
281         log "@ #{sourcenick} set topic \"#{topic}\"", channel
282       end
283       m = TopicMessage.new(self, data[:source], data[:channel], timestamp, data[:topic])
284
285       ontopic(m)
286       @plugins.delegate("listen", m)
287       @plugins.delegate("topic", m)
288     }
289     @client[:topic] = @client[:topicinfo] = proc {|data|
290       channel = data[:channel]
291       m = TopicMessage.new(self, data[:source], data[:channel], data[:unixtime], data[:topic])
292         ontopic(m)
293     }
294     @client[:names] = proc {|data|
295       channel = data[:channel]
296       users = data[:users]
297       unless(@channels[channel])
298         puts "bug: got names for channel '#{channel}' I didn't think I was in\n"
299         exit 2
300       end
301       @channels[channel].users.clear
302       users.each {|u|
303         @channels[channel].users[u[0].sub(/^[@&~+]/, '')] = ["mode", u[1]]
304       }
305     }
306     @client[:unknown] = proc {|data|
307       #debug "UNKNOWN: #{data[:serverstring]}"
308       log data[:serverstring], ":unknown"
309     }
310   end
311
312   # connect the bot to IRC
313   def connect
314     begin
315       trap("SIGTERM") { quit }
316       trap("SIGHUP") { quit }
317       trap("SIGINT") { quit }
318     rescue
319       debug "failed to trap signals, probably running on windows?"
320     end
321     begin
322       @socket.connect
323       rescue => e
324       raise "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
325     end
326     @socket.puts "PASS " + @config['server.password'] if @config['server.password']
327     @socket.puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
328     start_server_pings
329   end
330
331   # begin event handling loop
332   def mainloop
333     while true
334       connect
335       @timer.start
336       
337       begin
338         while true
339           if @socket.select
340             break unless reply = @socket.gets
341             @client.process reply
342           end
343         end
344       # I despair of this. Some of my users get "connection reset by peer"
345       # exceptions that ARENT SocketError's. How am I supposed to handle
346       # that?
347       #rescue TimeoutError, SocketError => e
348       rescue Exception => e
349         puts "network exception: connection closed: #{e}"
350         puts e.backtrace.join("\n")
351         @socket.shutdown # now we reconnect
352       rescue => e
353         puts "unexpected exception: connection closed: #{e.inspect}"
354         puts e.backtrace.join("\n")
355         exit 2
356       end
357       
358       puts "disconnected"
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.chomp!
441     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
442     unless(@logs.has_key?(where))
443       @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
444       @logs[where].sync = true
445     end
446     @logs[where].puts "[#{stamp}] #{message}"
447     #debug "[#{stamp}] <#{where}> #{message}"
448   end
449   
450   # set topic of channel +where+ to +topic+
451   def topic(where, topic)
452     sendq "TOPIC #{where} :#{topic}"
453   end
454
455   # disconnect from the server and cleanup all plugins and modules
456   def shutdown(message = nil)
457     trap("SIGTERM", "DEFAULT")
458     trap("SIGHUP", "DEFAULT")
459     trap("SIGINT", "DEFAULT")
460     message = @lang.get("quit") if (message.nil? || message.empty?)
461     @socket.clearq
462     save
463     @plugins.cleanup
464     @channels.each_value {|v|
465       log "@ quit (#{message})", v.name
466     }
467     @socket.puts "QUIT :#{message}"
468     @socket.flush
469     @socket.shutdown
470     @registry.close
471     puts "rbot quit (#{message})"
472   end
473   
474   # message:: optional IRC quit message
475   # quit IRC, shutdown the bot
476   def quit(message=nil)
477     shutdown(message)
478     exit 0
479   end
480
481   # totally shutdown and respawn the bot
482   def restart(message = false)
483     msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
484     shutdown(msg)
485     sleep @config['server.reconnect_wait']
486     # now we re-exec
487     exec($0, *@argv)
488   end
489
490   # call the save method for bot's config, keywords, auth and all plugins
491   def save
492     @registry.flush
493     @config.save
494     @keywords.save
495     @auth.save
496     @plugins.save
497   end
498
499   # call the rescan method for the bot's lang, keywords and all plugins
500   def rescan
501     @lang.rescan
502     @plugins.rescan
503     @keywords.rescan
504   end
505   
506   # channel:: channel to join
507   # key::     optional channel key if channel is +s
508   # join a channel
509   def join(channel, key=nil)
510     if(key)
511       sendq "JOIN #{channel} :#{key}"
512     else
513       sendq "JOIN #{channel}"
514     end
515   end
516
517   # part a channel
518   def part(channel, message="")
519     sendq "PART #{channel} :#{message}"
520   end
521
522   # attempt to change bot's nick to +name+
523   def nickchg(name)
524       sendq "NICK #{name}"
525   end
526
527   # changing mode
528   def mode(channel, mode, target)
529       sendq "MODE #{channel} #{mode} #{target}"
530   end
531   
532   # m::     message asking for help
533   # topic:: optional topic help is requested for
534   # respond to online help requests
535   def help(topic=nil)
536     topic = nil if topic == ""
537     case topic
538     when nil
539       helpstr = "help topics: core, auth, keywords"
540       helpstr += @plugins.helptopics
541       helpstr += " (help <topic> for more info)"
542     when /^core$/i
543       helpstr = corehelp
544     when /^core\s+(.+)$/i
545       helpstr = corehelp $1
546     when /^auth$/i
547       helpstr = @auth.help
548     when /^auth\s+(.+)$/i
549       helpstr = @auth.help $1
550     when /^keywords$/i
551       helpstr = @keywords.help
552     when /^keywords\s+(.+)$/i
553       helpstr = @keywords.help $1
554     else
555       unless(helpstr = @plugins.help(topic))
556         helpstr = "no help for topic #{topic}"
557       end
558     end
559     return helpstr
560   end
561
562   # returns a string describing the current status of the bot (uptime etc)
563   def status
564     secs_up = Time.new - @startup_time
565     uptime = Utils.secs_to_string secs_up
566     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
567   end
568
569   # we'll ping the server every 30 seconds or so, and expect a response
570   # before the next one come around..
571   def start_server_pings
572     # stop existing timers if running
573     unless @ping_timer.nil?
574       @timer.remove @ping_timer
575       @ping_timer = nil
576     end
577     remove_timeout_timer
578     timeout = @config['server.ping_timeout']
579     return unless timeout > 0
580     timeout = 30 if timeout > 30
581     # we want to respond to a hung server within 30 secs or so
582     @ping_timer = @timer.add(30) {
583       remove_timeout_timer
584       @socket.puts "PING :rbot"
585       @timeout_timer = @timer.add_once(timeout) {
586         debug "no PONG from server for #{timeout} seconds, reconnecting"
587         begin
588           @socket.shutdown
589         rescue
590           debug "couldn't shutdown connection (already shutdown?)"
591         end
592       } if @config['server.ping_timeout']
593     }
594   end
595
596   private
597
598   def remove_timeout_timer
599     unless @timeout_timer.nil?
600       @timer.remove(@timeout_timer)
601       @timeout_timer = nil
602     end
603   end
604
605   # handle help requests for "core" topics
606   def corehelp(topic="")
607     case topic
608       when "quit"
609         return "quit [<message>] => quit IRC with message <message>"
610       when "restart"
611         return "restart => completely stop and restart the bot (including reconnect)"
612       when "join"
613         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"
614       when "part"
615         return "part <channel> => part channel <channel>"
616       when "hide"
617         return "hide => part all channels"
618       when "save"
619         return "save => save current dynamic data and configuration"
620       when "rescan"
621         return "rescan => reload modules and static facts"
622       when "nick"
623         return "nick <nick> => attempt to change nick to <nick>"
624       when "say"
625         return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
626       when "action"
627         return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
628       when "topic"
629         return "topic <channel> <message> => set topic of <channel> to <message>"
630       when "quiet"
631         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>"
632       when "talk"
633         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>"
634       when "version"
635         return "version => describes software version"
636       when "botsnack"
637         return "botsnack => reward #{@nick} for being good"
638       when "hello"
639         return "hello|hi|hey|yo [#{@nick}] => greet the bot"
640       else
641         return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
642     end
643   end
644
645   # handle incoming IRC PRIVMSG +m+
646   def onprivmsg(m)
647     # log it first
648     if(m.action?)
649       if(m.private?)
650         log "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
651       else
652         log "* #{m.sourcenick} #{m.message}", m.target
653       end
654     else
655       if(m.public?)
656         log "<#{m.sourcenick}> #{m.message}", m.target
657       else
658         log "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
659       end
660     end
661
662     # pass it off to plugins that want to hear everything
663     @plugins.delegate "listen", m
664
665     if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
666       notice m.sourcenick, "\001PING #$1\001"
667       log "@ #{m.sourcenick} pinged me"
668       return
669     end
670
671     if(m.address?)
672       case m.message
673         when (/^join\s+(\S+)\s+(\S+)$/i)
674           join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
675         when (/^join\s+(\S+)$/i)
676           join $1 if(@auth.allow?("join", m.source, m.replyto))
677         when (/^part$/i)
678           part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
679         when (/^part\s+(\S+)$/i)
680           part $1 if(@auth.allow?("join", m.source, m.replyto))
681         when (/^quit(?:\s+(.*))?$/i)
682           quit $1 if(@auth.allow?("quit", m.source, m.replyto))
683         when (/^restart(?:\s+(.*))?$/i)
684           restart $1 if(@auth.allow?("quit", m.source, m.replyto))
685         when (/^hide$/i)
686           join 0 if(@auth.allow?("join", m.source, m.replyto))
687         when (/^save$/i)
688           if(@auth.allow?("config", m.source, m.replyto))
689             save
690             m.okay
691           end
692         when (/^nick\s+(\S+)$/i)
693           nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
694         when (/^say\s+(\S+)\s+(.*)$/i)
695           say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
696         when (/^action\s+(\S+)\s+(.*)$/i)
697           action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
698         when (/^topic\s+(\S+)\s+(.*)$/i)
699           topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
700         when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
701           mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
702         when (/^ping$/i)
703           say m.replyto, "pong"
704         when (/^rescan$/i)
705           if(@auth.allow?("config", m.source, m.replyto))
706             m.okay
707             rescan
708           end
709         when (/^quiet$/i)
710           if(auth.allow?("talk", m.source, m.replyto))
711             m.okay
712             @channels.each_value {|c| c.quiet = true }
713           end
714         when (/^quiet in (\S+)$/i)
715           where = $1
716           if(auth.allow?("talk", m.source, m.replyto))
717             m.okay
718             where.gsub!(/^here$/, m.target) if m.public?
719             @channels[where].quiet = true if(@channels.has_key?(where))
720           end
721         when (/^talk$/i)
722           if(auth.allow?("talk", m.source, m.replyto))
723             @channels.each_value {|c| c.quiet = false }
724             m.okay
725           end
726         when (/^talk in (\S+)$/i)
727           where = $1
728           if(auth.allow?("talk", m.source, m.replyto))
729             where.gsub!(/^here$/, m.target) if m.public?
730             @channels[where].quiet = false if(@channels.has_key?(where))
731             m.okay
732           end
733         when (/^status\??$/i)
734           m.reply status if auth.allow?("status", m.source, m.replyto)
735         when (/^registry stats$/i)
736           if auth.allow?("config", m.source, m.replyto)
737             m.reply @registry.stat.inspect
738           end
739         when (/^(help\s+)?config(\s+|$)/)
740           @config.privmsg(m)
741         when (/^(version)|(introduce yourself)$/i)
742           say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
743         when (/^help(?:\s+(.*))?$/i)
744           say m.replyto, help($1)
745           #TODO move these to a "chatback" plugin
746         when (/^(botsnack|ciggie)$/i)
747           say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
748           say m.replyto, @lang.get("thanks") if(m.private?)
749         when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
750           say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
751           say m.replyto, @lang.get("hello") if(m.private?)
752         else
753           delegate_privmsg(m)
754       end
755     else
756       # stuff to handle when not addressed
757       case m.message
758         when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
759           say m.replyto, @lang.get("hello_X") % m.sourcenick
760         when (/^#{Regexp.escape(@nick)}!*$/)
761           say m.replyto, @lang.get("hello_X") % m.sourcenick
762         else
763           @keywords.privmsg(m)
764       end
765     end
766   end
767
768   # log a message. Internal use only.
769   def log_sent(type, where, message)
770     case type
771       when "NOTICE"
772         if(where =~ /^#/)
773           log "-=#{@nick}=- #{message}", where
774         elsif (where =~ /(\S*)!.*/)
775              log "[-=#{where}=-] #{message}", $1
776         else
777              log "[-=#{where}=-] #{message}"
778         end
779       when "PRIVMSG"
780         if(where =~ /^#/)
781           log "<#{@nick}> #{message}", where
782         elsif (where =~ /^(\S*)!.*$/)
783           log "[msg(#{where})] #{message}", $1
784         else
785           log "[msg(#{where})] #{message}", where
786         end
787     end
788   end
789
790   def onjoin(m)
791     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
792     if(m.address?)
793       debug "joined channel #{m.channel}"
794       log "@ Joined channel #{m.channel}", m.channel
795     else
796       log "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
797       @channels[m.channel].users[m.sourcenick] = Hash.new
798       @channels[m.channel].users[m.sourcenick]["mode"] = ""
799     end
800
801     @plugins.delegate("listen", m)
802     @plugins.delegate("join", m)
803   end
804
805   def onpart(m)
806     if(m.address?)
807       debug "left channel #{m.channel}"
808       log "@ Left channel #{m.channel} (#{m.message})", m.channel
809       @channels.delete(m.channel)
810     else
811       log "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
812       @channels[m.channel].users.delete(m.sourcenick)
813     end
814     
815     # delegate to plugins
816     @plugins.delegate("listen", m)
817     @plugins.delegate("part", m)
818   end
819
820   # respond to being kicked from a channel
821   def onkick(m)
822     if(m.address?)
823       debug "kicked from channel #{m.channel}"
824       @channels.delete(m.channel)
825       log "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
826     else
827       @channels[m.channel].users.delete(m.sourcenick)
828       log "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
829     end
830
831     @plugins.delegate("listen", m)
832     @plugins.delegate("kick", m)
833   end
834
835   def ontopic(m)
836     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
837     @channels[m.channel].topic = m.topic if !m.topic.nil?
838     @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
839     @channels[m.channel].topic.by = m.source if !m.source.nil?
840
841           debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
842   end
843
844   # delegate a privmsg to auth, keyword or plugin handlers
845   def delegate_privmsg(message)
846     [@auth, @plugins, @keywords].each {|m|
847       break if m.privmsg(message)
848     }
849   end
850 end
851
852 end