]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/plugins.rb
revert previous useless commit and rdocify documentation of accessors to BotModule
[user/henk/code/ruby/rbot.git] / lib / rbot / plugins.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: rbot plugin management
5
6 require 'singleton'
7
8 module Irc
9 class Bot
10     Config.register Config::ArrayValue.new('plugins.blacklist',
11       :default => [], :wizard => false, :requires_rescan => true,
12       :desc => "Plugins that should not be loaded")
13 module Plugins
14   require 'rbot/messagemapper'
15
16 =begin rdoc
17   BotModule is the base class for the modules that enhance the rbot
18   functionality. Rather than subclassing BotModule, however, one should
19   subclass either CoreBotModule (reserved for system modules) or Plugin
20   (for user plugins).
21
22   A BotModule interacts with Irc events by defining one or more of the following
23   methods, which get called as appropriate when the corresponding Irc event
24   happens.
25
26   map(template, options)::
27   map!(template, options)::
28      map is the new, cleaner way to respond to specific message formats without
29      littering your plugin code with regexps, and should be used instead of
30      #register() and #privmsg() (see below) when possible.
31
32      The difference between map and map! is that map! will not register the new
33      command as an alternative name for the plugin.
34
35      Examples:
36
37        plugin.map 'karmastats', :action => 'karma_stats'
38
39        # while in the plugin...
40        def karma_stats(m, params)
41          m.reply "..."
42        end
43
44        # the default action is the first component
45        plugin.map 'karma'
46
47        # attributes can be pulled out of the match string
48        plugin.map 'karma for :key'
49        plugin.map 'karma :key'
50
51        # while in the plugin...
52        def karma(m, params)
53          item = params[:key]
54          m.reply 'karma for #{item}'
55        end
56
57        # you can setup defaults, to make parameters optional
58        plugin.map 'karma :key', :defaults => {:key => 'defaultvalue'}
59
60        # the default auth check is also against the first component
61        # but that can be changed
62        plugin.map 'karmastats', :auth => 'karma'
63
64        # maps can be restricted to public or private message:
65        plugin.map 'karmastats', :private => false
66        plugin.map 'karmastats', :public => false
67
68      See MessageMapper#map for more information on the template format and the
69      allowed options.
70
71   listen(UserMessage)::
72                          Called for all messages of any type. To
73                          differentiate them, use message.kind_of? It'll be
74                          either a PrivMessage, NoticeMessage, KickMessage,
75                          QuitMessage, PartMessage, JoinMessage, NickMessage,
76                          etc.
77
78   ctcp_listen(UserMessage)::
79                          Called for all messages that contain a CTCP command.
80                          Use message.ctcp to get the CTCP command, and
81                          message.message to get the parameter string. To reply,
82                          use message.ctcp_reply, which sends a private NOTICE
83                          to the sender.
84
85   message(PrivMessage)::
86                          Called for all PRIVMSG. Hook on this method if you
87                          need to handle PRIVMSGs regardless of whether they are
88                          addressed to the bot or not, and regardless of
89
90   privmsg(PrivMessage)::
91                          Called for a PRIVMSG if the first word matches one
92                          the plugin #register()ed for. Use m.plugin to get
93                          that word and m.params for the rest of the message,
94                          if applicable.
95
96   unreplied(PrivMessage)::
97                          Called for a PRIVMSG which has not been replied to.
98
99   kick(KickMessage)::
100                          Called when a user (or the bot) is kicked from a
101                          channel the bot is in.
102
103   invite(InviteMessage)::
104                          Called when the bot is invited to a channel.
105
106   join(JoinMessage)::
107                          Called when a user (or the bot) joins a channel
108
109   part(PartMessage)::
110                          Called when a user (or the bot) parts a channel
111
112   quit(QuitMessage)::
113                          Called when a user (or the bot) quits IRC
114
115   nick(NickMessage)::
116                          Called when a user (or the bot) changes Nick
117   topic(TopicMessage)::
118                          Called when a user (or the bot) changes a channel
119                          topic
120
121   connect::              Called when a server is joined successfully, but
122                          before autojoin channels are joined (no params)
123
124   set_language(String)::
125                          Called when the user sets a new language
126                          whose name is the given String
127
128   save::                 Called when you are required to save your plugin's
129                          state, if you maintain data between sessions
130
131   cleanup::              called before your plugin is "unloaded", prior to a
132                          plugin reload or bot quit - close any open
133                          files/connections or flush caches here
134 =end
135
136   class BotModule
137     # the associated bot
138     attr_reader :bot
139
140     # the plugin registry
141     attr_reader :registry
142
143     # the message map handler
144     attr_reader :handler
145
146     # Initialise your bot module. Always call super if you override this method,
147     # as important variables are set up for you:
148     #
149     # @bot::
150     #   the rbot instance
151     # @registry::
152     #   the botmodule's registry, which can be used to store permanent data
153     #   (see Registry::Accessor for additional documentation)
154     #
155     # Other instance variables which are defined and should not be overwritten
156     # byt the user, but aren't usually accessed directly, are:
157     #
158     # @manager::
159     #   the plugins manager instance
160     # @botmodule_triggers::
161     #   an Array of words this plugin #register()ed itself for
162     # @handler::
163     #   the MessageMapper that handles this plugin's maps
164     #
165     def initialize
166       @manager = Plugins::manager
167       @bot = @manager.bot
168
169       @botmodule_triggers = Array.new
170
171       @handler = MessageMapper.new(self)
172       @registry = Registry::Accessor.new(@bot, self.class.to_s.gsub(/^.*::/, ""))
173
174       @manager.add_botmodule(self)
175       if self.respond_to?('set_language')
176         self.set_language(@bot.lang.language)
177       end
178     end
179
180     # Returns the symbol :BotModule 
181     def botmodule_class
182       :BotModule
183     end
184
185     # Method called to flush the registry, thus ensuring that the botmodule's permanent
186     # data is committed to disk
187     #
188     def flush_registry
189       # debug "Flushing #{@registry}"
190       @registry.flush
191     end
192
193     # Method called to cleanup before the plugin is unloaded. If you overload
194     # this method to handle additional cleanup tasks, remember to call super()
195     # so that the default cleanup actions are taken care of as well.
196     #
197     def cleanup
198       # debug "Closing #{@registry}"
199       @registry.close
200     end
201
202     # Handle an Irc::PrivMessage for which this BotModule has a map. The method
203     # is called automatically and there is usually no need to call it
204     # explicitly.
205     #
206     def handle(m)
207       @handler.handle(m)
208     end
209
210     # Signal to other BotModules that an even happened.
211     #
212     def call_event(ev, *args)
213       @bot.plugins.delegate('event_' + ev.to_s.gsub(/[^\w\?!]+/, '_'), *args)
214     end
215
216     # call-seq: map(template, options)
217     #
218     # This is the preferred way to register the BotModule so that it
219     # responds to appropriately-formed messages on Irc.
220     #
221     def map(*args)
222       do_map(false, *args)
223     end
224
225     # call-seq: map!(template, options)
226     #
227     # This is the same as map but doesn't register the new command
228     # as an alternative name for the plugin.
229     #
230     def map!(*args)
231       do_map(true, *args)
232     end
233
234     # Auxiliary method called by #map and #map!
235     def do_map(silent, *args)
236       @handler.map(self, *args)
237       # register this map
238       map = @handler.last
239       name = map.items[0]
240       self.register name, :auth => nil, :hidden => silent
241       @manager.register_map(self, map)
242       unless self.respond_to?('privmsg')
243         def self.privmsg(m) #:nodoc:
244           handle(m)
245         end
246       end
247     end
248
249     # Sets the default auth for command path _cmd_ to _val_ on channel _chan_:
250     # usually _chan_ is either "*" for everywhere, public and private (in which
251     # case it can be omitted) or "?" for private communications
252     #
253     def default_auth(cmd, val, chan="*")
254       case cmd
255       when "*", ""
256         c = nil
257       else
258         c = cmd
259       end
260       Auth::defaultbotuser.set_default_permission(propose_default_path(c), val)
261     end
262
263     # Gets the default command path which would be given to command _cmd_
264     def propose_default_path(cmd)
265       [name, cmd].compact.join("::")
266     end
267
268     # Return an identifier for this plugin, defaults to a list of the message
269     # prefixes handled (used for error messages etc)
270     def name
271       self.class.to_s.downcase.sub(/^#<module:.*?>::/,"").sub(/(plugin|module)?$/,"")
272     end
273
274     # Just calls name
275     def to_s
276       name
277     end
278
279     # Intern the name
280     def to_sym
281       self.name.to_sym
282     end
283
284     # Return a help string for your module. For complex modules, you may wish
285     # to break your help into topics, and return a list of available topics if
286     # +topic+ is nil. +plugin+ is passed containing the matching prefix for
287     # this message - if your plugin handles multiple prefixes, make sure you
288     # return the correct help for the prefix requested
289     def help(plugin, topic)
290       "no help"
291     end
292
293     # Register the plugin as a handler for messages prefixed _cmd_.
294     #
295     # This can be called multiple times for a plugin to handle multiple message
296     # prefixes.
297     #
298     # This command is now superceded by the #map() command, which should be used
299     # instead whenever possible.
300     # 
301     def register(cmd, opts={})
302       raise ArgumentError, "Second argument must be a hash!" unless opts.kind_of?(Hash)
303       who = @manager.who_handles?(cmd)
304       if who
305         raise "Command #{cmd} is already handled by #{who.botmodule_class} #{who}" if who != self
306         return
307       end
308       if opts.has_key?(:auth)
309         @manager.register(self, cmd, opts[:auth])
310       else
311         @manager.register(self, cmd, propose_default_path(cmd))
312       end
313       @botmodule_triggers << cmd unless opts.fetch(:hidden, false)
314     end
315
316     # Default usage method provided as a utility for simple plugins. The
317     # MessageMapper uses 'usage' as its default fallback method.
318     #
319     def usage(m, params = {})
320       m.reply(_("incorrect usage, ask for help using '%{command}'") % {:command => "#{@bot.nick}: help #{m.plugin}"})
321     end
322
323   end
324
325   # A CoreBotModule is a BotModule that provides core functionality.
326   #
327   # This class should not be used by user plugins, as it's reserved for system
328   # plugins such as the ones that handle authentication, configuration and basic
329   # functionality.
330   #
331   class CoreBotModule < BotModule
332     def botmodule_class
333       :CoreBotModule
334     end
335   end
336
337   # A Plugin is a BotModule that provides additional functionality.
338   #
339   # A user-defined plugin should subclass this, and then define any of the
340   # methods described in the documentation for BotModule to handle interaction
341   # with Irc events.
342   #
343   class Plugin < BotModule
344     def botmodule_class
345       :Plugin
346     end
347   end
348
349   # Singleton to manage multiple plugins and delegate messages to them for
350   # handling
351   class PluginManagerClass
352     include Singleton
353     attr_reader :bot
354     attr_reader :botmodules
355     attr_reader :maps
356
357     # This is the list of patterns commonly delegated to plugins.
358     # A fast delegation lookup is enabled for them.
359     DEFAULT_DELEGATE_PATTERNS = %r{^(?:
360       connect|names|nick|
361       listen|ctcp_listen|privmsg|unreplied|
362       kick|join|part|quit|
363       save|cleanup|flush_registry|
364       set_.*|event_.*
365     )$}x
366
367     def initialize
368       @botmodules = {
369         :CoreBotModule => [],
370         :Plugin => []
371       }
372
373       @names_hash = Hash.new
374       @commandmappers = Hash.new
375       @maps = Hash.new
376       @delegate_list = Hash.new { |h, k|
377         h[k] = Array.new
378       }
379
380       @dirs = []
381
382       @failed = Array.new
383       @ignored = Array.new
384
385       bot_associate(nil)
386     end
387
388     def inspect
389       ret = self.to_s[0..-2]
390       ret << ' corebotmodules='
391       ret << @botmodules[:CoreBotModule].map { |m|
392         m.name
393       }.inspect
394       ret << ' plugins='
395       ret << @botmodules[:Plugin].map { |m|
396         m.name
397       }.inspect
398       ret << ">"
399     end
400
401     # Reset lists of botmodules
402     def reset_botmodule_lists
403       @botmodules[:CoreBotModule].clear
404       @botmodules[:Plugin].clear
405       @names_hash.clear
406       @commandmappers.clear
407       @maps.clear
408       @failures_shown = false
409     end
410
411     # Associate with bot _bot_
412     def bot_associate(bot)
413       reset_botmodule_lists
414       @bot = bot
415     end
416
417     # Returns the botmodule with the given _name_
418     def [](name)
419       @names_hash[name.to_sym]
420     end
421
422     # Returns +true+ if _cmd_ has already been registered as a command
423     def who_handles?(cmd)
424       return nil unless @commandmappers.has_key?(cmd.to_sym)
425       return @commandmappers[cmd.to_sym][:botmodule]
426     end
427
428     # Registers botmodule _botmodule_ with command _cmd_ and command path _auth_path_
429     def register(botmodule, cmd, auth_path)
430       raise TypeError, "First argument #{botmodule.inspect} is not of class BotModule" unless botmodule.kind_of?(BotModule)
431       @commandmappers[cmd.to_sym] = {:botmodule => botmodule, :auth => auth_path}
432     end
433
434     # Registers botmodule _botmodule_ with map _map_. This adds the map to the #maps hash
435     # which has three keys:
436     #
437     # botmodule:: the associated botmodule
438     # auth:: an array of auth keys checked by the map; the first is the full_auth_path of the map
439     # map:: the actual MessageTemplate object
440     #
441     #
442     def register_map(botmodule, map)
443       raise TypeError, "First argument #{botmodule.inspect} is not of class BotModule" unless botmodule.kind_of?(BotModule)
444       @maps[map.template] = { :botmodule => botmodule, :auth => [map.options[:full_auth_path]], :map => map }
445     end
446
447     def add_botmodule(botmodule)
448       raise TypeError, "Argument #{botmodule.inspect} is not of class BotModule" unless botmodule.kind_of?(BotModule)
449       kl = botmodule.botmodule_class
450       if @names_hash.has_key?(botmodule.to_sym)
451         case self[botmodule].botmodule_class
452         when kl
453           raise "#{kl} #{botmodule} already registered!"
454         else
455           raise "#{self[botmodule].botmodule_class} #{botmodule} already registered, cannot re-register as #{kl}"
456         end
457       end
458       @botmodules[kl] << botmodule
459       @names_hash[botmodule.to_sym] = botmodule
460     end
461
462     # Returns an array of the loaded plugins
463     def core_modules
464       @botmodules[:CoreBotModule]
465     end
466
467     # Returns an array of the loaded plugins
468     def plugins
469       @botmodules[:Plugin]
470     end
471
472     # Returns a hash of the registered message prefixes and associated
473     # plugins
474     def commands
475       @commandmappers
476     end
477
478     # Makes a string of error _err_ by adding text _str_
479     def report_error(str, err)
480       ([str, err.inspect] + err.backtrace).join("\n")
481     end
482
483     # This method is the one that actually loads a module from the
484     # file _fname_
485     #
486     # _desc_ is a simple description of what we are loading (plugin/botmodule/whatever)
487     #
488     # It returns the Symbol :loaded on success, and an Exception
489     # on failure
490     #
491     def load_botmodule_file(fname, desc=nil)
492       # create a new, anonymous module to "house" the plugin
493       # the idea here is to prevent namespace pollution. perhaps there
494       # is another way?
495       plugin_module = Module.new
496
497       desc = desc.to_s + " " if desc
498
499       begin
500         plugin_string = IO.readlines(fname).join("")
501         debug "loading #{desc}#{fname}"
502         plugin_module.module_eval(plugin_string, fname)
503         return :loaded
504       rescue Exception => err
505         # rescue TimeoutError, StandardError, NameError, LoadError, SyntaxError => err
506         error report_error("#{desc}#{fname} load failed", err)
507         bt = err.backtrace.select { |line|
508           line.match(/^(\(eval\)|#{fname}):\d+/)
509         }
510         bt.map! { |el|
511           el.gsub(/^\(eval\)(:\d+)(:in `.*')?(:.*)?/) { |m|
512             "#{fname}#{$1}#{$3}"
513           }
514         }
515         msg = err.to_str.gsub(/^\(eval\)(:\d+)(:in `.*')?(:.*)?/) { |m|
516           "#{fname}#{$1}#{$3}"
517         }
518         newerr = err.class.new(msg)
519         newerr.set_backtrace(bt)
520         return newerr
521       end
522     end
523     private :load_botmodule_file
524
525     # add one or more directories to the list of directories to
526     # load botmodules from
527     #
528     # TODO find a way to specify necessary plugins which _must_ be loaded
529     #
530     def add_botmodule_dir(*dirlist)
531       @dirs += dirlist
532       debug "Botmodule loading path: #{@dirs.join(', ')}"
533     end
534
535     def clear_botmodule_dirs
536       @dirs.clear
537       debug "Botmodule loading path cleared"
538     end
539
540     # load plugins from pre-assigned list of directories
541     def scan
542       @failed.clear
543       @ignored.clear
544       @delegate_list.clear
545
546       processed = Hash.new
547
548       @bot.config['plugins.blacklist'].each { |p|
549         pn = p + ".rb"
550         processed[pn.intern] = :blacklisted
551       }
552
553       dirs = @dirs
554       dirs.each {|dir|
555         if(FileTest.directory?(dir))
556           d = Dir.new(dir)
557           d.sort.each {|file|
558
559             next if(file =~ /^\./)
560
561             if processed.has_key?(file.intern)
562               @ignored << {:name => file, :dir => dir, :reason => processed[file.intern]}
563               next
564             end
565
566             if(file =~ /^(.+\.rb)\.disabled$/)
567               # GB: Do we want to do this? This means that a disabled plugin in a directory
568               #     will disable in all subsequent directories. This was probably meant
569               #     to be used before plugins.blacklist was implemented, so I think
570               #     we don't need this anymore
571               processed[$1.intern] = :disabled
572               @ignored << {:name => $1, :dir => dir, :reason => processed[$1.intern]}
573               next
574             end
575
576             next unless(file =~ /\.rb$/)
577
578             did_it = load_botmodule_file("#{dir}/#{file}", "plugin")
579             case did_it
580             when Symbol
581               processed[file.intern] = did_it
582             when Exception
583               @failed <<  { :name => file, :dir => dir, :reason => did_it }
584             end
585
586           }
587         end
588       }
589       debug "finished loading plugins: #{status(true)}"
590       (core_modules + plugins).each { |p|
591        p.methods.grep(DEFAULT_DELEGATE_PATTERNS).each { |m|
592          @delegate_list[m.intern] << p
593        }
594       }
595     end
596
597     # call the save method for each active plugin
598     def save
599       delegate 'flush_registry'
600       delegate 'save'
601     end
602
603     # call the cleanup method for each active plugin
604     def cleanup
605       delegate 'cleanup'
606       reset_botmodule_lists
607     end
608
609     # drop all plugins and rescan plugins on disk
610     # calls save and cleanup for each plugin before dropping them
611     def rescan
612       save
613       cleanup
614       scan
615     end
616
617     def status(short=false)
618       output = []
619       if self.core_length > 0
620         if short
621           output << n_("%{count} core module loaded", "%{count} core modules loaded",
622                     self.core_length) % {:count => self.core_length}
623         else
624           output <<  n_("%{count} core module: %{list}",
625                      "%{count} core modules: %{list}", self.core_length) %
626                      { :count => self.core_length,
627                        :list => core_modules.collect{ |p| p.name}.sort.join(", ") }
628         end
629       else
630         output << _("no core botmodules loaded")
631       end
632       # Active plugins first
633       if(self.length > 0)
634         if short
635           output << n_("%{count} plugin loaded", "%{count} plugins loaded",
636                        self.length) % {:count => self.length}
637         else
638           output << n_("%{count} plugin: %{list}",
639                        "%{count} plugins: %{list}", self.length) %
640                    { :count => self.length,
641                      :list => plugins.collect{ |p| p.name}.sort.join(", ") }
642         end
643       else
644         output << "no plugins active"
645       end
646       # Ignored plugins next
647       unless @ignored.empty? or @failures_shown
648         if short
649           output << n_("%{highlight}%{count} plugin ignored%{highlight}",
650                        "%{highlight}%{count} plugins ignored%{highlight}",
651                        @ignored.length) %
652                     { :count => @ignored.length, :highlight => Underline }
653         else
654           output << n_("%{highlight}%{count} plugin ignored%{highlight}: use %{bold}%{command}%{bold} to see why",
655                        "%{highlight}%{count} plugins ignored%{highlight}: use %{bold}%{command}%{bold} to see why",
656                        @ignored.length) %
657                     { :count => @ignored.length, :highlight => Underline,
658                       :bold => Bold, :command => "help ignored plugins"}
659         end
660       end
661       # Failed plugins next
662       unless @failed.empty? or @failures_shown
663         if short
664           output << n_("%{highlight}%{count} plugin failed to load%{highlight}",
665                        "%{highlight}%{count} plugins failed to load%{highlight}",
666                        @failed.length) %
667                     { :count => @failed.length, :highlight => Reverse }
668         else
669           output << n_("%{highlight}%{count} plugin failed to load%{highlight}: use %{bold}%{command}%{bold} to see why",
670                        "%{highlight}%{count} plugins failed to load%{highlight}: use %{bold}%{command}%{bold} to see why",
671                        @failed.length) %
672                     { :count => @failed.length, :highlight => Reverse,
673                       :bold => Bold, :command => "help failed plugins"}
674         end
675       end
676       output.join '; '
677     end
678
679     # return list of help topics (plugin names)
680     def helptopics
681       rv = status
682       @failures_shown = true
683       rv
684     end
685
686     def length
687       plugins.length
688     end
689
690     def core_length
691       core_modules.length
692     end
693
694     # return help for +topic+ (call associated plugin's help method)
695     def help(topic="")
696       case topic
697       when /fail(?:ed)?\s*plugins?.*(trace(?:back)?s?)?/
698         # debug "Failures: #{@failed.inspect}"
699         return _("no plugins failed to load") if @failed.empty?
700         return @failed.collect { |p|
701           _('%{highlight}%{plugin}%{highlight} in %{dir} failed with error %{exception}: %{reason}') % {
702               :highlight => Bold, :plugin => p[:name], :dir => p[:dir],
703               :exception => p[:reason].class, :reason => p[:reason],
704           } + if $1 && !p[:reason].backtrace.empty?
705                 _('at %{backtrace}') % {:backtrace => p[:reason].backtrace.join(', ')}
706               else
707                 ''
708               end
709         }.join("\n")
710       when /ignored?\s*plugins?/
711         return _('no plugins were ignored') if @ignored.empty?
712
713         tmp = Hash.new
714         @ignored.each do |p|
715           reason = p[:loaded] ? _('overruled by previous') : _(p[:reason].to_s)
716           ((tmp[p[:dir]] ||= Hash.new)[reason] ||= Array.new).push(p[:name])
717         end
718
719         return tmp.map do |dir, reasons|
720           # FIXME get rid of these string concatenations to make gettext easier
721           s = reasons.map { |r, list|
722             list.map { |_| _.sub(/\.rb$/, '') }.join(', ') + " (#{r})"
723           }.join('; ')
724           "in #{dir}: #{s}"
725         end.join('; ')
726       when /^(\S+)\s*(.*)$/
727         key = $1
728         params = $2
729
730         # Let's see if we can match a plugin by the given name
731         (core_modules + plugins).each { |p|
732           next unless p.name == key
733           begin
734             return p.help(key, params)
735           rescue Exception => err
736             #rescue TimeoutError, StandardError, NameError, SyntaxError => err
737             error report_error("#{p.botmodule_class} #{p.name} help() failed:", err)
738           end
739         }
740
741         # Nope, let's see if it's a command, and ask for help at the corresponding botmodule
742         k = key.to_sym
743         if commands.has_key?(k)
744           p = commands[k][:botmodule]
745           begin
746             return p.help(key, params)
747           rescue Exception => err
748             #rescue TimeoutError, StandardError, NameError, SyntaxError => err
749             error report_error("#{p.botmodule_class} #{p.name} help() failed:", err)
750           end
751         end
752       end
753       return false
754     end
755
756     # see if each plugin handles +method+, and if so, call it, passing
757     # +message+ as a parameter
758     def delegate(method, *args)
759       # debug "Delegating #{method.inspect}"
760       ret = Array.new
761       if method.match(DEFAULT_DELEGATE_PATTERNS)
762         debug "fast-delegating #{method}"
763         m = method.to_sym
764         debug "no-one to delegate to" unless @delegate_list.has_key?(m)
765         return [] unless @delegate_list.has_key?(m)
766         @delegate_list[m].each { |p|
767           begin
768             ret.push p.send(method, *args)
769           rescue Exception => err
770             raise if err.kind_of?(SystemExit)
771             error report_error("#{p.botmodule_class} #{p.name} #{method}() failed:", err)
772             raise if err.kind_of?(BDB::Fatal)
773           end
774         }
775       else
776         debug "slow-delegating #{method}"
777         (core_modules + plugins).each { |p|
778           if(p.respond_to? method)
779             begin
780               # debug "#{p.botmodule_class} #{p.name} responds"
781               ret.push p.send(method, *args)
782             rescue Exception => err
783               raise if err.kind_of?(SystemExit)
784               error report_error("#{p.botmodule_class} #{p.name} #{method}() failed:", err)
785               raise if err.kind_of?(BDB::Fatal)
786             end
787           end
788         }
789       end
790       return ret
791       # debug "Finished delegating #{method.inspect}"
792     end
793
794     # see if we have a plugin that wants to handle this message, if so, pass
795     # it to the plugin and return true, otherwise false
796     def privmsg(m)
797       # debug "Delegating privmsg #{m.message.inspect} from #{m.source} to #{m.replyto} with pluginkey #{m.plugin.inspect}"
798       return unless m.plugin
799       k = m.plugin.to_sym
800       if commands.has_key?(k)
801         p = commands[k][:botmodule]
802         a = commands[k][:auth]
803         # We check here for things that don't check themselves
804         # (e.g. mapped things)
805         # debug "Checking auth ..."
806         if a.nil? || @bot.auth.allow?(a, m.source, m.replyto)
807           # debug "Checking response ..."
808           if p.respond_to?("privmsg")
809             begin
810               # debug "#{p.botmodule_class} #{p.name} responds"
811               p.privmsg(m)
812             rescue Exception => err
813               raise if err.kind_of?(SystemExit)
814               error report_error("#{p.botmodule_class} #{p.name} privmsg() failed:", err)
815               raise if err.kind_of?(BDB::Fatal)
816             end
817             # debug "Successfully delegated #{m.message}"
818             return true
819           else
820             # debug "#{p.botmodule_class} #{p.name} is registered, but it doesn't respond to privmsg()"
821           end
822         else
823           # debug "#{p.botmodule_class} #{p.name} is registered, but #{m.source} isn't allowed to call #{m.plugin.inspect} on #{m.replyto}"
824         end
825       end
826       # debug "Finished delegating privmsg with key #{m.plugin.inspect}" + ( pl.empty? ? "" : " to #{pl.values.first[:botmodule].botmodule_class}s" )
827       return false
828       # debug "Finished delegating privmsg with key #{m.plugin.inspect}"
829     end
830
831     # delegate IRC messages, by delegating 'listen' first, and the actual method
832     # afterwards. Delegating 'privmsg' also delegates ctcp_listen and message
833     # as appropriate.
834     def irc_delegate(method, m)
835       delegate('listen', m)
836       if method.to_sym == :privmsg
837         delegate('ctcp_listen', m) if m.ctcp
838         delegate('message', m)
839         privmsg(m) if m.address?
840         delegate('unreplied', m) unless m.replied
841       else
842         delegate(method, m)
843       end
844     end
845   end
846
847   # Returns the only PluginManagerClass instance
848   def Plugins.manager
849     return PluginManagerClass.instance
850   end
851
852 end
853 end
854 end