// ==UserScript==
// @name 特种考试自动答题脚本-中安云教育
// @namespace http://tampermonkey.net/
// @version 4.1.0
// @description 特种考试自动答题脚本-中安云教育
// @author You
// @match https://txsyaqpx.zhongancloud.com/*
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_xmlhttpRequest
// @grant GM_info
// @grant unsafeWindow
// @require https://lib.baomitu.com/jquery/3.6.0/jquery.min.js
// @run-at document-start
// ==/UserScript==
(function() {
'use strict';
// 全局配置
const CONFIG = {
delay: 2000,
stop: true,
// 智谱AI应用配置(使用最新API)
ZHIPU_CONFIG: {
api_key: '51ae1d1540dd4d2d9418c32d3cefd868.3nX8rj0r87zTFSdl',
application_id: '1975919497449705472', // 您的智能体ID作为应用ID
knowledge_base_id: '1975919768523378688',
base_url: 'https://open.bigmodel.cn/api/llm-application/open'
}
};
let logContainer;
let stats = {
total: 0,
processed: 0,
success: 0,
failed: 0,
knowledgeHits: 0,
aiBackup: 0
};
// 日志函数
function log(message) {
const time = new Date().toLocaleTimeString();
const logMessage = `[${time}] ${message}`;
console.log(logMessage);
if (logContainer) {
logContainer.innerHTML += `
${logMessage}
`;
logContainer.scrollTop = logContainer.scrollHeight;
}
}
// 调用智谱应用API(使用最新接口)
async function callKnowledgeBaseAPI(question, options) {
const query = `请回答这道低压电工题目,只回答选项字母:
题目:${question}
选项:
${options.map((opt, i) => `${String.fromCharCode(65 + i)}. ${opt}`).join('\n')}
请基于低压电工专业知识,只回答正确选项的字母(如:A 或 B 或 C)。`;
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'POST',
url: `${CONFIG.ZHIPU_CONFIG.base_url}/v3/application/invoke`,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${CONFIG.ZHIPU_CONFIG.api_key}`
},
data: JSON.stringify({
app_id: CONFIG.ZHIPU_CONFIG.application_id,
stream: false,
messages: [
{
role: "user",
content: [
{
type: "input",
value: query
}
]
}
]
}),
timeout: 20000,
onload: function(response) {
try {
// 简化日志输出
if (response.status !== 200) {
reject(new Error(`知识库API错误: ${response.status}`));
return;
}
const result = JSON.parse(response.responseText);
if (result.choices && result.choices[0] && result.choices[0].messages) {
const messages = result.choices[0].messages;
const content = messages.content;
if (content && content.type === "text" && content.msg) {
const answer = content.msg.trim();
log(`🧠 AI回答: ${answer}`);
stats.knowledgeHits++;
resolve(answer);
} else {
log(`❌ 智能体响应内容格式错误`);
reject(new Error('智能体响应内容格式错误'));
}
} else {
log(`❌ 智能体API错误: ${result.message || '未知错误'}`);
reject(new Error(result.message || '智能体API调用失败'));
}
} catch (e) {
log(`❌ 知识库响应解析失败: ${e.message}`);
reject(new Error('知识库响应解析失败'));
}
},
onerror: function(error) {
log(`❌ 知识库网络错误: ${JSON.stringify(error)}`);
reject(new Error('知识库网络请求失败'));
}
});
});
}
// 备用AI调用(修复版)
async function callBackupAI(question, options) {
const prompt = `请回答这道${options.length === 2 ? '判断' : '选择'}题,只回答选项字母:
题目:${question}
选项:
${options.map((opt, i) => `${String.fromCharCode(65 + i)}. ${opt}`).join('\n')}
请只回答一个字母,如:A 或 B 或 C
答案:`;
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'POST',
url: `${CONFIG.ZHIPU_CONFIG.base_url}/chat/completions`,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${CONFIG.ZHIPU_CONFIG.api_key}`
},
data: JSON.stringify({
model: 'glm-4-flash',
messages: [
{
role: "system",
content: "你是专业的低压电工,只回答选项字母,不要解释。"
},
{
role: "user",
content: prompt
}
],
temperature: 0.1,
max_tokens: 3
}),
timeout: 10000,
onload: function(response) {
try {
const result = JSON.parse(response.responseText);
if (result.choices && result.choices[0]) {
const answer = result.choices[0].message.content.trim();
log(`🤖 备用AI回答: "${answer}"`);
stats.aiBackup++;
resolve(answer);
} else if (result.error) {
log(`❌ 备用AI错误: ${result.error.message}`);
reject(new Error('备用AI响应错误'));
} else {
reject(new Error('备用AI响应格式错误'));
}
} catch (e) {
log(`❌ 备用AI解析失败: ${e.message}`);
reject(new Error('备用AI解析失败'));
}
},
onerror: () => reject(new Error('备用AI网络错误'))
});
});
}
// 智能获取答案
async function getSmartAnswer(question, options) {
// 优先使用知识库
try {
log('📚 正在调用知识库...');
const knowledgeAnswer = await callKnowledgeBaseAPI(question, options);
return knowledgeAnswer;
} catch (error) {
log(`⚠️ 知识库调用失败: ${error.message}`);
// 备用AI
try {
log('🤖 使用备用AI...');
const aiAnswer = await callBackupAI(question, options);
return aiAnswer;
} catch (aiError) {
log(`❌ 备用AI也失败: ${aiError.message}`);
throw new Error('所有答案获取方式都失败');
}
}
}
// 解析答案(增强版)- 返回详细信息
function parseAnswer(answer, options = []) {
const cleanAnswer = answer.toUpperCase().trim();
log(`🔍 解析答案: "${cleanAnswer}"`);
// 1. 直接匹配单个字母(最优先)
if (/^[A-Z]$/.test(cleanAnswer)) {
const index = cleanAnswer.charCodeAt(0) - 65;
if (index >= 0 && index < (options.length || 4)) {
const result = {
letter: cleanAnswer,
index: index,
content: options[index] || `选项${cleanAnswer}`,
source: 'direct_letter'
};
log(`✅ 直接匹配: ${cleanAnswer} -> ${result.content}`);
return result;
}
}
// 2. 提取第一个字母
const letterMatch = cleanAnswer.match(/[A-Z]/);
if (letterMatch) {
const letter = letterMatch[0];
const index = letter.charCodeAt(0) - 65;
if (index >= 0 && index < (options.length || 4)) {
const result = {
letter: letter,
index: index,
content: options[index] || `选项${letter}`,
source: 'extract_letter'
};
log(`✅ 提取字母: ${letter} -> ${result.content}`);
return result;
}
}
// 3. 判断题关键词匹配
if (cleanAnswer.includes('正确') || cleanAnswer.includes('对') || cleanAnswer.includes('TRUE')) {
const result = {
letter: 'A',
index: 0,
content: options[0] || '正确',
source: 'keyword_correct'
};
log(`✅ 判断题-正确: A -> ${result.content}`);
return result;
} else if (cleanAnswer.includes('错误') || cleanAnswer.includes('错') || cleanAnswer.includes('FALSE')) {
const result = {
letter: 'B',
index: 1,
content: options[1] || '错误',
source: 'keyword_wrong'
};
log(`✅ 判断题-错误: B -> ${result.content}`);
return result;
}
// 4. 数字匹配
const numberMatch = cleanAnswer.match(/\d+/);
if (numberMatch) {
const number = parseInt(numberMatch[0]);
if (number >= 1 && number <= (options.length || 4)) {
const index = number - 1;
const letter = String.fromCharCode(65 + index);
const result = {
letter: letter,
index: index,
content: options[index] || `选项${letter}`,
source: 'number_match'
};
log(`✅ 数字匹配: ${number} -> ${letter}: ${result.content}`);
return result;
}
}
// 5. 选项内容关键词匹配
if (options.length > 0) {
for (let i = 0; i < options.length; i++) {
const option = options[i].trim();
const optionWords = option.split(/[\s,。、]/);
for (const word of optionWords) {
if (word.length >= 2 && cleanAnswer.includes(word.toUpperCase())) {
const letter = String.fromCharCode(65 + i);
const result = {
letter: letter,
index: i,
content: option,
source: 'content_match'
};
log(`✅ 内容匹配: "${word}" -> ${letter}: ${result.content}`);
return result;
}
}
}
}
log(`❌ 无法解析答案: "${cleanAnswer}"`);
return null;
}
// 处理单个题目
async function processQuestion(container, index) {
try {
log(`\n📝 === 第 ${index + 1} 题 ===`);
// 提取题目
const questionEl = container.querySelector('.question-name .content p');
if (!questionEl) {
log(`❌ 找不到题目`);
return false;
}
const question = questionEl.textContent.trim();
log(`📖 题目: ${question.substring(0, 50)}...`);
// 提取选项
const optionGroups = container.querySelectorAll('.option-group');
const options = [];
optionGroups.forEach(group => {
const content = group.querySelector('.option-content p');
if (content) {
const text = content.textContent.trim();
if (text && !options.includes(text)) {
options.push(text);
}
}
});
if (options.length === 0) {
log(`❌ 找不到选项`);
return false;
}
log(`📋 选项: ${options.join(' | ')}`);
// 获取智能答案
const answer = await getSmartAnswer(question, options);
// 解析并点击
const parseResult = parseAnswer(answer, options);
if (parseResult && parseResult.index >= 0 && parseResult.index < optionGroups.length) {
const targetGroup = optionGroups[parseResult.index];
const radioInput = targetGroup.querySelector('input[type="radio"]');
if (radioInput) {
radioInput.checked = true;
radioInput.dispatchEvent(new Event('change', { bubbles: true }));
targetGroup.click();
log(`✅ 已选择: ${parseResult.letter} - ${parseResult.content}`);
stats.success++;
return true;
}
}
log(`❌ 无法选择答案: 解析失败或选项不存在`);
stats.failed++;
return false;
} catch (error) {
log(`❌ 处理异常: ${error.message}`);
stats.failed++;
return false;
} finally {
stats.processed++;
}
}
// 测试单题
function testSingle() {
log('🧪 开始测试知识库调用...');
const containers = document.querySelectorAll('.ques-type-item');
if (containers.length > 0) {
processQuestion(containers[0], 0).then(() => {
log('🧪 === 测试完成 ===');
log(`📊 知识库使用: ${stats.knowledgeHits}次`);
log(`🤖 备用AI使用: ${stats.aiBackup}次`);
});
} else {
log('❌ 未找到题目');
}
}
// 开始答题
function startAnswering() {
if (!CONFIG.stop) return;
CONFIG.stop = false;
stats = { total: 0, processed: 0, success: 0, failed: 0, knowledgeHits: 0, aiBackup: 0 };
log('🚀 开始知识库增强答题');
log(`📚 使用知识库: ${CONFIG.ZHIPU_CONFIG.knowledge_base_id}`);
log(`🎯 目标:利用专业知识库突破82分`);
const containers = document.querySelectorAll('.ques-type-item');
stats.total = containers.length;
log(`📚 找到 ${stats.total} 道题目`);
(async () => {
for (let i = 0; i < containers.length && !CONFIG.stop; i++) {
await processQuestion(containers[i], i);
const progress = Math.round((i + 1) / containers.length * 100);
const accuracy = stats.processed > 0 ? Math.round(stats.success / stats.processed * 100) : 0;
const knowledgeRate = stats.processed > 0 ? Math.round(stats.knowledgeHits / stats.processed * 100) : 0;
log(`📊 进度: ${i + 1}/${containers.length} (${progress}%) | 准确率: ${accuracy}% | 知识库: ${knowledgeRate}%`);
if (i < containers.length - 1) {
const delay = parseInt(document.getElementById('delayInput')?.value || 3) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
const finalScore = Math.round(stats.success / stats.total * 100);
const knowledgeUsage = Math.round(stats.knowledgeHits / stats.processed * 100);
log(`\n🎉 知识库答题完成!`);
log(`📊 最终统计:`);
log(` • 总题目: ${stats.total}题`);
log(` • 成功: ${stats.success}题`);
log(` • 知识库使用: ${stats.knowledgeHits}次 (${knowledgeUsage}%)`);
log(` • 备用AI使用: ${stats.aiBackup}次`);
log(`📈 预估得分: ${finalScore}分`);
log(`🎯 相比82分: ${finalScore > 82 ? '提升' : '下降'}${Math.abs(finalScore - 82)}分`);
CONFIG.stop = true;
})();
}
// 停止答题
function stopAnswering() {
CONFIG.stop = true;
log('⏹️ 停止答题');
}
// 创建控制面板
function createPanel() {
const panel = document.createElement('div');
panel.id = 'knowledgePanel';
panel.style.cssText = `
position: fixed;
top: 50px;
right: 20px;
width: 360px;
background: #f0f2f5;
border: none;
border-radius: 20px;
box-shadow:
20px 20px 40px rgba(0,0,0,0.1),
-20px -20px 40px rgba(255,255,255,0.8),
inset 0 0 0 1px rgba(255,255,255,0.3);
z-index: 10000;
font-family: 'Microsoft YaHei', Arial, sans-serif;
transition: all 0.3s ease;
backdrop-filter: blur(10px);
`;
panel.innerHTML = `
🔮 智能知识库引擎
应用ID: ****${CONFIG.ZHIPU_CONFIG.application_id.substr(-4)} | 知识库: ****${CONFIG.ZHIPU_CONFIG.knowledge_base_id.substr(-4)}
📚 答题助手已就绪...
🧠 已配置真实知识库API调用
🎯 目标:利用专业知识库达到95分+
💡 知识库优先,AI备用
🎯 智能答题系统
知识库优先 + AI备用 + 选项智能匹配
支持拖拽移动 | 可最小化悬浮 | 智能选项识别
`;
document.body.appendChild(panel);
logContainer = document.getElementById('logArea');
// 创建最小化悬浮窗
createFloatingPet();
// 绑定事件
setTimeout(() => {
const testBtn = document.getElementById('testBtn');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const minimizeBtn = document.getElementById('minimizeBtn');
const closeBtn = document.getElementById('closeBtn');
if (testBtn) testBtn.onclick = testSingle;
if (startBtn) startBtn.onclick = startAnswering;
if (stopBtn) stopBtn.onclick = stopAnswering;
if (minimizeBtn) minimizeBtn.onclick = minimizePanel;
if (closeBtn) closeBtn.onclick = closePanel;
// 拖拽功能
setupDragFunctionality();
log('✅ 面板已就绪,支持拖拽和最小化');
}, 100);
// 实时更新统计
setInterval(() => {
const statsArea = document.getElementById('statsArea');
const pet = document.getElementById('floatingPet');
if (statsArea && stats.total > 0) {
const progress = Math.round((stats.processed / stats.total) * 100);
const accuracy = stats.processed > 0 ? Math.round((stats.success / stats.processed) * 100) : 0;
const knowledgeRate = stats.processed > 0 ? Math.round((stats.knowledgeHits / stats.processed) * 100) : 0;
const aiRate = stats.processed > 0 ? Math.round((stats.aiBackup / stats.processed) * 100) : 0;
statsArea.innerHTML = `
进度
${stats.processed}/${stats.total}
📚 知识库: ${stats.knowledgeHits}次 | 🤖 备用AI: ${stats.aiBackup}次
`;
// 同时更新悬浮宠物状态
if (pet && pet.style.display === 'flex') {
pet.className = ''; // 清除之前的状态类
if (CONFIG.stop === false && stats.processed > 0) {
// 答题进行中
pet.className = 'pet-working';
pet.innerHTML = `
`;
pet.title = `🚀 答题进行中: ${stats.processed}/${stats.total} (准确率${accuracy}%) - 点击展开面板`;
} else if (stats.processed > 0) {
// 答题完成
if (accuracy >= 90) {
pet.className = 'pet-success';
pet.innerHTML = `
`;
} else {
pet.className = 'pet-warning';
pet.innerHTML = `
`;
}
pet.title = `✅ 答题完成: ${accuracy}分 (${stats.success}/${stats.total}) - 点击展开面板`;
} else {
// 待机状态
pet.innerHTML = `
`;
pet.title = '🤖 知识库答题助手 - 点击展开面板';
}
}
}
}, 1000);
}
// 创建悬浮小宠物
function createFloatingPet() {
const pet = document.createElement('div');
pet.id = 'floatingPet';
pet.style.cssText = `
position: fixed;
top: 50px;
right: 20px;
width: 75px;
height: 75px;
background: #f0f2f5;
border-radius: 50%;
box-shadow:
12px 12px 24px rgba(0,0,0,0.15),
-12px -12px 24px rgba(255,255,255,0.9);
z-index: 10001;
cursor: pointer;
display: none;
align-items: center;
justify-content: center;
font-size: 28px;
color: #4a5568;
transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
user-select: none;
animation: petFloat 4s ease-in-out infinite;
border: none;
`;
pet.innerHTML = `
`;
pet.title = '知识库答题助手 - 点击展开';
pet.onclick = restorePanel;
// 添加悬浮动画和样式
const style = document.createElement('style');
style.textContent = `
@keyframes petFloat {
0%, 100% {
transform: translateY(0px) rotate(0deg);
box-shadow:
12px 12px 24px rgba(0,0,0,0.15),
-12px -12px 24px rgba(255,255,255,0.9);
}
25% {
transform: translateY(-6px) rotate(1deg);
box-shadow:
15px 15px 30px rgba(0,0,0,0.2),
-15px -15px 30px rgba(255,255,255,0.95);
}
50% {
transform: translateY(-10px) rotate(0deg);
box-shadow:
18px 18px 36px rgba(0,0,0,0.25),
-18px -18px 36px rgba(255,255,255,1);
}
75% {
transform: translateY(-6px) rotate(-1deg);
box-shadow:
15px 15px 30px rgba(0,0,0,0.2),
-15px -15px 30px rgba(255,255,255,0.95);
}
}
@keyframes petPulse {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.05);
}
}
#floatingPet:hover {
transform: scale(1.1) translateY(-3px) !important;
box-shadow:
inset 6px 6px 12px rgba(0,0,0,0.1),
inset -6px -6px 12px rgba(255,255,255,0.8) !important;
animation: petPulse 1s ease-in-out infinite !important;
}
#floatingPet:active {
transform: scale(0.95) !important;
transition: all 0.1s ease !important;
box-shadow:
inset 8px 8px 16px rgba(0,0,0,0.15),
inset -8px -8px 16px rgba(255,255,255,0.9) !important;
}
/* 状态指示器样式 */
.pet-working {
background: #e6fffa !important;
color: #38a169 !important;
animation: petFloat 2s ease-in-out infinite, petPulse 1.5s ease-in-out infinite !important;
box-shadow:
12px 12px 24px rgba(56, 161, 105, 0.2),
-12px -12px 24px rgba(255,255,255,0.9) !important;
}
.pet-success {
background: #ebf8ff !important;
color: #3182ce !important;
box-shadow:
12px 12px 24px rgba(49, 130, 206, 0.2),
-12px -12px 24px rgba(255,255,255,0.9) !important;
}
.pet-warning {
background: #fffaf0 !important;
color: #ed8936 !important;
box-shadow:
12px 12px 24px rgba(237, 137, 54, 0.2),
-12px -12px 24px rgba(255,255,255,0.9) !important;
}
`;
document.head.appendChild(style);
document.body.appendChild(pet);
}
// 设置拖拽功能
function setupDragFunctionality() {
const panel = document.getElementById('knowledgePanel');
const header = document.getElementById('panelHeader');
const pet = document.getElementById('floatingPet');
let isDragging = false;
let dragOffset = { x: 0, y: 0 };
// 面板拖拽
if (header) {
header.onmousedown = (e) => {
// 如果点击的是按钮,不触发拖拽
if (e.target.id === 'minimizeBtn' || e.target.id === 'closeBtn') {
return;
}
isDragging = true;
dragOffset.x = e.clientX - panel.offsetLeft;
dragOffset.y = e.clientY - panel.offsetTop;
header.style.cursor = 'grabbing';
e.preventDefault();
};
}
// 悬浮宠物拖拽
if (pet) {
pet.onmousedown = (e) => {
if (e.detail === 1) { // 单击时不拖拽,双击时拖拽
setTimeout(() => {
if (e.detail === 1) return; // 如果是单击就返回
isDragging = true;
dragOffset.x = e.clientX - pet.offsetLeft;
dragOffset.y = e.clientY - pet.offsetTop;
pet.style.cursor = 'grabbing';
e.preventDefault();
e.stopPropagation();
}, 200);
}
};
}
// 全局鼠标移动事件
document.onmousemove = (e) => {
if (isDragging) {
const activeElement = panel.style.display !== 'none' ? panel : pet;
if (activeElement) {
const newX = e.clientX - dragOffset.x;
const newY = e.clientY - dragOffset.y;
// 限制在屏幕范围内
const maxX = window.innerWidth - activeElement.offsetWidth;
const maxY = window.innerHeight - activeElement.offsetHeight;
activeElement.style.left = Math.max(0, Math.min(newX, maxX)) + 'px';
activeElement.style.top = Math.max(0, Math.min(newY, maxY)) + 'px';
activeElement.style.right = 'auto';
activeElement.style.bottom = 'auto';
}
}
};
// 全局鼠标释放事件
document.onmouseup = () => {
if (isDragging) {
isDragging = false;
if (header) header.style.cursor = 'move';
if (pet) pet.style.cursor = 'pointer';
}
};
}
// 最小化面板
function minimizePanel() {
const panel = document.getElementById('knowledgePanel');
const pet = document.getElementById('floatingPet');
if (panel && pet) {
panel.style.display = 'none';
pet.style.display = 'flex';
// 悬浮宠物显示状态
if (stats.processed > 0) {
const accuracy = Math.round((stats.success / stats.processed) * 100);
pet.innerHTML = `${accuracy}%`;
pet.title = `答题进度: ${stats.processed}/${stats.total} (${accuracy}%) - 点击展开`;
} else {
pet.innerHTML = '📚';
pet.title = '知识库答题助手 - 点击展开';
}
log('📱 已最小化为悬浮小宠物');
}
}
// 恢复面板
function restorePanel() {
const panel = document.getElementById('knowledgePanel');
const pet = document.getElementById('floatingPet');
if (panel && pet) {
panel.style.display = 'block';
pet.style.display = 'none';
log('📱 已恢复面板显示');
}
}
// 关闭面板
function closePanel() {
const panel = document.getElementById('knowledgePanel');
const pet = document.getElementById('floatingPet');
if (confirm('确定要关闭知识库答题助手吗?')) {
if (panel) panel.remove();
if (pet) pet.remove();
// 停止答题
CONFIG.stop = true;
log('❌ 答题助手已关闭');
console.log('📚 知识库答题助手已关闭');
}
}
// 初始化
function init() {
if (!location.href.includes('txsyaqpx.zhongancloud.com')) {
return;
}
log('🚀 知识库答题助手已启动');
const checkReady = () => {
if (document.querySelector('.ques-type-item')) {
log('✅ 页面加载完成');
createPanel();
} else {
setTimeout(checkReady, 1000);
}
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', checkReady);
} else {
setTimeout(checkReady, 1000);
}
}
// 启动
init();
})();