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