grape-slack-bot 2.1.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require "active_support"
2
4
  require "active_support/core_ext/object"
3
5
  require "active_support/security_utils"
@@ -14,6 +16,9 @@ module SlackBot
14
16
  TIMESTAMP_TOLERANCE_SECONDS = 300
15
17
  # Minimum length for Slack signing secret (Slack's requirement)
16
18
  MIN_SIGNING_SECRET_LENGTH = 32
19
+ PAYLOAD_OBJECTS = %w[team user view].freeze
20
+ ROUTE_IDENTIFIERS = %w[callback_id action_id].freeze
21
+ NEW_INTERACTION_TYPES = %w[shortcut message_actions message_action view_closed].freeze
17
22
 
18
23
  def fetch_team_id
19
24
  params.dig("team_id") || params.dig("team", "id")
@@ -23,7 +28,13 @@ module SlackBot
23
28
  params.dig("user_id") || params.dig("user", "id") || params.dig("event", "user")
24
29
  end
25
30
 
31
+ def current_user
32
+ resolve_user_session(fetch_team_id, fetch_user_id)&.user
33
+ end
34
+
26
35
  def verify_slack_signature!
36
+ remove_instance_variable(:@request_body_content) if instance_variable_defined?(:@request_body_content)
37
+
27
38
  slack_signing_secret = ENV["SLACK_SIGNING_SECRET"]
28
39
  timestamp = slack_request_header("x-slack-request-timestamp", "X-Slack-Request-Timestamp")
29
40
  slack_signature = slack_request_header("x-slack-signature", "X-Slack-Signature")
@@ -72,7 +83,7 @@ module SlackBot
72
83
  end
73
84
 
74
85
  def url_verification(params)
75
- SlackBot::DevConsole.log_input "SlackApi::Events#url_verification: #{params.inspect}"
86
+ SlackBot::DevConsole.log_input "Slack URL verification"
76
87
  {challenge: params[:challenge]}
77
88
  end
78
89
 
@@ -95,7 +106,7 @@ module SlackBot
95
106
  end
96
107
 
97
108
  def validate_request_timestamp!(timestamp)
98
- request_timestamp = timestamp.to_i
109
+ request_timestamp = Integer(timestamp, 10)
99
110
  current_timestamp = Time.now.to_i
100
111
  return if (current_timestamp - request_timestamp).abs <= TIMESTAMP_TOLERANCE_SECONDS
101
112
 
@@ -103,33 +114,84 @@ module SlackBot
103
114
  end
104
115
 
105
116
  def verify_signature_match!(slack_signing_secret, timestamp, slack_signature)
106
- return true if ActiveSupport::SecurityUtils.secure_compare(computed_signature(slack_signing_secret, timestamp), slack_signature)
117
+ body = request_body_content
118
+ sig_basestring = "v0:#{timestamp}:#{body}"
119
+ expected_digest_bin = OpenSSL::HMAC.digest("SHA256", slack_signing_secret, sig_basestring)
120
+ actual_hex = slack_signature.delete_prefix("v0=")
121
+ return true if ActiveSupport::SecurityUtils.secure_compare(expected_digest_bin, [actual_hex].pack("H*"))
107
122
 
108
123
  raise SlackBot::Errors::SignatureAuthenticationError.new("Signature mismatch")
109
124
  end
110
125
 
111
- def computed_signature(slack_signing_secret, timestamp)
112
- sig_basestring = "v0:#{timestamp}:#{request_body_content}"
113
- "v0=" + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha256"), slack_signing_secret, sig_basestring)
114
- end
115
-
116
126
  def request_body_content
117
- return "" unless request.body
127
+ return @request_body_content if instance_variable_defined?(:@request_body_content)
128
+
129
+ return @request_body_content = "" unless request.body
118
130
 
119
131
  request.body.rewind if request.body.respond_to?(:rewind)
120
132
  body_content = request.body.read
121
133
  request.body.rewind if request.body.respond_to?(:rewind)
122
- body_content
134
+
135
+ @request_body_content = body_content
123
136
  end
124
137
 
125
138
  def parse_interaction_payload!(raw_payload)
126
- JSON.parse(raw_payload)
127
- rescue JSON::ParserError => e
128
- raise SlackBot::Errors::InvalidPayloadError.new("Invalid JSON payload: #{e.message}")
139
+ payload = JSON.parse(raw_payload) if raw_payload.is_a?(String)
140
+ raise SlackBot::Errors::InvalidPayloadError.new("Invalid JSON payload: expected an object") unless payload.is_a?(Hash)
141
+
142
+ validate_interaction_shape!(payload)
143
+ payload
144
+ rescue JSON::ParserError
145
+ raise SlackBot::Errors::InvalidPayloadError.new("Invalid JSON payload"), cause: nil
146
+ end
147
+
148
+ def validate_interaction_shape!(payload)
149
+ return if PAYLOAD_OBJECTS.all? { |field| payload[field].nil? || payload[field].is_a?(Hash) } &&
150
+ ROUTE_IDENTIFIERS.all? { |field| payload[field].nil? || payload[field].is_a?(String) } &&
151
+ valid_action_list?(payload["actions"])
152
+
153
+ raise SlackBot::Errors::InvalidPayloadError.new("Invalid Slack payload fields")
154
+ end
155
+
156
+ def valid_action_list?(actions)
157
+ actions.nil? || (actions.is_a?(Array) && actions.all? do |action|
158
+ action.is_a?(Hash) && (action["action_id"].nil? || action["action_id"].is_a?(String))
159
+ end)
160
+ end
161
+
162
+ def authorize_interaction_team!(payload)
163
+ team_id = interaction_team_id(payload)
164
+ raise SlackBot::Errors::TeamAuthenticationError.new("Team is not authorized") if team_id.blank?
165
+
166
+ verify_slack_team!(team_id)
167
+ team_id
129
168
  end
130
169
 
131
- def resolve_action_user(payload)
132
- resolve_user_session(payload.dig("user", "team_id"), payload.dig("user", "id"))
170
+ def resolve_action_user(payload, team_id)
171
+ resolve_user_session(team_id, payload.dig("user", "id"))
172
+ end
173
+
174
+ def load_menu_options(options_params, user)
175
+ klass = slack_bot_config.find_menu_options(options_params[:action_id])
176
+ raise SlackBot::Errors::MenuOptionsNotImplemented.new if klass.blank?
177
+
178
+ klass.new(current_user: user, params: options_params, config: slack_bot_config).call
179
+ end
180
+
181
+ def empty_slack_ack!
182
+ api_format :txt
183
+ blank_slack_response!
184
+ end
185
+
186
+ def invoke_slack_handler(handler)
187
+ result = handler.call
188
+ if handler.is_a?(Schema::Responses)
189
+ return empty_slack_ack! if result.blank?
190
+
191
+ status 200
192
+ end
193
+
194
+ result
133
195
  end
134
196
 
135
197
  def blank_slack_response!
@@ -152,6 +214,9 @@ module SlackBot
152
214
  base.content_type :json, "application/json"
153
215
  base.use ActionDispatch::RemoteIp if defined?(ActionDispatch::RemoteIp)
154
216
  base.helpers SlackBot::GrapeHelpers
217
+ base.rescue_from SlackBot::Errors::SignatureAuthenticationError do |e|
218
+ error!({error: e.message}, 401)
219
+ end
155
220
  base.rescue_from SlackBot::Error do |e|
156
221
  error!({error: e.message}, 200)
157
222
  end
@@ -167,15 +232,15 @@ module SlackBot
167
232
  command_klass = command_config&.command_klass
168
233
  raise SlackBot::Errors::SlashCommandNotImplemented.new if command_klass.blank?
169
234
 
170
- args = params[:text].gsub(/^#{command_config.full_token}\s?/, "")
171
- SlackBot::DevConsole.log_input "SlackApi::SlashCommands#post: #{command_config.url_token} | #{command_config.full_token} | #{args}"
235
+ args = params[:text].to_s.sub(/\A#{Regexp.escape(command_config.full_token)}\s?/, "")
236
+ SlackBot::DevConsole.log_input "Slack slash command"
172
237
 
173
238
  action = command_klass.new(current_user: current_user, params: params, args: args, config: slack_bot_config)
174
239
  verify_slack_team! if action.only_slack_team?
175
240
  verify_direct_message_channel! if action.only_direct_message?
176
241
  verify_current_user! if action.only_user?
177
242
 
178
- result = action.call
243
+ result = invoke_slack_handler(action)
179
244
  return blank_slack_response! unless result
180
245
 
181
246
  result
@@ -186,12 +251,13 @@ module SlackBot
186
251
  def self.add_interactions_resource!(base)
187
252
  base.resource :interactions do
188
253
  post do
189
- payload = parse_interaction_payload!(params[:payload])
190
- verify_slack_team!(interaction_team_id(payload))
191
- action_user = resolve_action_user(payload)&.user
254
+ payload = parse_interaction_payload!(request.POST["payload"])
255
+ team_id = authorize_interaction_team!(payload)
256
+ action_user = resolve_action_user(payload, team_id)&.user
192
257
 
193
258
  result = route_interaction(payload: payload, user: action_user, params: params)
194
259
 
260
+ status 200 if GrapeHelpers::NEW_INTERACTION_TYPES.include?(payload["type"])
195
261
  return blank_slack_response! if result.blank? || result == false
196
262
 
197
263
  result
@@ -223,17 +289,24 @@ module SlackBot
223
289
  def self.add_menu_options_resource!(base)
224
290
  base.resource :menu_options do
225
291
  get do
226
- SlackBot::DevConsole.log_input "SlackApi::MenuOptions#get: #{params.inspect}"
292
+ SlackBot::DevConsole.log_input "Slack menu options"
227
293
 
228
294
  verify_slack_team!
229
- menu_options_klass = slack_bot_config.find_menu_options(params[:action_id])
230
- raise SlackBot::Errors::MenuOptionsNotImplemented.new if menu_options_klass.blank?
231
-
232
- menu_options = menu_options_klass.new(current_user: current_user, params: params, config: slack_bot_config).call
295
+ menu_options = load_menu_options(params, current_user)
233
296
  return blank_slack_response! if menu_options.blank?
234
297
 
235
298
  menu_options
236
299
  end
300
+
301
+ post do
302
+ payload = parse_interaction_payload!(request.POST["payload"])
303
+ team_id = authorize_interaction_team!(payload)
304
+ raise SlackBot::Errors::UnknownActionTypeError.new(payload["type"]) unless payload["type"] == "block_suggestion"
305
+
306
+ user = resolve_action_user(payload, team_id)&.user
307
+ status 200
308
+ load_menu_options(payload.with_indifferent_access, user).presence || {options: []}
309
+ end
237
310
  end
238
311
  end
239
312
  end
@@ -8,7 +8,7 @@ module SlackBot
8
8
  return false if event.blank?
9
9
  return false if bot_message_event?(event)
10
10
 
11
- SlackBot::DevConsole.log_input "SlackApi::Events#events_callback: #{params.inspect}"
11
+ SlackBot::DevConsole.log_input "Slack event callback"
12
12
  handler = event_handler_for(params)
13
13
  return false if handler.blank?
14
14
 
@@ -40,14 +40,19 @@ module SlackBot
40
40
 
41
41
  def event_handler_for(params)
42
42
  event_type = params[:event][:type] || params[:event]["type"]
43
- slack_bot_config.find_event_handler(event_type.to_sym)
43
+ slack_bot_config.find_event_handler(event_type) if event_type.is_a?(String) || event_type.is_a?(Symbol)
44
44
  end
45
45
 
46
46
  def run_event_handler(handler, params)
47
47
  current_user = resolve_event_user(params)
48
- return dispatch_event(handler: handler, params: params, current_user: current_user) if slack_bot_config.event_dispatcher_method
49
-
50
- handler.new(params: params, current_user: current_user).call
48
+ if slack_bot_config.event_dispatcher_method
49
+ result = dispatch_event(handler: handler, params: params, current_user: current_user)
50
+ return (handler <= Schema::Event) ? empty_slack_ack! : result
51
+ end
52
+
53
+ arguments = {params: params, current_user: current_user}
54
+ arguments[:config] = slack_bot_config if handler <= Schema::Event
55
+ invoke_slack_handler(handler.new(**arguments))
51
56
  end
52
57
  end
53
58
  end
@@ -1,18 +1,21 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module SlackBot
2
4
  module GrapeHelpers
3
5
  module Interactions
4
6
  def route_interaction(payload:, user:, params:)
5
- case payload["type"]
6
- when "view_submission"
7
- handle_block_actions_view(view: payload["view"], user: user, params: params)
7
+ type = payload["type"]
8
+ case type
9
+ when "view_submission", "view_closed"
10
+ route_view(payload, user, params, type)
8
11
  when "block_actions"
9
- if payload["view"].present?
10
- handle_block_actions_view(view: payload["view"], user: user, params: params)
11
- else
12
- handle_block_actions_message(payload: payload, user: user, params: params)
13
- end
12
+ route_block_actions(payload, user, params)
13
+ when "shortcut"
14
+ run_registered_interaction(type, payload["callback_id"], user, params, payload)
15
+ when "message_actions", "message_action"
16
+ run_registered_interaction("message_action", payload["callback_id"], user, params, payload)
14
17
  else
15
- raise SlackBot::Errors::UnknownActionTypeError.new(payload["type"])
18
+ raise SlackBot::Errors::UnknownActionTypeError.new(type)
16
19
  end
17
20
  end
18
21
 
@@ -23,42 +26,80 @@ module SlackBot
23
26
  interaction_klass = slack_bot_config.find_block_action(action_id)
24
27
  raise SlackBot::Errors::BlockActionNotImplemented.new if interaction_klass.blank?
25
28
 
26
- interaction_klass.new(current_user: user, params: params, config: slack_bot_config).call
29
+ handler = interaction_klass.new(current_user: user, params: params, config: slack_bot_config)
30
+ invoke_interaction(handler, payload)
27
31
  end
28
32
 
29
33
  def validate_callback_user!(callback, user)
30
- if callback.user_id != user.id
34
+ if user.nil? || callback.user_id != user.id
31
35
  raise SlackBot::Errors::CallbackUserMismatchError.new("Callback user is not equal to action user")
32
36
  end
33
37
  end
34
38
 
35
- def handle_block_actions_view(view:, user:, params:)
36
- callback = find_callback!(view: view, user: user)
37
- log_callback_check(callback, user)
38
- validate_callback_user!(callback, user)
39
+ def handle_block_actions_view(view:, user:, params:, type: "block_actions", payload: nil)
40
+ callback_id = view&.dig("callback_id")
41
+ callback = find_view_callback(view, user, type)
42
+ if callback.nil?
43
+ return run_registered_interaction(type, callback_id, user, params, payload) if type == "view_closed"
44
+
45
+ raise SlackBot::Errors::CallbackNotFound
46
+ end
39
47
 
40
- interaction_klass = callback_interaction_klass(callback)
48
+ validate_callback_user!(callback, user)
49
+ interaction_klass = callback_interaction_klass(callback, type)
41
50
  return false if interaction_klass.blank?
42
51
 
43
- interaction_klass.new(current_user: user, params: params, callback: callback, config: slack_bot_config).call
52
+ handler = interaction_klass.new(current_user: user, params: params, callback: callback, config: slack_bot_config)
53
+ invoke_interaction(handler, payload)
44
54
  end
45
55
 
46
56
  private
47
57
 
48
- def find_callback!(view:, user:)
49
- callback = SlackBot::Callback.find(view&.dig("callback_id"), user: user, config: slack_bot_config)
50
- raise SlackBot::Errors::CallbackNotFound.new if callback.blank?
58
+ def find_view_callback(view, user, type)
59
+ return if user.nil?
60
+ return if type == "view_closed" && slack_bot_config.callback_storage_instance.nil?
61
+
62
+ callback_id = view&.dig("callback_id")
63
+ if callback_id.present?
64
+ SlackBot::Callback.find(callback_id, user: user, config: slack_bot_config)
65
+ elsif view&.dig("id").present?
66
+ SlackBot::Callback.find_by_view_id(view["id"], user: user, config: slack_bot_config)
67
+ end
68
+ end
69
+
70
+ def route_block_actions(payload, user, params)
71
+ view = payload["view"]
72
+ if view.blank? || (view["type"] == "home" && view["callback_id"].blank?)
73
+ handle_block_actions_message(payload: payload, user: user, params: params)
74
+ else
75
+ route_view(payload, user, params, "block_actions")
76
+ end
77
+ end
78
+
79
+ def route_view(payload, user, params, type)
80
+ handle_block_actions_view(view: payload["view"], user: user, params: params, type: type, payload: payload)
81
+ end
82
+
83
+ def run_registered_interaction(type, callback_id, user, params, payload)
84
+ klass = slack_bot_config.find_interaction_callback(type, callback_id)
85
+ return empty_slack_ack! unless klass
51
86
 
52
- callback
87
+ handler = klass.new(current_user: user, params: params, config: slack_bot_config)
88
+ invoke_interaction(handler, payload).presence || empty_slack_ack!
53
89
  end
54
90
 
55
- def log_callback_check(callback, user)
56
- SlackBot::DevConsole.log_check "SlackApi::Interactions##{__method__}: #{callback.id} #{callback.payload} #{callback.user_id} #{user&.id}"
91
+ def invoke_interaction(handler, payload)
92
+ handler.payload = payload if payload && handler.is_a?(SlackBot::Interaction)
93
+ invoke_slack_handler(handler)
57
94
  end
58
95
 
59
- def callback_interaction_klass(callback)
60
- handler_class_obj = callback.handler_class
61
- handler_class_obj&.interaction_klass if handler_class_obj&.respond_to?(:interaction_klass)
96
+ def callback_interaction_klass(callback, type)
97
+ owner = callback.handler_class
98
+ if owner.respond_to?(:interaction_handlers)
99
+ owner.interaction_handlers[type]
100
+ elsif type != "view_closed" && owner.respond_to?(:interaction_klass)
101
+ owner.interaction_klass
102
+ end
62
103
  end
63
104
  end
64
105
  end
@@ -23,9 +23,15 @@ module SlackBot
23
23
  build_view_reply(response: response, callback: callback, payload: view, error_class: SlackBot::Errors::OpenModalError)
24
24
  end
25
25
 
26
- def self.update_modal(callback:, view_id:, view:)
26
+ def self.push_modal(callback:, trigger_id:, view:)
27
27
  view = modal_payload(callback, view)
28
- response = api_client.views_update(view_id: view_id, view: view)
28
+ response = api_client.views_push(trigger_id: trigger_id, view: view)
29
+ build_view_reply(response: response, callback: callback, payload: view, error_class: SlackBot::Errors::PushModalError)
30
+ end
31
+
32
+ def self.update_modal(callback:, view_id:, view:, **options)
33
+ view = modal_payload(callback, view)
34
+ response = api_client.views_update(view_id: view_id, view: view, **options)
29
35
  build_view_reply(response: response, callback: callback, payload: view, error_class: SlackBot::Errors::UpdateModalError)
30
36
  end
31
37
 
@@ -35,6 +41,7 @@ module SlackBot
35
41
  end
36
42
 
37
43
  attr_reader :current_user, :params, :callback, :config
44
+ attr_writer :payload
38
45
  def initialize(current_user: nil, params: nil, callback: nil, config: nil)
39
46
  @current_user = current_user
40
47
  @params = params
@@ -47,7 +54,8 @@ module SlackBot
47
54
  end
48
55
 
49
56
  def self.modal_payload(callback, view)
50
- view.merge(type: "modal", callback_id: callback&.id)
57
+ modal = view.except("type").merge(type: "modal")
58
+ callback ? modal.except("callback_id").merge(callback_id: callback.id) : modal
51
59
  end
52
60
 
53
61
  def self.publish_payload(callback, metadata, view)
@@ -0,0 +1,43 @@
1
+ require "uri"
2
+
3
+ module SlackBot
4
+ module ResponseUrl
5
+ HOSTS = %w[hooks.slack.com hooks.slack-gov.com].freeze
6
+ PATH = %r{\A/(?:actions|services|app(?:-actions)?)/[a-zA-Z0-9_/-]+\z}
7
+
8
+ Reply = Struct.new(:status) do
9
+ def ok?
10
+ (200...300).cover?(status)
11
+ end
12
+ end
13
+
14
+ module_function
15
+
16
+ def post(url, message)
17
+ destination = validate(url)
18
+ response = client.post(destination, JSON.generate(message))
19
+ Reply.new(response.status)
20
+ rescue Faraday::Error
21
+ raise Errors::SlackApiError.new("Slack response URL request failed"), cause: nil
22
+ end
23
+
24
+ def validate(url)
25
+ uri = URI.parse(url) if url.is_a?(String)
26
+ return uri if uri.is_a?(URI::HTTPS) && valid_destination?(uri)
27
+
28
+ raise Errors::SlackApiError.new("Invalid Slack response URL")
29
+ rescue URI::InvalidURIError
30
+ raise Errors::SlackApiError.new("Invalid Slack response URL"), cause: nil
31
+ end
32
+
33
+ def valid_destination?(uri)
34
+ HOSTS.include?(uri.host) && uri.port == 443 && PATH.match?(uri.path) &&
35
+ uri.userinfo.nil? && uri.query.nil? && uri.fragment.nil?
36
+ end
37
+
38
+ def client
39
+ Faraday.new(headers: {"Content-Type" => "application/json; charset=utf-8"},
40
+ request: {timeout: 2, open_timeout: 1})
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SlackBot
4
+ class Schema
5
+ class BlockActions < Interaction
6
+ class_attribute :action_handlers, instance_accessor: false, default: {}.freeze
7
+
8
+ def self.action(action_id, args: {}, with: action_id.to_sym)
9
+ self.action_handlers = action_handlers.merge(action_id.to_s => [with, args.dup.freeze].freeze).freeze
10
+ end
11
+
12
+ def resolve
13
+ handlers = self.class.action_handlers
14
+ return if handlers.empty?
15
+
16
+ matched = false
17
+ actions&.each do |action|
18
+ destination, extractors = handlers[action["action_id"]]
19
+ next unless destination
20
+
21
+ matched = true
22
+ result = run_action(destination, extractors, action)
23
+ return result if result == :halt || result.is_a?(Hash)
24
+ end
25
+ :halt unless matched
26
+ end
27
+
28
+ private
29
+
30
+ def run_action(destination, extractors, action)
31
+ arguments = extractors.transform_values { |source| extract_argument(source, action) }
32
+ if destination.is_a?(Class)
33
+ destination.new(**arguments).call
34
+ else
35
+ send(destination, **arguments)
36
+ end
37
+ end
38
+
39
+ def extract_argument(source, action)
40
+ case source
41
+ when :selected_option_value then action.dig("selected_option", "value")
42
+ when :selected_option_values then action["selected_options"]&.map { |option| option["value"] }
43
+ else source.respond_to?(:call) ? source.call(action) : action[source.to_s]
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,57 @@
1
+ module SlackBot
2
+ class Schema
3
+ class SlashCommand < SlackBot::Command
4
+ include Responses
5
+ include ViewOwner
6
+ include SlackResponses
7
+
8
+ class_attribute :input_class, instance_accessor: false
9
+
10
+ def self.input(klass)
11
+ self.input_class = klass
12
+ end
13
+
14
+ private
15
+
16
+ def resolve_request
17
+ input = self.class.input_class
18
+ input ? resolve(**input.coerce(args)) : super
19
+ end
20
+ end
21
+
22
+ class Event < SlackBot::Event
23
+ include Responses
24
+ include ViewOwner
25
+ include SlackResponses
26
+ end
27
+
28
+ class Interaction < SlackBot::Interaction
29
+ include Responses
30
+ include ViewOwner
31
+ include SlackResponses
32
+
33
+ private
34
+
35
+ def interaction_payload
36
+ payload
37
+ end
38
+ end
39
+
40
+ class ViewClosed < Interaction
41
+ end
42
+
43
+ class Shortcut < Interaction
44
+ end
45
+
46
+ class MessageAction < Interaction
47
+ end
48
+
49
+ class Options < SlackBot::MenuOptions
50
+ include Responses
51
+
52
+ def value
53
+ params[:value]
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,35 @@
1
+ module SlackBot
2
+ class Schema
3
+ class InputObject
4
+ COERCERS = {
5
+ String => ->(value) { String(value) },
6
+ Integer => ->(value) { Integer(value, 10) },
7
+ Float => ->(value) { Float(value) }
8
+ }.freeze
9
+
10
+ class_attribute :arguments, instance_accessor: false, default: {}.freeze
11
+
12
+ def self.argument(name, type = String, required: false, default: nil)
13
+ self.arguments = arguments.merge(name.to_sym => [type, required, default].freeze).freeze
14
+ end
15
+
16
+ def self.coerce(args)
17
+ arguments.each_with_object({}) do |(name, (type, required, default)), values|
18
+ raw = args[name]
19
+ value = raw.nil? ? default : coerce_argument(raw, type, name)
20
+ raise Errors::InvalidPayloadError.new("Missing argument #{name}") if required && value.nil?
21
+
22
+ values[name] = value
23
+ end
24
+ end
25
+
26
+ def self.coerce_argument(value, type, name)
27
+ COERCERS.fetch(type, type).call(value)
28
+ rescue ArgumentError, TypeError, RangeError
29
+ raise Errors::InvalidPayloadError.new("Invalid argument #{name}"), cause: nil
30
+ end
31
+
32
+ private_class_method :coerce_argument
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,34 @@
1
+ module SlackBot
2
+ class Schema
3
+ class Registrar
4
+ def initialize(config)
5
+ @config = config
6
+ end
7
+
8
+ def register(schema)
9
+ schema.registrations.each do |(route, _key), arguments|
10
+ case route
11
+ when :slash_command
12
+ register_slash(*arguments)
13
+ when :block_actions
14
+ @config.block_action(*arguments)
15
+ else
16
+ @config.public_send(route, *arguments)
17
+ end
18
+ end
19
+ @config
20
+ end
21
+
22
+ private
23
+
24
+ def register_slash(url_token, handler)
25
+ if handler <= SlashCommandGroup
26
+ endpoint = @config.slash_command_endpoint(url_token, handler.default_handler)
27
+ handler.commands.each { |token, command| endpoint.command(token, command) }
28
+ else
29
+ @config.slash_command_endpoint(url_token, handler)
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end