1 # First of all we add a method to the Regexp class
4 # a Regexp has captures when its source has open parenthesis which are
5 # preceded by an even number of slashes and not followed by a question mark
8 self.source.match(/(?:^|[^\\])(?:\\\\)*\([^?]/)
11 # We may want to remove captures
13 new = self.source.gsub(/(^|[^\\])((?:\\\\)*)\(([^?])/) {
14 "%s%s(?:%s" % [$1, $2, $3]
22 # +MessageMapper+ is a class designed to reduce the amount of regexps and
23 # string parsing plugins and bot modules need to do, in order to process
24 # and respond to messages.
26 # You add templates to the MessageMapper which are examined by the handle
27 # method when handling a message. The templates tell the mapper which
28 # method in its parent class (your class) to invoke for that message. The
29 # string is split, optionally defaulted and validated before being passed
30 # to the matched method.
32 # A template such as "foo :option :otheroption" will match the string "foo
33 # bar baz" and, by default, result in method +foo+ being called, if
34 # present, in the parent class. It will receive two parameters, the
35 # Message (derived from BasicUserMessage) and a Hash containing
36 # {:option => "bar", :otheroption => "baz"}
37 # See the #map method for more details.
39 # used to set the method name used as a fallback for unmatched messages.
40 # The default fallback is a method called "usage".
43 # parent:: parent class which will receive mapped messages
45 # create a new MessageMapper with parent class +parent+. This class will
46 # receive messages from the mapper via the handle() method.
47 def initialize(parent)
49 @templates = Array.new
53 # args:: hash format containing arguments for this template
55 # map a template string to an action. example:
56 # map 'myplugin :parameter1 :parameter2'
57 # (other examples follow). By default, maps a matched string to an
58 # action with the name of the first word in the template. The action is
59 # a method which takes a message and a parameter hash for arguments.
61 # The :action => 'method_name' option can be used to override this
62 # default behaviour. Example:
63 # map 'myplugin :parameter1 :parameter2', :action => 'mymethod'
65 # By default whether a handler is fired depends on an auth check. The
66 # first component of the string is used for the auth check, unless
67 # overridden via the :auth => 'auth_name' option.
69 # Static parameters (not prefixed with ':' or '*') must match the
70 # respective component of the message exactly. Example:
71 # map 'myplugin :foo is :bar'
72 # will only match messages of the form "myplugin something is
75 # Dynamic parameters can be specified by a colon ':' to match a single
76 # component (whitespace seperated), or a * to suck up all following
77 # parameters into an array. Example:
78 # map 'myplugin :parameter1 *rest'
80 # You can provide defaults for dynamic components using the :defaults
81 # parameter. If a component has a default, then it is optional. e.g:
82 # map 'myplugin :foo :bar', :defaults => {:bar => 'qux'}
83 # would match 'myplugin param param2' and also 'myplugin param'. In the
84 # latter case, :bar would be provided from the default.
86 # Components can be validated before being allowed to match, for
87 # example if you need a component to be a number:
88 # map 'myplugin :param', :requirements => {:param => /^\d+$/}
89 # will only match strings of the form 'myplugin 1234' or some other
92 # Templates can be set not to match public or private messages using the
93 # :public or :private boolean options.
97 # # match 'karmastats' and call my stats() method
98 # map 'karmastats', :action => 'stats'
99 # # match 'karma' with an optional 'key' and call my karma() method
100 # map 'karma :key', :defaults => {:key => false}
101 # # match 'karma for something' and call my karma() method
102 # map 'karma for :key'
104 # # two matches, one for public messages in a channel, one for
105 # # private messages which therefore require a channel argument
106 # map 'urls search :channel :limit :string', :action => 'search',
107 # :defaults => {:limit => 4},
108 # :requirements => {:limit => /^\d+$/},
110 # plugin.map 'urls search :limit :string', :action => 'search',
111 # :defaults => {:limit => 4},
112 # :requirements => {:limit => /^\d+$/},
115 def map(botmodule, *args)
116 @templates << MessageTemplate.new(botmodule, *args)
120 @templates.each {|tmpl| yield tmpl}
127 # m:: derived from BasicUserMessage
129 # examine the message +m+, comparing it with each map()'d template to
130 # find and process a match. Templates are examined in the order they
131 # were map()'d - first match wins.
133 # returns +true+ if a match is found including fallbacks, +false+
136 return false if @templates.empty?
138 @templates.each do |tmpl|
139 options, failure = tmpl.recognize(m)
141 failures << [tmpl, failure]
143 action = tmpl.options[:action]
144 unless @parent.respond_to?(action)
145 failures << [tmpl, "class does not respond to action #{action}"]
148 auth = tmpl.options[:full_auth_path]
149 debug "checking auth for #{auth}"
150 if m.bot.auth.allow?(auth, m.source, m.replyto)
151 debug "template match found and auth'd: #{action.inspect} #{options.inspect}"
152 @parent.send(action, m, options)
155 debug "auth failed for #{auth}"
156 # if it's just an auth failure but otherwise the match is good,
157 # don't try any more handlers
161 failures.each {|f, r|
162 debug "#{f.inspect} => #{r}"
164 debug "no handler found, trying fallback"
165 if @fallback && @parent.respond_to?(@fallback)
166 if m.bot.auth.allow?(@fallback, m.source, m.replyto)
167 @parent.send(@fallback, m, {})
176 # +MessageParameter+ is a class that collects all the necessary information
177 # about a message parameter (the :param or *param that can be found in a
180 # It has a +name+ attribute, +multi+ and +optional+ booleans that tell if the
181 # parameter collects more than one word, and if it's optional (respectively).
182 # In the latter case, it can also have a default value.
184 # It is possible to assign a collector to a MessageParameter. This can be either
185 # a Regexp with captures or an Array or a Hash. The collector defines what the
186 # collect() method is supposed to return.
187 class MessageParameter
190 attr_writer :optional
191 attr_accessor :default
214 # This method is used to turn a matched item into the actual parameter value.
215 # It only does something when collector= set the @regexp to something. In
216 # this case, _val_ is matched against @regexp and then the match result
217 # specified in @index is selected. As a special case, when @index is nil
218 # the first non-nil captured group is returned.
220 return val unless @regexp
221 mdata = @regexp.match(val)
225 return mdata[1..-1].compact.first
229 # This method allow the plugin programmer to choose to only pick a subset of the
230 # string matched by a parameter. This is done by passing the collector=()
231 # method either a Regexp with captures or an Array or a Hash.
233 # When the method is passed a Regexp with captures, the collect() method will
234 # return the first non-nil captured group.
236 # When the method is passed an Array, it will grab a regexp from the first
237 # element, and possibly an index from the second element. The index can
240 # When the method is passed a Hash, it will grab a regexp from the :regexp
241 # element, and possibly an index from the :index element. The index can
247 return unless val.has_captures?
250 warning "Collector #{val.inspect} is too long, ignoring extra entries" unless val.length <= 2
252 @index = val[1] rescue nil
254 raise "Collector #{val.inspect} doesn't have a :regexp key" unless val.has_key?(:regexp)
255 @regexp = val[:regexp]
256 @index = val.fetch(:regexp, nil)
258 raise "The regexp of collector #{val.inspect} isn't a Regexp" unless @regexp.kind_of?(Regexp)
259 raise "The index of collector #{val.inspect} is present but not an integer " if @index and not @index.kind_of?(Fixnum)
263 mul = multi? ? " multi" : " single"
264 opt = optional? ? " optional" : " needed"
266 reg = " regexp=%s index=%d" % [@regexp, @index]
270 "<#{self.class.to_s}%s%s%s%s>" % [name, mul, opt, reg]
274 class MessageTemplate
275 attr_reader :defaults # The defaults hash
276 attr_reader :options # The options hash
277 attr_reader :template
280 attr_reader :botmodule
282 def initialize(botmodule, template, hash={})
283 raise ArgumentError, "Third argument must be a hash!" unless hash.kind_of?(Hash)
284 @defaults = hash[:defaults].kind_of?(Hash) ? hash.delete(:defaults) : {}
285 @requirements = hash[:requirements].kind_of?(Hash) ? hash.delete(:requirements) : {}
289 @botmodule = botmodule
290 when Plugins::BotModule
291 @botmodule = botmodule.name
293 raise ArgumentError, "#{botmodule.inspect} is not a botmodule nor a botmodule name"
296 self.items = template
297 # @dyn_items is an array of MessageParameters, except for the first entry
298 # which is the template
299 @dyn_items = @items.collect { |it|
300 if it.kind_of?(Symbol)
302 opt = MessageParameter.new(i)
307 opt.default = @defaults[opt.name]
308 opt.collector = @requirements[opt.name]
314 @dyn_items.unshift(template).compact!
315 debug "Items: #{@items.inspect}; dyn items: #{@dyn_items.inspect}"
317 self.regexp = template
318 debug "Command #{template.inspect} in #{@botmodule} will match using #{@regexp}"
322 unless hash.has_key?(:action)
323 hash[:action] = items[0]
328 # debug "Create template #{self.inspect}"
331 def set_auth_path(hash)
332 if hash.has_key?(:auth)
333 warning "Command #{@template.inspect} in #{@botmodule} uses old :auth syntax, please upgrade"
335 if hash.has_key?(:full_auth_path)
336 warning "Command #{@template.inspect} in #{@botmodule} sets :full_auth_path, please don't do this"
339 words = items.reject{ |x|
340 x == pre || x.kind_of?(Symbol) || x =~ /\[|\]/
347 if hash.has_key?(:auth_path)
348 extra = hash[:auth_path]
349 if extra.sub!(/^:/, "")
353 if extra.sub!(/:$/, "")
355 post = [post,words[1]].compact.join("::")
358 pre = nil if extra.sub!(/^!/, "")
359 post = nil if extra.sub!(/!$/, "")
363 hash[:full_auth_path] = [pre,extra,post].compact.join("::")
364 debug "Command #{@template} in #{botmodule} will use authPath #{hash[:full_auth_path]}"
365 # TODO check if the full_auth_path is sane
370 raise ArgumentError, "template #{str.inspect} should be a String" unless str.kind_of?(String)
372 # split and convert ':xyz' to symbols
373 items = str.strip.split(/\]?\s+\[?|\]?$/).collect { |c|
374 # there might be extra (non-alphanumeric) stuff (e.g. punctuation) after the symbol name
375 if /^(:|\*)(\w+)(.*)/ =~ c
376 sym = ($1 == ':' ) ? $2.intern : "*#{$2}".intern
388 raise ArgumentError, "Illegal template -- first component cannot be dynamic: #{str.inspect}" if @items.first.kind_of? Symbol
390 raise ArgumentError, "Illegal template -- first component cannot be optional: #{str.inspect}" if @items.first =~ /\[|\]/
392 # Verify uniqueness of each component.
393 @items.inject({}) do |seen, item|
394 if item.kind_of? Symbol
395 # We must remove the initial * when present,
396 # because the parameters hash will intern both :item and *item as :item
397 it = item.to_s.sub(/^\*/,"").intern
398 raise ArgumentError, "Illegal template -- duplicate item #{it} in #{str.inspect}" if seen.key? it
406 # debug "Original string: #{str.inspect}"
407 rx = Regexp.escape(str)
408 # debug "Escaped: #{rx.inspect}"
409 rx.gsub!(/((?:\\ )*)(:|\\\*)(\w+)/) { |m|
411 is_single = $2 == ":"
414 not_needed = @defaults.has_key?(name)
416 has_req = @requirements[name]
417 debug "Requirements for #{name}: #{has_req.inspect}"
420 sub = is_single ? "\\S+" : ".*?"
422 # Remove captures and the ^ and $ that are sometimes placed in requirement regexps
423 sub = has_req.remove_captures.source.sub(/^\^/,'').sub(/\$$/,'')
425 sub = Regexp.escape(has_req)
427 sub = has_req[0].remove_captures.source.sub(/^\^/,'').sub(/\$$/,'')
429 sub = has_req[:regexp].remove_captures.source.sub(/^\^/,'').sub(/\$$/,'')
431 warning "Odd requirement #{has_req.inspect} of class #{has_req.class} for parameter '#{name}'"
432 sub = Regexp.escape(has_req.to_s) rescue "\\S+"
434 debug "Regexp for #{name}: #{sub.inspect}"
435 s = "#{not_needed ? "(?:" : ""}#{whites}(#{sub})#{ not_needed ? ")?" : ""}"
437 # debug "Replaced dyns: #{rx.inspect}"
438 rx.gsub!(/((?:\\ )*)\\\[/, "(?:\\1")
439 rx.gsub!(/\\\]/, ")?")
440 # debug "Delimited optionals: #{rx.inspect}"
441 rx.gsub!(/(?:\\ )+/, "\\s+")
442 # debug "Corrected spaces: #{rx.inspect}"
443 @regexp = Regexp.new("^#{rx}$")
446 # Recognize the provided string components, returning a hash of
447 # recognized values, or [nil, reason] if the string isn't recognized.
450 debug "Testing #{m.message.inspect} against #{self.inspect}"
453 return nil, "template #{@template} is not configured for private messages" if @options.has_key?(:private) && !@options[:private] && m.private?
454 return nil, "template #{@template} is not configured for public messages" if @options.has_key?(:public) && !@options[:public] && !m.private?
458 matching = @regexp.match(m.message)
459 return nil, "#{m.message.inspect} doesn't match #{@template} (#{@regexp})" unless matching
460 return nil, "#{m.message.inspect} only matches #{@template} (#{@regexp}) partially: #{matching[0].inspect}" unless matching[0] == m.message
462 debug_match = matching[1..-1].collect{ |d| d.inspect}.join(', ')
463 debug "#{m.message.inspect} matched #{@regexp} with #{debug_match}"
464 debug "Associating #{debug_match} with dyn items #{@dyn_items.join(', ')}"
466 @dyn_items.each_with_index { |it, i|
469 debug "dyn item #{item} (multi-word: #{it.multi?.inspect})"
475 value = default.clone
477 value = default.strip.split
481 warning "Unmanageable default #{default} detected for :*#{item.to_s}, using []"
486 value.instance_variable_set(:@string_value, default)
488 value.instance_variable_set(:@string_value, value.join(' '))
491 value = matching[i].split
492 value.instance_variable_set(:@string_value, matching[i])
499 warning "No default value for option #{item.inspect} specified" unless @defaults.has_key?(item)
502 value = it.collect(matching[i])
505 options[item] = value
506 debug "set #{item} to #{options[item].inspect}"
509 options.delete_if {|k, v| v.nil?} # Remove nil values.
514 when_str = @requirements.empty? ? "" : " when #{@requirements.inspect}"
515 default_str = @defaults.empty? ? "" : " || #{@defaults.inspect}"
516 "<#{self.class.to_s} #{@items.map { |c| c.inspect }.join(' ').inspect}#{default_str}#{when_str}>"
519 def requirements_for(name)
520 name = name.to_s.sub(/^\*/,"").intern if (/^\*/ =~ name.inspect)
521 presence = (@defaults.key?(name) && @defaults[name].nil?)
522 requirement = case @requirements[name]
524 when Regexp then "match #{@requirements[name].inspect}"
525 else "be equal to #{@requirements[name].inspect}"
527 if presence && requirement then "#{name} must be present and #{requirement}"
528 elsif presence || requirement then "#{name} must #{requirement || 'be present'}"
529 else "#{name} has no requirements"