From a356c824d0d9a45cd3ed72d0250cf639b0ed6293 Mon Sep 17 00:00:00 2001 From: Tejaswini Chile Date: Thu, 22 Dec 2022 18:43:49 +0530 Subject: [PATCH] fix: whatsapp cloud to consider multiple attachments --- .../providers/whatsapp_cloud_service.rb | 40 ++++++++++--------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/app/services/whatsapp/providers/whatsapp_cloud_service.rb b/app/services/whatsapp/providers/whatsapp_cloud_service.rb index a0c591783..5ba16d690 100644 --- a/app/services/whatsapp/providers/whatsapp_cloud_service.rb +++ b/app/services/whatsapp/providers/whatsapp_cloud_service.rb @@ -1,4 +1,7 @@ class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseService + ATTACHMENT_TYPE = [image, audio, video].freeze + MESSAGE_CONTENT = [audio, sticker].freeze + def send_message(phone_number, message) if message.attachments.present? send_attachment_message(phone_number, message) @@ -67,25 +70,26 @@ class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseServi end def send_attachment_message(phone_number, message) - attachment = message.attachments.first - type = %w[image audio video].include?(attachment.file_type) ? attachment.file_type : 'document' - type_content = { - 'link': attachment.download_url - } - type_content['caption'] = message.content unless %w[audio sticker].include?(type) - type_content['filename'] = attachment.file.filename if type == 'document' - response = HTTParty.post( - "#{phone_id_path}/messages", - headers: api_headers, - body: { - messaging_product: 'whatsapp', - 'to' => phone_number, - 'type' => type, - type.to_s => type_content - }.to_json - ) + message.attachments.each do |attachment| + type = ATTACHMENT_TYPE.include?(attachment.file_type) ? attachment.file_type : 'document' + type_content = { + 'link': attachment.download_url + } + type_content['caption'] = message.content unless MESSAGE_CONTENT.include?(type) + type_content['filename'] = attachment.file.filename if type == 'document' + response = HTTParty.post( + "#{phone_id_path}/messages", + headers: api_headers, + body: { + messaging_product: 'whatsapp', + 'to' => phone_number, + 'type' => type, + type.to_s => type_content + }.to_json + ) - process_response(response) + process_response(response) + end end def process_response(response)