Class: BirdGrinder::CommandHandler
- Defined in:
- lib/bird_grinder/command_handler.rb
Overview
A simple, method to command mapping for handlers. E.g.
class X < BirdGrinder::CommandHandler
exposes :hello
def hello(name)
reply "Why hello there yourself!"
end
end
When registerted, X will look for tweets that are of the form “@bot-name hello” or direct mentions with “hello” at the start (or if command_prefix is set to, for example, !, “!hello”) and reply.
Used for implementing the most common cases of bots that respond to commands.
Instance Attribute Summary
Attributes inherited from Base
Class Method Summary collapse
-
.exposes(*args) ⇒ Object
Marks a set of method names as being available.
-
.prefix_regexp ⇒ Regexp
Gets a regexp for easy matching.
Instance Method Summary collapse
-
#check_for_commands ⇒ Object
Checks in incoming mentions and direct messages for those that correctly match the format.
-
#extract_command_name(command) ⇒ Symbol
Given a prefix, e.g.
Methods inherited from Base
#dm, event_handlers_for, #handle, on_event, register!, #reply, #tweet
Class Method Details
.exposes(*args) ⇒ Object
Marks a set of method names as being available
29 30 31 |
# File 'lib/bird_grinder/command_handler.rb', line 29 def exposes(*args) args.each { |name| exposed_methods << name.to_sym } end |
.prefix_regexp ⇒ Regexp
Gets a regexp for easy matching
36 37 38 |
# File 'lib/bird_grinder/command_handler.rb', line 36 def prefix_regexp /^#{command_prefix}/ end |
Instance Method Details
#check_for_commands ⇒ Object
Checks in incoming mentions and direct messages for those that correctly match the format. If it’s found, it will call the given method with the result of the message, minus the command, as an argument.
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/bird_grinder/command_handler.rb', line 50 def check_for_commands data, command = nil, nil if ! logger.debug "Checking for command in mention" = .text.split(" ", 3) name, command, data = if name.downcase != "@#{BirdGrinder::Settings.username}".downcase logger.debug "Command is a mention but doesn't start with the username" return end else logger.debug "Checking for command in direct message" command, data = .text.split(/\s+/, 2) end if (command_name = extract_command_name(command)).present? logger.info "Processing command '#{command_name}' for #{user}" send(command_name, data.to_s) if respond_to?(command_name) end end |
#extract_command_name(command) ⇒ Symbol
Given a prefix, e.g. “!awesome”, will return the associated method name iff it is exposed.
75 76 77 78 79 80 81 |
# File 'lib/bird_grinder/command_handler.rb', line 75 def extract_command_name(command) re = self.class.prefix_regexp if command =~ re method_name = command.gsub(re, "").underscore.to_sym return method_name if exposed_methods.include?(method_name) end end |