Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to respond to text in attachments #177 #180

Merged
merged 6 commits into from
Mar 9, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions .rubocop_todo.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2017-12-22 16:54:31 -0500 using RuboCop version 0.51.0.
# on 2018-03-06 16:06:41 +0100 using RuboCop version 0.51.0.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
Expand Down Expand Up @@ -29,21 +29,21 @@ Lint/HandleExceptions:
Metrics/AbcSize:
Max: 40

# Offense count: 26
# Offense count: 30
# Configuration parameters: CountComments, ExcludedMethods.
Metrics/BlockLength:
Max: 131

# Offense count: 1
# Configuration parameters: CountComments.
Metrics/ClassLength:
Max: 104
Max: 131

# Offense count: 2
Metrics/CyclomaticComplexity:
Max: 13
Max: 16

# Offense count: 219
# Offense count: 248
# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
# URISchemes: http, https
Metrics/LineLength:
Expand All @@ -52,11 +52,11 @@ Metrics/LineLength:
# Offense count: 11
# Configuration parameters: CountComments.
Metrics/MethodLength:
Max: 19
Max: 27

# Offense count: 2
Metrics/PerceivedComplexity:
Max: 13
Max: 14

# Offense count: 1
# Configuration parameters: ExpectMatchingDefinition, Regex, IgnoreExecutableScripts, AllowedAcronyms.
Expand All @@ -79,7 +79,7 @@ Performance/HashEachMethods:
Exclude:
- 'lib/slack-ruby-bot/hooks/set.rb'

# Offense count: 31
# Offense count: 32
Style/Documentation:
Enabled: false

Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
### 0.10.6 (Next)

* Your contribution here.
* [#180](https://github.com/slack-ruby/slack-ruby-bot/pull/180): Allow to respond to text in attachments #177 - [@mdudzinski](https://github.com/mdudzinski).
* [#173](https://github.com/slack-ruby/slack-ruby-bot/pull/173): Exposing SlackRubyBot::CommandsHelper.find_command_help_attrs - [@alexagranov](https://github.com/alexagranov).
* [#179](https://github.com/slack-ruby/slack-ruby-bot/pull/179): Allow multiline expression - [@tiagotex](https://github.com/tiagotex).

Expand Down
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,46 @@ end

See [examples/market](examples/market/marketbot.rb) for a working example.

### Matching text in message attachments

You can respond to text in [attachments](https://api.slack.com/docs/message-attachments) with
`attachment`. It will scan `text`, `pretext` and `title` fields in each attachment until a first
match is found.

For example you can match [this example attachment](http://goo.gl/K0cLkH)
by its `title` with the following bot:

```ruby
class Attachment < SlackRubyBot::Bot
attachment 'Slack API Documentation' do |client, data, match|
client.say(channel: data.channel, text: "Matched by #{match.attachment_field}.")
client.say(channel: data.channel, text: "The attachment's text: #{match.attachment.text}.")
end
end
```

You can also define which fields in attachment object should be scanned.

Scan only a single field:

```ruby
class Attachment < SlackRubyBot::Bot
attachment 'Slack API Documentation', :title do |client, data, match|
# implementation details
end
end
```

Scan multiple fields:

```ruby
class Attachment < SlackRubyBot::Bot
attachment 'Slack API Documentation', %i[text pretext author_name] do |client, data, match|
# implementation details
end
end
```

### Providing description for your bot and commands

You can specify help information for bot or commands with `help` block, for example:
Expand Down
44 changes: 38 additions & 6 deletions lib/slack-ruby-bot/commands/base.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
require_relative 'help/match.rb'

module SlackRubyBot
module Commands
class Base
include Loggable
class_attribute :routes

class << self
attr_accessor :command_classes
Expand Down Expand Up @@ -52,18 +53,26 @@ def command(*values, &block)
def invoke(client, data)
finalize_routes!
expression, text = parse(client, data)
return false unless expression
return false unless expression || data.attachments
routes.each_pair do |route, options|
match_method = options[:match_method]
case match_method
when :match
next unless expression
match = route.match(expression)
match ||= route.match(text) if text
next unless match
next if match.names.include?('bot') && !client.name?(match['bot'])
match = Help::Match.new(match)
when :scan
next unless expression
match = expression.scan(route)
next unless match.any?
when :attachment
next unless data.attachments && !data.attachments.empty?
match, attachment, field = match_attachments(data, route, options[:fields_to_scan])
next unless match
match = Help::Match.new(match, attachment, field)
end
call_command(client, data, match, options[:block])
return true
Expand All @@ -72,19 +81,30 @@ def invoke(client, data)
end

def match(match, &block)
self.routes ||= ActiveSupport::OrderedHash.new
self.routes[match] = { match_method: :match, block: block }
routes[match] = { match_method: :match, block: block }
end

def scan(match, &block)
self.routes ||= ActiveSupport::OrderedHash.new
self.routes[match] = { match_method: :scan, block: block }
routes[match] = { match_method: :scan, block: block }
end

def attachment(match, fields_to_scan = nil, &block)
fields_to_scan = [fields_to_scan] unless fields_to_scan.nil? || fields_to_scan.is_a?(Array)
routes[match] = {
match_method: :attachment,
block: block,
fields_to_scan: fields_to_scan
}
end

def bot_matcher
'(?<bot>\S*)'
end

def routes
@routes ||= ActiveSupport::OrderedHash.new
end

private

def call_command(client, data, match, block)
Expand Down Expand Up @@ -122,6 +142,18 @@ def finalize_routes!
command command_name_from_class
end

def match_attachments(data, route, fields_to_scan = nil)
fields_to_scan ||= %i[pretext text title]
data.attachments.each do |attachment|
fields_to_scan.each do |field|
next unless attachment[field]
match = route.match(attachment[field])
return match, attachment, field if match
end
end
false
end

# Intended to be overridden by subclasses to hook in an
# authorization mechanism.
def permitted?(_client, _data, _match)
Expand Down
22 changes: 22 additions & 0 deletions lib/slack-ruby-bot/commands/help/match.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module SlackRubyBot
module Commands
module Help
class Match
extend Forwardable

delegate MatchData.public_instance_methods(false) => :@match_data

attr_reader :attachment, :attachment_field

def initialize(match_data, attachment = nil, attachment_field = nil)
unless match_data.is_a? MatchData
raise ArgumentError, 'match_data should be a type of MatchData'
end
@match_data = match_data
@attachment = attachment
@attachment_field = attachment_field
end
end
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,19 @@
end

message_command = SlackRubyBot::Hooks::Message.new
channel, user, message = parse(actual)
channel, user, message, attachments = parse(actual)

expect(client).not_to receive(:message)
message_command.call(client, Hashie::Mash.new(text: message, channel: channel, user: user))
message_command.call(client, Hashie::Mash.new(text: message, channel: channel, user: user, attachments: attachments))
true
end

private

def parse(actual)
actual = { message: actual } unless actual.is_a?(Hash)
[actual[:channel] || 'channel', actual[:user] || 'user', actual[:message]]
attachments = actual[:attachments]
attachments = [attachments] unless attachments.nil? || attachments.is_a?(Array)
[actual[:channel] || 'channel', actual[:user] || 'user', actual[:message], attachments]
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
end

message_command = SlackRubyBot::Hooks::Message.new
channel, user, message = parse(actual)
channel, user, message, attachments = parse(actual)

allow(Giphy).to receive(:random) if defined?(Giphy)

begin
expect do
message_command.call(client, Hashie::Mash.new(text: message, channel: channel, user: user))
message_command.call(client, Hashie::Mash.new(text: message, channel: channel, user: user, attachments: attachments))
end.to raise_error error, error_message
rescue RSpec::Expectations::ExpectationNotMetError => e
@error_message = e.message
Expand All @@ -33,6 +33,8 @@

def parse(actual)
actual = { message: actual } unless actual.is_a?(Hash)
[actual[:channel] || 'channel', actual[:user] || 'user', actual[:message]]
attachments = actual[:attachments]
attachments = [attachments] unless attachments.nil? || attachments.is_a?(Array)
[actual[:channel] || 'channel', actual[:user] || 'user', actual[:message], attachments]
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ def client.say(options = {})
end

message_command = SlackRubyBot::Hooks::Message.new
channel, user, message = parse(actual)
channel, user, message, attachments = parse(actual)

allow(Giphy).to receive(:random) if defined?(Giphy)

allow(client).to receive(:message)
message_command.call(client, Hashie::Mash.new(text: message, channel: channel, user: user))
message_command.call(client, Hashie::Mash.new(text: message, channel: channel, user: user, attachments: attachments))
@messages = client.test_messages
expect(client).to have_received(:message).with(hash_including(channel: channel, text: expected)).once
true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ def client.say(options = {})
end

message_command = SlackRubyBot::Hooks::Message.new
channel, user, message = parse(actual)
channel, user, message, attachments = parse(actual)

allow(Giphy).to receive(:random) if defined?(Giphy)

allow(client).to receive(:message)
message_command.call(client, Hashie::Mash.new(text: message, channel: channel, user: user))
message_command.call(client, Hashie::Mash.new(text: message, channel: channel, user: user, attachments: attachments))
@messages = client.test_messages
@responses = []
expected.each do |exp|
Expand Down
4 changes: 3 additions & 1 deletion lib/slack-ruby-bot/rspec/support/spec_helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ module SpecHelpers

def parse(actual)
actual = { message: actual } unless actual.is_a?(Hash)
[actual[:channel] || 'channel', actual[:user] || 'user', actual[:message]]
attachments = actual[:attachments]
attachments = [attachments] unless attachments.nil? || attachments.is_a?(Array)
[actual[:channel] || 'channel', actual[:user] || 'user', actual[:message], attachments]
end
end
end
Loading