您需要先安装一个扩展,例如 篡改猴、Greasemonkey 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 Userscripts ,之后才能安装此脚本。
您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。
您需要先安装用户脚本管理器扩展后才能安装此脚本。
使用AI服务辅助算卦,支持提问和追问
// ==UserScript== // @name AI算卦辅助工具 // @namespace http://tampermonkey.net/ // @version 0.8 // @description 使用AI服务辅助算卦,支持提问和追问 // @author NULLUSER // @match https://www.china95.net/paipan/* // @match https://paipan.china95.net/* // @require https://cdn.jsdelivr.net/npm/[email protected]/dist/showdown.min.js // @grant GM_xmlhttpRequest // @grant GM_addStyle // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @license MIT // ==/UserScript== (function() { 'use strict'; // --------------------- CONFIGURATION --------------------- // Deno 服务地址 const DENO_SERVER_URL = 'https://works.shatang.me'; // 替换为你的 Deno 服务地址 const S_version = GM_info.script.version; // 功能 Work ID let ANALYSIS_WORK_ID = GM_getValue('ANALYSIS_WORK_ID', '01'); ; // 初始化的ID // 样式常量 const CONTAINER_WIDTH = '400px'; const MAX_CONTAINER_HEIGHT_PERCENT = 0.8; const BORDER_RADIUS = '10px'; const FONT_FAMILY = 'Arial, sans-serif'; const BOX_SHADOW = '0 5px 15px rgba(0, 0, 0, 0.2)'; const BUTTON_TOP_RIGHT_MARGIN = '40px'; const CONTAINER_RIGHT_MARGIN = '40px'; const CONTAINER_TOP_OFFSET = '10px'; const SECTION_MARGIN_BOTTOM = '15px'; const HEADING_COLOR = '#CBD5E1'; const TEXT_COLOR = '#94A3B8'; // 历史数据存储数量 (追问历史) const HISTORY_DATA_COUNT = 10; // --------------------- STATE MANAGEMENT --------------------- // API KEY和 MODEL (从 GM_getValue 读取) let GEMINI_API_KEY = GM_getValue('GEMINI_API_KEY', ''); let GEMINI_MODEL = GM_getValue('GEMINI_MODEL', ''); let SHOW_URL = ''; // 用于存储从 /query 获取的 showurl, 用于显示 let analysisContainer; let currentAnalysisResult = null; // 保存当前分析结果 let questionHistory = []; // 保存提问历史,用于追问 let latestQuestion = null; // 最近的一个问题 // --------------------- STYLING (CSS-in-JS) --------------------- const styleString = ` /* 全局样式 */ body { font-family: ${FONT_FAMILY}; } #analysis-container { position: fixed; top: calc(${BUTTON_TOP_RIGHT_MARGIN} + ${CONTAINER_TOP_OFFSET} + 40px); right: ${CONTAINER_RIGHT_MARGIN}; width: ${CONTAINER_WIDTH}; max-height: ${window.innerHeight * MAX_CONTAINER_HEIGHT_PERCENT}px; background-color: rgba(30, 41, 59, 0.9); color: ${TEXT_COLOR}; z-index: 1000; padding: 20px; overflow-y: auto; word-wrap: break-word; word-break: break-all; box-shadow: ${BOX_SHADOW}; border-radius: ${BORDER_RADIUS}; transition: all 0.3s ease; scrollbar-width: thin; scrollbar-color: #4F46E5 #1E293B; } #analysis-container::-webkit-scrollbar { width: 8px; } #analysis-container::-webkit-scrollbar-track { background: #1E293B; } #analysis-container::-webkit-scrollbar-thumb { background-color: #4F46E5; border-radius: 4px; border: 1px solid #1E293B; } #analysis-container:hover { box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3); } #analysis-button { position: fixed; top: ${BUTTON_TOP_RIGHT_MARGIN}; right: ${BUTTON_TOP_RIGHT_MARGIN}; z-index: 1001; background-color: #4F46E5; border: none; color: white; padding: 12px 24px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; cursor: pointer; border-radius: ${BORDER_RADIUS}; box-shadow: ${BOX_SHADOW}; transition: background-color 0.3s ease; } #analysis-button:hover { background-color: #6366F1; } #analysis-container.hidden { display: none; } #analysis-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; color: #94A3B8; } #analysis-header button { background-color: transparent; border: none; color: #94A3B8; cursor: pointer; font-size: 1.2em; transition: color 0.3s ease; } #analysis-header button:hover { color: #CBD5E1; } #analysis-container h2 { color: ${HEADING_COLOR}; border-bottom: 2px solid #475569; padding-bottom: 8px; margin-top: 1.2em; margin-bottom: 0.6em; font-size: 1.4em; } #analysis-container h3 { color: ${HEADING_COLOR}; margin-top: 1em; margin-bottom: 0.5em; font-size: 1.2em; } #analysis-container p { line-height: 1.7; margin-bottom: ${SECTION_MARGIN_BOTTOM}; } #analysis-container ul { list-style-type: square; padding-left: 20px; margin-bottom: ${SECTION_MARGIN_BOTTOM}; } #analysis-container li { line-height: 1.6; margin-bottom: 5px; } #analysis-container hr { border: none; border-top: 1px solid #475569; margin: 20px 0;} #analysis-container a { color: #6366F1; text-decoration: none; word-wrap: break-word; word-break: break-all; } #analysis-container a:hover { text-decoration: underline; } #analysis-container pre { background-color: #1E293B; color: #F8FAFC; padding: 12px; border-radius: ${BORDER_RADIUS}; word-wrap: break-word; white-space: pre-wrap; overflow-x: auto; font-size: 0.9em; margin-bottom: ${SECTION_MARGIN_BOTTOM}; } #analysis-container table { width: 100%; border-collapse: collapse; margin-bottom: ${SECTION_MARGIN_BOTTOM}; } #analysis-container th, #analysis-container td { border: 1px solid #475569; padding: 8px; text-align: left; } #analysis-container th { background-color: #334155; color: ${HEADING_COLOR}; } #analysis-container code { font-family: monospace; } #analysis-container.loading { text-align: center; font-style: italic; color: #64748B; } .info-box { background-color: #1E3A8A; color: #E0F2FE; padding: 10px 15px; border-radius: ${BORDER_RADIUS}; margin-bottom: ${SECTION_MARGIN_BOTTOM}; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); } .highlight { color: #A78BFA; font-weight: bold; } /* 输入框样式 */ #question-input { width: 95%; height: 70px; /* 增加高度 */ padding: 8px; margin-bottom: 10px; border: 1px solid #4A5568; border-radius: ${BORDER_RADIUS}; background-color: #1E293B; color: #CBD5E1; font-size: 14px; resize: vertical; /* 允许垂直方向调整大小 */ outline: none; transition: border-color 0.3s ease; } #question-input:focus { border-color: #6366F1; box-shadow: 0 0 5px rgba(79, 70, 229, 0.5); } /* 设置界面样式 */ #settings-container { padding: 20px; } #settings-container label { display: block; margin-bottom: 5px; color: ${HEADING_COLOR}; } #settings-container input[type="text"] { width: 100%; padding: 8px; margin-bottom: 15px; border: 1px solid #4A5568; border-radius: ${BORDER_RADIUS}; background-color: #1E293B; color: #CBD5E1; font-size: 14px; outline: none; transition: border-color 0.3s ease; } #settings-container input[type="text"]:focus { border-color: #6366F1; box-shadow: 0 0 5px rgba(79, 70, 229, 0.5); } #settings-container button, #ask-button { background-color: #4F46E5; border: none; color: white; padding: 10px 20px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; cursor: pointer; border-radius: ${BORDER_RADIUS}; box-shadow: ${BOX_SHADOW}; transition: background-color 0.3s ease; margin-top: 5px; /* 按钮间距 */ margin-bottom: 10px; } #settings-container button:hover, #ask-button:hover { background-color: #6366F1; } /* 结果和分析过程样式 */ .result-section { margin-bottom: ${SECTION_MARGIN_BOTTOM}; border-bottom: 1px solid #475569; padding-bottom: 15px; } .result-section h3 { color: ${HEADING_COLOR}; margin-bottom: 10px; } .result-section p { line-height: 1.6; } /* 复选框样式 */ #use-history { margin-right: 5px; } .checkbox-label { color: ${HEADING_COLOR}; display: inline-flex; align-items: center; margin-bottom: 10px; cursor: pointer; } `; GM_addStyle(styleString); // --------------------- HELPER FUNCTIONS --------------------- // 安全的 JSON 解析函数 function safeJsonParse(str) { try { return JSON.parse(str); } catch (e) { console.error("JSON 解析错误:", e, "原始字符串:", str); return null; } } /** * 尝试从包含额外文本的字符串中提取JSON。 * 优先查找Markdown代码块(```json或```), * 然后从提取出的代码块内容(或原始字符串)中,再查找第一个 `{` 和最后一个 `}` 之间的内容。 * 这样可以处理模型在代码块内部或外部添加额外文本的情况。 */ function extractJsonFromString(text) { let jsonCandidate = text; // 初始候选项是整个文本 // 1. 尝试从 Markdown 代码块中提取内容 // 优先匹配 ```json 代码块 let match = text.match(/```json\s*([\s\S]*?)```/); if (match && match[1]) { jsonCandidate = match[1].trim(); console.log("JSON extracted from ```json``` block initially:", jsonCandidate); } else { // 如果没有 ```json,尝试匹配通用 ``` 代码块 match = text.match(/```\s*([\s\S]*?)```/); if (match && match[1]) { jsonCandidate = match[1].trim(); console.log("JSON extracted from generic ``` block initially:", jsonCandidate); } } // 2. 从当前 jsonCandidate 中(可能是原始文本,也可能是代码块内容) // 再次查找第一个 '{' 和最后一个 '}' 之间的内容,以确保只获取JSON对象。 const firstBrace = jsonCandidate.indexOf('{'); const lastBrace = jsonCandidate.lastIndexOf('}'); if (firstBrace !== -1 && lastBrace !== -1 && firstBrace < lastBrace) { const finalJsonString = jsonCandidate.substring(firstBrace, lastBrace + 1); console.log("Final JSON string (after brace extraction):", finalJsonString); return finalJsonString; } // 如果以上方法都失败,返回原始的 jsonCandidate (可能是整个文本,也可能是代码块内容), // 此时 safeJsonParse 可能会失败,但这是最接近的猜测了。 console.warn("Could not find structured JSON content ({...}) within candidate, returning raw candidate."); return jsonCandidate; } // 从 Deno 服务获取showurl async function fetchShowUrl(workId) { try { const response = await new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: "GET", url: `${DENO_SERVER_URL}/query?id=${workId}`, onload: resolve, onerror: reject, }); }); if (response.status === 200) { const data = safeJsonParse(response.responseText); if (data?.showurl) { SHOW_URL = data.showurl; console.log("SHOW_URL 获取成功:", SHOW_URL); } else { throw new Error(`Deno server 返回无效数据: ${response.responseText}`); } } else { throw new Error(`Deno server 查询失败: ${response.status} ${response.responseText}`); } } catch (error) { console.error("获取 SHOW_URL 失败:", error); analysisContainer.innerHTML = `<p style="color: red;">初始化出错:${error.message}</p>`; //直接在UI显示 throw error; // Re-throw the error to be caught by the caller } } // 分析 HTML 并发送到 Deno 服务 async function analyzeHTML(htmlContent, question, previousResults = []) { analysisContainer.classList.add('loading'); analysisContainer.innerHTML = '分析中,请稍候...'; if (!GEMINI_API_KEY || !GEMINI_MODEL) { analysisContainer.innerHTML = `<p style="color: red;">请先设置 ${SHOW_URL} API key 和 Model. <a href="${SHOW_URL}" target="_blank">获取地址</a></p>`; analysisContainer.classList.remove('loading'); return; } // 构造 Prompt,包含历史数据 let fullPrompt = `用户提问:${question}\n\n`; if (previousResults && previousResults.length > 0) { fullPrompt += `\n\n历史分析数据 (最近 ${previousResults.length} 条):\n${JSON.stringify(previousResults)}`; } fullPrompt += `\n\n当前页面HTML内容:\n${htmlContent}`; const payload = { modelName: GEMINI_MODEL, modelKey: GEMINI_API_KEY, promptId: ANALYSIS_WORK_ID, userData: fullPrompt }; try { const response = await new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: "POST", url: `${DENO_SERVER_URL}/api`, headers: { "Content-Type": "application/json" }, data: JSON.stringify(payload), onload: resolve, onerror: reject, }); }); if (response.status === 200) { const outerResult = safeJsonParse(response.responseText); console.log("Outer Result:", outerResult); if (outerResult && outerResult.choices && outerResult.choices[0] && outerResult.choices[0].message && outerResult.choices[0].message.content) { let rawModelResponse = outerResult.choices[0].message.content; console.log("Raw Model Response (from choices[0].message.content):", rawModelResponse); // --- 关键修改部分:提取和解析JSON --- const cleanedJsonCandidate = extractJsonFromString(rawModelResponse); const analysisResult = safeJsonParse(cleanedJsonCandidate); // --- 关键修改部分结束 --- if (analysisResult) { console.log("Parsed Analysis Result:", analysisResult); analysisContainer.innerHTML = ''; displayAnalysis(analysisResult); currentAnalysisResult = analysisResult; // 保存当前分析结果 questionHistory.push({ question: question, result: analysisResult }); // 添加到提问历史 if (questionHistory.length > HISTORY_DATA_COUNT) { questionHistory.shift(); // 移除最早的记录 } displayQuestionInput(); // 重新显示提问输入框 (合并后的输入框) } else { analysisContainer.innerHTML = `<p style="color: red;">分析结果JSON解析失败。请检查大模型返回内容格式是否正确。</p><pre>${cleanedJsonCandidate}</pre>`; console.error("Analysis result JSON parse failed. Cleaned candidate:", cleanedJsonCandidate); } } else { analysisContainer.innerHTML = '<p style="color: red;">分析结果格式不正确 (缺少 choices[0].message.content)。</p>'; console.error("Incorrect response format. Missing expected fields."); } } else { analysisContainer.innerHTML = `<p style="color: red;">分析失败: ${response.status} - ${response.statusText}. 请检查API密钥、网络和 Deno 服务。</p>`; console.error("Deno Server Error:", response.status, response.statusText, response.responseText); } } catch (error) { analysisContainer.classList.remove('loading'); analysisContainer.innerHTML = `<p style="color: red;">分析失败, 网络错误: ${error.message}. 请检查Deno服务是否可以正常访问。 SHOW_URL:<a href="${SHOW_URL}" target="_blank">服务地址</a></p>`; console.error("analyzeHTML error:", error, error.message); } finally { analysisContainer.classList.remove('loading'); } } // 显示分析结果的函数,分为“结果”和“分析过程” function displayAnalysis(analysisResult) { try { const { "结果": finalResult, "分析过程": analysisProcess } = analysisResult || {}; let htmlContent = ''; if (finalResult) { htmlContent += ` <div class="result-section"> <h3>分析结果</h3> <p>${finalResult}</p> </div> `; } if (analysisProcess) { htmlContent += ` <div class="result-section"> <h3>分析过程</h3> <p>${analysisProcess}</p> </div> `; } htmlContent += `<p style="text-align: right; font-size: 0.8em;">Powered By 【${GEMINI_MODEL}】 脚本版本:${S_version}</p>`; analysisContainer.innerHTML = htmlContent; // 更新容器内容 } catch (error) { console.error("displayAnalysis error:", error); analysisContainer.innerHTML = `<p style="color: red;">显示分析结果时出错: ${error.message}</p>`; } } // 显示合并后的提问/追问输入框和按钮 function displayQuestionInput() { const questionInput = document.createElement('textarea'); questionInput.id = 'question-input'; questionInput.placeholder = '输入你的问题或追问...'; const useHistoryCheckbox = document.createElement('input'); useHistoryCheckbox.type = 'checkbox'; useHistoryCheckbox.id = 'use-history'; const checkboxLabel = document.createElement('label'); checkboxLabel.className = 'checkbox-label'; checkboxLabel.htmlFor = 'use-history'; // Corrected this line checkboxLabel.textContent = '基于历史数据追问'; const askButton = document.createElement('button'); askButton.id = 'ask-button'; askButton.textContent = '提问/追问'; const checkboxContainer = document.createElement('div'); // 创建一个包含复选框和标签的容器 checkboxContainer.appendChild(useHistoryCheckbox); checkboxContainer.appendChild(checkboxLabel); analysisContainer.appendChild(questionInput); analysisContainer.appendChild(checkboxContainer); // 添加复选框容器 analysisContainer.appendChild(askButton); askButton.addEventListener('click', () => { const question = questionInput.value.trim(); if (question) { latestQuestion = question; let previousResults = []; if (useHistoryCheckbox.checked) { previousResults = questionHistory.map(item => item.result).slice(-10); // 获取最近10条历史结果 } analysisContainer.innerHTML = ''; // 清空容器 analyzeHTML(document.body.innerHTML, question, previousResults); // 发送问题和页面内容 } else { alert('请输入你的问题'); } }); } // 初始化设置界面 function initializeSettings() { analysisContainer.innerHTML = ''; // Clear the analysis container const settingsContainer = document.createElement('div'); settingsContainer.id = 'settings-container'; analysisContainer.appendChild(settingsContainer); // API Key 输入框 const apiKeyLabel = document.createElement('label'); apiKeyLabel.textContent = `${SHOW_URL} API Key:`; settingsContainer.appendChild(apiKeyLabel); const apiKeyInput = document.createElement('input'); apiKeyInput.type = 'text'; apiKeyInput.value = GEMINI_API_KEY; settingsContainer.appendChild(apiKeyInput); // Model 名称输入框 const modelLabel = document.createElement('label'); modelLabel.textContent = `${SHOW_URL} Model Name:`; settingsContainer.appendChild(modelLabel); const modelInput = document.createElement('input'); modelInput.type = 'text'; modelInput.value = GEMINI_MODEL; settingsContainer.appendChild(modelInput); // work id 名称输入框 const workidLabel = document.createElement('label'); workidLabel.textContent = `WORK ID(详见:${DENO_SERVER_URL}):`; settingsContainer.appendChild(workidLabel); const workidInput = document.createElement('input'); workidInput.type = 'text'; workidInput.value = ANALYSIS_WORK_ID; settingsContainer.appendChild(workidInput); // 保存按钮 const saveButton = document.createElement('button'); saveButton.textContent = '保存设置'; settingsContainer.appendChild(saveButton); saveButton.addEventListener('click', async () => { async function setValueWithPromise(key, value) { return new Promise((resolve, reject) => { GM_setValue(key, value); resolve(); // GM_setValue 没有错误回调,直接 resolve }); } const newApiKey = apiKeyInput.value.trim(); const newModel = modelInput.value.trim(); const newWrokId = workidInput.value.trim(); if (newApiKey !== "" && newModel !== "" && newWrokId !== "") { await setValueWithPromise('GEMINI_API_KEY', newApiKey); // 等待 setValue 完成 GEMINI_API_KEY = newApiKey; // 更新全局变量 await setValueWithPromise('GEMINI_MODEL', newModel); // 等待 setValue 完成 GEMINI_MODEL = newModel; // 更新全局变量 await setValueWithPromise('ANALYSIS_WORK_ID', newWrokId); // 等待 setValue 完成 ANALYSIS_WORK_ID = newWrokId; // 更新全局变量 analysisContainer.innerHTML = '<p style="color: green;">设置已保存,脚本正在重新初始化...</p>'; // 代码 (async () => { // 重新初始化分析容器 analysisContainer.innerHTML = '<p style="text-align: center; font-size: 15px; color: white;">正在重新初始化...</p>'; try { await fetchShowUrl(ANALYSIS_WORK_ID); analysisContainer.innerHTML = ''; displayQuestionInput(); } catch (error) { analysisContainer.innerHTML = `<p style="color: red;">重新初始化出错,请检查控制台</p>`; } })(); } else { analysisContainer.innerHTML = '<p style="color: red;">API 密钥和模型名称不能为空。</p>'; } }); } // --------------------- INITIALIZATION --------------------- (function() { if (window.self !== window.top) { console.log("脚本在 iframe 中运行,已阻止初始化。"); return; } if (window.hasEastMoneyAnalysisAssistant) { console.log("脚本已经初始化过了,已阻止重复初始化。"); return; } window.hasEastMoneyAnalysisAssistant = true; console.log("脚本开始初始化..."); (async function initialize() { analysisContainer = document.createElement('div'); analysisContainer.id = 'analysis-container'; document.body.appendChild(analysisContainer); const analysisButton = document.createElement('button'); analysisButton.id = 'analysis-button'; analysisButton.textContent = 'AI算卦助手'; document.body.appendChild(analysisButton); analysisButton.addEventListener('click', () => { // 添加切换显示/隐藏状态的逻辑 analysisContainer.classList.toggle('hidden'); }); try { await fetchShowUrl(ANALYSIS_WORK_ID); } catch (error) { analysisContainer.innerHTML = `<p style="color: red;">初始化出错,请检查控制台</p>`; } if(analysisContainer.classList.contains('hidden')){ console.log("分析面板处于隐藏状态,跳过输入框的渲染"); return; } try{ analysisContainer.innerHTML = ''; // 初始化时清空内容 displayQuestionInput(); // 显示问题输入框 } catch(error) { analysisContainer.innerHTML = `<p style="color: red;">显示问题输入框出错:${error.message}</p>`; console.error("Failed to display question input:", error); } })(); GM_registerMenuCommand("设置API密钥和模型", () => { initializeSettings(); }); })(); console.log("脚本初始化完成。"); })();