koishi-plugin-phimg2 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Context, Schema } from 'koishi';
2
+ export declare const name = "phimg2";
2
3
  export declare const inject: string[];
3
4
  declare module 'koishi' {
4
5
  interface Tables {
@@ -11,12 +12,11 @@ export interface Config {
11
12
  defaultTags: string[];
12
13
  enabledByDefault: boolean;
13
14
  useGlobalTagsByDefault: boolean;
14
- proxy: string;
15
- timeout: number;
15
+ filterId: number;
16
16
  }
17
17
  export declare const Config: Schema<Config>;
18
18
  interface GroupConfig {
19
- id?: number;
19
+ id: number;
20
20
  groupId: string;
21
21
  enabled: boolean;
22
22
  useGlobalTags: boolean;
package/lib/index.js CHANGED
@@ -1,13 +1,11 @@
1
- var __create = Object.create;
2
1
  var __defProp = Object.defineProperty;
3
2
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
5
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
6
  var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
7
+ for (var name2 in all)
8
+ __defProp(target, name2, { get: all[name2], enumerable: true });
11
9
  };
12
10
  var __copyProps = (to, from, except, desc) => {
13
11
  if (from && typeof from === "object" || typeof from === "function") {
@@ -17,14 +15,6 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
20
  // src/index.ts
@@ -32,12 +22,13 @@ var src_exports = {};
32
22
  __export(src_exports, {
33
23
  Config: () => Config,
34
24
  apply: () => apply,
35
- inject: () => inject
25
+ inject: () => inject,
26
+ name: () => name
36
27
  });
37
28
  module.exports = __toCommonJS(src_exports);
38
29
  var import_koishi = require("koishi");
39
- var import_axios = __toESM(require("axios"));
40
- var inject = ["database"];
30
+ var name = "phimg2";
31
+ var inject = ["database", "http"];
41
32
  var translationTable = {
42
33
  ";": ";",
43
34
  ":": ":",
@@ -59,13 +50,12 @@ function translateText(text) {
59
50
  }
60
51
  __name(translateText, "translateText");
61
52
  var Config = import_koishi.Schema.object({
62
- apiKey: import_koishi.Schema.string().description("Philomena API 密钥").default(""),
63
- apiUrl: import_koishi.Schema.string().description("Philomena API 域名 (例如 derpibooru.org)").default("derpibooru.org"),
53
+ apiKey: import_koishi.Schema.string().description("Philomena API 密钥").role("secret").default(""),
54
+ apiUrl: import_koishi.Schema.string().description("Philomena API 域名 (无需 https://)").default("derpibooru.org"),
64
55
  defaultTags: import_koishi.Schema.array(String).description("全局默认标签").default(["safe"]),
65
56
  enabledByDefault: import_koishi.Schema.boolean().description("新群聊默认启用搜图功能").default(true),
66
57
  useGlobalTagsByDefault: import_koishi.Schema.boolean().description("新群聊默认启用全局标签").default(true),
67
- proxy: import_koishi.Schema.string().description("代理服务器 (例如 http://127.0.0.1:7890)").default(""),
68
- timeout: import_koishi.Schema.number().description("请求超时时间 (秒)").default(30)
58
+ filterId: import_koishi.Schema.number().description("搜索使用的 Filter ID (例如 100073)").default(100073)
69
59
  });
70
60
  function apply(ctx, config) {
71
61
  ctx.model.extend("phimg_config", {
@@ -82,82 +72,72 @@ function apply(ctx, config) {
82
72
  const getGroupConfig = /* @__PURE__ */ __name(async (groupId) => {
83
73
  let [groupConfig] = await ctx.database.get("phimg_config", { groupId });
84
74
  if (!groupConfig) {
85
- groupConfig = await ctx.database.create("phimg_config", {
86
- groupId,
87
- enabled: config.enabledByDefault,
88
- useGlobalTags: config.useGlobalTagsByDefault,
89
- customTags: []
90
- });
75
+ try {
76
+ groupConfig = await ctx.database.create("phimg_config", {
77
+ groupId,
78
+ enabled: config.enabledByDefault,
79
+ useGlobalTags: config.useGlobalTagsByDefault,
80
+ customTags: []
81
+ });
82
+ } catch (e) {
83
+ [groupConfig] = await ctx.database.get("phimg_config", { groupId });
84
+ }
91
85
  }
92
86
  return groupConfig;
93
87
  }, "getGroupConfig");
94
88
  const updateGroupConfig = /* @__PURE__ */ __name(async (groupId, data) => {
89
+ await getGroupConfig(groupId);
95
90
  await ctx.database.set("phimg_config", { groupId }, data);
96
91
  }, "updateGroupConfig");
97
92
  const makeRequest = /* @__PURE__ */ __name(async (method, params) => {
98
- let domain = config.apiUrl;
99
- if (domain.includes("://")) {
100
- domain = domain.split("://")[1];
101
- }
102
- domain = domain.split("/")[0];
103
- const url = `https://${domain}/api/v1/json/search/${method}`;
104
- const axiosConfig = {
105
- headers: {
106
- "Accept": "application/json",
107
- "User-Agent": "Phimg for Koishi"
108
- },
109
- timeout: config.timeout * 1e3
93
+ const host = config.apiUrl.replace(/^https?:\/\//, "").replace(/\/$/, "");
94
+ const endpoint = `https://${host}/api/v1/json/search/${method}`;
95
+ const queryParams = {
96
+ filter_id: config.filterId
110
97
  };
111
- if (config.proxy) {
112
- try {
113
- const urlParsed = new URL(config.proxy);
114
- axiosConfig.proxy = {
115
- host: urlParsed.hostname,
116
- port: parseInt(urlParsed.port),
117
- protocol: urlParsed.protocol.replace(":", "")
118
- };
119
- } catch (e) {
120
- ctx.logger.warn(`Invalid proxy URL: ${config.proxy}`);
121
- }
98
+ if (params.key) {
99
+ queryParams.key = params.key;
100
+ delete params.key;
122
101
  }
123
102
  try {
124
- let response;
103
+ let responseData;
125
104
  if (method === "images") {
126
- response = await import_axios.default.get(url, { ...axiosConfig, params });
105
+ responseData = await ctx.http.get(endpoint, {
106
+ params: { ...queryParams, ...params },
107
+ headers: { "User-Agent": "Phimg for Koishi" }
108
+ });
127
109
  } else {
128
- const formData = new URLSearchParams();
129
- for (const key in params) {
130
- formData.append(key, params[key]);
131
- }
132
- response = await import_axios.default.post(url, formData, axiosConfig);
110
+ responseData = await ctx.http.post(endpoint, params, {
111
+ params: queryParams,
112
+ headers: {
113
+ "User-Agent": "Phimg for Koishi",
114
+ "Content-Type": "application/x-www-form-urlencoded"
115
+ }
116
+ });
133
117
  }
134
- if (!response.data.images || response.data.images.length === 0) {
118
+ if (!responseData.images || responseData.images.length === 0) {
135
119
  throw new Error("未找到匹配的图片");
136
120
  }
137
- return response.data;
121
+ return responseData;
138
122
  } catch (error) {
139
- if (import_axios.default.isAxiosError(error)) {
140
- if (error.response?.status === 404) throw new Error("未找到匹配的图片");
141
- throw new Error(`API 请求失败: ${error.message}`);
142
- }
143
- throw error;
123
+ if (error.response?.status === 404) throw new Error("未找到匹配的图片");
124
+ ctx.logger("phimg").warn(error);
125
+ throw new Error(`${error.message}`);
144
126
  }
145
127
  }, "makeRequest");
146
128
  const VIDEO_TYPES = ["webm", "mp4"];
147
129
  const getMediaElement = /* @__PURE__ */ __name((selected) => {
130
+ if (!selected?.representations) return import_koishi.h.text("图片数据解析错误");
148
131
  const file = selected.representations.full;
149
132
  const url = file.endsWith(".webm") ? selected.representations.medium : selected.representations.large;
150
133
  const fileType = file.split(".").pop()?.toLowerCase() || "";
151
134
  if (VIDEO_TYPES.includes(fileType)) {
152
135
  return import_koishi.h.video(url);
153
- } else {
154
- return import_koishi.h.image(url);
155
136
  }
137
+ return import_koishi.h.image(url);
156
138
  }, "getMediaElement");
157
139
  const searchHelp = `用法: /搜图 [tags|distance]
158
140
 
159
- 输入标签为tags搜图;输入匹配距离为图搜图
160
-
161
141
  可选项:
162
142
  --tags 获取当前群聊内置标签列表
163
143
  --status 获取当前群聊的搜图功能状态
@@ -167,12 +147,8 @@ function apply(ctx, config) {
167
147
  --sd [sd] 排序方向,默认为desc
168
148
  --i [index] 选择结果索引,默认为-1(即随机)
169
149
 
170
- 示例:
171
- /搜图 [tags] # 直接通过标签搜索图片
172
-
173
150
  提示:
174
- 图搜图使用方式为引用图片,默认匹配距离为0.25
175
- 所有参数及变量全部遵循呆站(Philomena系图站)搜索API规范`;
151
+ 图搜图使用方式为引用图片,默认匹配距离为0.25`;
176
152
  const configHelp = `用法: 搜图-c [选项]
177
153
 
178
154
  可选项:
@@ -181,11 +157,10 @@ function apply(ctx, config) {
181
157
  --on 开启当前群聊的搜图功能
182
158
  --off 关闭当前群聊的搜图功能
183
159
  --onglobal 启用全局标签
184
- --offglobal 关闭全局标签
185
- `;
186
- ctx.command("搜图 [...params]", "从图站搜索图片").option("tags", "--tags 获取当前群聊内置标签列表").option("status", "--status 获取当前群聊的搜图功能状态").option("pp", "--pp <per_page:number> 每页结果数量,默认为50", { fallback: 50 }).option("p", "--p <page:number> 页码,默认为1", { fallback: 1 }).option("sf", "--sf <sf:string> 排序字段,默认为score", { fallback: "score" }).option("sd", "--sd <sd:string> 排序方向,默认为desc", { fallback: "desc" }).option("i", "--i <index:number> 选择结果索引,默认为-1(即随机)", { fallback: -1 }).action(async ({ session, options }, ...paramsArray) => {
160
+ --offglobal 关闭全局标签`;
161
+ ctx.command("搜图 [...params]", "从图站搜索图片").option("tags", "--tags").option("status", "--status").option("pp", "--pp <per_page:number>", { fallback: 50 }).option("p", "--p <page:number>", { fallback: 1 }).option("sf", "--sf <sf:string>", { fallback: "score" }).option("sd", "--sd <sd:string>", { fallback: "desc" }).option("i", "--i <index:number>", { fallback: -1 }).action(async ({ session, options }, ...paramsArray) => {
187
162
  if (!session?.guildId) return "搜图仅限群聊使用。";
188
- let params = paramsArray.join(" ");
163
+ let params = paramsArray.join(" ").trim();
189
164
  if (!params && !session.quote && !options.tags && !options.status) {
190
165
  return searchHelp;
191
166
  }
@@ -193,9 +168,9 @@ function apply(ctx, config) {
193
168
  const groupConfig = await getGroupConfig(groupId);
194
169
  if (options.status) {
195
170
  return `当前群聊搜图功能状态:
196
- 启用:${groupConfig.enabled}
197
- 标签:${groupConfig.customTags.join(", ") || "无"}
198
- 全局标签:${groupConfig.useGlobalTags ? "启用" : "禁用"}`;
171
+ 启用:${groupConfig.enabled}
172
+ 标签:${groupConfig.customTags.join(", ") || "无"}
173
+ 全局标签:${groupConfig.useGlobalTags ? "启用" : "禁用"}`;
199
174
  }
200
175
  if (options.tags) {
201
176
  return `当前群聊内置标签:${groupConfig.customTags.join(", ") || "无"}`;
@@ -207,17 +182,18 @@ function apply(ctx, config) {
207
182
  let imageUrl;
208
183
  const quote = session.quote;
209
184
  if (quote) {
210
- const imgElement = import_koishi.h.select(quote.content, "image")[0];
185
+ const imgElement = import_koishi.h.select(quote.content, "image")[0] || import_koishi.h.select(quote.content, "img")[0];
211
186
  if (imgElement) {
212
- imageUrl = imgElement.attrs.url;
187
+ imageUrl = imgElement.attrs.url || imgElement.attrs.src;
213
188
  }
214
189
  }
215
190
  try {
216
191
  if (imageUrl) {
217
192
  let distance = 0.25;
218
193
  if (params) {
219
- if (!isNaN(Number(params))) {
220
- distance = Number(params);
194
+ const parsed = Number(params);
195
+ if (!isNaN(parsed)) {
196
+ distance = parsed;
221
197
  } else {
222
198
  return "图片搜索仅支持数字参数,表示相似度距离(distance)。";
223
199
  }
@@ -232,22 +208,23 @@ function apply(ctx, config) {
232
208
  if (images.length > 10) {
233
209
  return `搜索到过多图片 (${images.length} 张),请尝试减小距离参数。`;
234
210
  }
235
- let result = "";
236
- result += (0, import_koishi.h)("at", { id: session.userId }).toString();
237
- result += `
238
- distance: ${distance}`;
211
+ if (images.length === 0) return "未找到匹配的图片";
212
+ const result = [(0, import_koishi.h)("at", { id: session.userId }), import_koishi.h.text(`
213
+ distance: ${distance}
214
+ `)];
239
215
  for (const img of images) {
240
- result += getMediaElement(img).toString();
241
- result += `
242
- id: ${img.id}
243
- score: ${img.score}`;
216
+ result.push(getMediaElement(img));
217
+ result.push(import_koishi.h.text(`
218
+ id: ${img.id} | score: ${img.score}
219
+ `));
244
220
  }
245
221
  return result;
246
222
  } else {
247
223
  const userTags = params ? params.split(",").map((t) => t.trim()).filter((t) => t) : [];
248
224
  const globalTags = groupConfig.useGlobalTags ? config.defaultTags : [];
249
225
  const groupTags = groupConfig.customTags;
250
- const allTags = [.../* @__PURE__ */ new Set([...groupTags, ...globalTags, ...userTags])];
226
+ const allTags = Array.from(/* @__PURE__ */ new Set([...groupTags, ...globalTags, ...userTags]));
227
+ if (allTags.length === 0 && !params) return "请输入搜索标签。";
251
228
  const queryParams = {
252
229
  q: allTags.join(", "),
253
230
  key: config.apiKey,
@@ -261,40 +238,33 @@ score: ${img.score}`;
261
238
  let index = options.i;
262
239
  let additionalMsg = "";
263
240
  if (index < 0 || index >= images.length) {
264
- if (index >= 0) {
265
- additionalMsg = `索引 ${index} 超出单页范围,已随机选择图片`;
266
- }
241
+ if (index >= 0) additionalMsg = `索引 ${index} 超出单页范围,已随机选择图片`;
267
242
  index = Math.floor(Math.random() * images.length);
268
243
  }
269
244
  const selected = images[index];
270
- let result = "";
271
- result += (0, import_koishi.h)("at", { id: session.userId }).toString();
272
- result += getMediaElement(selected).toString();
273
- result += `
274
- id: ${selected.id}
275
- score: ${selected.score}`;
276
- result += `
277
- tags: ${queryParams.q}`;
278
- if (additionalMsg) result += `
279
- 提示:${additionalMsg}`;
280
- return result;
245
+ return [
246
+ (0, import_koishi.h)("at", { id: session.userId }),
247
+ getMediaElement(selected),
248
+ import_koishi.h.text(`
249
+ id: ${selected.id} | score: ${selected.score}`),
250
+ import_koishi.h.text(`
251
+ tags: ${queryParams.q}`),
252
+ additionalMsg ? import_koishi.h.text(`
253
+ 提示:${additionalMsg}`) : null
254
+ ];
281
255
  }
282
256
  } catch (error) {
283
257
  return error instanceof Error ? error.message : String(error);
284
258
  }
285
259
  });
286
260
  const confirmOffGlobal = /* @__PURE__ */ new Set();
287
- ctx.command("搜图-c", "配置搜图功能", { authority: 3 }).option("on", "--on 开启当前群聊的搜图功能").option("off", "--off 关闭当前群聊的搜图功能").option("onglobal", "--onglobal 启用全局标签").option("offglobal", "--offglobal 关闭全局标签").option("add", "--add <tags:string> 添加标签,多个标签用逗号分隔").option("rm", "--rm <tags:string> 删除标签,多个标签用逗号分隔").action(async ({ session, options }) => {
261
+ ctx.command("搜图-c", "配置搜图功能", { authority: 3 }).option("on", "--on").option("off", "--off").option("onglobal", "--onglobal").option("offglobal", "--offglobal").option("add", "--add <tags:string>").option("rm", "--rm <tags:string>").action(async ({ session, options }) => {
288
262
  if (!session?.guildId) return "搜图配置仅限群聊使用。";
289
- if (Object.keys(options).length === 0) {
290
- return configHelp;
291
- }
263
+ if (Object.keys(options).length === 0) return configHelp;
292
264
  const groupId = session.guildId;
293
265
  const groupConfig = await getGroupConfig(groupId);
294
266
  let response = "";
295
- if (options.on && options.off) {
296
- return "不能同时开启和关闭搜图功能,请选择一个操作";
297
- }
267
+ if (options.on && options.off) return "不能同时开启和关闭搜图功能";
298
268
  if (options.on) {
299
269
  await updateGroupConfig(groupId, { enabled: true });
300
270
  response += "搜图功能已在本群开启\n";
@@ -302,9 +272,7 @@ tags: ${queryParams.q}`;
302
272
  await updateGroupConfig(groupId, { enabled: false });
303
273
  response += "搜图功能已在本群关闭\n";
304
274
  }
305
- if (options.onglobal && options.offglobal) {
306
- return "不能同时开启和关闭全局标签,请选择一个操作";
307
- }
275
+ if (options.onglobal && options.offglobal) return "不能同时开启和关闭全局标签";
308
276
  if (options.onglobal) {
309
277
  await updateGroupConfig(groupId, { useGlobalTags: true });
310
278
  response += "全局标签已启用\n";
@@ -313,28 +281,27 @@ tags: ${queryParams.q}`;
313
281
  if (!confirmOffGlobal.has(confirmKey)) {
314
282
  confirmOffGlobal.add(confirmKey);
315
283
  ctx.setTimeout(() => confirmOffGlobal.delete(confirmKey), 6e4);
316
- return "关闭全局标签,机器人将会搜出非safe图片\n请自行承担可能的炸群风险\n再输入一遍指令确认关闭";
284
+ return "关闭全局标签,机器人将会搜出非safe图片\n请自行承担风险,再次输入指令确认关闭";
317
285
  }
318
286
  confirmOffGlobal.delete(confirmKey);
319
287
  await updateGroupConfig(groupId, { useGlobalTags: false });
320
288
  response += "全局标签已禁用\n";
321
289
  }
322
290
  if (options.add || options.rm) {
323
- const currentTags = groupConfig.customTags;
324
- let newTags = [...currentTags];
291
+ let newTags = [...groupConfig.customTags];
325
292
  if (options.add) {
326
- const tagsToAdd = translateText(options.add).split(",").map((t) => t.trim()).filter((t) => t);
293
+ const tagsToAdd = translateText(options.add).split(/[,,]/).map((t) => t.trim()).filter((t) => t);
327
294
  newTags = [.../* @__PURE__ */ new Set([...newTags, ...tagsToAdd])];
328
295
  }
329
296
  if (options.rm) {
330
- const tagsToRm = translateText(options.rm).split(",").map((t) => t.trim()).filter((t) => t);
297
+ const tagsToRm = translateText(options.rm).split(/[,,]/).map((t) => t.trim()).filter((t) => t);
331
298
  newTags = newTags.filter((t) => !tagsToRm.includes(t));
332
299
  }
333
300
  await updateGroupConfig(groupId, { customTags: newTags });
334
301
  response += `修改成功,本群标签现为: ${newTags.join(", ") || "无"}
335
302
  `;
336
303
  }
337
- return response.trim() || '请输入有效的配置选项。可用 "搜图-c --help" 查看帮助。';
304
+ return response.trim();
338
305
  });
339
306
  }
340
307
  __name(apply, "apply");
@@ -342,5 +309,6 @@ __name(apply, "apply");
342
309
  0 && (module.exports = {
343
310
  Config,
344
311
  apply,
345
- inject
312
+ inject,
313
+ name
346
314
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-phimg2",
3
- "description": "该插件可以让机器人通过Philomena API在使用Philomena搭建的图站上使用标签(tags)搜图",
4
- "version": "1.0.3",
3
+ "description": "Koishi 插件,让机器人通过Philomena API在使用Philomena搭建的图站上使用标签(tags)搜图或图搜图",
4
+ "version": "1.0.5",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "files": [