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]
16 Regexp.new(new, self.options)
19 # We may want to remove head and tail anchors
21 new = self.source.sub(/^\^/,'').sub(/\$$/,'')
22 Regexp.new(new, self.options)
25 # The MessageMapper cleanup method: does both remove_capture
26 # and remove_head_tail
28 new = self.source.gsub(/(^|[^\\])((?:\\\\)*)\(([^?])/) {
29 "%s%s(?:%s" % [$1, $2, $3]
30 }.sub(/^\^/,'').sub(/\$$/,'')
31 Regexp.new(new, self.options)
38 # MessageMapper is a class designed to reduce the amount of regexps and
39 # string parsing plugins and bot modules need to do, in order to process
40 # and respond to messages.
42 # You add templates to the MessageMapper which are examined by the handle
43 # method when handling a message. The templates tell the mapper which
44 # method in its parent class (your class) to invoke for that message. The
45 # string is split, optionally defaulted and validated before being passed
46 # to the matched method.
48 # A template such as "foo :option :otheroption" will match the string "foo
49 # bar baz" and, by default, result in method +foo+ being called, if
50 # present, in the parent class. It will receive two parameters, the
51 # message (derived from BasicUserMessage) and a Hash containing
52 # {:option => "bar", :otheroption => "baz"}
53 # See the #map method for more details.
57 STRING = "template %{template} failed to recognize message %{message}"
58 FRIENDLY = "I failed to understand the command"
61 def initialize(tmpl, msg)
68 :template => template.template,
69 :regexp => template.regexp,
70 :message => message.message,
71 :action => template.options[:action]
76 # failures with a friendly message
77 class FriendlyFailure < Failure
79 self.class::FRIENDLY rescue FRIENDLY
83 class NotPrivateFailure < FriendlyFailure
84 STRING = "template %{template} is not configured for private messages"
85 FRIENDLY = "the command must not be given in private"
88 class NotPublicFailure < FriendlyFailure
89 STRING = "template %{template} is not configured for public messages"
90 FRIENDLY = "the command must not be given in public"
93 class NoMatchFailure < Failure
94 STRING = "%{message} does not match %{template} (%{regex})"
97 class PartialMatchFailure < Failure
98 STRING = "%{message} only matches %{template} (%{regex}) partially"
101 class NoActionFailure < FriendlyFailure
102 STRING = "%{template} calls undefined action %{action}"
103 FRIENDLY = "uh-ho, somebody forgot to tell me how to do that ..."
106 # used to set the method name used as a fallback for unmatched messages.
107 # The default fallback is a method called "usage".
108 attr_writer :fallback
110 # _parent_:: parent class which will receive mapped messages
112 # Create a new MessageMapper with parent class _parent_. This class will
113 # receive messages from the mapper via the handle() method.
114 def initialize(parent)
116 @templates = Array.new
120 # call-seq: map(botmodule, template, options)
122 # _botmodule_:: the BotModule which will handle this map
123 # _template_:: a String describing the messages to be matched
124 # _options_:: a Hash holding variouns options
126 # This method is used to register a new MessageTemplate that will map any
127 # BasicUserMessage matching the given _template_ to a corresponding action.
129 # plugin.map 'myplugin :parameter'
130 # (other examples follow).
132 # By default, the action to which the messages are mapped is a method named
133 # like the first word of the template. The
134 # :action => 'method_name'
135 # option can be used to override this default behaviour. Example:
136 # plugin.map 'myplugin :parameter', :action => 'mymethod'
138 # By default whether a handler is fired depends on an auth check. In rbot
139 # versions up to 0.9.10, the first component of the string was used for the
140 # auth check, unless overridden via the :auth => 'auth_name' option. Since
141 # version 0.9.11, a new auth method has been implemented. TODO document.
143 # Static parameters (not prefixed with ':' or '*') must match the
144 # respective component of the message exactly. Example:
145 # plugin.map 'myplugin :foo is :bar'
146 # will only match messages of the form "myplugin something is
149 # Dynamic parameters can be specified by a colon ':' to match a single
150 # component (whitespace separated), or a * to suck up all following
151 # parameters into an array. Example:
152 # plugin.map 'myplugin :parameter1 *rest'
154 # You can provide defaults for dynamic components using the :defaults
155 # parameter. If a component has a default, then it is optional. e.g:
156 # plugin.map 'myplugin :foo :bar', :defaults => {:bar => 'qux'}
157 # would match 'myplugin param param2' and also 'myplugin param'. In the
158 # latter case, :bar would be provided from the default.
160 # Static and dynamic parameters can also be made optional by wrapping them
161 # in square brackets []. For example
162 # plugin.map 'myplugin :foo [is] :bar'
163 # will match both 'myplugin something is somethingelse' and 'myplugin
164 # something somethingelse'.
166 # Components can be validated before being allowed to match, for
167 # example if you need a component to be a number:
168 # plugin.map 'myplugin :param', :requirements => {:param => /^\d+$/}
169 # will only match strings of the form 'myplugin 1234' or some other
172 # Templates can be set not to match public or private messages using the
173 # :public or :private boolean options.
175 # Summary of recognized options:
178 # method to call when the template is matched
182 # a Hash whose keys are names of dynamic parameters and whose values are
183 # regular expressions that the parameters must match
185 # a Hash whose keys are names of dynamic parameters and whose values are
186 # the values to be assigned to those parameters when they are missing from
187 # the message. Any dynamic parameter appearing in the :defaults Hash is
190 # a boolean (defaults to true) that determines whether the template should
191 # match public (in channel) messages.
193 # a boolean (defaults to true) that determines whether the template should
194 # match private (not in channel) messages.
196 # a boolean (defaults to false) that determines whether the action should be
197 # called in a separate thread.
202 # # match 'karmastats' and call my stats() method
203 # plugin.map 'karmastats', :action => 'stats'
204 # # match 'karma' with an optional 'key' and call my karma() method
205 # plugin.map 'karma :key', :defaults => {:key => false}
206 # # match 'karma for something' and call my karma() method
207 # plugin.map 'karma for :key'
209 # # two matches, one for public messages in a channel, one for
210 # # private messages which therefore require a channel argument
211 # plugin.map 'urls search :channel :limit :string',
212 # :action => 'search',
213 # :defaults => {:limit => 4},
214 # :requirements => {:limit => /^\d+$/},
216 # plugin.map 'urls search :limit :string',
217 # :action => 'search',
218 # :defaults => {:limit => 4},
219 # :requirements => {:limit => /^\d+$/},
222 def map(botmodule, *args)
223 @templates << MessageTemplate.new(botmodule, *args)
226 # Iterate over each MessageTemplate handled.
228 @templates.each {|tmpl| yield tmpl}
231 # Return the last added MessageTemplate
236 # _m_:: derived from BasicUserMessage
238 # Examine the message _m_, comparing it with each map()'d template to
239 # find and process a match. Templates are examined in the order they
240 # were map()'d - first match wins.
242 # Returns +true+ if a match is found including fallbacks, +false+
245 return false if @templates.empty?
247 @templates.each do |tmpl|
248 params = tmpl.recognize(m)
249 if params.kind_of? Failure
252 action = tmpl.options[:action]
253 unless @parent.respond_to?(action)
254 failures << NoActionFailure.new(tmpl, m)
257 auth = tmpl.options[:full_auth_path]
258 debug "checking auth for #{auth}"
259 if m.bot.auth.allow?(auth, m.source, m.replyto)
260 debug "template match found and auth'd: #{action.inspect} #{params.inspect}"
261 if !m.in_thread and (tmpl.options[:thread] or tmpl.options[:threaded]) and
262 (defined? WebServiceUser and not m.source.instance_of? WebServiceUser)
263 # Web service: requests are handled threaded anyway and we want to
264 # wait for the responses.
266 # since the message action is in a separate thread, the message may be
267 # delegated to unreplied() before the thread has a chance to actually
268 # mark it as replied. since threading is used mostly for commands that
269 # are known to take some processing time (e.g. download a web page) before
270 # giving an output, we just mark these as 'replied' here
274 @parent.send(action, m, params)
275 rescue Exception => e
276 error "In threaded action: #{e.message}"
277 debug e.backtrace.join("\n")
281 @parent.send(action, m, params)
286 debug "auth failed for #{auth}"
287 # if it's just an auth failure but otherwise the match is good,
288 # don't try any more handlers
293 debug "#{r.template.inspect} => #{r}"
295 debug "no handler found, trying fallback"
296 if @fallback && @parent.respond_to?(@fallback)
297 if m.bot.auth.allow?(@fallback, m.source, m.replyto)
298 @parent.send(@fallback, m, {:failures => failures})
307 # MessageParameter is a class that collects all the necessary information
308 # about a message (dynamic) parameter (the :param or *param that can be found
311 # It has a +name+ attribute, +multi+ and +optional+ booleans that tell if the
312 # parameter collects more than one word, and if it's optional (respectively).
313 # In the latter case, it can also have a default value.
315 # It is possible to assign a collector to a MessageParameter. This can be either
316 # a Regexp with captures or an Array or a Hash. The collector defines what the
317 # collect() method is supposed to return.
318 class MessageParameter
321 attr_writer :optional
322 attr_accessor :default
345 # This method is used to turn a matched item into the actual parameter value.
346 # It only does something when collector= set the @regexp to something. In
347 # this case, _val_ is matched against @regexp and then the match result
348 # specified in @index is selected. As a special case, when @index is nil
349 # the first non-nil captured group is returned.
351 return val unless @regexp
352 mdata = @regexp.match(val)
356 return mdata[1..-1].compact.first
360 # This method allow the plugin programmer to choose to only pick a subset of the
361 # string matched by a parameter. This is done by passing the collector=()
362 # method either a Regexp with captures or an Array or a Hash.
364 # When the method is passed a Regexp with captures, the collect() method will
365 # return the first non-nil captured group.
367 # When the method is passed an Array, it will grab a regexp from the first
368 # element, and possibly an index from the second element. The index can
371 # When the method is passed a Hash, it will grab a regexp from the :regexp
372 # element, and possibly an index from the :index element. The index can
378 return unless val.has_captures?
381 warning "Collector #{val.inspect} is too long, ignoring extra entries" unless val.length <= 2
383 @index = val[1] rescue nil
385 raise "Collector #{val.inspect} doesn't have a :regexp key" unless val.has_key?(:regexp)
386 @regexp = val[:regexp]
387 @index = val.fetch(:regexp, nil)
389 raise "The regexp of collector #{val.inspect} isn't a Regexp" unless @regexp.kind_of?(Regexp)
390 raise "The index of collector #{val.inspect} is present but not an integer " if @index and not @index.kind_of?(Fixnum)
394 mul = multi? ? " multi" : " single"
395 opt = optional? ? " optional" : " needed"
397 reg = " regexp=%s index=%s" % [@regexp, @index]
401 "<%s %s%s%s%s>" % [self.class, name, mul, opt, reg]
405 # MessageTemplate is the class that holds the actual message template map()'d
406 # by a BotModule and handled by a MessageMapper
408 class MessageTemplate
409 attr_reader :defaults # the defaults hash
410 attr_reader :options # the options hash
411 attr_reader :template # the actual template string
412 attr_reader :items # the collection of dynamic and static items in the template
413 attr_reader :regexp # the Regexp corresponding to the template
414 attr_reader :botmodule # the BotModule that map()'d this MessageTemplate
416 # call-seq: initialize(botmodule, template, opts={})
418 # Create a new MessageTemplate associated to BotModule _botmodule_, with
419 # template _template_ and options _opts_
421 def initialize(botmodule, template, hash={})
422 raise ArgumentError, "Third argument must be a hash!" unless hash.kind_of?(Hash)
423 @defaults = hash[:defaults].kind_of?(Hash) ? hash.delete(:defaults) : {}
424 @requirements = hash[:requirements].kind_of?(Hash) ? hash.delete(:requirements) : {}
428 @botmodule = botmodule
429 when Plugins::BotModule
430 @botmodule = botmodule.name
432 raise ArgumentError, "#{botmodule.inspect} is not a botmodule nor a botmodule name"
435 self.items = template
436 # @dyn_items is an array of MessageParameters, except for the first entry
437 # which is the template
438 @dyn_items = @items.collect { |it|
439 if it.kind_of?(Symbol)
441 opt = MessageParameter.new(i)
446 opt.default = @defaults[opt.name]
447 opt.collector = @requirements[opt.name]
453 @dyn_items.unshift(template).compact!
454 debug "Items: #{@items.inspect}; dyn items: #{@dyn_items.inspect}"
456 self.regexp = template
457 debug "Command #{template.inspect} in #{@botmodule} will match using #{@regexp}"
461 unless hash.has_key?(:action)
462 hash[:action] = items[0]
467 # debug "Create template #{self.inspect}"
470 def set_auth_path(hash)
471 if hash.has_key?(:auth)
472 warning "Command #{@template.inspect} in #{@botmodule} uses old :auth syntax, please upgrade"
474 if hash.has_key?(:full_auth_path)
475 warning "Command #{@template.inspect} in #{@botmodule} sets :full_auth_path, please don't do this"
478 words = items.reject{ |x|
479 x == pre || x.kind_of?(Symbol) || x =~ /\[|\]/
486 if hash.has_key?(:auth_path)
487 extra = hash[:auth_path]
488 if extra.sub!(/^:/, "")
492 if extra.sub!(/:$/, "")
494 post = [post,words[1]].compact.join("::")
497 pre = nil if extra.sub!(/^!/, "")
498 post = nil if extra.sub!(/!$/, "")
499 extra = nil if extra.empty?
503 hash[:full_auth_path] = [pre,extra,post].compact.join("::")
504 debug "Command #{@template} in #{botmodule} will use authPath #{hash[:full_auth_path]}"
505 # TODO check if the full_auth_path is sane
510 raise ArgumentError, "template #{str.inspect} should be a String" unless str.kind_of?(String)
512 # split and convert ':xyz' to symbols
513 items = str.strip.split(/\]?\s+\[?|\]?$/).collect { |c|
514 # there might be extra (non-alphanumeric) stuff (e.g. punctuation) after the symbol name
515 if /^(:|\*)(\w+)(.*)/ =~ c
516 sym = ($1 == ':' ) ? $2.intern : "*#{$2}".intern
528 raise ArgumentError, "Illegal template -- first component cannot be dynamic: #{str.inspect}" if @items.first.kind_of? Symbol
530 raise ArgumentError, "Illegal template -- first component cannot be optional: #{str.inspect}" if @items.first =~ /\[|\]/
532 # Verify uniqueness of each component.
533 @items.inject({}) do |seen, item|
534 if item.kind_of? Symbol
535 # We must remove the initial * when present,
536 # because the parameters hash will intern both :item and *item as :item
537 it = item.to_s.sub(/^\*/,"").intern
538 raise ArgumentError, "Illegal template -- duplicate item #{it} in #{str.inspect}" if seen.key? it
546 # debug "Original string: #{str.inspect}"
547 rx = Regexp.escape(str)
548 # debug "Escaped: #{rx.inspect}"
549 rx.gsub!(/((?:\\ )*)(:|\\\*)(\w+)/) { |m|
551 is_single = $2 == ":"
554 not_needed = @defaults.has_key?(name)
556 has_req = @requirements[name]
557 debug "Requirements for #{name}: #{has_req.inspect}"
560 sub = is_single ? "\\S+" : ".*?"
562 # Remove captures and the ^ and $ that are sometimes placed in requirement regexps
563 sub = has_req.mm_cleanup
565 sub = Regexp.escape(has_req)
567 sub = has_req[0].mm_cleanup
569 sub = has_req[:regexp].mm_cleanup
571 warning "Odd requirement #{has_req.inspect} of class #{has_req.class} for parameter '#{name}'"
572 sub = Regexp.escape(has_req.to_s) rescue "\\S+"
574 debug "Regexp for #{name}: #{sub.inspect}"
575 s = "#{not_needed ? "(?:" : ""}#{whites}(#{sub})#{ not_needed ? ")?" : ""}"
577 # debug "Replaced dyns: #{rx.inspect}"
578 rx.gsub!(/((?:\\ )*)((?:\\\[)+)/, '\2\1')
579 # debug "Corrected optionals spacing: #{rx.inspect}"
580 rx.gsub!(/\\\[/, "(?:")
581 rx.gsub!(/\\\]/, ")?")
582 # debug "Delimited optionals: #{rx.inspect}"
583 rx.gsub!(/(?:\\ )+/, "\\s+")
584 # debug "Corrected spaces: #{rx.inspect}"
585 # Created message (such as by fake_message) can contain multiple lines
586 @regexp = /\A#{rx}\z/m
589 # Recognize the provided string components, returning a hash of
590 # recognized values, or [nil, reason] if the string isn't recognized.
593 debug "Testing #{m.message.inspect} against #{self.inspect}"
595 matching = @regexp.match(m.message)
596 return MessageMapper::NoMatchFailure.new(self, m) unless matching
597 return MessageMapper::PartialMatchFailure.new(self, m) unless matching[0] == m.message
599 return MessageMapper::NotPrivateFailure.new(self, m) if @options.has_key?(:private) && !@options[:private] && m.private?
600 return MessageMapper::NotPublicFailure.new(self, m) if @options.has_key?(:public) && !@options[:public] && !m.private?
602 debug_match = matching[1..-1].collect{ |d| d.inspect}.join(', ')
603 debug "#{m.message.inspect} matched #{@regexp} with #{debug_match}"
604 debug "Associating #{debug_match} with dyn items #{@dyn_items.join(', ')}"
606 options = @defaults.dup
608 @dyn_items.each_with_index { |it, i|
611 debug "dyn item #{item} (multi-word: #{it.multi?.inspect})"
617 value = default.clone
619 value = default.strip.split
623 warning "Unmanageable default #{default} detected for :*#{item.to_s}, using []"
628 value.instance_variable_set(:@string_value, default)
630 value.instance_variable_set(:@string_value, value.join(' '))
633 value = matching[i].split
634 value.instance_variable_set(:@string_value, matching[i])
641 warning "No default value for option #{item.inspect} specified" unless @defaults.has_key?(item)
644 value = it.collect(matching[i])
647 options[item] = value
648 debug "set #{item} to #{options[item].inspect}"
651 options.delete_if {|k, v| v.nil?} # Remove nil values.
656 when_str = @requirements.empty? ? "" : " when #{@requirements.inspect}"
657 default_str = @defaults.empty? ? "" : " || #{@defaults.inspect}"
658 "<#{self.class.to_s} #{@items.map { |c| c.inspect }.join(' ').inspect}#{default_str}#{when_str}>"
661 def requirements_for(name)
662 name = name.to_s.sub(/^\*/,"").intern if (/^\*/ =~ name.inspect)
663 presence = (@defaults.key?(name) && @defaults[name].nil?)
664 requirement = case @requirements[name]
666 when Regexp then "match #{@requirements[name].inspect}"
667 else "be equal to #{@requirements[name].inspect}"
669 if presence && requirement then "#{name} must be present and #{requirement}"
670 elsif presence || requirement then "#{name} must #{requirement || 'be present'}"
671 else "#{name} has no requirements"