### Home Classes Methods

### In Files

- lib/rbot/messagemapper.rb

### Parent

Object

### Namespace

- CLASS Irc::Bot::MessageMapper::Failure
- CLASS Irc::Bot::MessageMapper::FriendlyFailure
- CLASS Irc::Bot::MessageMapper::NoActionFailure
- CLASS Irc::Bot::MessageMapper::NoMatchFailure
- CLASS Irc::Bot::MessageMapper::NotPrivateFailure
- CLASS Irc::Bot::MessageMapper::NotPublicFailure
- CLASS Irc::Bot::MessageMapper::PartialMatchFailure

### Methods

- ::new
- #each
- #handle
- #last
- #map

### Class/Module Index

Quicksearch

- Irc
- Irc::AsciiCasemap
- Irc::BanlistMessage
- Irc::BasicUserMessage
- Irc::Bot
- Irc::Bot::Auth
- Irc::Bot::Auth::BotOwnerClass
- Irc::Bot::Auth::BotUser
- Irc::Bot::Auth::Command
- Irc::Bot::Auth::DefaultBotUserClass
- Irc::Bot::Auth::InvalidPassword
- Irc::Bot::Auth::ManagerClass
- Irc::Bot::Auth::PermissionSet
- Irc::Bot::Config
- Irc::Bot::Config::ArrayValue
- Irc::Bot::Config::BooleanValue
- Irc::Bot::Config::EnumValue
- Irc::Bot::Config::FloatValue
- Irc::Bot::Config::IntegerValue
- Irc::Bot::Config::ManagerClass
- Irc::Bot::Config::StringValue
- Irc::Bot::Config::Value
- Irc::Bot::Config::Wizard
- Irc::Bot::DataFilter
- Irc::Bot::DataStream
- Irc::Bot::Language
- Irc::Bot::MessageMapper
- Irc::Bot::MessageMapper::Failure
- Irc::Bot::MessageMapper::FriendlyFailure
- Irc::Bot::MessageMapper::NoActionFailure
- Irc::Bot::MessageMapper::NoMatchFailure
- Irc::Bot::MessageMapper::NotPrivateFailure
- Irc::Bot::MessageMapper::NotPublicFailure
- Irc::Bot::MessageMapper::PartialMatchFailure
- Irc::Bot::MessageParameter
- Irc::Bot::MessageTemplate
- Irc::Bot::Plugins
- Irc::Bot::Plugins::BotModule
- Irc::Bot::Plugins::CoreBotModule
- Irc::Bot::Plugins::Plugin
- Irc::Bot::Plugins::PluginManagerClass
- Irc::Bot::Plugins::RecurseTooDeep
- Irc::Bot::Plugins::RemoteBotModule
- Irc::Bot::Plugins::RemoteCoreBotModule
- Irc::Bot::Plugins::RemotePlugin
- Irc::Bot::Registry
- Irc::Bot::Registry::Accessor
- Irc::Bot::RemoteDispatcher
- Irc::Bot::RemoteMessage
- Irc::Bot::RemoteObject
- Irc::Bot::Wordlist
- Irc::BotConfig
- Irc::Casemap
- Irc::Channel
- Irc::Channel::Mode
- Irc::Channel::ModeHash
- Irc::Channel::ModeTypeA
- Irc::Channel::ModeTypeB
- Irc::Channel::ModeTypeC
- Irc::Channel::ModeTypeD
- Irc::Channel::Topic
- Irc::Channel::UserMode
- Irc::ChannelList
- Irc::Client
- Irc::DBHash
- Irc::DBTree
- Irc::InviteMessage
- Irc::JoinMessage
- Irc::KickMessage
- Irc::MessageQueue
- Irc::ModeChangeMessage
- Irc::MotdMessage
- Irc::NamesMessage
- Irc::Netmask
- Irc::NetmaskDb
- Irc::NetmaskDb::Tree
- Irc::NetmaskList
- Irc::NickMessage
- Irc::NoSuchTargetMessage
- Irc::NoticeMessage
- Irc::PartMessage
- Irc::PrivMessage
- Irc::QueueRing
- Irc::QuitMessage
- Irc::RfcCasemap
- Irc::Server
- Irc::ServerOrCasemap
- Irc::Socket
- Irc::Socket::IdentityFilter
- Irc::StrictRfcCasemap
- Irc::TopicMessage
- Irc::UnknownMessage
- Irc::User
- Irc::UserList
- Irc::UserMessage
- Irc::Utils
- Irc::Utils::HttpUtil
- Irc::Utils::HttpUtil::CachedObject
- Irc::Utils::ParseTime
- Irc::WelcomeMessage
- Irc::WhoisMessage
- BDB
- BDB::CIBtree
- MonitorMixin
- MonitorMixin::ConditionVariable
- Net
- Net::HTTPResponse
- Regexp
- Regexp::Irc
- Singleton
- Singleton::SingletonClassMethods
- Timer
- Timer::Action
- TokyoCabinet
- TokyoCabinet::CIBDB
- UnicodePlugin
- UnicodePlugin::UnicodeFilter
- Array
- ArrayOf
- AuthModule
- BasicsModule
- ConditionVariable
- ConfigModule
- DottedIndex
- Enumerable
- Exception
- FiltersModule
- GetText
- GetTextVersionError
- HttpUtilPlugin
- IrcLogModule
- Module
- Numeric
- Object
- Range
- RemoteModule
- ServerError
- String
- Symbol
- UserDataModule
- WordlistModule
- YAML

No matching classes.

# Irc::Bot::MessageMapper

MessageMapper is a class designed to reduce the amount of regexps and string parsing plugins and bot modules need to do, in order to process and respond to messages.

You add templates to the MessageMapper which are examined by the handle method when handling a message. The templates tell the mapper which method in its parent class (your class) to invoke for that message. The string is split, optionally defaulted and validated before being passed to the matched method.

A template such as "foo :option :otheroption" will match the string "foo bar baz" and, by default, result in method `foo` being called, if present, in the parent class. It will receive two parameters, the message (derived from BasicUserMessage) and a Hash containing

    {:option => "bar", :otheroption => "baz"}

See the map method for more details.

### Attributes

fallback[W]

used to set the method name used as a fallback for unmatched messages. The default fallback is a method called "usage".

### Public Class Methods

new(parent) click to toggle source

parent | parent class which will receive mapped messages

Create a new MessageMapper with parent class parent. This class will receive messages from the mapper via the handle() method.

    # File lib/rbot/messagemapper.rb, line 114
    def initialize(parent)
      @parent = parent
      @templates = Array.new
      @fallback = :usage
    end

### Public Instance Methods

each() click to toggle source

Iterate over each MessageTemplate handled.

    # File lib/rbot/messagemapper.rb, line 227
    def each
      @templates.each {|tmpl| yield tmpl}
    end

handle(m) click to toggle source

m | derived from BasicUserMessage

Examine the message m, comparing it with each map()'d template to find and process a match. Templates are examined in the order they were map()'d - first match wins.

Returns `true` if a match is found including fallbacks, `false` otherwise.

    # File lib/rbot/messagemapper.rb, line 244
    def handle(m)
      return false if @templates.empty?
      failures = []
      @templates.each do |tmpl|
        options = tmpl.recognize(m)
        if options.kind_of? Failure
          failures << options
        else
          action = tmpl.options[:action]
          unless @parent.respond_to?(action)
            failures << NoActionFailure.new(tmpl, m)
            next
          end
          auth = tmpl.options[:full_auth_path]
          debug "checking auth for #{auth}"
          if m.bot.auth.allow?(auth, m.source, m.replyto)
            debug "template match found and auth'd: #{action.inspect} #{options.inspect}"
            if !m.in_thread && (tmpl.options[:thread] || tmpl.options[:threaded])
              Thread.new do
                begin
                  @parent.send(action, m, options)
                rescue Exception => e
                  error "In threaded action: #{e.message}"
                  debug e.backtrace.join("\n")
                end
              end
            else
              @parent.send(action, m, options)
            end

            return true
          end
          debug "auth failed for #{auth}"
          # if it's just an auth failure but otherwise the match is good,
          # don't try any more handlers
          return false
        end
      end
      failures.each {|r|
        debug "#{r.template.inspect} => #{r}"
      }
      debug "no handler found, trying fallback"
      if @fallback && @parent.respond_to?(@fallback)
        if m.bot.auth.allow?(@fallback, m.source, m.replyto)
          @parent.send(@fallback, m, {:failures => failures})
          return true
        end
      end
      return false
    end

last() click to toggle source

Return the last added MessageTemplate

    # File lib/rbot/messagemapper.rb, line 232
    def last
      @templates.last
    end

map(botmodule, template, options) click to toggle source

botmodule | the BotModule which will handle this map
template | a String describing the messages to be matched
options | a Hash holding variouns options

This method is used to register a new MessageTemplate that will map any BasicUserMessage matching the given template to a corresponding action. A simple example:

    plugin.map 'myplugin :parameter'

(other examples follow).

By default, the action to which the messages are mapped is a method named like the first word of the template. The

    :action => 'method_name'

option can be used to override this default behaviour. Example:

    plugin.map 'myplugin :parameter', :action => 'mymethod'

By default whether a handler is fired depends on an auth check. In rbot versions up to 0.9.10, the first component of the string was used for the auth check, unless overridden via the :auth => 'auth_name' option. Since version 0.9.11, a new auth method has been implemented. TODO document.

Static parameters (not prefixed with ':' or '*') must match the respective component of the message exactly. Example:

    plugin.map 'myplugin :foo is :bar'

will only match messages of the form "myplugin something is somethingelse"

Dynamic parameters can be specified by a colon ':' to match a single component (whitespace separated), or a * to suck up all following parameters into an array. Example:

    plugin.map 'myplugin :parameter1 *rest'

You can provide defaults for dynamic components using the :defaults parameter. If a component has a default, then it is optional. e.g:

    plugin.map 'myplugin :foo :bar', :defaults => {:bar => 'qux'}

would match 'myplugin param param2' and also 'myplugin param'. In the latter case, :bar would be provided from the default.

Static and dynamic parameters can also be made optional by wrapping them in square brackets []. For example

    plugin.map 'myplugin :foo [is] :bar'

will match both 'myplugin something is somethingelse' and 'myplugin something somethingelse'.

Components can be validated before being allowed to match, for example if you need a component to be a number:

    plugin.map 'myplugin :param', :requirements => {:param => /^\d+$/}

will only match strings of the form 'myplugin 1234' or some other number.

Templates can be set not to match public or private messages using the :public or :private boolean options.

Summary of recognized options:

action | method to call when the template is matched
auth_path | TODO document
requirements | a Hash whose keys are names of dynamic parameters and whose values are regular expressions that the parameters must match
defaults | a Hash whose keys are names of dynamic parameters and whose values are the values to be assigned to those parameters when they are missing from the message. Any dynamic parameter appearing in the :defaults Hash is therefore optional
public | a boolean (defaults to true) that determines whether the template should match public (in channel) messages.
private | a boolean (defaults to true) that determines whether the template should match private (not in channel) messages.
threaded | a boolean (defaults to false) that determines whether the action should be called in a separate thread.

Further examples:

    # match 'karmastats' and call my stats() method
    plugin.map 'karmastats', :action => 'stats'
    # match 'karma' with an optional 'key' and call my karma() method
    plugin.map 'karma :key', :defaults => {:key => false}
    # match 'karma for something' and call my karma() method
    plugin.map 'karma for :key'

    # two matches, one for public messages in a channel, one for
    # private messages which therefore require a channel argument
    plugin.map 'urls search :channel :limit :string',
              :action => 'search',
              :defaults => {:limit => 4},
              :requirements => {:limit => /^\d+$/},
              :public => false
    plugin.map 'urls search :limit :string',
              :action => 'search',
              :defaults => {:limit => 4},
              :requirements => {:limit => /^\d+$/},
              :private => false

    # File lib/rbot/messagemapper.rb, line 222
    def map(botmodule, *args)
      @templates << MessageTemplate.new(botmodule, *args)
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.