Class: SlackBot::ApiResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/slack_bot/api_client.rb,
sig/slack_bot.rbs

Constant Summary collapse

RATE_LIMIT_RETRY_SLEEP_SECONDS =

Cap in-request sleep so rate-limit retries do not hold web workers for Slack's default Retry-After.

3

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize { ... } ⇒ ApiResponse

Returns a new instance of ApiResponse.

Yields:

Yield Returns:

  • (Faraday::Response)


22
23
24
25
# File 'lib/slack_bot/api_client.rb', line 22

def initialize(&block)
  @response = block.call
  SlackBot::DevConsole.log_output "#{self.class.name}: #{response.body}"
end

Instance Attribute Details

#responseFaraday::Response (readonly)

Returns the value of attribute response.

Returns:

  • (Faraday::Response)


8
9
10
# File 'lib/slack_bot/api_client.rb', line 8

def response
  @response
end

Class Method Details

.from_request { ... } ⇒ ApiResponse

Yields:

Yield Returns:

  • (Faraday::Response)

Returns:



10
11
12
13
14
15
16
# File 'lib/slack_bot/api_client.rb', line 10

def self.from_request(&block)
  response = new(&block)
  return response unless response.rate_limited?

  Kernel.sleep(rate_limit_retry_sleep_seconds(response.retry_after))
  new(&block)
end

.rate_limit_retry_sleep_seconds(retry_after) ⇒ Object



18
19
20
# File 'lib/slack_bot/api_client.rb', line 18

def self.rate_limit_retry_sleep_seconds(retry_after)
  [retry_after.to_i, RATE_LIMIT_RETRY_SLEEP_SECONDS].min
end

Instance Method Details

#authentication_error?Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/slack_bot/api_client.rb', line 47

def authentication_error?
  slack_error? && %w[invalid_auth account_inactive].include?(error)
end

#dataHash[String, untyped]

Returns:

  • (Hash[String, untyped])


51
52
53
54
55
56
# File 'lib/slack_bot/api_client.rb', line 51

def data
  JSON.parse(response.body)
rescue JSON::ParserError => e
  SlackBot::Logger.error("Failed to parse Slack API response: #{e.message}")
  {"ok" => false, "error" => "invalid_json_response"}
end

#errorString?

Returns:

  • (String, nil)


31
32
33
# File 'lib/slack_bot/api_client.rb', line 31

def error
  data["error"]
end

#ok?Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/slack_bot/api_client.rb', line 27

def ok?
  response.status == 200 && data["ok"]
end

#rate_limited?Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/slack_bot/api_client.rb', line 35

def rate_limited?
  response.status == 429 || (data["ok"] == false && data["error"] == "rate_limited")
end

#retry_afterInteger

Returns:

  • (Integer)


39
40
41
# File 'lib/slack_bot/api_client.rb', line 39

def retry_after
  response.headers["Retry-After"]&.to_i || 60
end

#slack_error?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/slack_bot/api_client.rb', line 43

def slack_error?
  !ok? && error.present?
end