client.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. # WhatsApp API returns code 100 for various input errors
  33. # Such as too long body or too large attachment
  34. original_error.code != 100
  35. end
  36. end
  37. protected
  38. def with_tmpfile(prefix:, &)
  39. Tempfile.create(prefix, &)
  40. end
  41. end