client.rb 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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_052, # Media download error'
  39. 131_053 # Media upload error'
  40. ]
  41. recoverable_errors.include?(original_error.code)
  42. end
  43. end
  44. protected
  45. def with_tmpfile(prefix:, &)
  46. Tempfile.create(prefix, &)
  47. end
  48. end