koishi-plugin-randompic
Version:
随机获取图片
77 lines (76 loc) • 3.51 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Config = exports.name = void 0;
exports.apply = apply;
const koishi_1 = require("koishi");
const node_fetch_1 = __importDefault(require("node-fetch")); // 改用 CommonJS 版本
const jsonpath_1 = __importDefault(require("jsonpath")); // 使用 require 语法
exports.name = 'randompic';
exports.Config = koishi_1.Schema.object({
apis: koishi_1.Schema.array(koishi_1.Schema.object({
url: koishi_1.Schema.string()
.description('固定API地址(无需修改)')
.default('https://image.anosu.top/pixiv/json'),
params: koishi_1.Schema.string()
.description('请求参数(如 num=3&r18=1)')
.default('num=1'),
jsonPath: koishi_1.Schema.string()
.description('JSON路径(默认提取所有URL)')
.default('$[*].url')
})).default([
{
url: "https://image.anosu.top/pixiv/json",
params: "num=1&r18=0",
jsonPath: "$[*].url"
}
]),
timeout: koishi_1.Schema.number().description('请求超时(毫秒)').default(5000),
prompt: koishi_1.Schema.string().description('发送前的提示词').default('正在加载中~')
});
function apply(ctx, config) {
ctx.command('randompic', '获取随机图片')
.alias('sjst', '随机涩图', '随机图', '获取随机涩图')
.action(async ({ session }) => {
if (!config.apis || config.apis.length === 0) {
return session.text('未配置图片 API');
}
if (config.prompt) {
await session.send(config.prompt);
}
let availableApis = [...config.apis];
let error = null;
while (availableApis.length > 0) {
const randomIndex = Math.floor(Math.random() * availableApis.length);
const api = availableApis[randomIndex];
// 移除已尝试的 API
availableApis = availableApis.filter((_, i) => i !== randomIndex);
try {
const params = new URLSearchParams(api.params);
const fullUrl = `${api.url}?${params.toString()}`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), config.timeout);
const res = await (0, node_fetch_1.default)(fullUrl, { signal: controller.signal });
clearTimeout(timer);
if (!res.ok)
throw new Error(`HTTP ${res.status}`);
const data = await res.json();
// JSONPath 解析
const urls = jsonpath_1.default.query(data, api.jsonPath)
.filter((url) => typeof url === 'string' && url.startsWith('http'));
if (urls.length === 0) {
throw new Error('未找到有效图片URL');
}
const selectedUrl = urls[Math.floor(Math.random() * urls.length)];
return session.send(koishi_1.h.image(selectedUrl));
}
catch (err) {
const message = err instanceof Error ? err.message : String(err);
ctx.logger('randompic').warn(`API ${api.url} 失败: ${message}`);
}
}
return session.text('所有API均失败');
});
}