]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/plugins.rb
Sun Jul 31 02:20:08 BST 2005 Tom Gilbert <tom@linuxbrit.co.uk>
[user/henk/code/ruby/rbot.git] / lib / rbot / plugins.rb
1 module Irc
2 module Plugins
3   require 'rbot/messagemapper'
4
5   # base class for all rbot plugins
6   # certain methods will be called if they are provided, if you define one of
7   # the following methods, it will be called as appropriate:
8   #
9   # map(template, options)::
10   #    map is the new, cleaner way to respond to specific message formats
11   #    without littering your plugin code with regexps
12   #    examples:
13   #      plugin.map 'karmastats', :action => 'karma_stats'
14   #
15   #      # while in the plugin...
16   #      def karma_stats(m, params)
17   #        m.reply "..."
18   #      end
19   #      
20   #      # the default action is the first component
21   #      plugin.map 'karma'
22   #
23   #      # attributes can be pulled out of the match string
24   #      plugin.map 'karma for :key'
25   #      plugin.map 'karma :key'
26   #
27   #      # while in the plugin...
28   #      def karma(m, params)
29   #        item = params[:key]
30   #        m.reply 'karma for #{item}'
31   #      end
32   #      
33   #      # you can setup defaults, to make parameters optional
34   #      plugin.map 'karma :key', :defaults => {:key => 'defaultvalue'}
35   #      
36   #      # the default auth check is also against the first component
37   #      # but that can be changed
38   #      plugin.map 'karmastats', :auth => 'karma'
39   #
40   #      # maps can be restricted to public or private message:
41   #      plugin.map 'karmastats', :private false,
42   #      plugin.map 'karmastats', :public false,
43   #    end
44   #
45   #    To activate your maps, you simply register them
46   #    plugin.register_maps
47   #    This also sets the privmsg handler to use the map lookups for
48   #    handling messages. You can still use listen(), kick() etc methods
49   # 
50   # listen(UserMessage)::
51   #                        Called for all messages of any type. To
52   #                        differentiate them, use message.kind_of? It'll be
53   #                        either a PrivMessage, NoticeMessage, KickMessage,
54   #                        QuitMessage, PartMessage, JoinMessage, NickMessage,
55   #                        etc.
56   #                              
57   # privmsg(PrivMessage)::
58   #                        called for a PRIVMSG if the first word matches one
59   #                        the plugin register()d for. Use m.plugin to get
60   #                        that word and m.params for the rest of the message,
61   #                        if applicable.
62   #
63   # kick(KickMessage)::
64   #                        Called when a user (or the bot) is kicked from a
65   #                        channel the bot is in.
66   #
67   # join(JoinMessage)::
68   #                        Called when a user (or the bot) joins a channel
69   #
70   # part(PartMessage)::
71   #                        Called when a user (or the bot) parts a channel
72   #
73   # quit(QuitMessage)::    
74   #                        Called when a user (or the bot) quits IRC
75   #
76   # nick(NickMessage)::
77   #                        Called when a user (or the bot) changes Nick
78   # topic(TopicMessage)::
79   #                        Called when a user (or the bot) changes a channel
80   #                        topic
81   # 
82   # save::                 Called when you are required to save your plugin's
83   #                        state, if you maintain data between sessions
84   #
85   # cleanup::              called before your plugin is "unloaded", prior to a
86   #                        plugin reload or bot quit - close any open
87   #                        files/connections or flush caches here
88   class Plugin
89     attr_reader :bot   # the associated bot
90     # initialise your plugin. Always call super if you override this method,
91     # as important variables are set up for you
92     def initialize
93       @bot = Plugins.bot
94       @names = Array.new
95       @handler = MessageMapper.new(self)
96       @registry = BotRegistryAccessor.new(@bot, self.class.to_s.gsub(/^.*::/, ""))
97     end
98
99     def map(*args)
100       @handler.map(*args)
101       # register this map
102       name = @handler.last.items[0]
103       self.register name
104       unless self.respond_to?('privmsg')
105         def self.privmsg(m)
106           @handler.handle(m)
107         end
108       end
109     end
110
111     # return an identifier for this plugin, defaults to a list of the message
112     # prefixes handled (used for error messages etc)
113     def name
114       @names.join("|")
115     end
116     
117     # return a help string for your module. for complex modules, you may wish
118     # to break your help into topics, and return a list of available topics if
119     # +topic+ is nil. +plugin+ is passed containing the matching prefix for
120     # this message - if your plugin handles multiple prefixes, make sure your
121     # return the correct help for the prefix requested
122     def help(plugin, topic)
123       "no help"
124     end
125     
126     # register the plugin as a handler for messages prefixed +name+
127     # this can be called multiple times for a plugin to handle multiple
128     # message prefixes
129     def register(name)
130       return if Plugins.plugins.has_key?(name)
131       Plugins.plugins[name] = self
132       @names << name
133     end
134
135     # default usage method provided as a utility for simple plugins. The
136     # MessageMapper uses 'usage' as its default fallback method.
137     def usage(m, params = {})
138       m.reply "incorrect usage, ask for help using '#{@bot.nick}: help #{m.plugin}'"
139     end
140
141   end
142
143   # class to manage multiple plugins and delegate messages to them for
144   # handling
145   class Plugins
146     # hash of registered message prefixes and associated plugins
147     @@plugins = Hash.new
148     # associated IrcBot class
149     @@bot = nil
150
151     # bot::     associated IrcBot class
152     # dirlist:: array of directories to scan (in order) for plugins
153     #
154     # create a new plugin handler, scanning for plugins in +dirlist+
155     def initialize(bot, dirlist)
156       @@bot = bot
157       @dirs = dirlist
158       scan
159     end
160     
161     # access to associated bot
162     def Plugins.bot
163       @@bot
164     end
165
166     # access to list of plugins
167     def Plugins.plugins
168       @@plugins
169     end
170
171     # load plugins from pre-assigned list of directories
172     def scan
173       dirs = Array.new
174       dirs << Config::DATADIR + "/plugins"
175       dirs += @dirs
176       dirs.each {|dir|
177         if(FileTest.directory?(dir))
178           d = Dir.new(dir)
179           d.sort.each {|file|
180             next if(file =~ /^\./)
181             next unless(file =~ /\.rb$/)
182             @tmpfilename = "#{dir}/#{file}"
183
184             # create a new, anonymous module to "house" the plugin
185             # the idea here is to prevent namespace pollution. perhaps there
186             # is another way?
187             plugin_module = Module.new
188             
189             begin
190               plugin_string = IO.readlines(@tmpfilename).join("")
191               debug "loading module: #{@tmpfilename}"
192               plugin_module.module_eval(plugin_string)
193             rescue StandardError, NameError, LoadError, SyntaxError => err
194               puts "warning: plugin #{@tmpfilename} load failed: " + err
195               puts err.backtrace.join("\n")
196             end
197           }
198         end
199       }
200     end
201
202     # call the save method for each active plugin
203     def save
204       delegate 'save'
205     end
206
207     # call the cleanup method for each active plugin
208     def cleanup
209       delegate 'cleanup'
210     end
211
212     # drop all plugins and rescan plugins on disk
213     # calls save and cleanup for each plugin before dropping them
214     def rescan
215       save
216       cleanup
217       @@plugins = Hash.new
218       scan
219     end
220
221     # return list of help topics (plugin names)
222     def helptopics
223       if(@@plugins.length > 0)
224         # return " [plugins: " + @@plugins.keys.sort.join(", ") + "]"
225         return " [#{length} plugins: " + @@plugins.values.uniq.collect{|p| p.name}.sort.join(", ") + "]"
226       else
227         return " [no plugins active]" 
228       end
229     end
230
231     def length
232       @@plugins.values.uniq.length
233     end
234
235     # return help for +topic+ (call associated plugin's help method)
236     def help(topic="")
237       if(topic =~ /^(\S+)\s*(.*)$/)
238         key = $1
239         params = $2
240         if(@@plugins.has_key?(key))
241           begin
242             return @@plugins[key].help(key, params)
243           rescue StandardError, NameError, SyntaxError => err
244             puts "plugin #{@@plugins[key].name} help() failed: " + err
245             puts err.backtrace.join("\n")
246           end
247         else
248           return false
249         end
250       end
251     end
252     
253     # see if each plugin handles +method+, and if so, call it, passing
254     # +message+ as a parameter
255     def delegate(method, *args)
256       @@plugins.values.uniq.each {|p|
257         if(p.respond_to? method)
258           begin
259             p.send method, *args
260           rescue StandardError, NameError, SyntaxError => err
261             puts "plugin #{p.name} #{method}() failed: " + err
262             puts err.backtrace.join("\n")
263           end
264         end
265       }
266     end
267
268     # see if we have a plugin that wants to handle this message, if so, pass
269     # it to the plugin and return true, otherwise false
270     def privmsg(m)
271       return unless(m.plugin)
272       if (@@plugins.has_key?(m.plugin) &&
273           @@plugins[m.plugin].respond_to?("privmsg") &&
274           @@bot.auth.allow?(m.plugin, m.source, m.replyto))
275         begin
276           @@plugins[m.plugin].privmsg(m)
277         rescue StandardError, NameError, SyntaxError => err
278           puts "plugin #{@@plugins[m.plugin].name} privmsg() failed: " + err
279           puts err.backtrace.join("\n")
280         end
281         return true
282       end
283       return false
284     end
285   end
286
287 end
288 end