Skip to content

Commit

Permalink
feat: Handle Instagram send message/attachments errors (#8174)
Browse files Browse the repository at this point in the history
Co-authored-by: Pranav Raj S <pranav@chatwoot.com>
  • Loading branch information
muhsin-k and pranavrajs committed Oct 25, 2023
1 parent 4a89bab commit 4fc62ed
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
18 changes: 16 additions & 2 deletions app/services/instagram/send_on_instagram_service.rb
Expand Up @@ -66,12 +66,26 @@ def send_to_facebook_page(message_content)
query: query
)

Rails.logger.error("Instagram response: #{response['error']} : #{message_content}") if response['error']
message.update!(source_id: response['message_id']) if response['message_id'].present?
if response[:error].present?
Rails.logger.error("Instagram response: #{response['error']} : #{message_content}")
message.status = :failed
message.external_error = external_error(response)
end

message.source_id = response['message_id'] if response['message_id'].present?
message.save!

response
end

def external_error(response)
# https://developers.facebook.com/docs/instagram-api/reference/error-codes/
error_message = response[:error][:message]
error_code = response[:error][:code]

"#{error_code} - #{error_message}"
end

def calculate_app_secret_proof(app_secret, access_token)
Facebook::Messenger::Configuration::AppSecretProofCalculator.call(
app_secret, access_token
Expand Down
19 changes: 19 additions & 0 deletions spec/services/instagram/send_on_instagram_service_spec.rb
Expand Up @@ -62,6 +62,25 @@

expect(response).to eq({ message_id: 'anyrandommessageid1234567890' })
end

it 'if message sent from chatwoot is failed' do
message = create(:message, message_type: 'outgoing', inbox: instagram_inbox, account: account, conversation: conversation)

allow(HTTParty).to receive(:post).and_return(
{
'error': {
'message': 'The Instagram account is restricted.',
'type': 'OAuthException',
'code': 400,
'fbtrace_id': 'anyrandomfbtraceid1234567890'
}
}
)
described_class.new(message: message).perform
expect(HTTParty).to have_received(:post)
expect(message.reload.status).to eq('failed')
expect(message.reload.external_error).to eq('400 - The Instagram account is restricted.')
end
end

context 'with message_tag HUMAN_AGENT' do
Expand Down

0 comments on commit 4fc62ed

Please sign in to comment.