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