🦄 refactor: 优化 OpenaiBuilder 类和工具模块代码结构

- 移除 utils/openai-builder.js 中不再使用的 import 语句和方法
- 简化 apps/tools.js 中的下载队列逻辑,直接执行下载任务
- 移除 package.json 中不再使用的依赖项
- 确保代码清晰和功能正常运行,提升代码可维护性
- 优化哔哩哔哩视频下载流程,提高下载效率和稳定性
- 修复潜在的文件路径问题,确保文件操作安全有效
- 移除冗余的上传至小飞机逻辑,简化代码结构
- 优化视频预览功能,提升用户体验和操作便捷性
This commit is contained in:
zhiyu1998 2024-09-19 21:42:45 +08:00
parent b114084276
commit 75d10fbd45
4 changed files with 76 additions and 147 deletions

View File

@ -96,7 +96,7 @@ import { deepSeekChat, llmRead } from "../utils/llm-util.js";
import { getDS } from "../utils/mihoyo.js"; import { getDS } from "../utils/mihoyo.js";
import { OpenaiBuilder } from "../utils/openai-builder.js"; import { OpenaiBuilder } from "../utils/openai-builder.js";
import { redisExistKey, redisGetKey, redisSetKey } from "../utils/redis-util.js"; import { redisExistKey, redisGetKey, redisSetKey } from "../utils/redis-util.js";
import { saveTDL, startTDL, uploadTDL } from "../utils/tdl-util.js"; import { saveTDL, startTDL } from "../utils/tdl-util.js";
import Translate from "../utils/trans-strategy.js"; import Translate from "../utils/trans-strategy.js";
import { mid2id } from "../utils/weibo.js"; import { mid2id } from "../utils/weibo.js";
import { ytDlpGetTilt, ytDlpHelper } from "../utils/yt-dlp-util.js"; import { ytDlpGetTilt, ytDlpHelper } from "../utils/yt-dlp-util.js";
@ -394,11 +394,9 @@ export class tools extends plugin {
// logger.info(resUrl); // logger.info(resUrl);
const path = `${ this.getCurDownloadPath(e) }/temp.mp4`; const path = `${ this.getCurDownloadPath(e) }/temp.mp4`;
// 加入队列 // 加入队列
this.queue.add(async () => { await this.downloadVideo(resUrl).then(() => {
await this.downloadVideo(resUrl).then(() => { this.sendVideoToUpload(e, path)
this.sendVideoToUpload(e, path) });
});
})
} else if (urlType === "image") { } else if (urlType === "image") {
// 发送描述 // 发送描述
e.reply(`${ this.identifyPrefix } 识别:抖音, ${ item.desc }`); e.reply(`${ this.identifyPrefix } 识别:抖音, ${ item.desc }`);
@ -575,11 +573,8 @@ export class tools extends plugin {
const ep = await this.biliEpInfo(url, e); const ep = await this.biliEpInfo(url, e);
// 如果使用了BBDown && 没有填写session 就放开下载 // 如果使用了BBDown && 没有填写session 就放开下载
if (this.biliUseBBDown) { if (this.biliUseBBDown) {
// 加入队列 // 下载文件
this.queue.add(async () => { await this.biliDownloadStrategy(e, `https://www.bilibili.com/bangumi/play/ep${ ep }`, path);
// 下载文件
await this.biliDownloadStrategy(e, `https://www.bilibili.com/bangumi/play/ep${ ep }`, path);
})
} }
return true; return true;
} }
@ -613,11 +608,8 @@ export class tools extends plugin {
if (e.msg !== undefined && e.msg.startsWith("音乐")) { if (e.msg !== undefined && e.msg.startsWith("音乐")) {
return await this.biliMusic(e, url); return await this.biliMusic(e, url);
} }
// 加入队列 // 下载文件
this.queue.add(async () => { await this.biliDownloadStrategy(e, url, path);
// 下载文件
await this.biliDownloadStrategy(e, url, path);
})
return true; return true;
} }
@ -721,43 +713,45 @@ export class tools extends plugin {
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async biliDownloadStrategy(e, url, path) { async biliDownloadStrategy(e, url, path) {
// =================以下是调用BBDown的逻辑===================== return this.queue.add(async () => {
// 下载视频和音频 // =================以下是调用BBDown的逻辑=====================
const tempPath = `${ path }temp`; // 下载视频和音频
// 检测是否开启BBDown const tempPath = `${ path }temp`;
if (this.biliUseBBDown) { // 检测是否开启BBDown
// 检测环境的 BBDown if (this.biliUseBBDown) {
const isExistBBDown = await checkToolInCurEnv("BBDown"); // 检测环境的 BBDown
// 存在 BBDown const isExistBBDown = await checkToolInCurEnv("BBDown");
if (isExistBBDown) { // 存在 BBDown
// 删除之前的文件 if (isExistBBDown) {
await checkAndRemoveFile(`${ tempPath }.mp4`); // 删除之前的文件
// 下载视频 await checkAndRemoveFile(`${ tempPath }.mp4`);
await startBBDown(url, path, { // 下载视频
biliSessData: this.biliSessData, await startBBDown(url, path, {
biliUseAria2: this.biliDownloadMethod === 1, biliSessData: this.biliSessData,
biliCDN: BILI_CDN_SELECT_LIST.find(item => item.value === this.biliCDN)?.sign, biliUseAria2: this.biliDownloadMethod === 1,
biliResolution: this.biliResolution, biliCDN: BILI_CDN_SELECT_LIST.find(item => item.value === this.biliCDN)?.sign,
}); biliResolution: this.biliResolution,
// 发送视频 });
return this.sendVideoToUpload(e, `${ tempPath }.mp4`); // 发送视频
return this.sendVideoToUpload(e, `${ tempPath }.mp4`);
}
e.reply("🚧 R插件提醒你开启但未检测到当前环境有【BBDown】即将使用默认下载方式 ( ◡̀_◡́)ᕤ");
} }
e.reply("🚧 R插件提醒你开启但未检测到当前环境有【BBDown】即将使用默认下载方式 ( ◡̀_◡́)ᕤ"); // =================默认下载方式=====================
} try {
// =================默认下载方式===================== // 获取下载链接
try { const data = await getDownloadUrl(url, this.biliSessData);
// 获取下载链接
const data = await getDownloadUrl(url, this.biliSessData);
await this.downBili(tempPath, data.videoUrl, data.audioUrl); await this.downBili(tempPath, data.videoUrl, data.audioUrl);
// 上传视频 // 上传视频
return this.sendVideoToUpload(e, `${ tempPath }.mp4`); return this.sendVideoToUpload(e, `${ tempPath }.mp4`);
} catch (err) { } catch (err) {
// 错误处理 // 错误处理
logger.error('[R插件][哔哩哔哩视频发送]下载错误,具体原因为:', err); logger.error('[R插件][哔哩哔哩视频发送]下载错误,具体原因为:', err);
e.reply("解析失败,请重试一下"); e.reply("解析失败,请重试一下");
} }
})
} }
/** /**
@ -1928,10 +1922,8 @@ export class tools extends plugin {
// 处理视频 // 处理视频
if (link) { if (link) {
this.queue.add(async () => { const filePath = await this.downloadVideo(link);
const filePath = await this.downloadVideo(link); this.sendVideoToUpload(e, `${ filePath }/temp.mp4`);
this.sendVideoToUpload(e, `${ filePath }/temp.mp4`);
});
} }
} }
} }
@ -1981,7 +1973,7 @@ export class tools extends plugin {
const tag = e.msg.replace(/#验车/g, ""); const tag = e.msg.replace(/#验车/g, "");
const reqUrl = `https://whatslink.info/api/v1/link?url=${tag}`; const reqUrl = `https://whatslink.info/api/v1/link?url=${ tag }`;
const resp = await axios.get(reqUrl, { const resp = await axios.get(reqUrl, {
headers: { headers: {
"User-Agent": COMMON_USER_AGENT, "User-Agent": COMMON_USER_AGENT,
@ -2100,7 +2092,7 @@ export class tools extends plugin {
* @param isProxy * @param isProxy
* @param headers * @param headers
* @param numThreads * @param numThreads
* @returns {Promise<void>} * @returns {Promise<string>}
*/ */
async downloadVideo(url, isProxy = false, headers = null, numThreads = this.videoDownloadConcurrency) { async downloadVideo(url, isProxy = false, headers = null, numThreads = this.videoDownloadConcurrency) {
// 构造群信息参数 // 构造群信息参数
@ -2129,17 +2121,19 @@ export class tools extends plugin {
target, target,
groupPath, groupPath,
} }
logger.info(`[R插件][视频下载]:当前队列长度为 ${ this.queue.size + 1 }`);
// 如果是用户设置了单线程,则不分片下载 return await this.queue.add(async () => {
if (numThreads === 1) { // 如果是用户设置了单线程,则不分片下载
return await this.downloadVideoWithSingleThread(downloadVideoParams); if (numThreads === 1) {
} else if (numThreads !== 1 && this.biliDownloadMethod === 1) { await this.downloadVideoWithSingleThread(downloadVideoParams);
return await this.downloadVideoWithAria2(downloadVideoParams, numThreads); } else if (numThreads !== 1 && this.biliDownloadMethod === 1) {
} else if (numThreads !== 1 && this.biliDownloadMethod === 2) { await this.downloadVideoWithAria2(downloadVideoParams, numThreads);
return await this.downloadVideoUseAxel(downloadVideoParams, numThreads); } else if (numThreads !== 1 && this.biliDownloadMethod === 2) {
} else { await this.downloadVideoUseAxel(downloadVideoParams, numThreads);
return await this.downloadVideoWithMultiThread(downloadVideoParams, numThreads); } else {
} await this.downloadVideoWithMultiThread(downloadVideoParams, numThreads);
}
});
} }
/** /**
@ -2468,14 +2462,8 @@ export class tools extends plugin {
} }
const stats = fs.statSync(path); const stats = fs.statSync(path);
const videoSize = Math.floor(stats.size / (1024 * 1024)); const videoSize = Math.floor(stats.size / (1024 * 1024));
// 顺便发送一份到小飞机 // 预览视频逻辑
if (e.msg.startsWith("上传飞机")) { if (e.msg.startsWith("预览视频")) {
this.queue.add(async () => {
await uploadTDL(path, this.isOverseasServer(), this.proxyAddr);
e.reply("✈️ 已发送一份到您的小飞机收藏夹了!");
})
} else if (e.msg.startsWith("预览视频")) {
// 预览视频逻辑
const keyframesPath = this.getCurDownloadPath(e) + "keyframes"; const keyframesPath = this.getCurDownloadPath(e) + "keyframes";
await mkdirIfNotExists(keyframesPath); await mkdirIfNotExists(keyframesPath);
await extractKeyframes(path, keyframesPath); await extractKeyframes(path, keyframesPath);

View File

@ -1,11 +1,11 @@
- { - {
version: 1.8.2, version: 1.9.0,
data: data:
[ [
优化<span class="cmd">队列下载和GPT</span>功能,
新增<span class="cmd">哔哩哔哩下载分辨率设置</span>功能, 新增<span class="cmd">哔哩哔哩下载分辨率设置</span>功能,
新增<span class="cmd">自定义识别</span>功能, 新增<span class="cmd">自定义识别</span>功能,
修正<span class="cmd">油管分辨率降低到720P</span>功能, 修正<span class="cmd">油管分辨率降低到720P</span>功能,
新增<span class="cmd">小飞机解析 Beta</span>功能,
支持<span class="cmd">锅巴</span>插件,方便查看和修改配置, 支持<span class="cmd">锅巴</span>插件,方便查看和修改配置,
输入<span class="cmd">#R帮助</span>获取插件帮助, 输入<span class="cmd">#R帮助</span>获取插件帮助,
输入<span class="cmd">#R更新</span>更新插件, 输入<span class="cmd">#R更新</span>更新插件,

View File

@ -6,7 +6,6 @@
"axios": "^1.3.4", "axios": "^1.3.4",
"qrcode": "^1.5.3", "qrcode": "^1.5.3",
"p-queue": "^8.0.1", "p-queue": "^8.0.1",
"ws": "^8.17.0", "ws": "^8.17.0"
"openai": "^4.47.1"
} }
} }

View File

@ -1,8 +1,4 @@
import { toBase64 } from "./file.js"; import axios from "axios";
// openai库
import OpenAI from 'openai';
// fs
import fs from "node:fs";
export class OpenaiBuilder { export class OpenaiBuilder {
constructor() { constructor() {
@ -14,7 +10,7 @@ export class OpenaiBuilder {
} }
setBaseURL(baseURL) { setBaseURL(baseURL) {
this.baseURL = baseURL + "/v1"; this.baseURL = baseURL;
return this; return this;
} }
@ -41,16 +37,20 @@ export class OpenaiBuilder {
async build() { async build() {
// logger.info(this.baseURL, this.apiKey) // logger.info(this.baseURL, this.apiKey)
// 创建客户端 // 创建客户端
this.client = new OpenAI({ this.client = axios.create({
baseURL: this.baseURL, baseURL: this.baseURL,
apiKey: this.apiKey timeout: 10000,
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + this.apiKey
}
}); });
return this; return this;
} }
async kimi(query) { async kimi(query) {
// 请求Kimi // 请求Kimi
const completion = await this.client.chat.completions.create({ const completion = await this.client.post("/v1/chat/completions", {
model: "moonshot-v1-8k", model: "moonshot-v1-8k",
messages: [ messages: [
{ {
@ -68,62 +68,4 @@ export class OpenaiBuilder {
"ans": completion.choices[0].message.content "ans": completion.choices[0].message.content
} }
} }
async kimi_pic(path) {
let file_object = await this.client.files.create({
file: fs.createReadStream(path),
purpose: "file-extract"
})
let file_content = await (await this.client.files.content(file_object.id)).text()
// 请求Kimi
const completion = await this.client.chat.completions.create({
model: "moonshot-v1-8k",
messages: [
{
"role": "system",
"content": file_content,
},
{
role: "user",
content: this.prompt
},
],
});
return {
"model": "月之暗面 Kimi",
"ans": completion.choices[0].message.content
}
}
async openai_pic(path) {
// 转换base64
const pic = await toBase64(path);
const completion = await this.client.chat.completions.create({
model: this.model,
messages: [
{
role: "user",
content: [
{
type: "image_url",
image_url: {
url: pic,
},
},
{
type: "text",
text: this.prompt,
},
],
},
],
use_search: false,
});
return {
"model": "OpenAI",
"ans": completion.choices[0].message.content
}
}
} }