]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
Better workaround for ticket #58; now the {{{names}}} delegationg passes on the chann...
[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 = File.expand_path(botclass)
128     @botclass = botclass.gsub(/\/$/, "")
129
130     unless FileTest.directory? botclass
131       puts "no #{botclass} directory found, creating from templates.."
132       if FileTest.exist? botclass
133         puts "Error: file #{botclass} exists but isn't a directory"
134         exit 2
135       end
136       FileUtils.cp_r Config::datadir+'/templates', botclass
137     end
138     
139     Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
140     Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
141
142     @ping_timer = nil
143     @pong_timer = nil
144     @last_ping = nil
145     @startup_time = Time.new
146     @config = BotConfig.new(self)
147 # TODO background self after botconfig has a chance to run wizard
148     @timer = Timer::Timer.new(1.0) # only need per-second granularity
149     @registry = BotRegistry.new self
150     @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
151     @channels = Hash.new
152     @logs = Hash.new
153     @httputil = Utils::HttpUtil.new(self)
154     @lang = Language::Language.new(@config['core.language'])
155     @keywords = Keywords.new(self)
156     @auth = IrcAuth.new(self)
157
158     Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
159     @plugins = Plugins::Plugins.new(self, ["#{botclass}/plugins"])
160
161     @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
162     @nick = @config['irc.nick']
163
164     @client = IrcClient.new
165     @client[:privmsg] = proc { |data|
166       message = PrivMessage.new(self, data[:source], data[:target], data[:message])
167       onprivmsg(message)
168     }
169     @client[:notice] = proc { |data|
170       message = NoticeMessage.new(self, data[:source], data[:target], data[:message])
171       # pass it off to plugins that want to hear everything
172       @plugins.delegate "listen", message
173     }
174     @client[:motd] = proc { |data|
175       data[:motd].each_line { |line|
176         log "MOTD: #{line}", "server"
177       }
178     }
179     @client[:nicktaken] = proc { |data| 
180       nickchg "#{data[:nick]}_"
181       @plugins.delegate "nicktaken", 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       @socket.puts "PONG #{data[:pingid]}"
189     }
190     @client[:pong] = proc {|data|
191       @last_ping = nil
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       @plugins.delegate "names", data[:channel], data[:users]
306     }
307     @client[:unknown] = proc {|data|
308       #debug "UNKNOWN: #{data[:serverstring]}"
309       log data[:serverstring], ".unknown"
310     }
311   end
312
313   # connect the bot to IRC
314   def connect
315     begin
316       trap("SIGINT") { quit }
317       trap("SIGTERM") { quit }
318       trap("SIGHUP") { quit }
319     rescue
320       debug "failed to trap signals, probably running on windows?"
321     end
322     begin
323       @socket.connect
324     rescue => e
325       raise "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
326     end
327     @socket.puts "PASS " + @config['server.password'] if @config['server.password']
328     @socket.puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
329     start_server_pings
330   end
331
332   # begin event handling loop
333   def mainloop
334     while true
335       begin
336         connect
337         @timer.start
338       
339         while @socket.connected?
340           if @socket.select
341             break unless reply = @socket.gets
342             @client.process reply
343           end
344         end
345       # I despair of this. Some of my users get "connection reset by peer"
346       # exceptions that ARENT SocketError's. How am I supposed to handle
347       # that?
348       #rescue TimeoutError, SocketError => e
349       rescue SystemExit
350         exit 0
351       rescue TimeoutError => e
352         puts e
353       rescue Exception => e
354         puts "network exception: #{e.inspect}"
355         puts e.backtrace.join("\n")
356         @socket.shutdown # now we reconnect
357       rescue => e
358         puts "unexpected exception: connection closed: #{e.inspect}"
359         puts e.backtrace.join("\n")
360         exit 2
361       end
362       
363       puts "disconnected"
364       @last_ping = nil
365       @channels.clear
366       @socket.clearq
367       
368       puts "waiting to reconnect"
369       sleep @config['server.reconnect_wait']
370     end
371   end
372   
373   # type:: message type
374   # where:: message target
375   # message:: message text
376   # send message +message+ of type +type+ to target +where+
377   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
378   # relevant say() or notice() methods. This one should be used for IRCd
379   # extensions you want to use in modules.
380   def sendmsg(type, where, message)
381     # limit it 440 chars + CRLF.. so we have to split long lines
382     left = 440 - type.length - where.length - 3
383     begin
384       if(left >= message.length)
385         sendq("#{type} #{where} :#{message}")
386         log_sent(type, where, message)
387         return
388       end
389       line = message.slice!(0, left)
390       lastspace = line.rindex(/\s+/)
391       if(lastspace)
392         message = line.slice!(lastspace, line.length) + message
393         message.gsub!(/^\s+/, "")
394       end
395       sendq("#{type} #{where} :#{line}")
396       log_sent(type, where, line)
397     end while(message.length > 0)
398   end
399
400   # queue an arbitraty message for the server
401   def sendq(message="")
402     # temporary
403     @socket.queue(message)
404   end
405
406   # send a notice message to channel/nick +where+
407   def notice(where, message)
408     message.each_line { |line|
409       line.chomp!
410       next unless(line.length > 0)
411       sendmsg("NOTICE", where, line)
412     }
413   end
414
415   # say something (PRIVMSG) to channel/nick +where+
416   def say(where, message)
417     message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
418       line.chomp!
419       next unless(line.length > 0)
420       unless((where =~ /^#/) && (@channels.has_key?(where) && @channels[where].quiet))
421         sendmsg("PRIVMSG", where, line)
422       end
423     }
424   end
425
426   # perform a CTCP action with message +message+ to channel/nick +where+
427   def action(where, message)
428     sendq("PRIVMSG #{where} :\001ACTION #{message}\001")
429     if(where =~ /^#/)
430       log "* #{@nick} #{message}", where
431     elsif (where =~ /^(\S*)!.*$/)
432          log "* #{@nick}[#{where}] #{message}", $1
433     else
434          log "* #{@nick}[#{where}] #{message}", where
435     end
436   end
437
438   # quick way to say "okay" (or equivalent) to +where+
439   def okay(where)
440     say where, @lang.get("okay")
441   end
442
443   # log message +message+ to a file determined by +where+. +where+ can be a
444   # channel name, or a nick for private message logging
445   def log(message, where="server")
446     message = message.chomp
447     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
448     where = where.gsub(/[:!?$*()\/\\<>|"']/, "_")
449     unless(@logs.has_key?(where))
450       @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
451       @logs[where].sync = true
452     end
453     @logs[where].puts "[#{stamp}] #{message}"
454     #debug "[#{stamp}] <#{where}> #{message}"
455   end
456   
457   # set topic of channel +where+ to +topic+
458   def topic(where, topic)
459     sendq "TOPIC #{where} :#{topic}"
460   end
461
462   # disconnect from the server and cleanup all plugins and modules
463   def shutdown(message = nil)
464     begin
465       trap("SIGINT", "DEFAULT")
466       trap("SIGTERM", "DEFAULT")
467       trap("SIGHUP", "DEFAULT")
468     rescue
469       debug "failed to trap signals, probably running on windows?"
470     end
471     message = @lang.get("quit") if (message.nil? || message.empty?)
472     debug "Clearing socket"
473     @socket.clearq
474     debug "Saving"
475     save
476     debug "Cleaning up"
477     @plugins.cleanup
478     debug "Logging quits"
479     @channels.each_value {|v|
480       log "@ quit (#{message})", v.name
481     }
482     # debug "Closing registries"
483     # @registry.close
484     debug "Cleaning up the db environment"
485     DBTree.cleanup_env
486     debug "Sending quit message"
487     @socket.puts "QUIT :#{message}"
488     debug "Flushing socket"
489     @socket.flush
490     debug "Shutting down socket"
491     @socket.shutdown
492     puts "rbot quit (#{message})"
493   end
494   
495   # message:: optional IRC quit message
496   # quit IRC, shutdown the bot
497   def quit(message=nil)
498     begin
499       shutdown(message)
500     ensure
501       exit 0
502     end
503   end
504
505   # totally shutdown and respawn the bot
506   def restart(message = false)
507     msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
508     shutdown(msg)
509     sleep @config['server.reconnect_wait']
510     # now we re-exec
511     exec($0, *@argv)
512   end
513
514   # call the save method for bot's config, keywords, auth and all plugins
515   def save
516     @config.save
517     @keywords.save
518     @auth.save
519     @plugins.save
520     DBTree.cleanup_logs
521   end
522
523   # call the rescan method for the bot's lang, keywords and all plugins
524   def rescan
525     @lang.rescan
526     @plugins.rescan
527     @keywords.rescan
528   end
529   
530   # channel:: channel to join
531   # key::     optional channel key if channel is +s
532   # join a channel
533   def join(channel, key=nil)
534     if(key)
535       sendq "JOIN #{channel} :#{key}"
536     else
537       sendq "JOIN #{channel}"
538     end
539   end
540
541   # part a channel
542   def part(channel, message="")
543     sendq "PART #{channel} :#{message}"
544   end
545
546   # attempt to change bot's nick to +name+
547   def nickchg(name)
548       sendq "NICK #{name}"
549   end
550
551   # changing mode
552   def mode(channel, mode, target)
553       sendq "MODE #{channel} #{mode} #{target}"
554   end
555   
556   # m::     message asking for help
557   # topic:: optional topic help is requested for
558   # respond to online help requests
559   def help(topic=nil)
560     topic = nil if topic == ""
561     case topic
562     when nil
563       helpstr = "help topics: core, auth, keywords"
564       helpstr += @plugins.helptopics
565       helpstr += " (help <topic> for more info)"
566     when /^core$/i
567       helpstr = corehelp
568     when /^core\s+(.+)$/i
569       helpstr = corehelp $1
570     when /^auth$/i
571       helpstr = @auth.help
572     when /^auth\s+(.+)$/i
573       helpstr = @auth.help $1
574     when /^keywords$/i
575       helpstr = @keywords.help
576     when /^keywords\s+(.+)$/i
577       helpstr = @keywords.help $1
578     else
579       unless(helpstr = @plugins.help(topic))
580         helpstr = "no help for topic #{topic}"
581       end
582     end
583     return helpstr
584   end
585
586   # returns a string describing the current status of the bot (uptime etc)
587   def status
588     secs_up = Time.new - @startup_time
589     uptime = Utils.secs_to_string secs_up
590     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
591     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
592   end
593
594   # we'll ping the server every 30 seconds or so, and expect a response
595   # before the next one come around..
596   def start_server_pings
597     @last_ping = nil
598     # stop existing timers if running
599     unless @ping_timer.nil?
600       @timer.remove @ping_timer
601       @ping_timer = nil
602     end
603     unless @pong_timer.nil?
604       @timer.remove @pong_timer
605       @pong_timer = nil
606     end
607     return unless @config['server.ping_timeout'] > 0
608     # we want to respond to a hung server within 30 secs or so
609     @ping_timer = @timer.add(30) {
610       @last_ping = Time.now
611       @socket.puts "PING :rbot"
612     }
613     @pong_timer = @timer.add(10) {
614       unless @last_ping.nil?
615         diff = Time.now - @last_ping
616         unless diff < @config['server.ping_timeout']
617           debug "no PONG from server for #{diff} seconds, reconnecting"
618           begin
619             @socket.shutdown
620           rescue
621             debug "couldn't shutdown connection (already shutdown?)"
622           ensure
623             raise TimeoutError, "no PONG from server in #{diff} seconds"
624           end
625           @last_ping = nil
626         end
627       end
628     }
629   end
630
631   private
632
633   # handle help requests for "core" topics
634   def corehelp(topic="")
635     case topic
636       when "quit"
637         return "quit [<message>] => quit IRC with message <message>"
638       when "restart"
639         return "restart => completely stop and restart the bot (including reconnect)"
640       when "join"
641         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"
642       when "part"
643         return "part <channel> => part channel <channel>"
644       when "hide"
645         return "hide => part all channels"
646       when "save"
647         return "save => save current dynamic data and configuration"
648       when "rescan"
649         return "rescan => reload modules and static facts"
650       when "nick"
651         return "nick <nick> => attempt to change nick to <nick>"
652       when "say"
653         return "say <channel>|<nick> <message> => say <message> to <channel> or in private message to <nick>"
654       when "action"
655         return "action <channel>|<nick> <message> => does a /me <message> to <channel> or in private message to <nick>"
656         #       when "topic"
657         #         return "topic <channel> <message> => set topic of <channel> to <message>"
658       when "quiet"
659         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>"
660       when "talk"
661         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>"
662       when "version"
663         return "version => describes software version"
664       when "botsnack"
665         return "botsnack => reward #{@nick} for being good"
666       when "hello"
667         return "hello|hi|hey|yo [#{@nick}] => greet the bot"
668       else
669         return "Core help topics: quit, restart, config, join, part, hide, save, rescan, nick, say, action, topic, quiet, talk, version, botsnack, hello"
670     end
671   end
672
673   # handle incoming IRC PRIVMSG +m+
674   def onprivmsg(m)
675     # log it first
676     if(m.action?)
677       if(m.private?)
678         log "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
679       else
680         log "* #{m.sourcenick} #{m.message}", m.target
681       end
682     else
683       if(m.public?)
684         log "<#{m.sourcenick}> #{m.message}", m.target
685       else
686         log "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
687       end
688     end
689
690     # pass it off to plugins that want to hear everything
691     @plugins.delegate "listen", m
692
693     if(m.private? && m.message =~ /^\001PING\s+(.+)\001/)
694       notice m.sourcenick, "\001PING #$1\001"
695       log "@ #{m.sourcenick} pinged me"
696       return
697     end
698
699     if(m.address?)
700       delegate_privmsg(m)
701       case m.message
702         when (/^join\s+(\S+)\s+(\S+)$/i)
703           join $1, $2 if(@auth.allow?("join", m.source, m.replyto))
704         when (/^join\s+(\S+)$/i)
705           join $1 if(@auth.allow?("join", m.source, m.replyto))
706         when (/^part$/i)
707           part m.target if(m.public? && @auth.allow?("join", m.source, m.replyto))
708         when (/^part\s+(\S+)$/i)
709           part $1 if(@auth.allow?("join", m.source, m.replyto))
710         when (/^quit(?:\s+(.*))?$/i)
711           quit $1 if(@auth.allow?("quit", m.source, m.replyto))
712         when (/^restart(?:\s+(.*))?$/i)
713           restart $1 if(@auth.allow?("quit", m.source, m.replyto))
714         when (/^hide$/i)
715           join 0 if(@auth.allow?("join", m.source, m.replyto))
716         when (/^save$/i)
717           if(@auth.allow?("config", m.source, m.replyto))
718             save
719             m.okay
720           end
721         when (/^nick\s+(\S+)$/i)
722           nickchg($1) if(@auth.allow?("nick", m.source, m.replyto))
723         when (/^say\s+(\S+)\s+(.*)$/i)
724           say $1, $2 if(@auth.allow?("say", m.source, m.replyto))
725         when (/^action\s+(\S+)\s+(.*)$/i)
726           action $1, $2 if(@auth.allow?("say", m.source, m.replyto))
727           # when (/^topic\s+(\S+)\s+(.*)$/i)
728           #   topic $1, $2 if(@auth.allow?("topic", m.source, m.replyto))
729         when (/^mode\s+(\S+)\s+(\S+)\s+(.*)$/i)
730           mode $1, $2, $3 if(@auth.allow?("mode", m.source, m.replyto))
731         when (/^ping$/i)
732           say m.replyto, "pong"
733         when (/^rescan$/i)
734           if(@auth.allow?("config", m.source, m.replyto))
735             m.reply "Saving ..."
736             save
737             m.reply "Rescanning ..."
738             rescan
739             m.okay
740           end
741         when (/^quiet$/i)
742           if(auth.allow?("talk", m.source, m.replyto))
743             m.okay
744             @channels.each_value {|c| c.quiet = true }
745           end
746         when (/^quiet in (\S+)$/i)
747           where = $1
748           if(auth.allow?("talk", m.source, m.replyto))
749             m.okay
750             where.gsub!(/^here$/, m.target) if m.public?
751             @channels[where].quiet = true if(@channels.has_key?(where))
752           end
753         when (/^talk$/i)
754           if(auth.allow?("talk", m.source, m.replyto))
755             @channels.each_value {|c| c.quiet = false }
756             m.okay
757           end
758         when (/^talk in (\S+)$/i)
759           where = $1
760           if(auth.allow?("talk", m.source, m.replyto))
761             where.gsub!(/^here$/, m.target) if m.public?
762             @channels[where].quiet = false if(@channels.has_key?(where))
763             m.okay
764           end
765         when (/^status\??$/i)
766           m.reply status if auth.allow?("status", m.source, m.replyto)
767         when (/^registry stats$/i)
768           if auth.allow?("config", m.source, m.replyto)
769             m.reply @registry.stat.inspect
770           end
771         when (/^(help\s+)?config(\s+|$)/)
772           @config.privmsg(m)
773         when (/^(version)|(introduce yourself)$/i)
774           say m.replyto, "I'm a v. #{$version} rubybot, (c) Tom Gilbert - http://linuxbrit.co.uk/rbot/"
775         when (/^help(?:\s+(.*))?$/i)
776           say m.replyto, help($1)
777           #TODO move these to a "chatback" plugin
778         when (/^(botsnack|ciggie)$/i)
779           say m.replyto, @lang.get("thanks_X") % m.sourcenick if(m.public?)
780           say m.replyto, @lang.get("thanks") if(m.private?)
781         when (/^(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi(\W|$)|yo(\W|$)).*/i)
782           say m.replyto, @lang.get("hello_X") % m.sourcenick if(m.public?)
783           say m.replyto, @lang.get("hello") if(m.private?)
784       end
785     else
786       # stuff to handle when not addressed
787       case m.message
788         when (/^\s*(hello|howdy|hola|salut|bonjour|sup|niihau|hey|hi|yo(\W|$))[\s,-.]+#{Regexp.escape(@nick)}$/i)
789           say m.replyto, @lang.get("hello_X") % m.sourcenick
790         when (/^#{Regexp.escape(@nick)}!*$/)
791           say m.replyto, @lang.get("hello_X") % m.sourcenick
792         else
793           @keywords.privmsg(m)
794       end
795     end
796   end
797
798   # log a message. Internal use only.
799   def log_sent(type, where, message)
800     case type
801       when "NOTICE"
802         if(where =~ /^#/)
803           log "-=#{@nick}=- #{message}", where
804         elsif (where =~ /(\S*)!.*/)
805              log "[-=#{where}=-] #{message}", $1
806         else
807              log "[-=#{where}=-] #{message}"
808         end
809       when "PRIVMSG"
810         if(where =~ /^#/)
811           log "<#{@nick}> #{message}", where
812         elsif (where =~ /^(\S*)!.*$/)
813           log "[msg(#{where})] #{message}", $1
814         else
815           log "[msg(#{where})] #{message}", where
816         end
817     end
818   end
819
820   def onjoin(m)
821     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
822     if(m.address?)
823       debug "joined channel #{m.channel}"
824       log "@ Joined channel #{m.channel}", m.channel
825     else
826       log "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
827       @channels[m.channel].users[m.sourcenick] = Hash.new
828       @channels[m.channel].users[m.sourcenick]["mode"] = ""
829     end
830
831     @plugins.delegate("listen", m)
832     @plugins.delegate("join", m)
833   end
834
835   def onpart(m)
836     if(m.address?)
837       debug "left channel #{m.channel}"
838       log "@ Left channel #{m.channel} (#{m.message})", m.channel
839       @channels.delete(m.channel)
840     else
841       log "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
842       @channels[m.channel].users.delete(m.sourcenick)
843     end
844     
845     # delegate to plugins
846     @plugins.delegate("listen", m)
847     @plugins.delegate("part", m)
848   end
849
850   # respond to being kicked from a channel
851   def onkick(m)
852     if(m.address?)
853       debug "kicked from channel #{m.channel}"
854       @channels.delete(m.channel)
855       log "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
856     else
857       @channels[m.channel].users.delete(m.sourcenick)
858       log "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
859     end
860
861     @plugins.delegate("listen", m)
862     @plugins.delegate("kick", m)
863   end
864
865   def ontopic(m)
866     @channels[m.channel] = IRCChannel.new(m.channel) unless(@channels.has_key?(m.channel))
867     @channels[m.channel].topic = m.topic if !m.topic.nil?
868     @channels[m.channel].topic.timestamp = m.timestamp if !m.timestamp.nil?
869     @channels[m.channel].topic.by = m.source if !m.source.nil?
870
871           debug "topic of channel #{m.channel} is now #{@channels[m.channel].topic}"
872   end
873
874   # delegate a privmsg to auth, keyword or plugin handlers
875   def delegate_privmsg(message)
876     [@auth, @plugins, @keywords].each {|m|
877       break if m.privmsg(message)
878     }
879   end
880 end
881
882 end