// Criação do contêiner de botões
let botoesContainer = document.createElement('div');
console.log("passou dos botões");
botoesContainer.innerHTML = `
<div class="container">
<h2>Hack CMSP</h2>
<label>Quanto tempo quer esperar para responder?</label>
<input id="tempoEspera" type="number" placeholder="Segundos" class="input-field">
<label>Responder quantas questões?</label>
<input id="quantidadeQuestoes" type="number" placeholder="Quantidade" class="input-field">
<label>Todas as questões?</label>
<select id="todasQuestoes" class="input-field">
<option value="sim">Sim</option>
<option value="nao">Não</option>
</select>
<button onclick="responder()" id="responderButton" class="custom-button">Responder</button>
</div>
`;
code
Assistant
Ao examinar os dois scripts que você forneceu, algumas diferenças e possíveis problemas no primeiro script podem ser identificados:
Início Observador na URL:
No primeiro script, o domínio do observador de mutações começa dentro da função responder, enquanto no segundo script começa antes da função ser chamada. Isso significa que, no primeiro script, o código só começará a observar mudanças na URL após a função responder ser chamada, o que pode nunca acontecer se não houver um clique no botão.
// Estilos do contêiner
botoesContainer.style.position = 'fixed';
botoesContainer.style.right = '20px';
botoesContainer.style.bottom = '20px';
botoesContainer.style.zIndex = '9999'; // Garantir que o z-index é alto o suficiente
botoesContainer.style.backgroundColor = '#f9f9f9';
botoesContainer.style.padding = '20px';
botoesContainer.style.borderRadius = '12px';
botoesContainer.style.boxShadow = '0 8px 16px rgba(0, 0, 0, 0.2)';
botoesContainer.style.width = '300px';
botoesContainer.style.fontFamily = '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif';
// Estilos adicionais
const title = botoesContainer.querySelector('h2');
title.style.fontSize = '18px';
title.style.marginBottom = '10px';
title.style.color = '#333';
const inputs = botoesContainer.querySelectorAll('.input-field');
inputs.forEach(input => {
input.style.width = '100%';
input.style.padding = '8px';
input.style.margin = '5px 0 15px 0';
input.style.borderRadius = '6px';
input.style.border = '1px solid #ccc';
input.style.fontSize = '14px';
});
// Estilo do botão "Responder"
const button = botoesContainer.querySelector('#responderButton');
button.style.backgroundColor = '#007bff';
button.style.color = '#fff';
button.style.padding = '12px 20px';
button.style.border = 'none';
button.style.borderRadius = '6px';
button.style.cursor = 'pointer';
button.style.fontSize = '16px';
button.style.width = '100%';
button.style.transition = 'background-color 0.3s ease';
// Adicionar efeito hover no botão
button.onmouseover = function () {
button.style.backgroundColor = '#0056b3';
};
button.onmouseout = function () {
button.style.backgroundColor = '#007bff';
};
// Adicionar o contêiner ao corpo da página
function adicionarBotoes() {
document.body.appendChild(botoesContainer);
}
// Verificar se o documento já está carregado
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', adicionarBotoes);
console.log("paginacarregada");
} else {
adicionarBotoes();
console.log("aaaaaaaaa");
}
let responderfoiapertado = document.querySelector("#responderButton");
if (responderfoiapertado) {
responderfoiapertado.addEventListener("click", responder, false)
}
console.log("script cmsp");
let enviarLicoes = /https:\/\/cmsp\.ip\.tv\/mobile\/tms\/task\/\d+\/apply/;
function responder() {
console.log("responderFunction");
function respostasJson(json) {
console.log("respostasJson");
let novoJson = {
status: "submitted",
accessed_on: json.accessed_on,
executed_on: json.executed_on,
answers: {}
};
for (let questionId in json.answers) {
let pergunta = json.answers[questionId];
let infoPergunta = json.task.questions.find(q => q.id === parseInt(questionId));
const respostasA = {
question_id: pergunta.question_id,
question_type: infoPergunta.type,
answer: resposta
}
let resposta;
if (infoPergunta.type === "order-sentences") {
resposta = infoPergunta.options.sentences.map(sentence => sentence.value);
novoJson.answers[questionId] = respostasA;
} else if (infoPergunta.type === "fill-words") {
resposta = infoPergunta.options.phrase.map(item => item.value);
novoJson.answers[questionId] = respostasA;
} else if (infoPergunta.type === "text_ai") {
resposta = infoPergunta.comment.replace(/<\/?p>/g, '');
novoJson.answers[questionId] = {
question_id: pergunta.question_id,
question_type: infoPergunta.type,
answer: { "0": resposta }
};
continue;
} else if (infoPergunta.type === "cloud") {
resposta = infoPergunta.options.ids;
novoJson.answers[questionId] = respostasA;
} else {
resposta = Object.fromEntries(
Object.keys(infoPergunta.options).map(optionId => [optionId, infoPergunta.options[optionId].answer])
);
}
};
return novoJson;
}
let antigoLink = document.location.href
const observar = new MutationObserver(() => {
if (antigoLink !== document.location.href) {
antigoLink = document.location.href;
if (enviarLicoes.test(antigoLink)) {
let authxkey = JSON.parse(sessionStorage.getItem("cmsp.ip.tv:iptvdashboard:state")).auth.auth_token;
let sala = JSON.parse(sessionStorage.getItem("cmsp.ip.tv:iptvdashboard:state")).room.room.name;
let id = antigoLink.split("/")[6];
let aaaaajaencheuosaco = {
status: "draft",
accessed_on: "room",
executed_on: sala,
answers: {}
}
const sendRequest = (method, url, data, callback) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader("X-Api-Key", authxkey);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = () => callback(xhr);
xhr.onerror = () => console.error('Request failed');
xhr.send(data ? JSON.stringify(data) : null);
};
sendRequest("POST", `https://edusp-api.ip.tv/tms/task/${id}/answer`, aaaaajaencheuosaco, (response) => {
let respostaJson = JSON.parse(response.responseText);
let tarefaId = respostaJson.id;
let respostasURL = `https://edusp-api.ip.tv/tms/task/${id}/answer/${tarefaId}?with_task=true&with_genre=true&with_questions=true&with_assessed_skills=true`
sendRequest("GET", respostasURL, null, (response) => {
let respostasdaURL = JSON.parse(response.responseText);
let enviarRespostas = respostasJson(respostasdaURL)
sendRequest("PUT", `https://edusp-api.ip.t v/tms/task/${id}/answer/${tarefaId}`, enviarRespostas, (response => {
if (response.status !== 200) {
alert(`DEU ERRO NESSA MERDA, VAI SE FODER, TOMAR NO MEIO DO SEU BUTICO CARALHO, deu erro, erro é o: ${response.responseText}`);
}
console.log("nsei");
}));
});
});
}
}
});
console.log("fff");
observar.observe(document.body, { // Adicionando a observação ao body do documento
childList: true,
subtree: true
});
}
// Corrigido: Inicialização correta do observer
})();
let lesson_regex = /https:\/\/cmsp\.ip\.tv\/mobile\/tms\/task\/\d+\/apply/;
console.log("-- STARTING CMSP CHEETO By marcos10pc --");
function transformJson(jsonOriginal) {
let novoJson = {
status: "submitted",
accessed_on: jsonOriginal.accessed_on,
executed_on: jsonOriginal.executed_on,
answers: {}
};
for (let questionId in jsonOriginal.answers) {
let question = jsonOriginal.answers[questionId];
let taskQuestion = jsonOriginal.task.questions.find(q => q.id === parseInt(questionId));
if (taskQuestion.type === "order-sentences") {
let answer = taskQuestion.options.sentences.map(sentence => sentence.value);
novoJson.answers[questionId] = {
question_id: question.question_id,
question_type: taskQuestion.type,
answer: answer
};
} else if (taskQuestion.type === "fill-words") {
let pre_anwser = taskQuestion.options
let anwser = pre_anwser.phrase.map(item => item.value);
//console.log(`[DEBUG] ${JSON.stringify(anwser)}`)
novoJson.answers[questionId] = {
question_id: question.question_id,
question_type: taskQuestion.type,
answer: anwser
};
} else if (taskQuestion.type === "text_ai") {
let answer = taskQuestion.comment.replace(/<\/?p>/g, '');
novoJson.answers[questionId] = {
question_id: question.question_id,
question_type: taskQuestion.type,
answer: {
"0": answer
}
};
} else if (taskQuestion.type === "fill-letters") {
let answer = taskQuestion.options.answer;
novoJson.answers[questionId] = {
question_id: question.question_id,
question_type: taskQuestion.type,
answer: answer
};
} else if (taskQuestion.type === "cloud") {
let answer = taskQuestion.options.ids;
novoJson.answers[questionId] = {
question_id: question.question_id,
question_type: taskQuestion.type,
answer: answer
};
} else {
let answer = Object.fromEntries(
Object.keys(taskQuestion.options).map(optionId => [optionId, taskQuestion.options[optionId].answer])
);
novoJson.answers[questionId] = {
question_id: question.question_id,
question_type: taskQuestion.type,
answer: answer
};
}
}
return novoJson;
}
let oldHref = document.location.href;
const observer = new MutationObserver(() => {
if (oldHref !== document.location.href) {
oldHref = document.location.href;
if (lesson_regex.test(oldHref)) {
console.log("[DEBUG] LESSON DETECTED");
let x_auth_key = JSON.parse(sessionStorage.getItem("cmsp.ip.tv:iptvdashboard:state")).auth.auth_token;
let room_name = JSON.parse(sessionStorage.getItem("cmsp.ip.tv:iptvdashboard:state")).room.room.name;
let id = oldHref.split("/")[6];
console.log(`[DEBUG] LESSON_ID: ${id} ROOM_NAME: ${room_name}`);
let draft_body = {
status: "draft",
accessed_on: "room",
executed_on: room_name,
answers: {}
};
const sendRequest = (method, url, data, callback) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader("X-Api-Key", x_auth_key);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = () => callback(xhr);
xhr.onerror = () => console.error('Request failed');
xhr.send(data ? JSON.stringify(data) : null);
};
sendRequest("POST", `https://edusp-api.ip.tv/tms/task/${id}/answer`, draft_body, (response) => {
console.log("[DEBUG] DRAFT_DONE, RESPONSE: ", response.responseText);
let response_json = JSON.parse(response.responseText);
let task_id = response_json.id;
let get_anwsers_url = `https://edusp-api.ip.tv/tms/task/${id}/answer/${task_id}?with_task=true&with_genre=true&with_questions=true&with_assessed_skills=true`;
console.log("[DEBUG] Getting Answers...");
sendRequest("GET", get_anwsers_url, null, (response) => {
console.log(`[DEBUG] Get Answers request received response`);
console.log(`[DEBUG] GET ANSWERS RESPONSE: ${response.responseText}`);
let get_anwsers_response = JSON.parse(response.responseText);
let send_anwsers_body = transformJson(get_anwsers_response);
console.log(`[DEBUG] Sending Answers... BODY: ${JSON.stringify(send_anwsers_body)}`);
sendRequest("PUT", `https://edusp-api.ip.tv/tms/task/${id}/answer/${task_id}`, send_anwsers_body, (response) => {
if (response.status !== 200) {
alert(`[ERROR] An error occurred while sending the answers. RESPONSE: ${response.responseText}`);
}
console.log(`[DEBUG] Answers Sent! RESPONSE: ${response.responseText}`);
const watermark = document.querySelector('.MuiTypography-root.MuiTypography-body1.css-1exusee');
if (watermark) {
watermark.textContent = 'sussy baka amongus';
watermark.style.fontSize = '70px';
setTimeout(() => {
document.querySelector('button.MuiButtonBase-root.MuiButton-root.MuiLoadingButton-root.MuiButton-contained.MuiButton-containedInherit.MuiButton-sizeMedium.MuiButton-containedSizeMedium.MuiButton-colorInherit.css-prsfpd').click();
}, 500);
}
});
});
});
}
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
})();
Função responder:
A função responder() é atribuída a um botão e só se conecta ao evento de clique no DOMContentLoaded. Se por algum motivo esse evento não for disparado ou o botão não for encontrado, a função nunca será vinculada ao botão e, portanto, nunca será chamada.
Declaração da sendRequest:
No primeiro script, a função sendRequest é definida dentro da função responder, enquanto no segundo script, ela está fora. Isso facilita a compreensão e o uso em múltiplas funções.
Estrutura Geral:
O segundo script parece ser mais organizado e fácil de seguir em termos de estrutura. É mais claro quais funções são auxiliares (transformJson, sendRequest) e qual função principal está observando as mutações de URL.
Para corrigir o primeiro script, recomendo:
Mover o observador de mutação para fora da função responder e inicializá-lo diretamente.
Verificar a correta ligação da função responder ao botão correndo o risco de não ser encontrada.
Organizar o código, separando funções auxiliares para uma melhor leitura e manutenção.
Validar erros e garantir que todos os elementos necessários estejam carregados e disponíveis no momento certo.
Examinar esses pontos pode ajudar a compreender onde o primeiro script não está funcionando como esperado e adaptar seu comportamento para que obtenha sucesso.