jgorset / facebook-messenger

Definitely the best way to make Bots on Facebook Messenger with Ruby
MIT License
962 stars 211 forks source link

feat: expose response and API usage headers #275

Open BroHandTW opened 2 years ago

BroHandTW commented 2 years ago

according to rate limit doc https://developers.facebook.com/docs/graph-api/overview/rate-limiting, we can get app usage or Business Use Case(buc) usage from API request.

so i add two features here -

  1. make deliver method can get request headers

    response = Facebook::Messenger::Bot.deliver(message_obj, ... , return_response: true)
    response.body 
    # => "{\"recipient_id\":\"...\",\"message_id\":\"...\"}"
    response.headers['x-business-use-case-usage']
    # => "{\"YOUR_PAGE_ID\":[{\"type\":\"messenger\",\"call_count\":1,\"total_cputime\":1,\"total_time\":1,\"estimated_time_to_regain_access\":0}]}"
  2. ensure exception object can get usage headers

    
    # case 1
    begin
    response = Facebook::Messenger::Bot.deliver({}, ...)
    # <Facebook::Messenger::Bot::BadParameterError: (#100) The parameter recipient is required (subcode: )>
    rescue Facebook::Messenger::FacebookError => e
    e.code
    # => 100
    e.buc_usage
    # => nil
    e.app_usage
    # => "{\"call_count\":0,\"total_cputime\":0,\"total_time\":0}"
    end

case 2

begin response = Facebook::Messenger::Bot.deliver(message_obj, ... )

(#613) Calls to this api have exceeded the rate limit

rescue Facebook::Messenger::LimitError => e e.code

=> 613

e.buc_usage

=> {\"YOUR_PAGE_ID\":[{\"type\":\"pages\",\"call_count\":107,\"total_cputime\":1,\"total_time\":125,\"estimated_time_to_regain_access\":1406}]}

NOTE: estimated_time_to_regain_access -> Time, in minutes, until calls will not longer be throttled.



and this PR should resolve this issue https://github.com/jgorset/facebook-messenger/issues/127