Files
leadchat/app/services/facebook/send_on_facebook_service.rb
2023-03-09 16:28:45 +05:30

79 lines
2.3 KiB
Ruby

class Facebook::SendOnFacebookService < Base::SendOnChannelService
private
def channel_class
Channel::FacebookPage
end
def perform_reply
send_message_to_facebook fb_text_message_params if message.content.present?
send_message_to_facebook fb_attachment_message_params if message.attachments.present?
rescue Facebook::Messenger::FacebookError => e
# TODO : handle specific errors or else page will get disconnected
handle_facebook_error(e)
end
def send_message_to_facebook(delivery_params)
result = Facebook::Messenger::Bot.deliver(delivery_params, page_id: channel.page_id)
message.update!(source_id: JSON.parse(result)['message_id'])
end
def fb_text_message_params
{
recipient: { id: contact.get_source_id(inbox.id) },
message: { text: message.content },
messaging_type: 'MESSAGE_TAG',
tag: 'ACCOUNT_UPDATE'
}
end
def fb_attachment_message_params
attachment = message.attachments.first
{
recipient: { id: contact.get_source_id(inbox.id) },
message: {
attachment: {
type: attachment_type(attachment),
payload: {
url: attachment.download_url
}
}
},
messaging_type: 'MESSAGE_TAG',
tag: 'ACCOUNT_UPDATE'
}
end
def attachment_type(attachment)
return attachment.file_type if %w[image audio video file].include? attachment.file_type
'file'
end
def fb_message_params
if message.attachments.blank?
fb_text_message_params
else
fb_attachment_message_params
end
end
def sent_first_outgoing_message_after_24_hours?
# we can send max 1 message after 24 hour window
conversation.messages.outgoing.where('id > ?', last_incoming_message.id).count == 1
end
def last_incoming_message
conversation.messages.incoming.last
end
def handle_facebook_error(exception)
# Refer: https://github.com/jgorset/facebook-messenger/blob/64fe1f5cef4c1e3fca295b205037f64dfebdbcab/lib/facebook/messenger/error.rb
if exception.to_s.include?('The session has been invalidated') || exception.to_s.include?('Error validating access token')
channel.authorization_error!
else
ChatwootExceptionTracker.new(exception, account: message.account, user: message.sender).capture_exception
end
end
end