Update
This commit is contained in:
+103
-104
@@ -1,5 +1,5 @@
|
||||
const defaultMessages = [
|
||||
'😊 ¡Hola! Qué gusto saludarte. Soy xxxxxxxx, asesor de Claro, y es un placer para mí ser la persona que le dé solución a tu solicitud. ¿Me confirmas por favor tu nombre completo, número de cédula y cómo puedo ayudarte hoy🌤️? 📄',
|
||||
'😊 ¡Hola! Qué gusto saludarte. Soy xxxxxxxx, asesor de Claro, y es un placer para mí ser la persona que le dé solución a tu solicitud. ¿Me confirmas por favor tu nombre completo, número de cédula y cómo puedo ayudarte hoy🌤️? 📄',
|
||||
'👋 ¡Hola! Bienvenido(a) al canal de atención de Claro. Mi nombre es xxxxxxxx y con gusto me encargaré de tu solicitud🤩 haré todo lo que esté a mi alcance para encontrar solución a cualquier novedad que estés presentando. Para comenzar, ¿puedes indicarme tu nombre y número de documento? 📝',
|
||||
'🤗 ¡Hola! Gracias por contactarnos. Soy xxxxxxxx, me complace mucho poder ayudarte el día de hoy;🌈🌸 Me comprometo a hacer todo lo que esté en mis manos para encontrar una solución a cualquier percance que tengas hoy. Cuéntame con qué puedo ayudarte, y por favor compárteme tu nombre completo, cédula y el número de la línea si es posible. 📱',
|
||||
'🌟 ¡Hola! Espero que estés muy bien. Mi nombre es xxxxxxxx y con gusto te acompañaré con tu solicitud para poder darle solución a cualquier inquietud que presentes. ¿Podrías confirmarme tus datos: nombre, cédula y si es un servicio hogar o móvil? 💬',
|
||||
@@ -87,112 +87,98 @@ async function procesarElementosWhatsapp() {
|
||||
if (element.classList.contains('new-case')) {
|
||||
console.log('Elemento es un new-case');
|
||||
element.click();
|
||||
await new Promise(resolve => setTimeout(resolve, 1200));
|
||||
const caseID = document.querySelector('.social-case-conversation-header span')?.textContent || '';
|
||||
console.log('Nuevo caso: ' + caseID);
|
||||
await new Promise(resolve => setTimeout(resolve, 1500));
|
||||
const headerText = document.querySelector('.social-case-conversation-header span')?.textContent || '';
|
||||
console.log('Nuevo caso: ' + headerText);
|
||||
|
||||
const clientConversationItems = document.querySelectorAll('.case-conversation-item.client');
|
||||
const allBodyTextsClient = [];
|
||||
|
||||
// Process client conversation items asynchronously
|
||||
await Promise.all(Array.from(clientConversationItems).map(async (item) => {
|
||||
const bodyTextSpansClient = item.querySelectorAll('span.body-text');
|
||||
await Promise.all(Array.from(bodyTextSpansClient).map(async (span) => {
|
||||
const randomId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
|
||||
allBodyTextsClient.push({
|
||||
id: randomId,
|
||||
role: "user",
|
||||
content: span.textContent.trim()
|
||||
});
|
||||
}));
|
||||
}));
|
||||
|
||||
console.log('Textos span.body-text de elementos .case-conversation-item.client:', allBodyTextsClient);
|
||||
// Check if there are any messages in the conversation
|
||||
if (allBodyTextsClient.length === 0) {
|
||||
console.log('No client messages found, skipping case');
|
||||
element.classList.add('caso-gestionado');
|
||||
continue;
|
||||
}
|
||||
// Get the last message from the client
|
||||
const lastMessage = allBodyTextsClient[allBodyTextsClient.length - 1];
|
||||
// Verify if the last message is empty or only contains whitespace
|
||||
if (!lastMessage.content || lastMessage.content.trim() === '') {
|
||||
console.log('Last message is empty, skipping case');
|
||||
element.classList.add('caso-gestionado');
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
console.log('Caso new-case: ' + headerText);
|
||||
const textarea = document.querySelector('.selected-message-container-all-case textarea#textareaActAsChat');
|
||||
if (textarea && textarea.offsetHeight > 0 && textarea.offsetWidth > 0 && getComputedStyle(textarea).display !== 'none' && getComputedStyle(textarea).visibility !== 'hidden') {
|
||||
console.log('El textarea está visible.');
|
||||
|
||||
// Capturar TODOS los mensajes en orden cronológico
|
||||
const conversationItems = document.querySelectorAll(
|
||||
'.case-conversation-item.client, .case-conversation-item.agent, .case-conversation-item.system'
|
||||
);
|
||||
|
||||
const allMessages = [];
|
||||
conversationItems.forEach(item => {
|
||||
if (item.classList.contains("client")) {
|
||||
const spans = item.querySelectorAll("span.body-text");
|
||||
spans.forEach(span => {
|
||||
if (span.textContent.trim() !== "") {
|
||||
allMessages.push({
|
||||
id: Math.random().toString(36).substring(2, 15),
|
||||
role: "user",
|
||||
content: span.textContent.trim()
|
||||
});
|
||||
}
|
||||
});
|
||||
} else if (item.classList.contains("agent") || item.classList.contains("system")) {
|
||||
const texts = item.querySelectorAll(".sm-whatsapp .text, span.body-text");
|
||||
texts.forEach(t => {
|
||||
if (t.innerText.trim() !== "") {
|
||||
allMessages.push({
|
||||
id: Math.random().toString(36).substring(2, 15),
|
||||
role: "assistant",
|
||||
content: t.innerText.trim()
|
||||
});
|
||||
}
|
||||
});
|
||||
// Intentar obtener el mensaje guardado en chrome.storage.local
|
||||
let selectedMessage;
|
||||
try {
|
||||
// Obtener el mensaje guardado de forma sincrónica
|
||||
const data = await chrome.storage.local.get(['mensaje']);
|
||||
if (data.mensaje) {
|
||||
console.log('Usando mensaje guardado desde chrome.storage.local');
|
||||
selectedMessage = data.mensaje;
|
||||
} else {
|
||||
console.log('No hay mensaje guardado, usando uno aleatorio');
|
||||
selectedMessage = defaultMessages[Math.floor(Math.random() * defaultMessages.length)].replace(/xxxxxxxx/g, capitalizedName);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error al obtener mensaje guardado:', error);
|
||||
selectedMessage = defaultMessages[Math.floor(Math.random() * defaultMessages.length)].replace(/xxxxxxxx/g, capitalizedName);
|
||||
}
|
||||
textarea.value = selectedMessage;
|
||||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
console.log('Mensaje 1 escrito en caso:', selectedMessage);
|
||||
|
||||
console.log("Conversación en orden:", allMessages);
|
||||
await new Promise(resolve => setTimeout(resolve, 1500));
|
||||
const sendButton = document.querySelector('a.social-case-reply-as-chat-send');
|
||||
if (sendButton && sendButton.offsetParent !== null) {
|
||||
// sendButton.click();
|
||||
console.log('Mensaje 1 enviado');
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 2500));
|
||||
const selectedMessageTwo = secondMessages[Math.floor(Math.random() * secondMessages.length)];
|
||||
textarea.value = selectedMessageTwo;
|
||||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
console.log('Mensaje 2 escrito en caso:', selectedMessageTwo);
|
||||
|
||||
const data = await chrome.storage.local.get("okanToken");
|
||||
const okanToken = data.okanToken;
|
||||
let mensaje;
|
||||
|
||||
if (okanToken) {
|
||||
console.log('Token obtenido: ' + okanToken);
|
||||
const options = {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': '*/*',
|
||||
'Authorization': `Bearer ${okanToken}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
"datos": { "tema": "", "extraContext": "" },
|
||||
"history": allMessages
|
||||
})
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch('https://io.linguogpt.ai/api/assistant/7cb1a048-8e67-44fe-a71e-ccacf19ef944', { ...options, timeout: 15000 });
|
||||
if (response.status === 200) {
|
||||
const data = await response.json();
|
||||
if (data.suggestions && data.suggestions.length > 0) {
|
||||
mensaje = data.suggestions[0].text;
|
||||
console.log('Mensaje obtenido del endpoint:', mensaje);
|
||||
}
|
||||
} else if (response.status === 401) {
|
||||
alert("Debes iniciar sesión en Okan");
|
||||
console.warn('Authentication error: User needs to login to Okan');
|
||||
} else {
|
||||
console.error('Error en respuesta de linguo:', response.status);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error en la petición a linguo:', error);
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 1200));
|
||||
if (sendButton && sendButton.offsetParent !== null) {
|
||||
// sendButton.click();
|
||||
console.log('Mensaje 2 enviado');
|
||||
}
|
||||
|
||||
const overlay_hide = document.getElementById(`robotOverlay`);
|
||||
if (overlay_hide) overlay_hide.remove();
|
||||
|
||||
if (mensaje) {
|
||||
textarea.value = mensaje;
|
||||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
console.log('Mensaje escrito en caso:', mensaje);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1200));
|
||||
const sendButton = document.querySelector('a.social-case-reply-as-chat-send');
|
||||
if (sendButton && sendButton.offsetParent !== null) {
|
||||
sendButton.click();
|
||||
console.log('Mensaje enviado');
|
||||
}
|
||||
} else {
|
||||
console.log("No se obtuvo mensaje de Linguo, caso se marca como gestionado igualmente.");
|
||||
}
|
||||
|
||||
element.classList.add('caso-gestionado');
|
||||
console.log('Caso gestionado: ' + headerText);
|
||||
}
|
||||
} else if (element.classList.contains('unread') && !element.classList.contains('new-case')) {
|
||||
}
|
||||
else if (element.classList.contains('unread') && !element.classList.contains('new-case')) {
|
||||
console.log('Element classes:', element.classList.toString());
|
||||
element.click();
|
||||
await new Promise(resolve => setTimeout(resolve, 1200));
|
||||
const headerText = document.querySelector('.social-case-conversation-header span')?.textContent || '';
|
||||
console.log('Caso unread: ' + headerText);
|
||||
const caseID = document.querySelector('.social-case-conversation-header span')?.textContent || '';
|
||||
console.log('Caso unread: ' + caseID);
|
||||
const textarea = document.querySelector('.selected-message-container-all-case textarea#textareaActAsChat');
|
||||
if (textarea && textarea.offsetHeight > 0 && textarea.offsetWidth > 0 && getComputedStyle(textarea).display !== 'none' && getComputedStyle(textarea).visibility !== 'hidden') {
|
||||
console.log('El textarea está visible.');
|
||||
@@ -202,16 +188,26 @@ async function procesarElementosWhatsapp() {
|
||||
'.case-conversation-item.client, .case-conversation-item.agent, .case-conversation-item.system'
|
||||
);
|
||||
|
||||
const allMessages = [];
|
||||
// Construir el objeto con la estructura requerida
|
||||
const payload = {
|
||||
conversation_id: caseID,
|
||||
source_chat: 'SMCC Recap - Test',
|
||||
case_info: {
|
||||
base_id: '7cb1a048-8e67-44fe-a71e-ccacf19ef944',
|
||||
context_extra: ''
|
||||
},
|
||||
messages: []
|
||||
};
|
||||
|
||||
conversationItems.forEach(item => {
|
||||
if (item.classList.contains("client")) {
|
||||
const spans = item.querySelectorAll("span.body-text");
|
||||
spans.forEach(span => {
|
||||
if (span.textContent.trim() !== "") {
|
||||
allMessages.push({
|
||||
id: Math.random().toString(36).substring(2, 15),
|
||||
payload.messages.push({
|
||||
id: item.getAttribute('id'),
|
||||
role: "user",
|
||||
content: span.textContent.trim()
|
||||
content: span.textContent.replace(/\n{2,}/g, '\n').trim()
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -219,17 +215,17 @@ async function procesarElementosWhatsapp() {
|
||||
const texts = item.querySelectorAll(".sm-whatsapp .text, span.body-text");
|
||||
texts.forEach(t => {
|
||||
if (t.innerText.trim() !== "") {
|
||||
allMessages.push({
|
||||
id: Math.random().toString(36).substring(2, 15),
|
||||
payload.messages.push({
|
||||
id: item.getAttribute('id'),
|
||||
role: "assistant",
|
||||
content: t.innerText.trim()
|
||||
content: t.innerText.replace(/\n{2,}/g, '\n').trim()
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
console.log("Conversación en orden:", allMessages);
|
||||
console.log("Conversación en orden:\n" + JSON.stringify(payload, null, 2));
|
||||
|
||||
const data = await chrome.storage.local.get("okanToken");
|
||||
const okanToken = data.okanToken;
|
||||
@@ -251,11 +247,11 @@ async function procesarElementosWhatsapp() {
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch('https://io.linguogpt.ai/api/assistant/7cb1a048-8e67-44fe-a71e-ccacf19ef944', { ...options, timeout: 15000 });
|
||||
const response = await fetch('https://agent.linguogpt.ai/api/agent/run/bd63d7f5-667e-4f6b-ba31-9e4c02a26ed8', { ...options, timeout: 15000 });
|
||||
if (response.status === 200) {
|
||||
const data = await response.json();
|
||||
if (data.suggestions && data.suggestions.length > 0) {
|
||||
mensaje = data.suggestions[0].text;
|
||||
mensaje = data.message;
|
||||
console.log('Mensaje obtenido del endpoint:', mensaje);
|
||||
}
|
||||
} else if (response.status === 401) {
|
||||
@@ -272,6 +268,8 @@ async function procesarElementosWhatsapp() {
|
||||
const overlay_hide = document.getElementById(`robotOverlay`);
|
||||
if (overlay_hide) overlay_hide.remove();
|
||||
|
||||
console.log("Mensaje de linguo: "+mensaje);
|
||||
|
||||
if (mensaje) {
|
||||
textarea.value = mensaje;
|
||||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
@@ -280,7 +278,7 @@ async function procesarElementosWhatsapp() {
|
||||
await new Promise(resolve => setTimeout(resolve, 1200));
|
||||
const sendButton = document.querySelector('a.social-case-reply-as-chat-send');
|
||||
if (sendButton && sendButton.offsetParent !== null) {
|
||||
sendButton.click();
|
||||
// sendButton.click();
|
||||
console.log('Mensaje enviado');
|
||||
}
|
||||
} else {
|
||||
@@ -288,7 +286,7 @@ async function procesarElementosWhatsapp() {
|
||||
}
|
||||
|
||||
element.classList.add('caso-gestionado');
|
||||
console.log('Caso gestionado: ' + headerText);
|
||||
console.log('Caso gestionado: ' + caseID);
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
@@ -309,5 +307,6 @@ async function procesarElementosWhatsapp() {
|
||||
procesandoCasos = false;
|
||||
}
|
||||
|
||||
// Ejecutar la función cada 3 segundos
|
||||
setInterval(procesarElementosWhatsapp, 7000);
|
||||
// Ejecutar la función cada 7 segundos
|
||||
setInterval(procesarElementosWhatsapp, 7000);
|
||||
// procesarElementosWhatsapp();
|
||||
|
||||
Reference in New Issue
Block a user