client.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. require 'whatsapp_sdk'
  3. class Whatsapp::Client
  4. attr_reader :access_token, :client
  5. def initialize(access_token:)
  6. @access_token = access_token
  7. raise ArgumentError, __("The required parameter 'access_token' is missing.") if access_token.nil?
  8. @client = WhatsappSdk::Api::Client.new access_token
  9. end
  10. def log_request(response: nil)
  11. return if response.empty?
  12. Rails.logger.error "WhatsApp Client: remote response: #{response}"
  13. end
  14. def handle_error(response:)
  15. return if !response.error
  16. log_request response: response.raw_response
  17. message = response.error.message
  18. if response.error.respond_to?(:raw_data_response) &&
  19. (details = response.error.raw_data_response&.dig('error_data', 'details'))
  20. message = "#{message}: #{details}"
  21. end
  22. raise CloudAPIError.new(message, response.error)
  23. end
  24. class CloudAPIError < StandardError
  25. attr_reader :original_error
  26. def initialize(message, original_error)
  27. super(message)
  28. @original_error = original_error
  29. end
  30. def retryable?
  31. return true if !original_error
  32. # https://developers.facebook.com/docs/graph-api/guides/error-handling
  33. recoverable_errors = [
  34. 130_472, # User's number is part of an experiment
  35. 131_021, # Recipient cannot be sender
  36. 131_026, # Message undeliverable
  37. 131_047, # Re-engagement message
  38. 131_051, # Unsupported message type
  39. 131_052, # Media download error
  40. 131_053, # Media upload error
  41. ]
  42. recoverable_errors.include?(original_error.code)
  43. end
  44. end
  45. protected
  46. def with_tmpfile(prefix:, &)
  47. Tempfile.create(prefix, &)
  48. end
  49. end