|
|
@@ -0,0 +1,158 @@
|
|
|
+from odoo import models, fields, api
|
|
|
+from odoo.tools import groupby
|
|
|
+import logging
|
|
|
+import markupsafe
|
|
|
+import requests
|
|
|
+import json
|
|
|
+import time
|
|
|
+import random
|
|
|
+import re
|
|
|
+import html
|
|
|
+import base64
|
|
|
+
|
|
|
+_logger = logging.getLogger(__name__)
|
|
|
+
|
|
|
+class WhatsAppMessage(models.Model):
|
|
|
+ _inherit = 'whatsapp.message'
|
|
|
+
|
|
|
+
|
|
|
+ def _send_message(self, with_commit=False):
|
|
|
+
|
|
|
+ url = ''
|
|
|
+
|
|
|
+ if self.wa_account_id and self.wa_account_id.whatsapp_web_url:
|
|
|
+ url = self.wa_account_id.whatsapp_web_url
|
|
|
+ _logger.info('WHATSAPP WEB SEND MESSAGE' + url)
|
|
|
+
|
|
|
+ group = ''
|
|
|
+
|
|
|
+ if not url:
|
|
|
+ super()._send_message(with_commit)
|
|
|
+
|
|
|
+ for whatsapp_message in self:
|
|
|
+ #verificacion envio a grupo
|
|
|
+ #plantilla dada de alta en x_plantillas_whatsapp
|
|
|
+ marketing_traces = self.env['marketing.trace'].sudo().search([('whatsapp_message_id', '=', whatsapp_message.id)])
|
|
|
+ for marketing_trace in marketing_traces:
|
|
|
+ if marketing_trace.activity_id.x_studio_grupo_whatsapp:
|
|
|
+ group = marketing_trace.activity_id.x_studio_grupo_whatsapp.x_studio_destinatario
|
|
|
+
|
|
|
+ if not group and False:
|
|
|
+ notificaciones = self.env['x_notificaciones_whats'].sudo().search([('x_studio_plantilla_de_whatsapp', '=', whatsapp_message.wa_template_id.id)])
|
|
|
+ if notificaciones:
|
|
|
+ _logger.info('template encontrado')
|
|
|
+
|
|
|
+ phone_field = whatsapp_message.wa_template_id.phone_field
|
|
|
+ _logger.info(phone_field)
|
|
|
+ phone_field = (phone_field.rpartition('.')[0] + '.id') if '.' in phone_field else phone_field
|
|
|
+ _logger.info(phone_field)
|
|
|
+ partners_ids = record._find_value_from_field_path(phone_field)
|
|
|
+ if partners_ids:
|
|
|
+ partners_ids = list(map(int, partners_ids.split()))
|
|
|
+ for notificacion in notificaciones:
|
|
|
+ if notificacion.x_studio_partner_unico.id in partners_ids:
|
|
|
+ _logger.info('destinatario:' + notificacion.x_studio_destinatario)
|
|
|
+ group = notificacion.x_studio_destinatario
|
|
|
+ break
|
|
|
+ if not group:
|
|
|
+ for notificacion in notificaciones:
|
|
|
+ if not notificacion.x_studio_partner_unico:
|
|
|
+ group = notificacion.x_studio_destinatario
|
|
|
+ break
|
|
|
+
|
|
|
+ attachment = False
|
|
|
+
|
|
|
+ if whatsapp_message.wa_template_id:
|
|
|
+ record = self.env[whatsapp_message.wa_template_id.model].browse(whatsapp_message.mail_message_id.res_id)
|
|
|
+ #codigo con base a whatsapp.message y whatsapp.template para generacion de adjuntos
|
|
|
+ RecordModel = self.env[whatsapp_message.mail_message_id.model].with_user(whatsapp_message.create_uid)
|
|
|
+ from_record = RecordModel.browse(whatsapp_message.mail_message_id.res_id)
|
|
|
+
|
|
|
+ # if retrying message then we need to unlink previous attachment
|
|
|
+ # in case of header with report in order to generate it again
|
|
|
+ if whatsapp_message.wa_template_id.report_id and whatsapp_message.wa_template_id.header_type == 'document' and whatsapp_message.mail_message_id.attachment_ids:
|
|
|
+ whatsapp_message.mail_message_id.attachment_ids.unlink()
|
|
|
+
|
|
|
+ if not attachment and whatsapp_message.wa_template_id.report_id:
|
|
|
+ attachment = whatsapp_message.wa_template_id._generate_attachment_from_report(record)
|
|
|
+ if not attachment and whatsapp_message.wa_template_id.header_attachment_ids:
|
|
|
+ attachment = whatsapp_message.wa_template_id.header_attachment_ids[0]
|
|
|
+
|
|
|
+ if attachment and attachment not in whatsapp_message.mail_message_id.attachment_ids:
|
|
|
+ whatsapp_message.mail_message_id.attachment_ids = [(4, attachment.id)]
|
|
|
+ # no template
|
|
|
+ elif whatsapp_message.mail_message_id.attachment_ids:
|
|
|
+ attachment = whatsapp_message.mail_message_id.attachment_ids[0]
|
|
|
+
|
|
|
+ #codigo para limpiar body y numero
|
|
|
+ body = whatsapp_message.body
|
|
|
+ if isinstance(body, markupsafe.Markup):
|
|
|
+ text = html.unescape(str(body))
|
|
|
+
|
|
|
+ # Reemplazamos las etiquetas BR y P
|
|
|
+ text = re.sub(r'<br\s*/?>|<BR\s*/?>', '\n', text)
|
|
|
+ text = re.sub(r'<p>|<P>', '\n\n', text)
|
|
|
+ text = re.sub(r'</p>|</P>', '', text)
|
|
|
+
|
|
|
+ # Eliminamos el resto de etiquetas HTML
|
|
|
+ text = re.sub(r'<[^>]+>', '', text)
|
|
|
+
|
|
|
+ # Limpiamos múltiples saltos de línea
|
|
|
+ text = re.sub(r'\n\s*\n\s*\n', '\n\n', text)
|
|
|
+
|
|
|
+ # Limpiamos espacios en blanco al inicio y final
|
|
|
+ body = text.strip()
|
|
|
+
|
|
|
+ number = whatsapp_message.mobile_number
|
|
|
+ number = number.replace(' ', '').replace('+','')
|
|
|
+
|
|
|
+ if number.startswith("52") and len(number) == 12:
|
|
|
+ number = "521" + number[2:]
|
|
|
+
|
|
|
+ # ENVIO DE MENSAJE
|
|
|
+ # Headers de la petición, si es necesario
|
|
|
+ headers = {
|
|
|
+ "Content-Type": "application/json"
|
|
|
+ }
|
|
|
+
|
|
|
+ number = group if group else number + '@c.us'
|
|
|
+
|
|
|
+ #$wa::sendMessage("521{$fields_data[$settings['borax_whatsapp_mobile']]}@c.us", ['type' => 'MessageMedia', 'args' => [mime_content_type($file), base64_encode(file_get_contents($file)), $filename, $filesize]], ['caption' => $borax_whatsapp_mensaje]);
|
|
|
+ parent_message_id = ''
|
|
|
+ if whatsapp_message.mail_message_id and whatsapp_message.mail_message_id.parent_id:
|
|
|
+ parent_id = whatsapp_message.mail_message_id.parent_id.wa_message_ids
|
|
|
+ if parent_id:
|
|
|
+ parent_message_id = parent_id[0].msg_uid
|
|
|
+ if attachment:
|
|
|
+ payload = {
|
|
|
+ "method": "sendMessage",
|
|
|
+ "args": [number, {'type': 'MessageMedia', 'args': [attachment.mimetype, base64.b64encode(attachment.raw).decode('utf-8'), attachment.name, attachment.file_size]}, {'caption': body}]
|
|
|
+ }
|
|
|
+ else:
|
|
|
+ payload = {
|
|
|
+ "method": "sendMessage",
|
|
|
+ "args": [number, body, {}]
|
|
|
+ }
|
|
|
+
|
|
|
+ if parent_message_id:
|
|
|
+ payload['args'][2]['quotedMessageId'] = parent_message_id
|
|
|
+
|
|
|
+ # Realizando la petición POST
|
|
|
+ response = requests.post(url, data=json.dumps(payload), headers=headers)
|
|
|
+
|
|
|
+ # Verificando si la respuesta contiene data->id
|
|
|
+ if response.status_code == 200:
|
|
|
+ response_json = response.json()
|
|
|
+ if "_data" in response_json and "id" in response_json["_data"]:
|
|
|
+ _logger.info(f"Petición exitosa. ID: {response_json['_data']['id']['id']}")
|
|
|
+ whatsapp_message.write({
|
|
|
+ 'state': 'sent',
|
|
|
+ 'msg_uid': response_json['_data']['id']['_serialized']
|
|
|
+ })
|
|
|
+ self._cr.commit()
|
|
|
+ else:
|
|
|
+ _logger.info("La respuesta no contiene 'data->id'.")
|
|
|
+ else:
|
|
|
+ _logger.info(f"Error en la petición. Código de estado: {response.status_code}")
|
|
|
+
|
|
|
+ time.sleep(random.randint(3, 7))
|