第74批:简易agent工具调用+DeepSeek联网搜索/抓取+背包堆叠setItem写回+知识诚实条款
Auto Release / build (push) Successful in 2m26s
Auto Release / build (push) Successful in 2m26s
This commit is contained in:
@@ -116,6 +116,10 @@ public class AIChatManager {
|
||||
boolean isCustom; // true=自定义供应商(受自动补齐开关控制), false=内置供应商(总是拼接)
|
||||
}
|
||||
|
||||
// ★ 第74批:DeepSeek API key(用于联网搜索/抓取,与聊天 API 共用 key)
|
||||
// 在 loadConfig 时自动从模型接口配置中提取 DeepSeek 供应商的 key
|
||||
private String deepseekApiKey = "";
|
||||
|
||||
public AIChatManager(Main plugin) {
|
||||
this.plugin = plugin;
|
||||
this.httpClient = HttpClient.newBuilder()
|
||||
@@ -442,6 +446,14 @@ public class AIChatManager {
|
||||
continue;
|
||||
}
|
||||
|
||||
// ★ 第74批:自动提取 DeepSeek API key(用于联网搜索/抓取)
|
||||
// DeepSeek Search/Fetch API 与聊天 API 共用同一个 key
|
||||
// 只需检查 baseUrl 是否包含 api.deepseek.com
|
||||
if (deepseekApiKey.isEmpty() && baseUrl.contains("api.deepseek.com") && !apiKey.isEmpty()) {
|
||||
deepseekApiKey = apiKey;
|
||||
if (!quiet) plugin.getLogger().info("[AI聊天-Agent] 已提取 DeepSeek API key,联网搜索可用");
|
||||
}
|
||||
|
||||
// 存储原始 baseUrl(尾斜杠统一在发送时按自动补齐开关处理)
|
||||
ModelEndpoint endpoint = new ModelEndpoint();
|
||||
endpoint.baseUrl = baseUrl;
|
||||
@@ -765,7 +777,9 @@ public class AIChatManager {
|
||||
|
||||
// 构建请求体
|
||||
String systemPrompt = buildSystemPrompt();
|
||||
String jsonBody = buildChatRequest(modelFull, systemPrompt, prompt, endpoint.maxToken);
|
||||
// ★ 第74批:agent 工具说明追加到 systemPrompt
|
||||
String agentPrompt = buildAgentPrompt();
|
||||
String jsonBody = buildChatRequest(modelFull, systemPrompt + "\n" + agentPrompt, prompt, endpoint.maxToken);
|
||||
String requestUrl = buildRequestUrl(endpoint);
|
||||
|
||||
// ★ 400调试日志:请求发出前打印完整信息
|
||||
@@ -864,6 +878,64 @@ public class AIChatManager {
|
||||
return;
|
||||
}
|
||||
|
||||
// ★ 第74批:agent 工具调用循环
|
||||
// 模型回复含 "TOOL:SEARCH:关键词" 标记 → 联网搜索 → 追加结果再请求一次
|
||||
// 模型回复含 "TOOL:FETCH:URL" 标记 → 抓取该页面 → 追加内容再请求一次
|
||||
// 最多循环 2 轮,防止死循环
|
||||
int agentRound = 0;
|
||||
while (agentRound < 2) {
|
||||
ToolCall call = extractToolCall(reply);
|
||||
if (call == null) break;
|
||||
|
||||
plugin.getLogger().info("[AI聊天-Agent] 第" + (agentRound + 1) + "轮工具调用: " + call.type + " \"" + call.arg + "\"");
|
||||
String toolResults;
|
||||
if (call.type == ToolCall.Type.FETCH) {
|
||||
toolResults = WebSearchTool.fetchUrl(call.arg, deepseekApiKey);
|
||||
} else {
|
||||
toolResults = WebSearchTool.search(call.arg, deepseekApiKey);
|
||||
}
|
||||
if (toolResults == null) {
|
||||
plugin.getLogger().info("[AI聊天-Agent] 工具调用无结果,告知模型无法获取");
|
||||
reply = reply.replace("TOOL:" + call.type.name() + ":" + call.arg, "");
|
||||
// 追加说明让模型知道工具调用失败了,基于"不知道"回答
|
||||
reply = reply + "\n(系统提示:联网查询未获取到相关信息,请如实告知玩家你不知道。)";
|
||||
break;
|
||||
}
|
||||
|
||||
plugin.getLogger().info("[AI聊天-Agent] 工具结果: " + toolResults.substring(0, Math.min(100, toolResults.length())) + "...");
|
||||
|
||||
// 构建第二轮请求:原问题 + 工具结果 + 让模型基于结果回答
|
||||
String toolLabel = call.type == ToolCall.Type.FETCH ? "联网抓取结果" : "联网搜索结果";
|
||||
String followUpPrompt = "【玩家原始问题】\n" + prompt
|
||||
+ "\n\n【" + toolLabel + "】\n" + toolResults
|
||||
+ "\n\n请基于以上信息回答玩家的问题。如果信息不相关,就如实说不知道。";
|
||||
String followUpJson = buildChatRequest(finalModelFull, systemPrompt + "\n" + agentPrompt, followUpPrompt, endpoint.maxToken);
|
||||
|
||||
try {
|
||||
HttpRequest followUp = HttpRequest.newBuilder()
|
||||
.uri(URI.create(requestUrl))
|
||||
.header("Content-Type", "application/json; charset=utf-8")
|
||||
.header("Authorization", "Bearer " + endpoint.apiKey)
|
||||
.POST(HttpRequest.BodyPublishers.ofString(followUpJson, StandardCharsets.UTF_8))
|
||||
.timeout(Duration.ofSeconds(60))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> followUpResp = httpClient.send(followUp, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
if (followUpResp.statusCode() != 200) {
|
||||
plugin.getLogger().warning("[AI聊天-Agent] 第" + (agentRound + 1) + "轮请求失败: HTTP " + followUpResp.statusCode());
|
||||
break;
|
||||
}
|
||||
String followUpReply = parseChatResponse(followUpResp.body());
|
||||
if (followUpReply == null) break;
|
||||
// 过滤掉回复中可能残留的标记
|
||||
reply = followUpReply.replaceAll("TOOL:(SEARCH|FETCH):.*", "").trim();
|
||||
} catch (Exception e) {
|
||||
plugin.getLogger().warning("[AI聊天-Agent] 第" + (agentRound + 1) + "轮请求异常: " + e.getMessage());
|
||||
break;
|
||||
}
|
||||
agentRound++;
|
||||
}
|
||||
|
||||
// ★ 第69批-问题2:回复输出守卫(双保险),拦截代码块/破甲泄露
|
||||
reply = sanitizeReply(reply);
|
||||
|
||||
@@ -973,6 +1045,10 @@ public class AIChatManager {
|
||||
sb.append(" 现实人物、其它平台的玩家名),一律当作「本服务器之外的事」婉拒,\n");
|
||||
sb.append(" 不要猜测它的含义、不要尝试解释。例如玩家问「nighx是什么意思」,\n");
|
||||
sb.append(" 你只回答「我不认识这些外面的词呢,咱们聊聊服务器里的事?」\n");
|
||||
sb.append("7. ★ 知识诚实(防止编造)★ 游戏里的细节(合成配方、方块用途、版本变化、\n");
|
||||
sb.append(" 模组玩法等),你如果不确定,绝对不要凭记忆编造一个看似合理的答案。\n");
|
||||
sb.append(" 不确定时,你可以使用工具标记(见下方工具调用说明)联网查询后再回答,\n");
|
||||
sb.append(" 或者直接说「这个我还不太清楚」。编造错误信息比承认不知道糟糕得多。");
|
||||
|
||||
// ★ 第67批:安全约束(防破甲/防代码输出)
|
||||
sb.append("\n【安全约束】\n");
|
||||
@@ -986,6 +1062,76 @@ public class AIChatManager {
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ 第74批:agent 工具说明(追加到 systemPrompt)。
|
||||
* <p>
|
||||
* 告知模型:遇到不确定的游戏细节时,可以在回复开头加特殊标记,
|
||||
* 系统会自动联网搜索/抓取并把结果回传,然后重新请求一次让模型基于结果回答。
|
||||
*/
|
||||
private String buildAgentPrompt() {
|
||||
return "\n【工具调用(第74批)】\n"
|
||||
+ "如果你不确定某个游戏细节(比如某个方块的合成配方、某个版本新增的内容、\n"
|
||||
+ "某个模组的玩法),不要凭记忆编造。你可以在回复开头加上特殊标记:\n"
|
||||
+ "TOOL:SEARCH:搜索关键词\n"
|
||||
+ "系统会自动联网搜索,把结果回传给你,你再基于搜索结果回答。\n"
|
||||
+ "如果你知道一个具体网页地址想读全文,可以用:\n"
|
||||
+ "TOOL:FETCH:https://example.com\n"
|
||||
+ "系统会抓取该页面内容返回给你。\n"
|
||||
+ "注意:\n"
|
||||
+ "1. 只有你确实不确定、怕答错的时候才用这些标记。\n"
|
||||
+ "2. 日常聊天、你确定的事、拒答外部话题时,不要用这些标记。\n"
|
||||
+ "3. 标记格式必须严格是 TOOL:SEARCH:关键词 或 TOOL:FETCH:URL。\n"
|
||||
+ "4. 如果搜索/抓取也找不到答案,就老实告诉玩家「这个我还不太清楚」,\n"
|
||||
+ " 绝对不要编造。";
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ 第74批:agent 工具调用描述。
|
||||
* type=SEARCH → arg=搜索关键词;type=FETCH → arg=URL
|
||||
*/
|
||||
static class ToolCall {
|
||||
enum Type { SEARCH, FETCH }
|
||||
Type type;
|
||||
String arg;
|
||||
ToolCall(Type type, String arg) { this.type = type; this.arg = arg; }
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ 第74批:从模型回复中提取 TOOL:SEARCH: 或 TOOL:FETCH: 标记。
|
||||
*
|
||||
* @return ToolCall 对象;无标记返回 null
|
||||
*/
|
||||
private ToolCall extractToolCall(String reply) {
|
||||
if (reply == null) return null;
|
||||
|
||||
// 优先匹配 FETCH(含 URL 特征),再匹配 SEARCH
|
||||
// TOOL:FETCH:https://...
|
||||
int fetchIdx = reply.indexOf("TOOL:FETCH:");
|
||||
if (fetchIdx >= 0) {
|
||||
String after = reply.substring(fetchIdx + "TOOL:FETCH:".length()).trim();
|
||||
int newline = after.indexOf('\n');
|
||||
if (newline >= 0) after = after.substring(0, newline).trim();
|
||||
after = after.replaceAll("[。,、!?.!?,)$\\]]$", "").trim();
|
||||
// URL 校验:必须含 http
|
||||
if (after.startsWith("http") && after.length() <= 2000) {
|
||||
return new ToolCall(ToolCall.Type.FETCH, after);
|
||||
}
|
||||
}
|
||||
|
||||
// TOOL:SEARCH:关键词
|
||||
int idx = reply.indexOf("TOOL:SEARCH:");
|
||||
if (idx >= 0) {
|
||||
String after = reply.substring(idx + "TOOL:SEARCH:".length()).trim();
|
||||
int newline = after.indexOf('\n');
|
||||
if (newline >= 0) after = after.substring(0, newline).trim();
|
||||
after = after.replaceAll("[。,、!?.!?,]$", "").trim();
|
||||
if (!after.isEmpty() && after.length() <= 100) {
|
||||
return new ToolCall(ToolCall.Type.SEARCH, after);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ 第69批-问题2:回复输出守卫(双保险)。
|
||||
* 提示词可能挡不住的,代码端兜底:
|
||||
@@ -1488,7 +1634,7 @@ public class AIChatManager {
|
||||
// 状态变化(失败→成功 或 成功→失败)时记一条恢复/告警
|
||||
|
||||
// 异步发送
|
||||
String systemPrompt = buildSystemPrompt();
|
||||
String systemPrompt = buildSystemPrompt() + "\n" + buildAgentPrompt();
|
||||
String jsonBody = buildChatRequest(defaultModelFull, systemPrompt, prompt, endpoint.maxToken);
|
||||
String requestUrl = buildRequestUrl(endpoint);
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import org.bukkit.event.entity.EntityPickupItemEvent;
|
||||
import org.bukkit.event.inventory.CraftItemEvent;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.inventory.InventoryDragEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
|
||||
@@ -423,9 +424,29 @@ public class StackConfigManager implements Listener {
|
||||
// 导致箱子里的 64 组苹果永远没有 max 组件,叠加上不去。
|
||||
// 点击事件在 LOWEST 优先级最先执行,meta 写完后
|
||||
// 服务端才执行实际的合并堆叠逻辑,因此生效。
|
||||
boolean changed = applyStackSize(e.getCurrentItem());
|
||||
changed |= applyStackSize(e.getCursor());
|
||||
if (changed) logApplyThrottled(e.getCurrentItem(), e.getCursor());
|
||||
//
|
||||
// ★ 第74批:玩家背包(CraftInventoryPlayer)的 getCurrentItem() 返回
|
||||
// 副本而非底层数组引用——改副本无效,服务端合并时读底层数组
|
||||
// (max=64)→ 背包里堆叠不上。箱子等容器返回引用,改即生效。
|
||||
// 因此修改后必须显式 setItem() 写回槽位、setCursor() 写回光标。
|
||||
Inventory clicked = e.getClickedInventory();
|
||||
if (clicked == null) return; // 第67批 NPE 修复
|
||||
|
||||
boolean changed = false;
|
||||
|
||||
ItemStack current = e.getCurrentItem();
|
||||
if (current != null && applyStackSize(current)) {
|
||||
changed = true;
|
||||
clicked.setItem(e.getRawSlot(), current);
|
||||
}
|
||||
|
||||
ItemStack cursor = e.getCursor();
|
||||
if (cursor != null && applyStackSize(cursor)) {
|
||||
changed = true;
|
||||
e.setCursor(cursor);
|
||||
}
|
||||
|
||||
if (changed) logApplyThrottled(current, cursor);
|
||||
}
|
||||
|
||||
/** 应用堆叠上限时记日志(30秒节流,防刷屏) */
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
package Sdf1_login;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 联网搜索工具(第74批,2026-11-03)。
|
||||
* <p>
|
||||
* 提供两种搜索后端:
|
||||
* <ul>
|
||||
* <li><b>DeepSeek Search API</b>(优先):POST https://api.deepseek.com/v1/tools/search
|
||||
* 与聊天 API 共用 Bearer key,返回结构化 JSON(title/url/snippet/summary/content)。</li>
|
||||
* <li><b>DuckDuckGo HTML</b>(兜底):无需 API key,解析 HTML 搜索结果页。</li>
|
||||
* </ul>
|
||||
* 同时提供 DeepSeek Fetch API(POST /v1/tools/fetch)抓取单页 URL 返回 Markdown。
|
||||
* <p>
|
||||
* 由 AIChatManager 的简易 agent 循环调用。
|
||||
*/
|
||||
public class WebSearchTool {
|
||||
|
||||
private static final int MAX_RESULTS = 5;
|
||||
private static final int TIMEOUT_MS = 10000;
|
||||
private static final String USER_AGENT =
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
|
||||
|
||||
private static final String DEEPSEEK_SEARCH_URL = "https://api.deepseek.com/v1/tools/search";
|
||||
private static final String DEEPSEEK_FETCH_URL = "https://api.deepseek.com/v1/tools/fetch";
|
||||
|
||||
/**
|
||||
* 联网搜索,返回摘要结果文本。
|
||||
* 优先用 DeepSeek Search API(如果有 key),否则回退到 DuckDuckGo HTML。
|
||||
*
|
||||
* @param query 搜索关键词
|
||||
* @param apiKey DeepSeek API key(可为 null/空,则回退 DDG)
|
||||
* @return 搜索结果摘要文本;全部失败返回 null
|
||||
*/
|
||||
public static String search(String query, String apiKey) {
|
||||
if (query == null || query.trim().isEmpty()) return null;
|
||||
|
||||
// 优先:DeepSeek Search API
|
||||
if (apiKey != null && !apiKey.isEmpty()) {
|
||||
String dsResult = deepseekSearch(query, apiKey);
|
||||
if (dsResult != null) return dsResult;
|
||||
}
|
||||
|
||||
// 兜底:DuckDuckGo HTML
|
||||
return duckDuckGoSearch(query);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用 DeepSeek Search API 搜索。
|
||||
* POST https://api.deepseek.com/v1/tools/search
|
||||
* Body: {"query":"...","count":5,"need_content":true}
|
||||
* Response: {"results":[{"title":"...","url":"...","snippet":"...","summary":"...","content":"..."}]}
|
||||
*/
|
||||
private static String deepseekSearch(String query, String apiKey) {
|
||||
try {
|
||||
String body = "{\"query\":\"" + escapeJson(query)
|
||||
+ "\",\"count\":" + MAX_RESULTS + ",\"need_content\":true}";
|
||||
|
||||
HttpURLConnection conn = (HttpURLConnection) new URL(DEEPSEEK_SEARCH_URL).openConnection();
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setRequestProperty("Authorization", "Bearer " + apiKey);
|
||||
conn.setRequestProperty("Content-Type", "application/json");
|
||||
conn.setConnectTimeout(TIMEOUT_MS);
|
||||
conn.setReadTimeout(TIMEOUT_MS);
|
||||
conn.setDoOutput(true);
|
||||
|
||||
java.io.OutputStreamWriter w = new java.io.OutputStreamWriter(
|
||||
conn.getOutputStream(), StandardCharsets.UTF_8);
|
||||
w.write(body);
|
||||
w.close();
|
||||
|
||||
int code = conn.getResponseCode();
|
||||
if (code != 200) {
|
||||
// 读取错误体用于诊断
|
||||
String err = readErrorBody(conn);
|
||||
return null; // 回退到 DDG
|
||||
}
|
||||
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
|
||||
StringBuilder resp = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
resp.append(line);
|
||||
}
|
||||
reader.close();
|
||||
conn.disconnect();
|
||||
|
||||
JsonObject json = JsonParser.parseString(resp.toString()).getAsJsonObject();
|
||||
if (!json.has("results")) return null;
|
||||
|
||||
JsonArray results = json.getAsJsonArray("results");
|
||||
if (results.size() == 0) return null;
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("搜索结果(共").append(results.size()).append("条):\n");
|
||||
int n = Math.min(results.size(), MAX_RESULTS);
|
||||
for (int i = 0; i < n; i++) {
|
||||
JsonObject item = results.get(i).getAsJsonObject();
|
||||
String title = item.has("title") ? item.get("title").getAsString() : "无标题";
|
||||
String snippet = item.has("snippet") ? item.get("snippet").getAsString() : "";
|
||||
String summary = item.has("summary") ? item.get("summary").getAsString() : "";
|
||||
String content = item.has("content") ? item.get("content").getAsString() : "";
|
||||
|
||||
sb.append(i + 1).append(". ").append(title).append("\n");
|
||||
if (!snippet.isEmpty()) sb.append(" 摘要: ").append(snippet).append("\n");
|
||||
if (!summary.isEmpty()) sb.append(" 总结: ").append(summary).append("\n");
|
||||
if (!content.isEmpty()) sb.append(" 内容: ").append(content.substring(0, Math.min(500, content.length()))).append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用 DeepSeek Fetch API 抓取单个 URL,返回 Markdown 内容。
|
||||
* POST https://api.deepseek.com/v1/tools/fetch
|
||||
* Body: {"url":"..."}
|
||||
* Response: {"title":"...","content":"Markdown..."}
|
||||
*/
|
||||
public static String fetchUrl(String url, String apiKey) {
|
||||
if (url == null || url.isEmpty() || apiKey == null || apiKey.isEmpty()) return null;
|
||||
try {
|
||||
String body = "{\"url\":\"" + escapeJson(url) + "\"}";
|
||||
|
||||
HttpURLConnection conn = (HttpURLConnection) new URL(DEEPSEEK_FETCH_URL).openConnection();
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setRequestProperty("Authorization", "Bearer " + apiKey);
|
||||
conn.setRequestProperty("Content-Type", "application/json");
|
||||
conn.setConnectTimeout(TIMEOUT_MS);
|
||||
conn.setReadTimeout(TIMEOUT_MS);
|
||||
conn.setDoOutput(true);
|
||||
|
||||
java.io.OutputStreamWriter w = new java.io.OutputStreamWriter(
|
||||
conn.getOutputStream(), StandardCharsets.UTF_8);
|
||||
w.write(body);
|
||||
w.close();
|
||||
|
||||
int code = conn.getResponseCode();
|
||||
if (code != 200) return null;
|
||||
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
|
||||
StringBuilder resp = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
resp.append(line);
|
||||
}
|
||||
reader.close();
|
||||
conn.disconnect();
|
||||
|
||||
JsonObject json = JsonParser.parseString(resp.toString()).getAsJsonObject();
|
||||
String title = json.has("title") ? json.get("title").getAsString() : "";
|
||||
String content = json.has("content") ? json.get("content").getAsString() : "";
|
||||
if (content.isEmpty()) return null;
|
||||
return title.isEmpty() ? content : title + "\n\n" + content;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** DuckDuckGo HTML 搜索兜底 */
|
||||
private static String duckDuckGoSearch(String query) {
|
||||
try {
|
||||
String encoded = URLEncoder.encode(query, StandardCharsets.UTF_8.name());
|
||||
String url = "https://html.duckduckgo.com/html/?q=" + encoded;
|
||||
|
||||
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setRequestProperty("User-Agent", USER_AGENT);
|
||||
conn.setRequestProperty("Accept", "text/html");
|
||||
conn.setConnectTimeout(TIMEOUT_MS);
|
||||
conn.setReadTimeout(TIMEOUT_MS);
|
||||
|
||||
int code = conn.getResponseCode();
|
||||
if (code != 200) return null;
|
||||
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
|
||||
StringBuilder html = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
html.append(line).append("\n");
|
||||
}
|
||||
reader.close();
|
||||
conn.disconnect();
|
||||
|
||||
return parseDdgResults(html.toString());
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 解析 DuckDuckGo HTML 搜索结果页 */
|
||||
private static String parseDdgResults(String html) {
|
||||
List<String> titles = new ArrayList<>();
|
||||
List<String> snippets = new ArrayList<>();
|
||||
|
||||
Pattern titlePattern = Pattern.compile(
|
||||
"<a[^>]*class=\"result__a\"[^>]*>(.*?)</a>", Pattern.DOTALL);
|
||||
Pattern snippetPattern = Pattern.compile(
|
||||
"<a[^>]*class=\"result__snippet\"[^>]*>(.*?)</a>", Pattern.DOTALL);
|
||||
|
||||
Matcher tm = titlePattern.matcher(html);
|
||||
Matcher sm = snippetPattern.matcher(html);
|
||||
|
||||
while (tm.find() && titles.size() < MAX_RESULTS) {
|
||||
titles.add(stripTags(tm.group(1)));
|
||||
}
|
||||
while (sm.find() && snippets.size() < MAX_RESULTS) {
|
||||
snippets.add(stripTags(sm.group(1)));
|
||||
}
|
||||
|
||||
int n = Math.min(titles.size(), snippets.size());
|
||||
if (n == 0) return null;
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("搜索结果(共").append(n).append("条):\n");
|
||||
for (int i = 0; i < n; i++) {
|
||||
sb.append(i + 1).append(". ").append(titles.get(i)).append("\n");
|
||||
sb.append(" ").append(snippets.get(i)).append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/** 读取 HTTP 错误响应体(用于诊断) */
|
||||
private static String readErrorBody(HttpURLConnection conn) {
|
||||
try {
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8));
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
sb.append(line);
|
||||
}
|
||||
reader.close();
|
||||
return sb.toString();
|
||||
} catch (Exception e) {
|
||||
return "(无法读取错误体)";
|
||||
}
|
||||
}
|
||||
|
||||
/** JSON 字符串转义 */
|
||||
private static String escapeJson(String s) {
|
||||
return s.replace("\\", "\\\\")
|
||||
.replace("\"", "\\\"")
|
||||
.replace("\n", "\\n")
|
||||
.replace("\r", "\\r")
|
||||
.replace("\t", "\\t");
|
||||
}
|
||||
|
||||
/** 去除 HTML 标签和转义字符 */
|
||||
private static String stripTags(String html) {
|
||||
return html.replaceAll("<[^>]+>", "")
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll(""", "\"")
|
||||
.replaceAll("'", "'")
|
||||
.replaceAll("'", "'")
|
||||
.replaceAll(" ", " ")
|
||||
.replaceAll("\\s+", " ")
|
||||
.trim();
|
||||
}
|
||||
}
|
||||
@@ -40,13 +40,15 @@
|
||||
"说明": "指标为在线玩家数量,当在线玩家大于等于指标才会触发自动互动。手动不受此影响。此字段为强制值,若你填写的值≤1,则代码仍按1执行。≥1时以此字段配置值为基准"
|
||||
},
|
||||
"黑名单": {
|
||||
"说明":"支持使用双引号字符串,写绝对路径/相对路径引用文件,也支持旧格式。兼容模式和路径2选1,路径>兼容模式。",
|
||||
"路径":"./黑名单",
|
||||
"兼容模式":[
|
||||
"说明": "支持使用双引号字符串,写绝对路径/相对路径引用文件,也支持旧格式。兼容模式和路径2选1,路径>兼容模式。",
|
||||
"路径": "./黑名单",
|
||||
"兼容模式": [
|
||||
"兼容旧模式,一行一个",
|
||||
"命中提前返回"
|
||||
]
|
||||
}
|
||||
],
|
||||
"联网模式": {
|
||||
"说明": "如果填sk-开头的,则默认使用deepseek的接口,填内置/留空则表示使用代码内置的简易agnet抓取",
|
||||
"type": ""
|
||||
}
|
||||
},
|
||||
"填写规范": {
|
||||
@@ -99,4 +101,6 @@
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user